text
stringlengths 5
1.04M
|
|---|
#include "WorkingWithProjects/WorkingWithProjectProperties/ReadCurrencyProperties.h"
#include <system/type_info.h>
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/reflection/method_base.h>
#include <system/object_ext.h>
#include <system/object.h>
#include <system/convert.h>
#include <system/console.h>
#include <Project.h>
#include <Prj.h>
#include <Key.h>
#include <enums/PrjKey.h>
#include <enums/CurrencySymbolPositionType.h>
#include <cstdint>
#include "RunExamples.h"
namespace Aspose {
namespace Tasks {
namespace Examples {
namespace CPP {
namespace WorkingWithProjects {
namespace WorkingWithProjectProperties {
RTTI_INFO_IMPL_HASH(3354857169u, ::Aspose::Tasks::Examples::CPP::WorkingWithProjects::WorkingWithProjectProperties::ReadCurrencyProperties, ThisTypeBaseTypesInfo);
void ReadCurrencyProperties::Run()
{
// ExStart:ReadCurrencyProperties
// The path to the documents directory.
System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName());
// Create project instance
System::SharedPtr<Project> project = System::MakeObject<Project>(dataDir + u"ReadCurrencyProperties.mpp");
// Display currency properties
System::Console::WriteLine(System::String(u"Currency Code : ") + System::ObjectExt::ToString(project->Get<System::String>(Prj::CurrencyCode())));
System::Console::WriteLine(System::String(u"<br>Currency Digits : ") + System::Convert::ToString(project->Get<int32_t>(Prj::CurrencyDigits())));
System::Console::WriteLine(System::String(u"<br>Currency Symbol : ") + System::ObjectExt::ToString(project->Get<System::String>(Prj::CurrencySymbol())));
System::Console::WriteLine(System::String(u"Currency Symbol Position") + System::ObjectExt::ToString(project->Get<CurrencySymbolPositionType>(Prj::CurrencySymbolPosition())));
// ExEnd:ReadCurrencyProperties
}
} // namespace WorkingWithProjectProperties
} // namespace WorkingWithProjects
} // namespace CPP
} // namespace Examples
} // namespace Tasks
} // namespace Aspose
|
#ifndef __autoanysdkbindings_h__
#define __autoanysdkbindings_h__
#include "jsapi.h"
#include "jsfriendapi.h"
extern JSClass *jsb_anysdk_framework_PluginProtocol_class;
extern JSObject *jsb_anysdk_framework_PluginProtocol_prototype;
bool js_autoanysdkbindings_PluginProtocol_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_PluginProtocol_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_PluginProtocol(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_PluginProtocol_isFunctionSupported(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginProtocol_getPluginName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginProtocol_getPluginVersion(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginProtocol_setPluginName(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginProtocol_getSDKVersion(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginProtocol_setDebugMode(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_PluginFactory_class;
extern JSObject *jsb_anysdk_framework_PluginFactory_prototype;
bool js_autoanysdkbindings_PluginFactory_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_PluginFactory_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_PluginFactory(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_PluginFactory_purgeFactory(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginFactory_getInstance(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_PluginManager_class;
extern JSObject *jsb_anysdk_framework_PluginManager_prototype;
bool js_autoanysdkbindings_PluginManager_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_PluginManager_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_PluginManager(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_PluginManager_unloadPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginManager_loadPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginManager_end(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_PluginManager_getInstance(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolIAP_class;
extern JSObject *jsb_anysdk_framework_ProtocolIAP_prototype;
bool js_autoanysdkbindings_ProtocolIAP_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolIAP_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolIAP(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolIAP_getPluginId(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolIAP_getOrderId(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolIAP_resetPayState(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolAnalytics_class;
extern JSObject *jsb_anysdk_framework_ProtocolAnalytics_prototype;
bool js_autoanysdkbindings_ProtocolAnalytics_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolAnalytics_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolAnalytics(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolAnalytics_logTimedEventBegin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAnalytics_logError(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAnalytics_setCaptureUncaughtException(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAnalytics_setSessionContinueMillis(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAnalytics_startSession(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAnalytics_stopSession(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAnalytics_logTimedEventEnd(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolAds_class;
extern JSObject *jsb_anysdk_framework_ProtocolAds_prototype;
bool js_autoanysdkbindings_ProtocolAds_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolAds_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolAds(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolAds_showAds(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAds_hideAds(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAds_preloadAds(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAds_queryPoints(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAds_spendPoints(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolAds_isAdTypeSupported(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolSocial_class;
extern JSObject *jsb_anysdk_framework_ProtocolSocial_prototype;
bool js_autoanysdkbindings_ProtocolSocial_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolSocial_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolSocial(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolSocial_showLeaderboard(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolSocial_signOut(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolSocial_showAchievements(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolSocial_signIn(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolSocial_submitScore(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolUser_class;
extern JSObject *jsb_anysdk_framework_ProtocolUser_prototype;
bool js_autoanysdkbindings_ProtocolUser_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolUser_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolUser(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolUser_isLogined(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolUser_getUserID(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolUser_login(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolUser_getPluginId(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolPush_class;
extern JSObject *jsb_anysdk_framework_ProtocolPush_prototype;
bool js_autoanysdkbindings_ProtocolPush_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolPush_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolPush(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolPush_startPush(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolPush_closePush(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolPush_delAlias(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolPush_setAlias(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolCrash_class;
extern JSObject *jsb_anysdk_framework_ProtocolCrash_prototype;
bool js_autoanysdkbindings_ProtocolCrash_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolCrash_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolCrash(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolCrash_setUserIdentifier(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolCrash_reportException(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolCrash_leaveBreadcrumb(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolREC_class;
extern JSObject *jsb_anysdk_framework_ProtocolREC_prototype;
bool js_autoanysdkbindings_ProtocolREC_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolREC_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolREC(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolREC_startRecording(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_ProtocolREC_stopRecording(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_ProtocolCustom_class;
extern JSObject *jsb_anysdk_framework_ProtocolCustom_prototype;
bool js_autoanysdkbindings_ProtocolCustom_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolCustom_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolCustom(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
extern JSClass *jsb_anysdk_framework_ProtocolAdTracking_class;
extern JSObject *jsb_anysdk_framework_ProtocolAdTracking_prototype;
bool js_autoanysdkbindings_ProtocolAdTracking_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_ProtocolAdTracking_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_ProtocolAdTracking(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_ProtocolAdTracking_onRegister(JSContext *cx, uint32_t argc, jsval *vp);
extern JSClass *jsb_anysdk_framework_AgentManager_class;
extern JSObject *jsb_anysdk_framework_AgentManager_prototype;
bool js_autoanysdkbindings_AgentManager_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_autoanysdkbindings_AgentManager_finalize(JSContext *cx, JSObject *obj);
void js_register_autoanysdkbindings_AgentManager(JSContext *cx, JSObject *global);
void register_all_autoanysdkbindings(JSContext* cx, JSObject* obj);
bool js_autoanysdkbindings_AgentManager_getSocialPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_unloadALLPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_loadALLPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_unloadAllPlugins(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_loadAllPlugins(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getCustomParam(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getUserPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_init(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getAdsPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getPushPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getSharePlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getAnalyticsPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getCrashPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getCustomPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getRECPlugin(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getChannelId(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_end(JSContext *cx, uint32_t argc, jsval *vp);
bool js_autoanysdkbindings_AgentManager_getInstance(JSContext *cx, uint32_t argc, jsval *vp);
#endif
|
// Copyright 2015 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 "media/video/gpu_memory_buffer_video_frame_pool.h"
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <list>
#include <memory>
#include <utility>
#include "base/barrier_closure.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/containers/circular_deque.h"
#include "base/containers/stack_container.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/stringprintf.h"
#include "base/sys_byteorder.h"
#include "base/time/default_tick_clock.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/memory_dump_provider.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "gpu/GLES2/gl2extchromium.h"
#include "gpu/command_buffer/client/shared_image_interface.h"
#include "gpu/command_buffer/common/shared_image_usage.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/media_switches.h"
#include "media/video/gpu_video_accelerator_factories.h"
#include "third_party/libyuv/include/libyuv.h"
#include "ui/gfx/buffer_format_util.h"
#include "ui/gfx/color_space.h"
#include "ui/gl/trace_util.h"
#if defined(OS_MAC)
#include "base/mac/mac_util.h"
#include "ui/gfx/mac/io_surface.h"
#endif
namespace media {
namespace {
bool MultiPlaneSharedImagesEnabled() {
return base::FeatureList::IsEnabled(kMultiPlaneSharedImageVideo);
}
} // namespace
// Implementation of a pool of GpuMemoryBuffers used to back VideoFrames.
class GpuMemoryBufferVideoFramePool::PoolImpl
: public base::RefCountedThreadSafe<
GpuMemoryBufferVideoFramePool::PoolImpl>,
public base::trace_event::MemoryDumpProvider {
public:
// |media_task_runner| is the media task runner associated with the
// GL context provided by |gpu_factories|
// |worker_task_runner| is a task runner used to asynchronously copy
// video frame's planes.
// |gpu_factories| is an interface to GPU related operation and can be
// null if a GL context is not available.
PoolImpl(const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
const scoped_refptr<base::TaskRunner>& worker_task_runner,
GpuVideoAcceleratorFactories* const gpu_factories)
: media_task_runner_(media_task_runner),
worker_task_runner_(worker_task_runner),
gpu_factories_(gpu_factories),
output_format_(GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED),
tick_clock_(base::DefaultTickClock::GetInstance()),
in_shutdown_(false) {
DCHECK(media_task_runner_);
DCHECK(worker_task_runner_);
}
// Takes a software VideoFrame and calls |frame_ready_cb| with a VideoFrame
// backed by native textures if possible.
// The data contained in |video_frame| is copied into the returned frame
// asynchronously posting tasks to |worker_task_runner_|, while
// |frame_ready_cb| will be called on |media_task_runner_| once all the data
// has been copied.
void CreateHardwareFrame(scoped_refptr<VideoFrame> video_frame,
FrameReadyCB cb);
bool OnMemoryDump(const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) override;
// Aborts any pending copies.
void Abort();
// Shuts down the frame pool and releases all frames in |frames_|.
// Once this is called frames will no longer be inserted back into
// |frames_|.
void Shutdown();
void SetTickClockForTesting(const base::TickClock* tick_clock);
private:
friend class base::RefCountedThreadSafe<
GpuMemoryBufferVideoFramePool::PoolImpl>;
~PoolImpl() override;
// Resource to represent a plane.
struct PlaneResource {
gfx::Size size;
std::unique_ptr<gfx::GpuMemoryBuffer> gpu_memory_buffer;
gpu::Mailbox mailbox;
};
// All the resources needed to compose a frame.
// TODO(dalecurtis): The method of use marking used is very brittle
// and prone to leakage. Switch this to pass around std::unique_ptr
// such that callers own resources explicitly.
struct FrameResources {
explicit FrameResources(const gfx::Size& size, gfx::BufferUsage usage)
: size(size), usage(usage) {}
void MarkUsed() {
is_used_ = true;
last_use_time_ = base::TimeTicks();
}
void MarkUnused(base::TimeTicks last_use_time) {
is_used_ = false;
last_use_time_ = last_use_time;
}
bool is_used() const { return is_used_; }
base::TimeTicks last_use_time() const { return last_use_time_; }
const gfx::Size size;
const gfx::BufferUsage usage;
PlaneResource plane_resources[VideoFrame::kMaxPlanes];
// The sync token used to recycle or destroy the resources. It is set when
// the resources are returned from the VideoFrame (via
// MailboxHoldersReleased).
gpu::SyncToken sync_token;
private:
bool is_used_ = true;
base::TimeTicks last_use_time_;
};
// Struct to keep track of requested videoframe copies.
struct VideoFrameCopyRequest {
VideoFrameCopyRequest(scoped_refptr<VideoFrame> video_frame,
FrameReadyCB frame_ready_cb,
bool passthrough)
: video_frame(std::move(video_frame)),
frame_ready_cb(std::move(frame_ready_cb)),
passthrough(passthrough) {}
scoped_refptr<VideoFrame> video_frame;
FrameReadyCB frame_ready_cb;
bool passthrough;
};
// Start the copy of a video_frame on the worker_task_runner_.
// It assumes there are currently no in-flight copies and works on the request
// in the front of |frame_copy_requests_| queue.
void StartCopy();
// Copy |video_frame| data into |frame_resources| and calls |frame_ready_cb|
// when done.
void CopyVideoFrameToGpuMemoryBuffers(scoped_refptr<VideoFrame> video_frame,
FrameResources* frame_resources);
// Called when all the data has been copied.
void OnCopiesDone(bool copy_failed,
scoped_refptr<VideoFrame> video_frame,
FrameResources* frame_resources);
// Called on the media thread when all data has been copied.
void OnCopiesDoneOnMediaThread(bool copy_failed,
scoped_refptr<VideoFrame> video_frame,
FrameResources* frame_resources);
// Prepares GL resources, mailboxes and allocates the new VideoFrame. This has
// to be run on `media_task_runner_`. On failure, this will release
// `frame_resources` and return nullptr.
scoped_refptr<VideoFrame> BindAndCreateMailboxesHardwareFrameResources(
FrameResources* frame_resources,
const gfx::Size& coded_size,
const gfx::Rect& visible_rect,
const gfx::Size& natural_size,
const gfx::ColorSpace& color_space,
base::TimeDelta timestamp,
bool allow_i420_overlay);
// Return true if |resources| can be used to represent a frame for
// specific |format| and |size|.
static bool AreFrameResourcesCompatible(const FrameResources* resources,
const gfx::Size& size,
gfx::BufferUsage usage) {
return size == resources->size && usage == resources->usage;
}
// Get the resources needed for a frame out of the pool, or create them if
// necessary.
// This also drops the LRU resources that can't be reuse for this frame.
FrameResources* GetOrCreateFrameResources(
const gfx::Size& size,
GpuVideoAcceleratorFactories::OutputFormat format,
gfx::BufferUsage usage);
// Calls the FrameReadyCB of the first entry in |frame_copy_requests_|, with
// the provided |video_frame|, then deletes the entry from
// |frame_copy_requests_| and attempts to start another copy if there are
// other |frame_copy_requests_| elements.
void CompleteCopyRequestAndMaybeStartNextCopy(
scoped_refptr<VideoFrame> video_frame);
// Callback called when a VideoFrame generated with GetFrameResources is no
// longer referenced.
void MailboxHoldersReleased(FrameResources* frame_resources,
const gpu::SyncToken& sync_token);
// Delete resources. This has to be called on the thread where |task_runner|
// is current.
static void DeleteFrameResources(
GpuVideoAcceleratorFactories* const gpu_factories,
FrameResources* frame_resources);
// Task runner associated to the GL context provided by |gpu_factories_|.
const scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
// Task runner used to asynchronously copy planes.
const scoped_refptr<base::TaskRunner> worker_task_runner_;
// Interface to GPU related operations.
GpuVideoAcceleratorFactories* const gpu_factories_;
// Pool of resources.
std::list<FrameResources*> resources_pool_;
GpuVideoAcceleratorFactories::OutputFormat output_format_;
// |tick_clock_| is always a DefaultTickClock outside of testing.
const base::TickClock* tick_clock_;
// Queued up video frames for copies. The front is the currently
// in-flight copy, new copies are added at the end.
base::circular_deque<VideoFrameCopyRequest> frame_copy_requests_;
bool in_shutdown_;
DISALLOW_COPY_AND_ASSIGN(PoolImpl);
};
namespace {
// VideoFrame copies to GpuMemoryBuffers will be split in copies where the
// output size is |kBytesPerCopyTarget| bytes and run in parallel.
constexpr size_t kBytesPerCopyTarget = 1024 * 1024; // 1MB
// Return the GpuMemoryBuffer format to use for a specific VideoPixelFormat
// and plane.
gfx::BufferFormat GpuMemoryBufferFormat(
GpuVideoAcceleratorFactories::OutputFormat format,
size_t plane) {
switch (format) {
case GpuVideoAcceleratorFactories::OutputFormat::I420:
DCHECK_LE(plane, 2u);
return gfx::BufferFormat::R_8;
case GpuVideoAcceleratorFactories::OutputFormat::P010:
DCHECK_LE(plane, 1u);
return gfx::BufferFormat::P010;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB:
DCHECK_LE(plane, 1u);
return gfx::BufferFormat::YUV_420_BIPLANAR;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB:
DCHECK_LE(plane, 1u);
return plane == 0 ? gfx::BufferFormat::R_8 : gfx::BufferFormat::RG_88;
case GpuVideoAcceleratorFactories::OutputFormat::XR30:
DCHECK_EQ(0u, plane);
return gfx::BufferFormat::BGRA_1010102;
case GpuVideoAcceleratorFactories::OutputFormat::XB30:
DCHECK_EQ(0u, plane);
return gfx::BufferFormat::RGBA_1010102;
case GpuVideoAcceleratorFactories::OutputFormat::RGBA:
DCHECK_EQ(0u, plane);
return gfx::BufferFormat::RGBA_8888;
case GpuVideoAcceleratorFactories::OutputFormat::BGRA:
DCHECK_EQ(0u, plane);
return gfx::BufferFormat::BGRA_8888;
case GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED:
NOTREACHED();
break;
}
return gfx::BufferFormat::BGRA_8888;
}
// The number of output planes to be copied in each iteration.
size_t PlanesPerCopy(GpuVideoAcceleratorFactories::OutputFormat format) {
switch (format) {
case GpuVideoAcceleratorFactories::OutputFormat::I420:
case GpuVideoAcceleratorFactories::OutputFormat::RGBA:
case GpuVideoAcceleratorFactories::OutputFormat::BGRA:
return 1;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB:
case GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB:
case GpuVideoAcceleratorFactories::OutputFormat::P010:
return 2;
case GpuVideoAcceleratorFactories::OutputFormat::XR30:
case GpuVideoAcceleratorFactories::OutputFormat::XB30:
return 3;
case GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED:
NOTREACHED();
break;
}
return 0;
}
VideoPixelFormat VideoFormat(
GpuVideoAcceleratorFactories::OutputFormat format) {
switch (format) {
case GpuVideoAcceleratorFactories::OutputFormat::I420:
return PIXEL_FORMAT_I420;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB:
case GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB:
return PIXEL_FORMAT_NV12;
case GpuVideoAcceleratorFactories::OutputFormat::P010:
return PIXEL_FORMAT_P016LE;
case GpuVideoAcceleratorFactories::OutputFormat::BGRA:
return PIXEL_FORMAT_ARGB;
case GpuVideoAcceleratorFactories::OutputFormat::RGBA:
return PIXEL_FORMAT_ABGR;
case GpuVideoAcceleratorFactories::OutputFormat::XR30:
return PIXEL_FORMAT_XR30;
case GpuVideoAcceleratorFactories::OutputFormat::XB30:
return PIXEL_FORMAT_XB30;
case GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED:
NOTREACHED();
break;
}
return PIXEL_FORMAT_UNKNOWN;
}
// The number of output planes to be copied in each iteration.
size_t NumGpuMemoryBuffers(GpuVideoAcceleratorFactories::OutputFormat format) {
switch (format) {
case GpuVideoAcceleratorFactories::OutputFormat::I420:
return 3;
case GpuVideoAcceleratorFactories::OutputFormat::P010:
return 1;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB:
return 1;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB:
return 2;
case GpuVideoAcceleratorFactories::OutputFormat::XR30:
case GpuVideoAcceleratorFactories::OutputFormat::XB30:
return 1;
case GpuVideoAcceleratorFactories::OutputFormat::RGBA:
case GpuVideoAcceleratorFactories::OutputFormat::BGRA:
return 1;
case GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED:
NOTREACHED();
break;
}
NOTREACHED();
return 0;
}
// The number of shared images for a given format. Note that a single
// GpuMemoryBuffer can be mapped to several SharedImages (one for each plane).
size_t NumSharedImages(GpuVideoAcceleratorFactories::OutputFormat format) {
if (MultiPlaneSharedImagesEnabled()) {
if (format == GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB) {
return 2;
}
}
return NumGpuMemoryBuffers(format);
}
// In the case of a format where a single GpuMemoryBuffer is used by multiple
// planes' shared images, this function returns the index of the PlaneResource
// in which the GpuMemoryBuffer for a plane is to be found.
size_t GpuMemoryBufferPlaneResourceIndexForPlane(
GpuVideoAcceleratorFactories::OutputFormat format,
size_t plane) {
if (MultiPlaneSharedImagesEnabled()) {
if (format == GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB) {
return 0;
}
}
return plane;
}
// When a single plane of a GpuMemoryBuffer is to bound to a SharedImage, this
// method will indicate that plane.
gfx::BufferPlane GetSharedImageBufferPlane(
GpuVideoAcceleratorFactories::OutputFormat format,
size_t plane) {
if (MultiPlaneSharedImagesEnabled()) {
if (format == GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB) {
switch (plane) {
case 0:
return gfx::BufferPlane::Y;
case 1:
return gfx::BufferPlane::UV;
default:
NOTREACHED();
break;
}
}
}
return gfx::BufferPlane::DEFAULT;
}
// The number of output rows to be copied in each iteration.
int RowsPerCopy(size_t plane, VideoPixelFormat format, int width) {
int bytes_per_row = VideoFrame::RowBytes(plane, format, width);
if (format == PIXEL_FORMAT_NV12) {
DCHECK_EQ(0u, plane);
bytes_per_row += VideoFrame::RowBytes(1, format, width);
}
// Copy an even number of lines, and at least one.
return std::max<size_t>((kBytesPerCopyTarget / bytes_per_row) & ~1, 1);
}
void CopyRowsToI420Buffer(int first_row,
int rows,
int bytes_per_row,
size_t bit_depth,
const uint8_t* source,
int source_stride,
uint8_t* output,
int dest_stride,
base::OnceClosure done) {
base::ScopedClosureRunner done_runner(std::move(done));
TRACE_EVENT2("media", "CopyRowsToI420Buffer", "bytes_per_row", bytes_per_row,
"rows", rows);
if (!output)
return;
DCHECK_NE(dest_stride, 0);
DCHECK_LE(bytes_per_row, std::abs(dest_stride));
DCHECK_LE(bytes_per_row, source_stride);
DCHECK_GE(bit_depth, 8u);
if (bit_depth == 8) {
libyuv::CopyPlane(source + source_stride * first_row, source_stride,
output + dest_stride * first_row, dest_stride,
bytes_per_row, rows);
} else {
const int scale = 0x10000 >> (bit_depth - 8);
libyuv::Convert16To8Plane(
reinterpret_cast<const uint16_t*>(source + source_stride * first_row),
source_stride / 2, output + dest_stride * first_row, dest_stride, scale,
bytes_per_row, rows);
}
}
void CopyRowsToP010Buffer(int first_row,
int rows,
int width,
const VideoFrame* source_frame,
uint8_t* dest_y,
int dest_stride_y,
uint8_t* dest_uv,
int dest_stride_uv,
base::OnceClosure done) {
base::ScopedClosureRunner done_runner(std::move(done));
TRACE_EVENT2("media", "CopyRowsToP010Buffer", "width", width, "rows", rows);
if (!dest_y || !dest_uv)
return;
DCHECK_NE(dest_stride_y, 0);
DCHECK_NE(dest_stride_uv, 0);
DCHECK_EQ(0, first_row % 2);
DCHECK_EQ(source_frame->format(), PIXEL_FORMAT_YUV420P10);
DCHECK_LE(width * 2, source_frame->stride(VideoFrame::kYPlane));
const uint16_t* y_plane = reinterpret_cast<const uint16_t*>(
source_frame->visible_data(VideoFrame::kYPlane) +
first_row * source_frame->stride(VideoFrame::kYPlane));
const size_t y_plane_stride = source_frame->stride(VideoFrame::kYPlane) / 2;
const uint16_t* u_plane = reinterpret_cast<const uint16_t*>(
source_frame->visible_data(VideoFrame::kUPlane) +
(first_row / 2) * source_frame->stride(VideoFrame::kUPlane));
const size_t u_plane_stride = source_frame->stride(VideoFrame::kUPlane) / 2;
const uint16_t* v_plane = reinterpret_cast<const uint16_t*>(
source_frame->visible_data(VideoFrame::kVPlane) +
(first_row / 2) * source_frame->stride(VideoFrame::kVPlane));
const size_t v_plane_stride = source_frame->stride(VideoFrame::kVPlane) / 2;
libyuv::I010ToP010(
y_plane, y_plane_stride, u_plane, u_plane_stride, v_plane, v_plane_stride,
reinterpret_cast<uint16_t*>(dest_y + first_row * dest_stride_y),
dest_stride_y / 2,
reinterpret_cast<uint16_t*>(dest_uv + (first_row / 2) * dest_stride_uv),
dest_stride_uv / 2, width, rows);
}
void CopyRowsToNV12Buffer(int first_row,
int rows,
int bytes_per_row,
const VideoFrame* source_frame,
uint8_t* dest_y,
int dest_stride_y,
uint8_t* dest_uv,
int dest_stride_uv,
base::OnceClosure done) {
base::ScopedClosureRunner done_runner(std::move(done));
TRACE_EVENT2("media", "CopyRowsToNV12Buffer", "bytes_per_row", bytes_per_row,
"rows", rows);
if (!dest_y || !dest_uv)
return;
DCHECK_NE(dest_stride_y, 0);
DCHECK_NE(dest_stride_uv, 0);
DCHECK_LE(bytes_per_row, std::abs(dest_stride_y));
DCHECK_LE(bytes_per_row, std::abs(dest_stride_uv));
DCHECK_EQ(0, first_row % 2);
DCHECK(source_frame->format() == PIXEL_FORMAT_I420 ||
source_frame->format() == PIXEL_FORMAT_YV12 ||
source_frame->format() == PIXEL_FORMAT_NV12);
if (source_frame->format() == PIXEL_FORMAT_NV12) {
libyuv::CopyPlane(source_frame->visible_data(VideoFrame::kYPlane) +
first_row * source_frame->stride(VideoFrame::kYPlane),
source_frame->stride(VideoFrame::kYPlane),
dest_y + first_row * dest_stride_y, dest_stride_y,
bytes_per_row, rows);
libyuv::CopyPlane(
source_frame->visible_data(VideoFrame::kUVPlane) +
first_row / 2 * source_frame->stride(VideoFrame::kUVPlane),
source_frame->stride(VideoFrame::kUVPlane),
dest_uv + first_row / 2 * dest_stride_uv, dest_stride_uv, bytes_per_row,
rows / 2);
return;
}
libyuv::I420ToNV12(
source_frame->visible_data(VideoFrame::kYPlane) +
first_row * source_frame->stride(VideoFrame::kYPlane),
source_frame->stride(VideoFrame::kYPlane),
source_frame->visible_data(VideoFrame::kUPlane) +
first_row / 2 * source_frame->stride(VideoFrame::kUPlane),
source_frame->stride(VideoFrame::kUPlane),
source_frame->visible_data(VideoFrame::kVPlane) +
first_row / 2 * source_frame->stride(VideoFrame::kVPlane),
source_frame->stride(VideoFrame::kVPlane),
dest_y + first_row * dest_stride_y, dest_stride_y,
dest_uv + first_row / 2 * dest_stride_uv, dest_stride_uv, bytes_per_row,
rows);
}
void CopyRowsToRGB10Buffer(bool is_argb,
int first_row,
int rows,
int width,
const VideoFrame* source_frame,
uint8_t* output,
int dest_stride,
base::OnceClosure done) {
base::ScopedClosureRunner done_runner(std::move(done));
TRACE_EVENT2("media", "CopyRowsToXR30Buffer", "bytes_per_row", width * 2,
"rows", rows);
if (!output)
return;
DCHECK_NE(dest_stride, 0);
DCHECK_LE(width, std::abs(dest_stride / 2));
DCHECK_EQ(0, first_row % 2);
DCHECK_EQ(source_frame->format(), PIXEL_FORMAT_YUV420P10);
const uint16_t* y_plane = reinterpret_cast<const uint16_t*>(
source_frame->visible_data(VideoFrame::kYPlane) +
first_row * source_frame->stride(VideoFrame::kYPlane));
const size_t y_plane_stride = source_frame->stride(VideoFrame::kYPlane) / 2;
const uint16_t* v_plane = reinterpret_cast<const uint16_t*>(
source_frame->visible_data(VideoFrame::kVPlane) +
first_row / 2 * source_frame->stride(VideoFrame::kVPlane));
const size_t v_plane_stride = source_frame->stride(VideoFrame::kVPlane) / 2;
const uint16_t* u_plane = reinterpret_cast<const uint16_t*>(
source_frame->visible_data(VideoFrame::kUPlane) +
first_row / 2 * source_frame->stride(VideoFrame::kUPlane));
const size_t u_plane_stride = source_frame->stride(VideoFrame::kUPlane) / 2;
uint8_t* dest_rgb10 = output + first_row * dest_stride;
SkYUVColorSpace skyuv = kRec709_SkYUVColorSpace;
source_frame->ColorSpace().ToSkYUVColorSpace(&skyuv);
if (skyuv == kRec601_SkYUVColorSpace) {
if (is_argb) {
libyuv::I010ToAR30(y_plane, y_plane_stride, u_plane, u_plane_stride,
v_plane, v_plane_stride, dest_rgb10, dest_stride,
width, rows);
} else {
libyuv::I010ToAB30(y_plane, y_plane_stride, u_plane, u_plane_stride,
v_plane, v_plane_stride, dest_rgb10, dest_stride,
width, rows);
}
} else if (skyuv == kBT2020_SkYUVColorSpace) {
if (is_argb) {
libyuv::U010ToAR30(y_plane, y_plane_stride, u_plane, u_plane_stride,
v_plane, v_plane_stride, dest_rgb10, dest_stride,
width, rows);
} else {
libyuv::U010ToAB30(y_plane, y_plane_stride, u_plane, u_plane_stride,
v_plane, v_plane_stride, dest_rgb10, dest_stride,
width, rows);
}
} else { // BT.709
if (is_argb) {
libyuv::H010ToAR30(y_plane, y_plane_stride, u_plane, u_plane_stride,
v_plane, v_plane_stride, dest_rgb10, dest_stride,
width, rows);
} else {
libyuv::H010ToAB30(y_plane, y_plane_stride, u_plane, u_plane_stride,
v_plane, v_plane_stride, dest_rgb10, dest_stride,
width, rows);
}
}
}
void CopyRowsToRGBABuffer(bool is_rgba,
int first_row,
int rows,
int width,
const VideoFrame* source_frame,
uint8_t* output,
int dest_stride,
base::OnceClosure done) {
base::ScopedClosureRunner done_runner(std::move(done));
TRACE_EVENT2("media", "CopyRowsToRGBABuffer", "bytes_per_row", width * 2,
"rows", rows);
if (!output)
return;
DCHECK_NE(dest_stride, 0);
DCHECK_LE(width, std::abs(dest_stride / 2));
DCHECK_EQ(0, first_row % 2);
DCHECK_EQ(source_frame->format(), PIXEL_FORMAT_I420A);
// libyuv uses little-endian for RGBx formats, whereas here we use big endian.
auto* func_ptr = is_rgba ? libyuv::I420AlphaToABGR : libyuv::I420AlphaToARGB;
func_ptr(source_frame->visible_data(VideoFrame::kYPlane) +
first_row * source_frame->stride(VideoFrame::kYPlane),
source_frame->stride(VideoFrame::kYPlane),
source_frame->visible_data(VideoFrame::kUPlane) +
first_row / 2 * source_frame->stride(VideoFrame::kUPlane),
source_frame->stride(VideoFrame::kUPlane),
source_frame->visible_data(VideoFrame::kVPlane) +
first_row / 2 * source_frame->stride(VideoFrame::kVPlane),
source_frame->stride(VideoFrame::kVPlane),
source_frame->visible_data(VideoFrame::kAPlane) +
first_row * source_frame->stride(VideoFrame::kAPlane),
source_frame->stride(VideoFrame::kAPlane),
output + first_row * dest_stride, dest_stride, width, rows,
// Textures are expected to be premultiplied by GL and compositors.
1 /* attenuate, meaning premultiply */);
}
gfx::Size CodedSize(const VideoFrame* video_frame,
GpuVideoAcceleratorFactories::OutputFormat output_format) {
DCHECK(gfx::Rect(video_frame->coded_size())
.Contains(video_frame->visible_rect()));
DCHECK((video_frame->visible_rect().x() & 1) == 0);
gfx::Size output;
switch (output_format) {
case GpuVideoAcceleratorFactories::OutputFormat::I420:
case GpuVideoAcceleratorFactories::OutputFormat::P010:
case GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB:
case GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB:
DCHECK((video_frame->visible_rect().y() & 1) == 0);
output = gfx::Size((video_frame->visible_rect().width() + 1) & ~1,
(video_frame->visible_rect().height() + 1) & ~1);
break;
case GpuVideoAcceleratorFactories::OutputFormat::XR30:
case GpuVideoAcceleratorFactories::OutputFormat::XB30:
case GpuVideoAcceleratorFactories::OutputFormat::RGBA:
case GpuVideoAcceleratorFactories::OutputFormat::BGRA:
output = gfx::Size((video_frame->visible_rect().width() + 1) & ~1,
video_frame->visible_rect().height());
break;
case GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED:
NOTREACHED();
}
DCHECK(gfx::Rect(video_frame->coded_size()).Contains(gfx::Rect(output)));
return output;
}
} // unnamed namespace
// Creates a VideoFrame backed by native textures starting from a software
// VideoFrame.
// The data contained in |video_frame| is copied into the VideoFrame passed to
// |frame_ready_cb|.
// This has to be called on the thread where |media_task_runner_| is current.
void GpuMemoryBufferVideoFramePool::PoolImpl::CreateHardwareFrame(
scoped_refptr<VideoFrame> video_frame,
FrameReadyCB frame_ready_cb) {
DCHECK(media_task_runner_->BelongsToCurrentThread());
// Lazily initialize |output_format_| since VideoFrameOutputFormat() has to be
// called on the media_thread while this object might be instantiated on any.
const VideoPixelFormat pixel_format = video_frame->format();
if (output_format_ == GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED)
output_format_ = gpu_factories_->VideoFrameOutputFormat(pixel_format);
// Bail if we have a change of GpuVideoAcceleratorFactories::OutputFormat;
// such changes should not happen in general (see https://crbug.com/875158).
if (output_format_ != gpu_factories_->VideoFrameOutputFormat(pixel_format)) {
std::move(frame_ready_cb).Run(std::move(video_frame));
return;
}
bool is_software_backed_video_frame = !video_frame->HasTextures();
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
is_software_backed_video_frame &= !video_frame->HasDmaBufs();
#endif
bool passthrough = false;
#if defined(OS_MAC)
if (!IOSurfaceCanSetColorSpace(video_frame->ColorSpace()))
passthrough = true;
#endif
if (!video_frame->IsMappable()) {
// Already a hardware frame.
passthrough = true;
}
if (output_format_ == GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED)
passthrough = true;
switch (pixel_format) {
// Supported cases.
case PIXEL_FORMAT_YV12:
case PIXEL_FORMAT_I420:
case PIXEL_FORMAT_YUV420P10:
case PIXEL_FORMAT_I420A:
case PIXEL_FORMAT_NV12:
break;
// Unsupported cases.
case PIXEL_FORMAT_I422:
case PIXEL_FORMAT_I444:
case PIXEL_FORMAT_NV21:
case PIXEL_FORMAT_UYVY:
case PIXEL_FORMAT_YUY2:
case PIXEL_FORMAT_ARGB:
case PIXEL_FORMAT_BGRA:
case PIXEL_FORMAT_XRGB:
case PIXEL_FORMAT_RGB24:
case PIXEL_FORMAT_MJPEG:
case PIXEL_FORMAT_YUV422P9:
case PIXEL_FORMAT_YUV420P9:
case PIXEL_FORMAT_YUV444P9:
case PIXEL_FORMAT_YUV422P10:
case PIXEL_FORMAT_YUV444P10:
case PIXEL_FORMAT_YUV420P12:
case PIXEL_FORMAT_YUV422P12:
case PIXEL_FORMAT_YUV444P12:
case PIXEL_FORMAT_Y16:
case PIXEL_FORMAT_ABGR:
case PIXEL_FORMAT_XBGR:
case PIXEL_FORMAT_P016LE:
case PIXEL_FORMAT_XR30:
case PIXEL_FORMAT_XB30:
case PIXEL_FORMAT_RGBAF16:
case PIXEL_FORMAT_UNKNOWN:
if (is_software_backed_video_frame) {
UMA_HISTOGRAM_ENUMERATION(
"Media.GpuMemoryBufferVideoFramePool.UnsupportedFormat",
pixel_format, PIXEL_FORMAT_MAX + 1);
}
passthrough = true;
}
// TODO(dcastagna): Handle odd positioned video frame input, see
// https://crbug.com/638906.
// TODO(emircan): Eliminate odd size video frame input cases as they are not
// valid, see https://crbug.com/webrtc/9033.
if ((video_frame->visible_rect().x() & 1) ||
(video_frame->visible_rect().y() & 1) ||
(video_frame->coded_size().width() & 1) ||
(video_frame->coded_size().height() & 1)) {
passthrough = true;
}
frame_copy_requests_.emplace_back(std::move(video_frame),
std::move(frame_ready_cb), passthrough);
if (frame_copy_requests_.size() == 1u)
StartCopy();
}
bool GpuMemoryBufferVideoFramePool::PoolImpl::OnMemoryDump(
const base::trace_event::MemoryDumpArgs& args,
base::trace_event::ProcessMemoryDump* pmd) {
const uint64_t tracing_process_id =
base::trace_event::MemoryDumpManager::GetInstance()
->GetTracingProcessId();
const int kImportance = 2;
for (const FrameResources* frame_resources : resources_pool_) {
for (const PlaneResource& plane_resource :
frame_resources->plane_resources) {
if (plane_resource.gpu_memory_buffer) {
gfx::GpuMemoryBufferId buffer_id =
plane_resource.gpu_memory_buffer->GetId();
std::string dump_name = base::StringPrintf(
"media/video_frame_memory/buffer_%d", buffer_id.id);
base::trace_event::MemoryAllocatorDump* dump =
pmd->CreateAllocatorDump(dump_name);
size_t buffer_size_in_bytes = gfx::BufferSizeForBufferFormat(
plane_resource.size, plane_resource.gpu_memory_buffer->GetFormat());
dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
base::trace_event::MemoryAllocatorDump::kUnitsBytes,
buffer_size_in_bytes);
dump->AddScalar("free_size",
base::trace_event::MemoryAllocatorDump::kUnitsBytes,
frame_resources->is_used() ? 0 : buffer_size_in_bytes);
plane_resource.gpu_memory_buffer->OnMemoryDump(
pmd, dump->guid(), tracing_process_id, kImportance);
}
}
}
return true;
}
void GpuMemoryBufferVideoFramePool::PoolImpl::Abort() {
DCHECK(media_task_runner_->BelongsToCurrentThread());
// Abort any pending copy requests. If one is already in flight, we can't do
// anything about it.
if (frame_copy_requests_.size() <= 1u)
return;
frame_copy_requests_.erase(frame_copy_requests_.begin() + 1,
frame_copy_requests_.end());
}
void GpuMemoryBufferVideoFramePool::PoolImpl::OnCopiesDone(
bool copy_failed,
scoped_refptr<VideoFrame> video_frame,
FrameResources* frame_resources) {
if (!copy_failed) {
for (const auto& plane_resource : frame_resources->plane_resources) {
if (plane_resource.gpu_memory_buffer) {
plane_resource.gpu_memory_buffer->Unmap();
plane_resource.gpu_memory_buffer->SetColorSpace(
video_frame->ColorSpace());
if (video_frame->hdr_metadata()) {
plane_resource.gpu_memory_buffer->SetHDRMetadata(
video_frame->hdr_metadata().value());
}
}
}
}
TRACE_EVENT_ASYNC_END0("media", "CopyVideoFrameToGpuMemoryBuffers",
video_frame->timestamp().InNanoseconds() /* id */);
media_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&PoolImpl::OnCopiesDoneOnMediaThread, this, copy_failed,
std::move(video_frame), frame_resources));
}
void GpuMemoryBufferVideoFramePool::PoolImpl::StartCopy() {
DCHECK(media_task_runner_->BelongsToCurrentThread());
DCHECK(!frame_copy_requests_.empty());
while (!frame_copy_requests_.empty()) {
VideoFrameCopyRequest& request = frame_copy_requests_.front();
// Acquire resources. Incompatible ones will be dropped from the pool.
FrameResources* frame_resources =
request.passthrough
? nullptr
: GetOrCreateFrameResources(
CodedSize(request.video_frame.get(), output_format_),
output_format_, gfx::BufferUsage::SCANOUT_CPU_READ_WRITE);
if (!frame_resources) {
std::move(request.frame_ready_cb).Run(std::move(request.video_frame));
frame_copy_requests_.pop_front();
continue;
}
worker_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&PoolImpl::CopyVideoFrameToGpuMemoryBuffers,
this, request.video_frame, frame_resources));
break;
}
}
// Copies |video_frame| into |frame_resources| asynchronously, posting n tasks
// that will be synchronized by a barrier.
// After the barrier is passed OnCopiesDone will be called.
void GpuMemoryBufferVideoFramePool::PoolImpl::CopyVideoFrameToGpuMemoryBuffers(
scoped_refptr<VideoFrame> video_frame,
FrameResources* frame_resources) {
// Compute the number of tasks to post and create the barrier.
const size_t num_planes = VideoFrame::NumPlanes(VideoFormat(output_format_));
const size_t planes_per_copy = PlanesPerCopy(output_format_);
const gfx::Size coded_size = CodedSize(video_frame.get(), output_format_);
size_t copies = 0;
for (size_t i = 0; i < num_planes; i += planes_per_copy) {
const int rows =
VideoFrame::Rows(i, VideoFormat(output_format_), coded_size.height());
const int rows_per_copy =
RowsPerCopy(i, VideoFormat(output_format_), coded_size.width());
copies += rows / rows_per_copy;
if (rows % rows_per_copy)
++copies;
}
for (size_t i = 0; i < NumGpuMemoryBuffers(output_format_); ++i) {
gfx::GpuMemoryBuffer* buffer =
frame_resources->plane_resources[i].gpu_memory_buffer.get();
if (!buffer || !buffer->Map()) {
DLOG(ERROR) << "Could not get or Map() buffer";
for (size_t j = 0; j < i; ++j)
frame_resources->plane_resources[j].gpu_memory_buffer->Unmap();
OnCopiesDone(/*copy_failed=*/true, std::move(video_frame),
frame_resources);
return;
}
}
// |barrier| keeps refptr of |video_frame| until all copy tasks are done.
const base::RepeatingClosure barrier = base::BarrierClosure(
copies,
base::BindOnce(&PoolImpl::OnCopiesDone, this, /*copy_failed=*/false,
video_frame, frame_resources));
TRACE_EVENT_ASYNC_BEGIN0("media", "CopyVideoFrameToGpuMemoryBuffers",
video_frame->timestamp().InNanoseconds() /* id */);
// Post all the async tasks.
for (size_t i = 0; i < num_planes; i += planes_per_copy) {
gfx::GpuMemoryBuffer* buffer =
frame_resources->plane_resources[i].gpu_memory_buffer.get();
const int rows =
VideoFrame::Rows(i, VideoFormat(output_format_), coded_size.height());
const int rows_per_copy =
RowsPerCopy(i, VideoFormat(output_format_), coded_size.width());
for (int row = 0; row < rows; row += rows_per_copy) {
const int rows_to_copy = std::min(rows_per_copy, rows - row);
switch (output_format_) {
case GpuVideoAcceleratorFactories::OutputFormat::I420: {
const int bytes_per_row = VideoFrame::RowBytes(
i, VideoFormat(output_format_), coded_size.width());
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&CopyRowsToI420Buffer, row, rows_to_copy,
bytes_per_row, video_frame->BitDepth(),
video_frame->visible_data(i),
video_frame->stride(i),
static_cast<uint8_t*>(buffer->memory(0)),
buffer->stride(0), barrier));
break;
}
case GpuVideoAcceleratorFactories::OutputFormat::P010:
// Using base::Unretained(video_frame) here is safe because |barrier|
// keeps refptr of |video_frame| until all copy tasks are done.
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&CopyRowsToP010Buffer, row, rows_to_copy, coded_size.width(),
base::Unretained(video_frame.get()),
static_cast<uint8_t*>(buffer->memory(0)), buffer->stride(0),
static_cast<uint8_t*>(buffer->memory(1)), buffer->stride(1),
barrier));
break;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB:
// Using base::Unretained(video_frame) here is safe because |barrier|
// keeps refptr of |video_frame| until all copy tasks are done.
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&CopyRowsToNV12Buffer, row, rows_to_copy, coded_size.width(),
base::Unretained(video_frame.get()),
static_cast<uint8_t*>(buffer->memory(0)), buffer->stride(0),
static_cast<uint8_t*>(buffer->memory(1)), buffer->stride(1),
barrier));
break;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB: {
gfx::GpuMemoryBuffer* buffer2 =
frame_resources->plane_resources[1].gpu_memory_buffer.get();
// Using base::Unretained(video_frame) here is safe because |barrier|
// keeps refptr of |video_frame| until all copy tasks are done.
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(
&CopyRowsToNV12Buffer, row, rows_to_copy, coded_size.width(),
base::Unretained(video_frame.get()),
static_cast<uint8_t*>(buffer->memory(0)), buffer->stride(0),
static_cast<uint8_t*>(buffer2->memory(0)), buffer2->stride(0),
barrier));
break;
}
case GpuVideoAcceleratorFactories::OutputFormat::XR30:
case GpuVideoAcceleratorFactories::OutputFormat::XB30: {
const bool is_argb = output_format_ ==
GpuVideoAcceleratorFactories::OutputFormat::XR30;
// Using base::Unretained(video_frame) here is safe because |barrier|
// keeps refptr of |video_frame| until all copy tasks are done.
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&CopyRowsToRGB10Buffer, is_argb, row, rows_to_copy,
coded_size.width(),
base::Unretained(video_frame.get()),
static_cast<uint8_t*>(buffer->memory(0)),
buffer->stride(0), barrier));
break;
}
case GpuVideoAcceleratorFactories::OutputFormat::RGBA:
case GpuVideoAcceleratorFactories::OutputFormat::BGRA: {
const bool is_rgba = output_format_ ==
GpuVideoAcceleratorFactories::OutputFormat::RGBA;
// Using base::Unretained(video_frame) here is safe because |barrier|
// keeps refptr of |video_frame| until all copy tasks are done.
worker_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&CopyRowsToRGBABuffer, is_rgba, row, rows_to_copy,
coded_size.width(),
base::Unretained(video_frame.get()),
static_cast<uint8_t*>(buffer->memory(0)),
buffer->stride(0), barrier));
break;
}
case GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED:
NOTREACHED();
}
}
}
}
void GpuMemoryBufferVideoFramePool::PoolImpl::OnCopiesDoneOnMediaThread(
bool copy_failed,
scoped_refptr<VideoFrame> video_frame,
FrameResources* frame_resources) {
DCHECK(media_task_runner_->BelongsToCurrentThread());
if (copy_failed) {
// Drop the resources if there was an error with them.
auto it = std::find(resources_pool_.begin(), resources_pool_.end(),
frame_resources);
DCHECK(it != resources_pool_.end());
resources_pool_.erase(it);
DeleteFrameResources(gpu_factories_, frame_resources);
delete frame_resources;
CompleteCopyRequestAndMaybeStartNextCopy(std::move(video_frame));
return;
}
scoped_refptr<VideoFrame> frame =
BindAndCreateMailboxesHardwareFrameResources(
frame_resources, CodedSize(video_frame.get(), output_format_),
gfx::Rect(video_frame->visible_rect().size()),
video_frame->natural_size(), video_frame->ColorSpace(),
video_frame->timestamp(), video_frame->metadata().allow_overlay);
if (!frame) {
CompleteCopyRequestAndMaybeStartNextCopy(std::move(video_frame));
return;
}
bool new_allow_overlay = frame->metadata().allow_overlay;
bool new_read_lock_fences_enabled =
frame->metadata().read_lock_fences_enabled;
frame->metadata().MergeMetadataFrom(video_frame->metadata());
frame->metadata().allow_overlay = new_allow_overlay;
frame->metadata().read_lock_fences_enabled = new_read_lock_fences_enabled;
CompleteCopyRequestAndMaybeStartNextCopy(std::move(frame));
}
scoped_refptr<VideoFrame> GpuMemoryBufferVideoFramePool::PoolImpl::
BindAndCreateMailboxesHardwareFrameResources(
FrameResources* frame_resources,
const gfx::Size& coded_size,
const gfx::Rect& visible_rect,
const gfx::Size& natural_size,
const gfx::ColorSpace& color_space,
base::TimeDelta timestamp,
bool allow_i420_overlay) {
DCHECK(media_task_runner_->BelongsToCurrentThread());
gpu::SharedImageInterface* sii = gpu_factories_->SharedImageInterface();
if (!sii) {
frame_resources->MarkUnused(tick_clock_->NowTicks());
return nullptr;
}
gpu::MailboxHolder mailbox_holders[VideoFrame::kMaxPlanes];
// Set up the planes creating the mailboxes needed to refer to the textures.
for (size_t plane = 0; plane < NumSharedImages(output_format_); plane++) {
size_t gpu_memory_buffer_plane =
GpuMemoryBufferPlaneResourceIndexForPlane(output_format_, plane);
PlaneResource& plane_resource = frame_resources->plane_resources[plane];
gfx::GpuMemoryBuffer* gpu_memory_buffer =
frame_resources->plane_resources[gpu_memory_buffer_plane]
.gpu_memory_buffer.get();
const gfx::BufferFormat buffer_format =
GpuMemoryBufferFormat(output_format_, plane);
unsigned texture_target = gpu_factories_->ImageTextureTarget(buffer_format);
// Bind the texture and create or rebind the image.
if (gpu_memory_buffer && plane_resource.mailbox.IsZero()) {
uint32_t usage =
gpu::SHARED_IMAGE_USAGE_GLES2 | gpu::SHARED_IMAGE_USAGE_RASTER |
gpu::SHARED_IMAGE_USAGE_DISPLAY | gpu::SHARED_IMAGE_USAGE_SCANOUT;
plane_resource.mailbox = sii->CreateSharedImage(
gpu_memory_buffer, gpu_factories_->GpuMemoryBufferManager(),
GetSharedImageBufferPlane(output_format_, plane), color_space,
kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, usage);
} else if (!plane_resource.mailbox.IsZero()) {
sii->UpdateSharedImage(frame_resources->sync_token,
plane_resource.mailbox);
}
mailbox_holders[plane] = gpu::MailboxHolder(
plane_resource.mailbox, gpu::SyncToken(), texture_target);
}
// Insert a sync_token, this is needed to make sure that the textures the
// mailboxes refer to will be used only after all the previous commands posted
// in the SharedImageInterface have been processed.
gpu::SyncToken sync_token = sii->GenUnverifiedSyncToken();
for (size_t plane = 0; plane < NumSharedImages(output_format_); plane++)
mailbox_holders[plane].sync_token = sync_token;
VideoPixelFormat frame_format = VideoFormat(output_format_);
// Create the VideoFrame backed by native textures.
scoped_refptr<VideoFrame> frame = VideoFrame::WrapNativeTextures(
frame_format, mailbox_holders, VideoFrame::ReleaseMailboxCB(), coded_size,
visible_rect, natural_size, timestamp);
if (!frame) {
frame_resources->MarkUnused(tick_clock_->NowTicks());
MailboxHoldersReleased(frame_resources, sync_token);
return nullptr;
}
frame->SetReleaseMailboxCB(
base::BindOnce(&PoolImpl::MailboxHoldersReleased, this, frame_resources));
frame->set_color_space(color_space);
bool allow_overlay = false;
#if defined(OS_WIN)
// Windows direct composition path only supports dual GMB NV12 video overlays.
allow_overlay = (output_format_ ==
GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB);
#else
switch (output_format_) {
case GpuVideoAcceleratorFactories::OutputFormat::I420:
allow_overlay = allow_i420_overlay;
break;
case GpuVideoAcceleratorFactories::OutputFormat::P010:
case GpuVideoAcceleratorFactories::OutputFormat::NV12_SINGLE_GMB:
allow_overlay = true;
break;
case GpuVideoAcceleratorFactories::OutputFormat::NV12_DUAL_GMB:
// Only used on Windows where we can't use single NV12 textures.
break;
case GpuVideoAcceleratorFactories::OutputFormat::XR30:
case GpuVideoAcceleratorFactories::OutputFormat::XB30:
// TODO(mcasas): Enable this for ChromeOS https://crbug.com/776093.
allow_overlay = false;
#if defined(OS_MAC)
allow_overlay = IOSurfaceCanSetColorSpace(color_space);
#endif
// We've converted the YUV to RGB, fix the color space.
// TODO(hubbe): The libyuv YUV to RGB conversion may not have
// honored the color space conversion 100%. We should either fix
// libyuv or find a way for later passes to make up the difference.
frame->set_color_space(color_space.GetAsRGB());
break;
case GpuVideoAcceleratorFactories::OutputFormat::RGBA:
case GpuVideoAcceleratorFactories::OutputFormat::BGRA:
allow_overlay = true;
break;
case GpuVideoAcceleratorFactories::OutputFormat::UNDEFINED:
break;
}
#endif // OS_WIN
frame->metadata().allow_overlay = allow_overlay;
frame->metadata().read_lock_fences_enabled = true;
return frame;
}
// Destroy all the resources posting one task per FrameResources
// to the |media_task_runner_|.
GpuMemoryBufferVideoFramePool::PoolImpl::~PoolImpl() {
DCHECK(in_shutdown_);
}
void GpuMemoryBufferVideoFramePool::PoolImpl::Shutdown() {
DCHECK(media_task_runner_->BelongsToCurrentThread());
// Clients don't care about copies once shutdown has started, so abort them.
Abort();
// Delete all the resources on the media thread.
in_shutdown_ = true;
for (auto* frame_resources : resources_pool_) {
// Will be deleted later upon return to pool.
if (frame_resources->is_used())
continue;
media_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&PoolImpl::DeleteFrameResources, gpu_factories_,
base::Owned(frame_resources)));
}
resources_pool_.clear();
}
void GpuMemoryBufferVideoFramePool::PoolImpl::SetTickClockForTesting(
const base::TickClock* tick_clock) {
tick_clock_ = tick_clock;
}
// Tries to find the resources in the pool or create them.
// Incompatible resources will be dropped.
GpuMemoryBufferVideoFramePool::PoolImpl::FrameResources*
GpuMemoryBufferVideoFramePool::PoolImpl::GetOrCreateFrameResources(
const gfx::Size& size,
GpuVideoAcceleratorFactories::OutputFormat format,
gfx::BufferUsage usage) {
DCHECK(media_task_runner_->BelongsToCurrentThread());
auto it = resources_pool_.begin();
while (it != resources_pool_.end()) {
FrameResources* frame_resources = *it;
if (!frame_resources->is_used()) {
if (AreFrameResourcesCompatible(frame_resources, size, usage)) {
frame_resources->MarkUsed();
return frame_resources;
} else {
resources_pool_.erase(it++);
DeleteFrameResources(gpu_factories_, frame_resources);
delete frame_resources;
}
} else {
it++;
}
}
// Create the resources.
FrameResources* frame_resources = new FrameResources(size, usage);
resources_pool_.push_back(frame_resources);
for (size_t i = 0; i < NumGpuMemoryBuffers(output_format_); i++) {
PlaneResource& plane_resource = frame_resources->plane_resources[i];
const size_t width =
VideoFrame::Columns(i, VideoFormat(format), size.width());
const size_t height =
VideoFrame::Rows(i, VideoFormat(format), size.height());
plane_resource.size = gfx::Size(width, height);
const gfx::BufferFormat buffer_format = GpuMemoryBufferFormat(format, i);
plane_resource.gpu_memory_buffer = gpu_factories_->CreateGpuMemoryBuffer(
plane_resource.size, buffer_format, usage);
}
return frame_resources;
}
void GpuMemoryBufferVideoFramePool::PoolImpl::
CompleteCopyRequestAndMaybeStartNextCopy(
scoped_refptr<VideoFrame> video_frame) {
DCHECK(!frame_copy_requests_.empty());
std::move(frame_copy_requests_.front().frame_ready_cb)
.Run(std::move(video_frame));
frame_copy_requests_.pop_front();
if (!frame_copy_requests_.empty())
StartCopy();
}
// static
void GpuMemoryBufferVideoFramePool::PoolImpl::DeleteFrameResources(
GpuVideoAcceleratorFactories* const gpu_factories,
FrameResources* frame_resources) {
// TODO(dcastagna): As soon as the context lost is dealt with in media,
// make sure that we won't execute this callback (use a weak pointer to
// the old context).
gpu::SharedImageInterface* sii = gpu_factories->SharedImageInterface();
if (!sii)
return;
for (PlaneResource& plane_resource : frame_resources->plane_resources) {
if (!plane_resource.mailbox.IsZero()) {
sii->DestroySharedImage(frame_resources->sync_token,
plane_resource.mailbox);
}
}
}
// Called when a VideoFrame is no longer referenced.
// Put back the resources in the pool.
void GpuMemoryBufferVideoFramePool::PoolImpl::MailboxHoldersReleased(
FrameResources* frame_resources,
const gpu::SyncToken& release_sync_token) {
if (!media_task_runner_->BelongsToCurrentThread()) {
media_task_runner_->PostTask(
FROM_HERE, base::BindOnce(&PoolImpl::MailboxHoldersReleased, this,
frame_resources, release_sync_token));
return;
}
frame_resources->sync_token = release_sync_token;
if (in_shutdown_) {
DeleteFrameResources(gpu_factories_, frame_resources);
delete frame_resources;
return;
}
const base::TimeTicks now = tick_clock_->NowTicks();
frame_resources->MarkUnused(now);
auto it = resources_pool_.begin();
while (it != resources_pool_.end()) {
FrameResources* frame_resources = *it;
constexpr base::TimeDelta kStaleFrameLimit =
base::TimeDelta::FromSeconds(10);
if (!frame_resources->is_used() &&
now - frame_resources->last_use_time() > kStaleFrameLimit) {
resources_pool_.erase(it++);
DeleteFrameResources(gpu_factories_, frame_resources);
delete frame_resources;
} else {
it++;
}
}
}
GpuMemoryBufferVideoFramePool::GpuMemoryBufferVideoFramePool() = default;
GpuMemoryBufferVideoFramePool::GpuMemoryBufferVideoFramePool(
const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
const scoped_refptr<base::TaskRunner>& worker_task_runner,
GpuVideoAcceleratorFactories* gpu_factories)
: pool_impl_(
new PoolImpl(media_task_runner, worker_task_runner, gpu_factories)) {
base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
pool_impl_.get(), "GpuMemoryBufferVideoFramePool", media_task_runner);
}
GpuMemoryBufferVideoFramePool::~GpuMemoryBufferVideoFramePool() {
// May be nullptr in tests.
if (!pool_impl_)
return;
pool_impl_->Shutdown();
base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
pool_impl_.get());
}
void GpuMemoryBufferVideoFramePool::MaybeCreateHardwareFrame(
scoped_refptr<VideoFrame> video_frame,
FrameReadyCB frame_ready_cb) {
DCHECK(video_frame);
pool_impl_->CreateHardwareFrame(std::move(video_frame),
std::move(frame_ready_cb));
}
void GpuMemoryBufferVideoFramePool::Abort() {
pool_impl_->Abort();
}
void GpuMemoryBufferVideoFramePool::SetTickClockForTesting(
const base::TickClock* tick_clock) {
pool_impl_->SetTickClockForTesting(tick_clock);
}
} // namespace media
|
/*=====================================================================
======================================================================*/
/**
* @file
* @brief Joystick interface
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
* @author Andreas Romer <mavteam@student.ethz.ch>
*
*/
#include "JoystickInput.h"
#include <QDebug>
#include <limits.h>
#include "UAS.h"
#include "UASManager.h"
#include "QGC.h"
#include <QMutexLocker>
#include <QSettings>
#include <math.h>
#include <limits>
using namespace std;
/**
* The coordinate frame of the joystick axis is the aeronautical frame like shown on this image:
* @image html http://pixhawk.ethz.ch/wiki/_media/standards/body-frame.png Aeronautical frame
*/
JoystickInput::JoystickInput() :
sdlJoystickMin(-32768.0f),
sdlJoystickMax(32767.0f),
isEnabled(false),
done(false),
uas(NULL),
autopilotType(0),
systemType(0),
uasCanReverse(false),
rollAxis(-1),
pitchAxis(-1),
yawAxis(-1),
throttleAxis(-1),
joystickName(""),
joystickID(-1),
joystickNumButtons(0)
{
for (int i = 0; i < 10; i++) {
calibrationPositive[i] = sdlJoystickMax;
calibrationNegative[i] = sdlJoystickMin;
}
// Make sure we initialize with the correct UAS.
setActiveUAS(UASManager::instance()->getActiveUAS());
// Start this thread. This allows the Joystick Settings window to work correctly even w/o any UASes connected.
start();
}
JoystickInput::~JoystickInput()
{
storeGeneralSettings();
storeJoystickSettings();
done = true;
}
void JoystickInput::loadGeneralSettings()
{
// Load defaults from settings
QSettings settings;
// Deal with settings specific to the JoystickInput
settings.beginGroup("JOYSTICK_INPUT");
isEnabled = settings.value("ENABLED", false).toBool();
joystickName = settings.value("JOYSTICK_NAME", "").toString();
settings.endGroup();
}
/**
* @brief Restores settings for the current joystick from saved settings file.
* Assumes that both joystickName & joystickNumAxes are correct.
*/
void JoystickInput::loadJoystickSettings()
{
// Load defaults from settings
QSettings settings;
// Now for the current joystick
settings.beginGroup(joystickName);
rollAxis = (settings.value("ROLL_AXIS_MAPPING", -1).toInt());
pitchAxis = (settings.value("PITCH_AXIS_MAPPING", -1).toInt());
yawAxis = (settings.value("YAW_AXIS_MAPPING", -1).toInt());
throttleAxis = (settings.value("THROTTLE_AXIS_MAPPING", -1).toInt());
// Clear out and then restore the (AUTOPILOT, SYSTEM) mapping for joystick settings
joystickSettings.clear();
int autopilots = settings.beginReadArray("AUTOPILOTS");
for (int i = 0; i < autopilots; i++)
{
settings.setArrayIndex(i);
int autopilotType = settings.value("AUTOPILOT_TYPE", 0).toInt();
int systems = settings.beginReadArray("SYSTEMS");
for (int j = 0; j < systems; j++)
{
settings.setArrayIndex(j);
int systemType = settings.value("SYSTEM_TYPE", 0).toInt();
// Now that both the autopilot and system type are available, update some references.
QMap<int, bool>* joystickAxesInverted = &joystickSettings[autopilotType][systemType].axesInverted;
QMap<int, bool>* joystickAxesLimited = &joystickSettings[autopilotType][systemType].axesLimited;
QMap<int, int>* joystickButtonActions = &joystickSettings[autopilotType][systemType].buttonActions;
// Read back the joystickAxesInverted QList one element at a time.
int axesStored = settings.beginReadArray("AXES_INVERTED");
for (int k = 0; k < axesStored; k++)
{
settings.setArrayIndex(k);
int index = settings.value("INDEX", 0).toInt();
bool inverted = settings.value("INVERTED", false).toBool();
joystickAxesInverted->insert(index, inverted);
}
settings.endArray();
// Read back the joystickAxesLimited QList one element at a time.
axesStored = settings.beginReadArray("AXES_LIMITED");
for (int k = 0; k < axesStored; k++)
{
settings.setArrayIndex(k);
int index = settings.value("INDEX", 0).toInt();
bool limited = settings.value("LIMITED", false).toBool();
joystickAxesLimited->insert(index, limited);
}
settings.endArray();
// Read back the button->action mapping.
int buttonsStored = settings.beginReadArray("BUTTONS_ACTIONS");
for (int k = 0; k < buttonsStored; k++)
{
settings.setArrayIndex(k);
int index = settings.value("INDEX", 0).toInt();
int action = settings.value("ACTION", 0).toInt();
joystickButtonActions->insert(index, action);
}
settings.endArray();
}
settings.endArray();
}
settings.endArray();
settings.endGroup();
emit joystickSettingsChanged();
}
void JoystickInput::storeGeneralSettings() const
{
QSettings settings;
settings.beginGroup("JOYSTICK_INPUT");
settings.setValue("ENABLED", isEnabled);
settings.setValue("JOYSTICK_NAME", joystickName);
settings.endGroup();
}
void JoystickInput::storeJoystickSettings() const
{
// Store settings
QSettings settings;
settings.beginGroup(joystickName);
settings.setValue("ROLL_AXIS_MAPPING", rollAxis);
settings.setValue("PITCH_AXIS_MAPPING", pitchAxis);
settings.setValue("YAW_AXIS_MAPPING", yawAxis);
settings.setValue("THROTTLE_AXIS_MAPPING", throttleAxis);
settings.beginWriteArray("AUTOPILOTS");
QMapIterator<int, QMap<int, JoystickSettings> > i(joystickSettings);
int autopilotIndex = 0;
while (i.hasNext())
{
i.next();
settings.setArrayIndex(autopilotIndex++);
int autopilotType = i.key();
settings.setValue("AUTOPILOT_TYPE", autopilotType);
settings.beginWriteArray("SYSTEMS");
QMapIterator<int, JoystickSettings> j(i.value());
int systemIndex = 0;
while (j.hasNext())
{
j.next();
settings.setArrayIndex(systemIndex++);
int systemType = j.key();
settings.setValue("SYSTEM_TYPE", systemType);
// Now that both the autopilot and system type are available, update some references.
QMapIterator<int, bool> joystickAxesInverted(joystickSettings[autopilotType][systemType].axesInverted);
QMapIterator<int, bool> joystickAxesLimited(joystickSettings[autopilotType][systemType].axesLimited);
QMapIterator<int, int> joystickButtonActions(joystickSettings[autopilotType][systemType].buttonActions);
settings.beginWriteArray("AXES_INVERTED");
int k = 0;
while (joystickAxesInverted.hasNext())
{
joystickAxesInverted.next();
int inverted = joystickAxesInverted.value();
// Only save this axes' inversion status if it's not the default
if (inverted)
{
settings.setArrayIndex(k++);
int index = joystickAxesInverted.key();
settings.setValue("INDEX", index);
settings.setValue("INVERTED", inverted);
}
}
settings.endArray();
settings.beginWriteArray("AXES_LIMITED");
k = 0;
while (joystickAxesLimited.hasNext())
{
joystickAxesLimited.next();
int limited = joystickAxesLimited.value();
if (limited)
{
settings.setArrayIndex(k++);
int index = joystickAxesLimited.key();
settings.setValue("INDEX", index);
settings.setValue("LIMITED", limited);
}
}
settings.endArray();
settings.beginWriteArray("BUTTONS_ACTIONS");
k = 0;
while (joystickButtonActions.hasNext())
{
joystickButtonActions.next();
int action = joystickButtonActions.value();
if (action != -1)
{
settings.setArrayIndex(k++);
int index = joystickButtonActions.key();
settings.setValue("INDEX", index);
settings.setValue("ACTION", action);
}
}
settings.endArray();
}
settings.endArray(); // SYSTEMS
}
settings.endArray(); // AUTOPILOTS
settings.endGroup();
}
void JoystickInput::setActiveUAS(UASInterface* uas)
{
// Do nothing if the UAS hasn't changed.
if (uas == this->uas)
{
return;
}
// Only connect / disconnect is the UAS is of a controllable UAS class
UAS* tmp = 0;
if (this->uas)
{
tmp = dynamic_cast<UAS*>(this->uas);
if(tmp)
{
disconnect(this, SIGNAL(joystickChanged(float,float,float,float,qint8,qint8,quint16)), tmp, SLOT(setManualControlCommands(float,float,float,float,qint8,qint8,quint16)));
disconnect(this, SIGNAL(actionTriggered(int)), tmp, SLOT(triggerAction(int)));
}
uasCanReverse = false;
}
// Save any settings for the last UAS
if (joystickID > -1)
{
storeJoystickSettings();
}
this->uas = uas;
if (this->uas && (tmp = dynamic_cast<UAS*>(this->uas)))
{
connect(this, SIGNAL(joystickChanged(float,float,float,float,qint8,qint8,quint16)), tmp, SLOT(setManualControlCommands(float,float,float,float,qint8,qint8,quint16)));
connect(this, SIGNAL(actionTriggered(int)), tmp, SLOT(triggerAction(int)));
uasCanReverse = tmp->systemCanReverse();
// Update the joystick settings for a new UAS.
autopilotType = uas->getAutopilotType();
systemType = uas->getSystemType();
}
// Make sure any UI elements know we've updated the UAS. The UASManager signal is re-emitted here so that UI elements know to
// update their UAS-specific UI.
emit activeUASSet(uas);
// Load any joystick-specific settings now that the UAS has changed.
if (joystickID > -1)
{
loadJoystickSettings();
}
}
void JoystickInput::setEnabled(bool enabled)
{
this->isEnabled = enabled;
storeJoystickSettings();
}
void JoystickInput::init()
{
// Initialize SDL Joystick support and detect number of joysticks.
if (SDL_InitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE) < 0) {
printf("Couldn't initialize SimpleDirectMediaLayer: %s\n", SDL_GetError());
}
// Enumerate joysticks and select one
numJoysticks = SDL_NumJoysticks();
// If no joysticks are connected, there's nothing we can do, so just keep
// going back to sleep every second unless the program quits.
while (!numJoysticks && !done)
{
QGC::SLEEP::sleep(1);
}
if (done)
{
return;
}
// Now that we've detected a joystick, load in the joystick-agnostic settings.
loadGeneralSettings();
// Enumerate all found devices
qDebug() << QString("%1 Input devices found:").arg(numJoysticks);
int activeJoystick = 0;
for(int i=0; i < numJoysticks; i++ )
{
QString name = SDL_JoystickName(i);
qDebug() << QString("\t%1").arg(name);
// If we've matched this joystick to what was last opened, note it.
// Note: The way this is implemented the LAST joystick of a given name will be opened.
if (name == joystickName)
{
activeJoystick = i;
}
SDL_Joystick* x = SDL_JoystickOpen(i);
qDebug() << QString("\tNumber of Axes: %1").arg(QString::number(SDL_JoystickNumAxes(x)));
qDebug() << QString("\tNumber of Buttons: %1").arg(QString::number(SDL_JoystickNumButtons(x)));
SDL_JoystickClose(x);
}
// Set the active joystick based on name, if a joystick was found in the saved settings, otherwise
// default to the first one.
setActiveJoystick(activeJoystick);
// Now make sure we know what the current UAS is and track changes to it.
setActiveUAS(UASManager::instance()->getActiveUAS());
connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setActiveUAS(UASInterface*)));
}
void JoystickInput::shutdown()
{
done = true;
}
/**
* @brief Execute the Joystick process
* Note that the SDL procedure is polled. This is because connecting and disconnecting while the event checker is running
* fails as of SDL 1.2. It is therefore much easier to just poll for the joystick we want to sample.
*/
void JoystickInput::run()
{
init();
forever
{
if (done)
{
done = false;
exit();
return;
}
// Poll the joystick for new values.
SDL_JoystickUpdate();
// Emit all necessary signals for all axes.
for (int i = 0; i < joystickNumAxes; i++)
{
// First emit the uncalibrated values for each axis based on their ID.
// This is generally not used for controlling a vehicle, but a UI representation, so it being slightly off is fine.
// Here we map the joystick axis value into the initial range of [0:1].
float axisValue = SDL_JoystickGetAxis(joystick, i);
if (joystickSettings[autopilotType][systemType].axesInverted[i])
{
axisValue = (axisValue - calibrationNegative[i]) / (calibrationPositive[i] - calibrationNegative[i]);
}
else
{
axisValue = (axisValue - calibrationPositive[i]) / (calibrationNegative[i] - calibrationPositive[i]);
}
axisValue = 1.0f - axisValue;
// For non-throttle axes or if the UAS can reverse, go ahead and convert this into the range [-1:1].
if (uasCanReverse || throttleAxis != i)
{
axisValue = axisValue * 2.0f - 1.0f;
}
// Otherwise if this vehicle can only go forward, but the axis is limited to only the positive range,
// scale this so the negative values are ignored for this axis and it's clamped to [0:1].
else if (throttleAxis == i && joystickSettings[autopilotType][systemType].axesLimited.value(i))
{
axisValue = axisValue * 2.0f - 1.0f;
if (axisValue < 0.0f)
{
axisValue = 0.0f;
}
}
// Bound rounding errors
if (axisValue > 1.0f) axisValue = 1.0f;
if (axisValue < -1.0f) axisValue = -1.0f;
if (joystickAxes[i] != axisValue)
{
joystickAxes[i] = axisValue;
emit axisValueChanged(i, axisValue);
}
}
// Build up vectors describing the hat position
int hatPosition = SDL_JoystickGetHat(joystick, 0);
qint8 newYHat = 0;
if ((SDL_HAT_UP & hatPosition) > 0) newYHat = 1;
if ((SDL_HAT_DOWN & hatPosition) > 0) newYHat = -1;
qint8 newXHat = 0;
if ((SDL_HAT_LEFT & hatPosition) > 0) newXHat = -1;
if ((SDL_HAT_RIGHT & hatPosition) > 0) newXHat = 1;
if (newYHat != yHat || newXHat != xHat)
{
xHat = newXHat;
yHat = newYHat;
emit hatDirectionChanged(newXHat, newYHat);
}
// Emit signals for each button individually
for (int i = 0; i < joystickNumButtons; i++)
{
// If the button was down, but now it's up, trigger a buttonPressed event
quint16 lastButtonState = joystickButtons & (1 << i);
if (SDL_JoystickGetButton(joystick, i) && !lastButtonState)
{
emit buttonPressed(i);
joystickButtons |= 1 << i;
}
else if (!SDL_JoystickGetButton(joystick, i) && lastButtonState)
{
emit buttonReleased(i);
if (isEnabled && joystickSettings[autopilotType][systemType].buttonActions.contains(i))
{
emit actionTriggered(joystickSettings[autopilotType][systemType].buttonActions.value(i));
}
joystickButtons &= ~(1 << i);
}
}
// Now signal an update for all UI together.
if (isEnabled)
{
float roll = rollAxis > -1?joystickAxes[rollAxis]:numeric_limits<float>::quiet_NaN();
float pitch = pitchAxis > -1?joystickAxes[pitchAxis]:numeric_limits<float>::quiet_NaN();
float yaw = yawAxis > -1?joystickAxes[yawAxis]:numeric_limits<float>::quiet_NaN();
float throttle = throttleAxis > -1?joystickAxes[throttleAxis]:numeric_limits<float>::quiet_NaN();
emit joystickChanged(roll, pitch, yaw, throttle, xHat, yHat, joystickButtons);
}
// Sleep, update rate of joystick is approx. 50 Hz (1000 ms / 50 = 20 ms)
QGC::SLEEP::msleep(20);
}
}
void JoystickInput::setActiveJoystick(int id)
{
// If we already had a joystick, close that one before opening a new one.
if (joystick && SDL_JoystickOpened(joystickID))
{
storeJoystickSettings();
SDL_JoystickClose(joystick);
joystick = NULL;
joystickID = -1;
}
joystickID = id;
joystick = SDL_JoystickOpen(joystickID);
if (joystick && SDL_JoystickOpened(joystickID))
{
// Update joystick configuration.
joystickName = QString(SDL_JoystickName(joystickID));
joystickNumButtons = SDL_JoystickNumButtons(joystick);
joystickNumAxes = SDL_JoystickNumAxes(joystick);
// Restore saved settings for this joystick.
loadJoystickSettings();
// Update cached joystick axes values.
// Also emit any signals for currently-triggering events
joystickAxes.clear();
for (int i = 0; i < joystickNumAxes; i++)
{
joystickAxes.append(numeric_limits<float>::quiet_NaN());
}
// Update cached joystick button values.
// Emit signals for any button events.
joystickButtons = 0;
}
else
{
joystickNumButtons = 0;
joystickNumAxes = 0;
}
// Specify that a new joystick has been selected, so that any UI elements can update.
emit newJoystickSelected();
// And then trigger an update of this new UI.
emit joystickSettingsChanged();
}
void JoystickInput::setAxisMapping(int axis, JOYSTICK_INPUT_MAPPING newMapping)
{
switch (newMapping)
{
case JOYSTICK_INPUT_MAPPING_ROLL:
rollAxis = axis;
break;
case JOYSTICK_INPUT_MAPPING_PITCH:
pitchAxis = axis;
break;
case JOYSTICK_INPUT_MAPPING_YAW:
yawAxis = axis;
break;
case JOYSTICK_INPUT_MAPPING_THROTTLE:
throttleAxis = axis;
break;
case JOYSTICK_INPUT_MAPPING_NONE:
default:
if (rollAxis == axis)
{
rollAxis = -1;
}
if (pitchAxis == axis)
{
pitchAxis = -1;
}
if (yawAxis == axis)
{
yawAxis = -1;
}
if (throttleAxis == axis)
{
throttleAxis = -1;
joystickSettings[autopilotType][systemType].axesLimited.remove(axis);
}
break;
}
storeJoystickSettings();
}
void JoystickInput::setAxisInversion(int axis, bool inverted)
{
if (axis < joystickNumAxes)
{
joystickSettings[autopilotType][systemType].axesInverted[axis] = inverted;
storeJoystickSettings();
}
}
void JoystickInput::setAxisRangeLimit(int axis, bool limitRange)
{
if (axis < joystickNumAxes)
{
joystickSettings[autopilotType][systemType].axesLimited[axis] = limitRange;
storeJoystickSettings();
}
}
void JoystickInput::setButtonAction(int button, int action)
{
if (button < joystickNumButtons)
{
joystickSettings[autopilotType][systemType].buttonActions[button] = action;
storeJoystickSettings();
}
}
float JoystickInput::getCurrentValueForAxis(int axis) const
{
if (axis < joystickNumAxes)
{
return joystickAxes.at(axis);
}
return 0.0f;
}
bool JoystickInput::getInvertedForAxis(int axis) const
{
if (axis < joystickNumAxes)
{
return joystickSettings[autopilotType][systemType].axesInverted.value(axis);
}
return false;
}
bool JoystickInput::getRangeLimitForAxis(int axis) const
{
if (axis < joystickNumAxes)
{
return joystickSettings[autopilotType][systemType].axesLimited.value(axis);
}
return false;
}
int JoystickInput::getActionForButton(int button) const
{
if (button < joystickNumButtons && joystickSettings[autopilotType][systemType].buttonActions.contains(button))
{
return joystickSettings[autopilotType][systemType].buttonActions.value(button);
}
return -1;
}
|
#include "DXUT.h"
#include "SceneManager.h"
#include "LightManager.h"
#include "SDKmisc.h"
#include "DXUTCamera.h"
extern UINT8 g_nSkyStencilFlag;
extern ID3D11Device* g_pDevice;
extern CFirstPersonCamera g_Camera;
#pragma pack(push,1)
struct CB_VS_PER_OBJECT
{
D3DXMATRIX m_mWorldViewProjection;
D3DXMATRIX m_mWorld;
};
struct CB_PS_PER_OBJECT
{
D3DXVECTOR3 m_vEyePosition;
float m_fSpecExp;
float m_fSpecIntensity;
float pad[3];
};
struct CB_EMISSIVE
{
D3DXMATRIX WolrdViewProj;
D3DXVECTOR3 Color;
float pad;
};
#pragma pack(pop)
// Helpers
HRESULT CompileShader(PWCHAR strPath, D3D10_SHADER_MACRO* pMacros, char* strEntryPoint, char* strProfile, DWORD dwShaderFlags, ID3DBlob** ppVertexShaderBuffer);
CSceneManager::CSceneManager() : m_fSunRadius(25.0f),
m_pSceneVertexShaderCB(NULL), m_pScenePixelShaderCB(NULL), m_pSceneVertexShader(NULL), m_pSceneVSLayout(NULL),
m_pEmissiveCB(NULL), m_pEmissiveVertexShader(NULL), m_pEmissiveVSLayout(NULL), m_pEmissivePixelShader(NULL),
m_pSkyNoDepthStencilMaskState(NULL)
{
}
CSceneManager::~CSceneManager()
{
Deinit();
}
HRESULT CSceneManager::Init()
{
HRESULT hr;
// Load the models
V_RETURN(DXUTSetMediaSearchPath(L"..\\Media\\"));
V_RETURN( m_MeshOpaque.Create( g_pDevice, L"..\\Media\\OutdoorColumns\\outdoor_columns.sdkmesh" ) );
V_RETURN( m_MeshSphere.Create( g_pDevice, L"..\\Media\\ball.sdkmesh" ) );
// Create constant buffers
D3D11_BUFFER_DESC cbDesc;
ZeroMemory( &cbDesc, sizeof(cbDesc) );
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.ByteWidth = sizeof( CB_VS_PER_OBJECT );
V_RETURN( g_pDevice->CreateBuffer( &cbDesc, NULL, &m_pSceneVertexShaderCB ) );
DXUT_SetDebugName( m_pSceneVertexShaderCB, "Scene Vertex Shader CB" );
cbDesc.ByteWidth = sizeof( CB_PS_PER_OBJECT );
V_RETURN( g_pDevice->CreateBuffer( &cbDesc, NULL, &m_pScenePixelShaderCB ) );
DXUT_SetDebugName( m_pScenePixelShaderCB, "Scene Pixel Shader CB" );
cbDesc.ByteWidth = sizeof( CB_EMISSIVE );
V_RETURN( g_pDevice->CreateBuffer( &cbDesc, NULL, &m_pEmissiveCB ) );
DXUT_SetDebugName( m_pEmissiveCB, "Emissive CB" );
// Read the HLSL file
WCHAR str[MAX_PATH];
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"DeferredShading.hlsl" ) );
// Compile the shaders
DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
// Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
// Load the prepass light shader
ID3DBlob* pShaderBlob = NULL;
V_RETURN( CompileShader(str, NULL, "RenderSceneVS", "vs_5_0", dwShaderFlags, &pShaderBlob) );
V_RETURN( g_pDevice->CreateVertexShader( pShaderBlob->GetBufferPointer(),
pShaderBlob->GetBufferSize(), NULL, &m_pSceneVertexShader ) );
DXUT_SetDebugName( m_pSceneVertexShader, "Scene VS" );
// Create a layout for the object data
const D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
V_RETURN( g_pDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), pShaderBlob->GetBufferPointer(),
pShaderBlob->GetBufferSize(), &m_pSceneVSLayout ) );
DXUT_SetDebugName( m_pSceneVSLayout, "Scene Vertex Layout" );
SAFE_RELEASE( pShaderBlob );
V_RETURN( CompileShader(str, NULL, "RenderScenePS", "ps_5_0", dwShaderFlags, &pShaderBlob) );
V_RETURN( g_pDevice->CreatePixelShader( pShaderBlob->GetBufferPointer(),
pShaderBlob->GetBufferSize(), NULL, &m_pScenePixelShader ) );
DXUT_SetDebugName( m_pScenePixelShader, "Scene PS" );
SAFE_RELEASE( pShaderBlob );
// Emissive shaders
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Emissive.hlsl" ) );
V_RETURN(CompileShader(str, NULL, "RenderEmissiveVS", "vs_5_0", dwShaderFlags, &pShaderBlob));
V_RETURN( g_pDevice->CreateVertexShader( pShaderBlob->GetBufferPointer(),
pShaderBlob->GetBufferSize(), NULL, &m_pEmissiveVertexShader ) );
DXUT_SetDebugName( m_pEmissiveVertexShader, "RenderEmissiveVS" );
// Create a layout for the object data
const D3D11_INPUT_ELEMENT_DESC layoutEmissive[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
V_RETURN( g_pDevice->CreateInputLayout( layoutEmissive, ARRAYSIZE( layoutEmissive ), pShaderBlob->GetBufferPointer(),
pShaderBlob->GetBufferSize(), &m_pEmissiveVSLayout ) );
DXUT_SetDebugName( m_pEmissiveVSLayout, "Emissive Layout" );
SAFE_RELEASE( pShaderBlob );
V_RETURN(CompileShader(str, NULL, "RenderEmissivePS", "ps_5_0", dwShaderFlags, &pShaderBlob));
V_RETURN( g_pDevice->CreatePixelShader( pShaderBlob->GetBufferPointer(),
pShaderBlob->GetBufferSize(), NULL, &m_pEmissivePixelShader ) );
DXUT_SetDebugName( m_pEmissivePixelShader, "RenderEmissivePS" );
SAFE_RELEASE( pShaderBlob );
D3D11_DEPTH_STENCIL_DESC descDepth;
descDepth.DepthEnable = FALSE;
descDepth.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
descDepth.DepthFunc = D3D11_COMPARISON_LESS;
descDepth.StencilEnable = TRUE;
descDepth.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
descDepth.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
const D3D11_DEPTH_STENCILOP_DESC noSkyStencilOp = { D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_STENCIL_OP_KEEP, D3D11_COMPARISON_EQUAL };
descDepth.FrontFace = noSkyStencilOp;
descDepth.BackFace = noSkyStencilOp;
V_RETURN( g_pDevice->CreateDepthStencilState(&descDepth, &m_pSkyNoDepthStencilMaskState) );
DXUT_SetDebugName( m_pSkyNoDepthStencilMaskState, "Sky No Depth Stencil Mask DS" );
return hr;
}
void CSceneManager::Deinit()
{
m_MeshOpaque.Destroy();
m_MeshSphere.Destroy();
SAFE_RELEASE( m_pSceneVertexShaderCB );
SAFE_RELEASE( m_pScenePixelShaderCB );
SAFE_RELEASE( m_pSceneVertexShader );
SAFE_RELEASE( m_pSceneVSLayout );
SAFE_RELEASE( m_pScenePixelShader );
SAFE_RELEASE( m_pEmissiveCB );
SAFE_RELEASE( m_pEmissiveVertexShader );
SAFE_RELEASE( m_pEmissiveVSLayout );
SAFE_RELEASE( m_pEmissivePixelShader );
SAFE_RELEASE( m_pSkyNoDepthStencilMaskState );
}
void CSceneManager::RenderSceneToGBuffer(ID3D11DeviceContext* pd3dImmediateContext)
{
// Get the projection & view matrix from the camera class
D3DXMATRIX mWorld; // No need for a real world matrix
D3DXMatrixIdentity(&mWorld);
D3DXMATRIX mView = *g_Camera.GetViewMatrix();
D3DXMATRIX mProj = *g_Camera.GetProjMatrix();
D3DXMATRIX mWorldViewProjection = mView * mProj;
// Set the constant buffers
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE MappedResource;
V( pd3dImmediateContext->Map( m_pSceneVertexShaderCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
CB_VS_PER_OBJECT* pVSPerObject = ( CB_VS_PER_OBJECT* )MappedResource.pData;
D3DXMatrixTranspose( &pVSPerObject->m_mWorldViewProjection, &mWorldViewProjection );
D3DXMatrixTranspose( &pVSPerObject->m_mWorld, &mWorld);
pd3dImmediateContext->Unmap( m_pSceneVertexShaderCB, 0 );
pd3dImmediateContext->VSSetConstantBuffers( 0, 1, &m_pSceneVertexShaderCB );
V( pd3dImmediateContext->Map( m_pScenePixelShaderCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
CB_PS_PER_OBJECT* pPSPerObject = ( CB_PS_PER_OBJECT* )MappedResource.pData;
pPSPerObject->m_vEyePosition = *g_Camera.GetEyePt();
pPSPerObject->m_fSpecExp = 250.0f;
pPSPerObject->m_fSpecIntensity = 0.25f;
pd3dImmediateContext->Unmap( m_pScenePixelShaderCB, 0 );
pd3dImmediateContext->PSSetConstantBuffers( 0, 1, &m_pScenePixelShaderCB );
// Set the vertex layout
pd3dImmediateContext->IASetInputLayout( m_pSceneVSLayout );
// Set the shaders
pd3dImmediateContext->VSSetShader(m_pSceneVertexShader, NULL, 0);
pd3dImmediateContext->PSSetShader(m_pScenePixelShader, NULL, 0);
// Render the opaque mesh
m_MeshOpaque.Render(pd3dImmediateContext, 0, 1);
}
void CSceneManager::RenderSceneNoShaders(ID3D11DeviceContext* pd3dImmediateContext)
{
// Render the opaque mesh
m_MeshOpaque.Render(pd3dImmediateContext);
}
void CSceneManager::RenderSky(ID3D11DeviceContext* pd3dImmediateContext, const D3DXVECTOR3& vSunDir, const D3DXVECTOR3& vSunColor)
{
// Store the previous depth state
ID3D11DepthStencilState* pPrevDepthState;
UINT nPrevStencil;
pd3dImmediateContext->OMGetDepthStencilState(&pPrevDepthState, &nPrevStencil);
// Set the depth state for the sky rendering
pd3dImmediateContext->OMSetDepthStencilState(m_pSkyNoDepthStencilMaskState, g_nSkyStencilFlag);
D3DXMATRIX mLightWorldScale;
D3DXMatrixScaling(&mLightWorldScale, m_fSunRadius, m_fSunRadius, m_fSunRadius);
D3DXMATRIX mLightWorldTrans;
const D3DXVECTOR3& vEyePos = *g_Camera.GetEyePt();
D3DXMatrixTranslation(&mLightWorldTrans, vEyePos.x - 200.0f * vSunDir.x, -200.0f * vSunDir.y, vEyePos.z - 200.0f * vSunDir.z);
D3DXMATRIX mView = *g_Camera.GetViewMatrix();
D3DXMATRIX mProj = *g_Camera.GetProjMatrix();
D3DXMATRIX mWorldViewProjection = mLightWorldScale * mLightWorldTrans * mView * mProj;
HRESULT hr;
D3D11_MAPPED_SUBRESOURCE MappedResource;
V( pd3dImmediateContext->Map( m_pEmissiveCB, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource ) );
CB_EMISSIVE* pEmissiveCB = ( CB_EMISSIVE* )MappedResource.pData;
D3DXMatrixTranspose( &pEmissiveCB->WolrdViewProj, &mWorldViewProjection );
pEmissiveCB->Color = vSunColor;
pd3dImmediateContext->Unmap( m_pEmissiveCB, 0 );
ID3D11Buffer* arrConstBuffers[1] = { m_pEmissiveCB };
pd3dImmediateContext->VSSetConstantBuffers( 2, 1, arrConstBuffers );
pd3dImmediateContext->PSSetConstantBuffers( 2, 1, arrConstBuffers );
// Set the vertex layout
pd3dImmediateContext->IASetInputLayout( m_pEmissiveVSLayout );
// Set the shaders
pd3dImmediateContext->VSSetShader(m_pEmissiveVertexShader, NULL, 0);
pd3dImmediateContext->PSSetShader(m_pEmissivePixelShader, NULL, 0);
// This is an over kill for rendering the sun but it works
m_MeshSphere.Render(pd3dImmediateContext);
// Cleanup
pd3dImmediateContext->VSSetShader(NULL, NULL, 0);
pd3dImmediateContext->PSSetShader(NULL, NULL, 0);
// Restore the states
pd3dImmediateContext->OMSetDepthStencilState(pPrevDepthState, nPrevStencil);
SAFE_RELEASE( pPrevDepthState );
}
|
// 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 "chrome/browser/chromeos/drive/sync_client.h"
#include <vector>
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/test/test_timeouts.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/drive_cache.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/mock_drive_file_system.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/google_apis/test_util.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::StrictMock;
using ::testing::_;
namespace drive {
namespace {
// Action used to set mock expectations for GetFileByResourceId().
ACTION_P4(MockGetFileByResourceId, error, local_path, mime_type, file_type) {
arg2.Run(error, local_path, mime_type, file_type);
}
// Action used to set mock expectations for UpdateFileByResourceId().
ACTION_P(MockUpdateFileByResourceId, error) {
arg2.Run(error);
}
// Action used to set mock expectations for GetFileInfoByResourceId().
ACTION_P2(MockUpdateFileByResourceId, error, md5) {
scoped_ptr<DriveEntryProto> entry_proto(new DriveEntryProto);
entry_proto->mutable_file_specific_info()->set_file_md5(md5);
arg1.Run(error, base::FilePath(), entry_proto.Pass());
}
} // namespace
class SyncClientTest : public testing::Test {
public:
SyncClientTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_),
mock_file_system_(new StrictMock<MockDriveFileSystem>) {
}
virtual void SetUp() OVERRIDE {
// Create a temporary directory.
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
// Initialize the cache.
scoped_refptr<base::SequencedWorkerPool> pool =
content::BrowserThread::GetBlockingPool();
cache_.reset(new DriveCache(
temp_dir_.path(),
pool->GetSequencedTaskRunner(pool->GetSequenceToken()),
NULL /* free_disk_space_getter */));
bool success = false;
cache_->RequestInitialize(
google_apis::test_util::CreateCopyResultCallback(&success));
google_apis::test_util::RunBlockingPoolTask();
ASSERT_TRUE(success);
SetUpCache();
// Initialize the sync client.
EXPECT_CALL(*mock_file_system_, AddObserver(_)).Times(1);
EXPECT_CALL(*mock_file_system_, RemoveObserver(_)).Times(1);
sync_client_.reset(new SyncClient(mock_file_system_.get(), cache_.get()));
// Disable delaying so that DoSyncLoop() starts immediately.
sync_client_->set_delay_for_testing(base::TimeDelta::FromSeconds(0));
}
virtual void TearDown() OVERRIDE {
sync_client_.reset();
cache_.reset();
}
// Sets up cache for tests.
void SetUpCache() {
// Prepare a temp file.
base::FilePath temp_file;
EXPECT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(),
&temp_file));
const std::string content = "hello";
EXPECT_EQ(static_cast<int>(content.size()),
file_util::WriteFile(temp_file, content.data(), content.size()));
// Prepare 3 pinned-but-not-present files.
FileError error = FILE_ERROR_OK;
cache_->Pin("resource_id_not_fetched_foo", "",
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
cache_->Pin("resource_id_not_fetched_bar", "",
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
cache_->Pin("resource_id_not_fetched_baz", "",
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
// Prepare a pinned-and-fetched file.
const std::string resource_id_fetched = "resource_id_fetched";
const std::string md5_fetched = "md5";
cache_->Store(resource_id_fetched, md5_fetched, temp_file,
DriveCache::FILE_OPERATION_COPY,
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
cache_->Pin(resource_id_fetched, md5_fetched,
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
// Prepare a pinned-and-fetched-and-dirty file.
const std::string resource_id_dirty = "resource_id_dirty";
const std::string md5_dirty = ""; // Don't care.
cache_->Store(resource_id_dirty, md5_dirty, temp_file,
DriveCache::FILE_OPERATION_COPY,
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
cache_->Pin(resource_id_dirty, md5_dirty,
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
cache_->MarkDirty(
resource_id_dirty, md5_dirty,
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
cache_->CommitDirty(
resource_id_dirty, md5_dirty,
google_apis::test_util::CreateCopyResultCallback(&error));
google_apis::test_util::RunBlockingPoolTask();
EXPECT_EQ(FILE_ERROR_OK, error);
}
// Sets the expectation for MockDriveFileSystem::GetFileByResourceId(),
// that simulates successful retrieval of a file for the given resource ID.
void SetExpectationForGetFileByResourceId(const std::string& resource_id) {
EXPECT_CALL(*mock_file_system_,
GetFileByResourceId(resource_id, _, _, _))
.WillOnce(
MockGetFileByResourceId(
FILE_ERROR_OK,
base::FilePath::FromUTF8Unsafe("local_path_does_not_matter"),
std::string("mime_type_does_not_matter"),
REGULAR_FILE));
}
// Sets the expectation for MockDriveFileSystem::UpdateFileByResourceId(),
// that simulates successful uploading of a file for the given resource ID.
void SetExpectationForUpdateFileByResourceId(
const std::string& resource_id) {
EXPECT_CALL(*mock_file_system_,
UpdateFileByResourceId(resource_id, _, _))
.WillOnce(MockUpdateFileByResourceId(FILE_ERROR_OK));
}
// Sets the expectation for MockDriveFileSystem::GetFileInfoByResourceId(),
// that simulates successful retrieval of file info for the given resource
// ID.
//
// This is used for testing StartCheckingExistingPinnedFiles(), hence we
// are only interested in the MD5 value in DriveEntryProto.
void SetExpectationForGetFileInfoByResourceId(
const std::string& resource_id,
const std::string& new_md5) {
EXPECT_CALL(*mock_file_system_,
GetEntryInfoByResourceId(resource_id, _))
.WillOnce(MockUpdateFileByResourceId(
FILE_ERROR_OK,
new_md5));
}
// Returns the resource IDs in the queue to be fetched.
std::vector<std::string> GetResourceIdsToBeFetched() {
return sync_client_->GetResourceIdsForTesting(SyncClient::FETCH);
}
// Returns the resource IDs in the queue to be uploaded.
std::vector<std::string> GetResourceIdsToBeUploaded() {
return sync_client_->GetResourceIdsForTesting(SyncClient::UPLOAD);
}
// Adds a resource ID of a file to fetch.
void AddResourceIdToFetch(const std::string& resource_id) {
sync_client_->AddResourceIdForTesting(SyncClient::FETCH, resource_id);
}
// Adds a resource ID of a file to upload.
void AddResourceIdToUpload(const std::string& resource_id) {
sync_client_->AddResourceIdForTesting(SyncClient::UPLOAD, resource_id);
}
protected:
MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
base::ScopedTempDir temp_dir_;
scoped_ptr<StrictMock<MockDriveFileSystem> > mock_file_system_;
scoped_ptr<DriveCache, test_util::DestroyHelperForTests> cache_;
scoped_ptr<SyncClient> sync_client_;
};
TEST_F(SyncClientTest, StartInitialScan) {
// Start processing the files in the backlog. This will collect the
// resource IDs of these files.
sync_client_->StartProcessingBacklog();
// Check the contents of the queue for fetching.
SetExpectationForGetFileByResourceId("resource_id_not_fetched_bar");
SetExpectationForGetFileByResourceId("resource_id_not_fetched_baz");
SetExpectationForGetFileByResourceId("resource_id_not_fetched_foo");
// Check the contents of the queue for uploading.
SetExpectationForUpdateFileByResourceId("resource_id_dirty");
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(SyncClientTest, OnCachePinned) {
// This file will be fetched by GetFileByResourceId() as OnCachePinned()
// will kick off the sync loop.
SetExpectationForGetFileByResourceId("resource_id_not_fetched_foo");
sync_client_->OnCachePinned("resource_id_not_fetched_foo", "md5");
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(SyncClientTest, OnCacheUnpinned) {
AddResourceIdToFetch("resource_id_not_fetched_foo");
AddResourceIdToFetch("resource_id_not_fetched_bar");
AddResourceIdToFetch("resource_id_not_fetched_baz");
ASSERT_EQ(3U, GetResourceIdsToBeFetched().size());
sync_client_->OnCacheUnpinned("resource_id_not_fetched_foo", "md5");
sync_client_->OnCacheUnpinned("resource_id_not_fetched_baz", "md5");
// Only resource_id_not_fetched_foo should be fetched.
SetExpectationForGetFileByResourceId("resource_id_not_fetched_bar");
google_apis::test_util::RunBlockingPoolTask();
}
TEST_F(SyncClientTest, Deduplication) {
AddResourceIdToFetch("resource_id_not_fetched_foo");
// Set the delay so that DoSyncLoop() is delayed.
sync_client_->set_delay_for_testing(TestTimeouts::action_max_timeout());
// Raise OnCachePinned() event. This shouldn't result in adding the second
// task, as tasks are de-duplicated.
sync_client_->OnCachePinned("resource_id_not_fetched_foo", "md5");
ASSERT_EQ(1U, GetResourceIdsToBeFetched().size());
}
TEST_F(SyncClientTest, ExistingPinnedFiles) {
// Set the expectation so that the MockDriveFileSystem returns "new_md5"
// for "resource_id_fetched". This simulates that the file is updated on
// the server side, and the new MD5 is obtained from the server (i.e. the
// local cache file is stale).
SetExpectationForGetFileInfoByResourceId("resource_id_fetched",
"new_md5");
// Set the expectation so that the MockDriveFileSystem returns "some_md5"
// for "resource_id_dirty". The MD5 on the server is always different from
// the MD5 of a dirty file, which is set to "local". We should not collect
// this by StartCheckingExistingPinnedFiles().
SetExpectationForGetFileInfoByResourceId("resource_id_dirty",
"some_md5");
// Start checking the existing pinned files. This will collect the resource
// IDs of pinned files, with stale local cache files.
sync_client_->StartCheckingExistingPinnedFiles();
SetExpectationForGetFileByResourceId("resource_id_fetched");
google_apis::test_util::RunBlockingPoolTask();
}
} // namespace drive
|
#ifndef _TENSOR_UTILS_HPP
#define _TENSOR_UTILS_HPP
#include <vector>
#include "product.hpp"
#include "sum.hpp"
#include "Vector.hpp"
#ifndef MAX_TENSOR_DIMENSION
#define MAX_TENSOR_DIMENSION 12
#endif
// Tuple types:
typedef unsigned long* __restrict const tup_t;
typedef const unsigned long* __restrict const const_tup_t;
inline void print_tuple(const_tup_t tup, unsigned char dim) {
for (unsigned char i=0; i<dim; ++i)
std::cout << tup[i] << " ";
std::cout << std::endl;
}
inline unsigned long flat_length(const_tup_t shape, unsigned char dimension) {
if (dimension > 0)
return product(shape, dimension);
return 0;
}
inline unsigned long flat_length(const Vector<unsigned long> & shape) {
return flat_length(static_cast<const unsigned long*const>(shape), shape.size());
}
inline void advance_tuple(unsigned long* __restrict tup, const_tup_t shape, unsigned char dimension) {
++tup[dimension-1];
for (unsigned char k=dimension-1; k>=1; --k)
if ( tup[k] >= shape[k] ) {
++tup[k-1];
tup[k] = 0;
}
else
// No more carry operations:
return;
}
inline unsigned long tuple_to_index(const_tup_t tup, const_tup_t shape, unsigned char dimension) {
unsigned long res = 0;
unsigned char k;
for (k=1; k<dimension; ++k) {
res += tup[k-1];
res *= shape[k];
}
res += tup[k-1];
return res;
}
template <unsigned int DIMENSION>
inline unsigned long tuple_to_index_fixed_dimension(const_tup_t tup, const_tup_t shape) {
unsigned long res = 0;
unsigned int k;
for (k=0; k<DIMENSION-1; ++k) {
res += tup[k];
res *= shape[k+1]; }
res += tup[k];
return res;
}
// Note: This is not very efficient, but is useful for debugging.
inline unsigned long* index_to_tuple(unsigned long index, const unsigned long* __restrict const shape, unsigned int dimension) {
unsigned long* __restrict result = aligned_calloc<unsigned long>(dimension);
for (int i=dimension-1; index>0 && i>=0; --i) {
unsigned long next_axis = shape[i];
// Note: There may be a speedup lurking in here where shared work
// between index / next_axis and index % next_axis can be reused;
// however, this code will only be used for bounds checking, so
// speed is not very important.
unsigned long next_value = index % next_axis;
result[i] = next_value;
index /= next_axis;
}
return result;
}
// No assertions when there are no duplicate indices and all are in
// range. Could also be implemented a set in O(n log(n)), but this
// version is in O(n).
inline void verify_subpermutation(const Vector<unsigned char> & permutation, unsigned char dim) {
std::vector<bool> indices(dim, false);
for (unsigned char i=0; i<permutation.size(); ++i) {
// All values must be in 0, 1, ... n-1, where n is the number of
// dimensions allowed:
assert(permutation[i] < dim);
indices[ permutation[i] ] = true;
}
unsigned char cardinality = 0;
for (unsigned char i=0; i<permutation.size(); ++i)
cardinality += indices[ permutation[i] ];
// All indices must be included exactly once (therefore, there must
// be no duplicates). Given all indices must also be in range (by
// the assertion above), this means it is a valid subpermutation.
assert(cardinality == permutation.size());
}
inline void verify_permutation(const Vector<unsigned char> & permutation) {
verify_subpermutation(permutation, permutation.size());
}
#endif
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_malloc_65b.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-65b.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_malloc_65
{
#ifndef OMITBAD
void bad_sink(twoints * data)
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2B_sink(twoints * data)
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2G_sink(twoints * data)
{
/* FIX: Free memory using free() */
free(data);
}
#endif /* OMITGOOD */
} // close namespace
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tsf/v20180326/model/UpdateRepositoryRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tsf::V20180326::Model;
using namespace std;
UpdateRepositoryRequest::UpdateRepositoryRequest() :
m_repositoryIdHasBeenSet(false),
m_repositoryDescHasBeenSet(false)
{
}
string UpdateRepositoryRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_repositoryIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RepositoryId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_repositoryId.c_str(), allocator).Move(), allocator);
}
if (m_repositoryDescHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RepositoryDesc";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_repositoryDesc.c_str(), allocator).Move(), allocator);
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string UpdateRepositoryRequest::GetRepositoryId() const
{
return m_repositoryId;
}
void UpdateRepositoryRequest::SetRepositoryId(const string& _repositoryId)
{
m_repositoryId = _repositoryId;
m_repositoryIdHasBeenSet = true;
}
bool UpdateRepositoryRequest::RepositoryIdHasBeenSet() const
{
return m_repositoryIdHasBeenSet;
}
string UpdateRepositoryRequest::GetRepositoryDesc() const
{
return m_repositoryDesc;
}
void UpdateRepositoryRequest::SetRepositoryDesc(const string& _repositoryDesc)
{
m_repositoryDesc = _repositoryDesc;
m_repositoryDescHasBeenSet = true;
}
bool UpdateRepositoryRequest::RepositoryDescHasBeenSet() const
{
return m_repositoryDescHasBeenSet;
}
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2016 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <blocmatrix/basics/StringUtilities.h>
#include <blocmatrix/protocol/Feature.h>
#include <blocmatrix/protocol/jss.h>
#include <test/jtx.h>
namespace blocmatrix {
class LedgerData_test : public beast::unit_test::suite
{
public:
// test helper
static bool checkArraySize(Json::Value const& val, unsigned int size)
{
return val.isArray() &&
val.size() == size;
}
// test helper
static bool checkMarker(Json::Value const& val)
{
return val.isMember(jss::marker) &&
val[jss::marker].isString() &&
val[jss::marker].asString().size() > 0;
}
void testCurrentLedgerToLimits(bool asAdmin)
{
using namespace test::jtx;
Env env {*this, asAdmin ? envconfig() : envconfig(no_admin)};
Account const gw {"gateway"};
auto const USD = gw["USD"];
env.fund(BMC(100000), gw);
int const max_limit = 256; //would be 2048 for binary requests, no need to test that here
for (auto i = 0; i < max_limit + 10; i++)
{
Account const bob {std::string("bob") + std::to_string(i)};
env.fund(BMC(1000), bob);
}
env.close();
// with no limit specified, we get the max_limit if the total number of
// accounts is greater than max, which it is here
Json::Value jvParams;
jvParams[jss::ledger_index] = "current";
jvParams[jss::binary] = false;
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT(
jrr[jss::ledger_current_index].isIntegral() &&
jrr[jss::ledger_current_index].asInt() > 0 );
BEAST_EXPECT( checkMarker(jrr) );
BEAST_EXPECT( checkArraySize(jrr[jss::state], max_limit) );
// check limits values around the max_limit (+/- 1)
for (auto delta = -1; delta <= 1; delta++)
{
jvParams[jss::limit] = max_limit + delta;
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT(
checkArraySize( jrr[jss::state],
(delta > 0 && !asAdmin) ? max_limit : max_limit + delta ));
}
}
void testCurrentLedgerBinary()
{
using namespace test::jtx;
Env env { *this, envconfig(no_admin) };
Account const gw { "gateway" };
auto const USD = gw["USD"];
env.fund(BMC(100000), gw);
int const num_accounts = 10;
for (auto i = 0; i < num_accounts; i++)
{
Account const bob { std::string("bob") + std::to_string(i) };
env.fund(BMC(1000), bob);
}
env.close();
// with no limit specified, we should get all of our fund entries
// plus three more related to the gateway setup
Json::Value jvParams;
jvParams[jss::ledger_index] = "current";
jvParams[jss::binary] = true;
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT(
jrr[jss::ledger_current_index].isIntegral() &&
jrr[jss::ledger_current_index].asInt() > 0);
BEAST_EXPECT( ! jrr.isMember(jss::marker) );
BEAST_EXPECT( checkArraySize(jrr[jss::state], num_accounts + 3) );
}
void testBadInput()
{
using namespace test::jtx;
Env env { *this };
Account const gw { "gateway" };
auto const USD = gw["USD"];
Account const bob { "bob" };
env.fund(BMC(10000), gw, bob);
env.trust(USD(1000), bob);
{
// bad limit
Json::Value jvParams;
jvParams[jss::limit] = "0"; // NOT an integer
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT(jrr[jss::error] == "invalidParams");
BEAST_EXPECT(jrr[jss::status] == "error");
BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'limit', not integer.");
}
{
// invalid marker
Json::Value jvParams;
jvParams[jss::marker] = "NOT_A_MARKER";
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT(jrr[jss::error] == "invalidParams");
BEAST_EXPECT(jrr[jss::status] == "error");
BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'marker', not valid.");
}
{
// invalid marker - not a string
Json::Value jvParams;
jvParams[jss::marker] = 1;
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT(jrr[jss::error] == "invalidParams");
BEAST_EXPECT(jrr[jss::status] == "error");
BEAST_EXPECT(jrr[jss::error_message] == "Invalid field 'marker', not valid.");
}
{
// ask for a bad ledger index
Json::Value jvParams;
jvParams[jss::ledger_index] = 10u;
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT(jrr[jss::error] == "lgrNotFound");
BEAST_EXPECT(jrr[jss::status] == "error");
BEAST_EXPECT(jrr[jss::error_message] == "ledgerNotFound");
}
}
void testMarkerFollow()
{
using namespace test::jtx;
Env env { *this, envconfig(no_admin) };
Account const gw { "gateway" };
auto const USD = gw["USD"];
env.fund(BMC(100000), gw);
int const num_accounts = 20;
for (auto i = 0; i < num_accounts; i++)
{
Account const bob { std::string("bob") + std::to_string(i) };
env.fund(BMC(1000), bob);
}
env.close();
// with no limit specified, we should get all of our fund entries
// plus three more related to the gateway setup
Json::Value jvParams;
jvParams[jss::ledger_index] = "current";
jvParams[jss::binary] = false;
auto jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
auto const total_count = jrr[jss::state].size();
// now make request with a limit and loop until we get all
jvParams[jss::limit] = 5;
jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT( checkMarker(jrr) );
auto running_total = jrr[jss::state].size();
while ( jrr.isMember(jss::marker) )
{
jvParams[jss::marker] = jrr[jss::marker];
jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
running_total += jrr[jss::state].size();
}
BEAST_EXPECT( running_total == total_count );
}
void testLedgerHeader()
{
using namespace test::jtx;
Env env { *this };
env.fund(BMC(100000), "alice");
env.close();
// Ledger header should be present in the first query
{
// Closed ledger with non binary form
Json::Value jvParams;
jvParams[jss::ledger_index] = "closed";
auto jrr = env.rpc("json", "ledger_data",
boost::lexical_cast<std::string>(jvParams))[jss::result];
if (BEAST_EXPECT(jrr.isMember(jss::ledger)))
BEAST_EXPECT(jrr[jss::ledger][jss::ledger_hash] ==
to_string(env.closed()->info().hash));
}
{
// Closed ledger with binary form
Json::Value jvParams;
jvParams[jss::ledger_index] = "closed";
jvParams[jss::binary] = true;
auto jrr = env.rpc("json", "ledger_data",
boost::lexical_cast<std::string>(jvParams))[jss::result];
if (BEAST_EXPECT(jrr.isMember(jss::ledger)))
{
auto data = strUnHex(
jrr[jss::ledger][jss::ledger_data].asString());
if (BEAST_EXPECT(data.second))
{
Serializer s(data.first.data(), data.first.size());
std::uint32_t seq = 0;
BEAST_EXPECT(s.getInteger<std::uint32_t>(seq, 0));
BEAST_EXPECT(seq == 3);
}
}
}
{
// Current ledger with binary form
Json::Value jvParams;
jvParams[jss::binary] = true;
auto jrr = env.rpc("json", "ledger_data",
boost::lexical_cast<std::string>(jvParams))[jss::result];
BEAST_EXPECT(jrr.isMember(jss::ledger));
BEAST_EXPECT(! jrr[jss::ledger].isMember(jss::ledger_data));
}
}
void testLedgerType()
{
// Put a bunch of different LedgerEntryTypes into a ledger
using namespace test::jtx;
using namespace std::chrono;
Env env{*this,
envconfig(validator, ""),
supported_amendments().set(featureTickets)};
Account const gw { "gateway" };
auto const USD = gw["USD"];
env.fund(BMC(100000), gw);
int const num_accounts = 10;
for (auto i = 0; i < num_accounts; i++)
{
Account const bob { std::string("bob") + std::to_string(i) };
env.fund(BMC(1000), bob);
}
env(offer(Account{"bob0"}, USD(100), BMC(100)));
env.trust(Account{"bob2"}["USD"](100), Account{"bob3"});
auto majorities = getMajorityAmendments(*env.closed());
for (int i = 0; i <= 256; ++i)
{
env.close();
majorities = getMajorityAmendments(*env.closed());
if (!majorities.empty())
break;
}
env(signers(Account{"bob0"}, 1,
{{Account{"bob1"}, 1}, {Account{"bob2"}, 1}}));
env(ticket::create(env.master));
{
Json::Value jv;
jv[jss::TransactionType] = jss::EscrowCreate;
jv[jss::Flags] = tfUniversal;
jv[jss::Account] = Account{"bob5"}.human();
jv[jss::Destination] = Account{"bob6"}.human();
jv[jss::Amount] = BMC(50).value().getJson(JsonOptions::none);
jv[sfFinishAfter.fieldName] =
NetClock::time_point{env.now() + 10s}
.time_since_epoch().count();
env(jv);
}
{
Json::Value jv;
jv[jss::TransactionType] = jss::PaymentChannelCreate;
jv[jss::Flags] = tfUniversal;
jv[jss::Account] = Account{"bob6"}.human ();
jv[jss::Destination] = Account{"bob7"}.human ();
jv[jss::Amount] = BMC(100).value().getJson (JsonOptions::none);
jv[jss::SettleDelay] = NetClock::duration{10s}.count();
jv[sfPublicKey.fieldName] = strHex (Account{"bob6"}.pk().slice ());
jv[sfCancelAfter.fieldName] =
NetClock::time_point{env.now() + 300s}
.time_since_epoch().count();
env(jv);
}
{
Json::Value jv;
jv[sfAccount.jsonName] = Account{"bob6"}.human ();
jv[sfSendMax.jsonName] = "100000000";
jv[sfDestination.jsonName] = Account{"bob7"}.human ();
jv[sfTransactionType.jsonName] = jss::CheckCreate;
jv[sfFlags.jsonName] = tfUniversal;
env(jv);
}
// bob9 DepositPreauths bob4 and bob8.
env (deposit::auth (Account {"bob9"}, Account {"bob4"}));
env (deposit::auth (Account {"bob9"}, Account {"bob8"}));
env.close();
// Now fetch each type
auto makeRequest = [&env](Json::StaticString t)
{
Json::Value jvParams;
jvParams[jss::ledger_index] = "current";
jvParams[jss::type] = t;
return env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
};
{ // jvParams[jss::type] = "account";
auto const jrr = makeRequest(jss::account);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 12) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::AccountRoot );
}
{ // jvParams[jss::type] = "amendments";
auto const jrr = makeRequest(jss::amendments);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::Amendments );
}
{ // jvParams[jss::type] = "check";
auto const jrr = makeRequest(jss::check);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::Check );
}
{ // jvParams[jss::type] = "directory";
auto const jrr = makeRequest(jss::directory);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 9) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::DirectoryNode );
}
{ // jvParams[jss::type] = "fee";
auto const jrr = makeRequest(jss::fee);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::FeeSettings );
}
{ // jvParams[jss::type] = "hashes";
auto const jrr = makeRequest(jss::hashes);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 2) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::LedgerHashes );
}
{ // jvParams[jss::type] = "offer";
auto const jrr = makeRequest(jss::offer);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::Offer );
}
{ // jvParams[jss::type] = "signer_list";
auto const jrr = makeRequest(jss::signer_list);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::SignerList );
}
{ // jvParams[jss::type] = "state";
auto const jrr = makeRequest(jss::state);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::BlocmatrixState );
}
{ // jvParams[jss::type] = "ticket";
auto const jrr = makeRequest(jss::ticket);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::Ticket );
}
{ // jvParams[jss::type] = "escrow";
auto const jrr = makeRequest(jss::escrow);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::Escrow );
}
{ // jvParams[jss::type] = "payment_channel";
auto const jrr = makeRequest(jss::payment_channel);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 1) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::PayChannel );
}
{ // jvParams[jss::type] = "deposit_preauth";
auto const jrr = makeRequest(jss::deposit_preauth);
BEAST_EXPECT( checkArraySize(jrr[jss::state], 2) );
for (auto const& j : jrr[jss::state])
BEAST_EXPECT( j["LedgerEntryType"] == jss::DepositPreauth );
}
{ // jvParams[jss::type] = "misspelling";
Json::Value jvParams;
jvParams[jss::ledger_index] = "current";
jvParams[jss::type] = "misspelling";
auto const jrr = env.rpc ( "json", "ledger_data",
boost::lexical_cast<std::string>(jvParams)) [jss::result];
BEAST_EXPECT( jrr.isMember("error") );
BEAST_EXPECT( jrr["error"] == "invalidParams" );
BEAST_EXPECT( jrr["error_message"] == "Invalid field 'type'." );
}
}
void run() override
{
testCurrentLedgerToLimits(true);
testCurrentLedgerToLimits(false);
testCurrentLedgerBinary();
testBadInput();
testMarkerFollow();
testLedgerHeader();
testLedgerType();
}
};
BEAST_DEFINE_TESTSUITE_PRIO(LedgerData,app,blocmatrix,1);
}
|
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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 "driver/d3d11/d3d11_device.h"
#include "driver/d3d11/d3d11_context.h"
#include "driver/d3d11/d3d11_resources.h"
bool WrappedID3D11Device::Serialise_CreateBuffer(const D3D11_BUFFER_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Buffer **ppBuffer)
{
D3D11_SUBRESOURCE_DATA fakeData;
RDCEraseEl(fakeData);
SERIALISE_ELEMENT_PTR(D3D11_BUFFER_DESC, Descriptor, pDesc);
if(pInitialData == NULL && m_State >= WRITING)
{
fakeData.pSysMem = new char[Descriptor.ByteWidth];
fakeData.SysMemPitch = fakeData.SysMemSlicePitch = Descriptor.ByteWidth;
memset((void *)fakeData.pSysMem, 0xfe, Descriptor.ByteWidth);
pInitialData = &fakeData;
}
// this is a bit of a hack, but to maintain backwards compatibility we have a
// separate function here that aligns the next serialised buffer to a 32-byte
// boundary in memory while writing (just skips the padding on read).
if(m_State >= WRITING || GetLogVersion() >= 0x000007)
m_pSerialiser->AlignNextBuffer(32);
// work around an nvidia driver bug, if a buffer is created as IMMUTABLE then it
// can't be CopySubresourceRegion'd with a box offset, the data that's read is
// wrong.
if(m_State < WRITING && Descriptor.Usage == D3D11_USAGE_IMMUTABLE)
{
Descriptor.Usage = D3D11_USAGE_DEFAULT;
// paranoid - I don't know what requirements might change, so set some sane default
if(Descriptor.BindFlags == 0)
Descriptor.BindFlags = D3D11_BIND_VERTEX_BUFFER;
}
SERIALISE_ELEMENT_BUF(byte *, InitialData, pInitialData->pSysMem, Descriptor.ByteWidth);
uint64_t offs = m_pSerialiser->GetOffset() - Descriptor.ByteWidth;
RDCASSERT((offs % 16) == 0);
SERIALISE_ELEMENT(uint32_t, MemPitch, pInitialData->SysMemPitch);
SERIALISE_ELEMENT(uint32_t, MemSlicePitch, pInitialData->SysMemSlicePitch);
SERIALISE_ELEMENT(ResourceId, pBuffer, GetIDForResource(*ppBuffer));
if(m_State >= WRITING)
{
RDCASSERT(GetResourceManager()->GetResourceRecord(pBuffer) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(pBuffer);
record->SetDataOffset(offs);
record->DataInSerialiser = true;
record->Length = Descriptor.ByteWidth;
}
if(m_State == READING)
{
ID3D11Buffer *ret;
HRESULT hr = S_OK;
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = InitialData;
data.SysMemPitch = MemPitch;
data.SysMemSlicePitch = MemSlicePitch;
hr = m_pDevice->CreateBuffer(&Descriptor, &data, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Buffer(ret, Descriptor.ByteWidth, this);
GetResourceManager()->AddLiveResource(pBuffer, ret);
}
if(Descriptor.Usage != D3D11_USAGE_IMMUTABLE)
{
ID3D11Buffer *stage = NULL;
D3D11_BUFFER_DESC desc;
desc.ByteWidth = Descriptor.ByteWidth;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
// We don't need to bind this, but IMMUTABLE requires at least one
// BindFlags.
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = 0;
desc.Usage = D3D11_USAGE_IMMUTABLE;
data.SysMemPitch = Descriptor.ByteWidth;
data.SysMemSlicePitch = Descriptor.ByteWidth;
hr = m_pDevice->CreateBuffer(&desc, &data, &stage);
if(FAILED(hr) || stage == NULL)
{
RDCERR("Failed to create staging buffer for buffer initial contents %08x", hr);
}
else
{
m_ResourceManager->SetInitialContents(
pBuffer, D3D11ResourceManager::InitialContentData(stage, eInitialContents_Copy, NULL));
}
}
SAFE_DELETE_ARRAY(InitialData);
}
char *arr = (char *)fakeData.pSysMem;
SAFE_DELETE_ARRAY(arr);
return true;
}
HRESULT WrappedID3D11Device::CreateBuffer(const D3D11_BUFFER_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Buffer **ppBuffer)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppBuffer == NULL)
return m_pDevice->CreateBuffer(pDesc, pInitialData, NULL);
ID3D11Buffer *real = NULL;
ID3D11Buffer *wrapped = NULL;
HRESULT ret = m_pDevice->CreateBuffer(pDesc, pInitialData, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Buffer(real, pDesc ? pDesc->ByteWidth : 0, this);
if(m_State >= WRITING)
{
Chunk *chunk = NULL;
{
SCOPED_SERIALISE_CONTEXT(CREATE_BUFFER);
Serialise_CreateBuffer(pDesc, pInitialData, &wrapped);
chunk = scope.Get();
}
D3D11ResourceRecord *record =
GetResourceManager()->GetResourceRecord(GetIDForResource(wrapped));
RDCASSERT(record);
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
}
else
{
WrappedID3D11Buffer *w = (WrappedID3D11Buffer *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppBuffer = wrapped;
}
return ret;
}
vector<D3D11_SUBRESOURCE_DATA> WrappedID3D11Device::Serialise_CreateTextureData(
ID3D11Resource *tex, ResourceId id, const D3D11_SUBRESOURCE_DATA *data, UINT w, UINT h, UINT d,
DXGI_FORMAT fmt, UINT mips, UINT arr, bool HasData)
{
UINT numSubresources = mips;
UINT numMips = mips;
if(mips == 0)
numSubresources = numMips = CalcNumMips(w, h, d);
numSubresources *= arr;
vector<D3D11_SUBRESOURCE_DATA> descs;
if(m_State == READING && HasData)
{
descs.resize(numSubresources);
}
byte *scratch = NULL;
for(UINT i = 0; i < numSubresources; i++)
{
int mip = i % numMips;
UINT subresourceSize = GetByteSize(w, h, d, fmt, mip);
RDCASSERT(subresourceSize > 0);
D3D11ResourceRecord *record = GetResourceManager()->GetResourceRecord(id);
if(m_State >= WRITING)
{
if(i == 0)
{
RDCASSERT(record == NULL);
record = GetResourceManager()->AddResourceRecord(id);
record->Length = 1;
if(HasData)
record->DataInSerialiser = true;
record->NumSubResources = numSubresources;
record->SubResources = new ResourceRecord *[record->NumSubResources];
for(UINT s = 0; s < numSubresources; s++)
{
record->SubResources[s] = new D3D11ResourceRecord(ResourceId());
record->SubResources[s]->DataInSerialiser = HasData;
}
}
RDCASSERT(record != NULL);
record->SubResources[i]->Length = subresourceSize;
}
if(!HasData)
continue;
if(scratch == NULL && m_State >= WRITING)
scratch = new byte[subresourceSize];
if(m_State >= WRITING)
{
MapIntercept intercept;
intercept.SetD3D(data[i]);
D3D11_RESOURCE_DIMENSION dim;
tex->GetType(&dim);
if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE1D)
intercept.Init((ID3D11Texture1D *)tex, i, scratch);
else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE2D)
intercept.Init((ID3D11Texture2D *)tex, i, scratch);
else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
intercept.Init((ID3D11Texture3D *)tex, i, scratch);
else
RDCERR("Unexpected resource type!");
intercept.CopyFromD3D();
}
// this is a bit of a hack, but to maintain backwards compatibility we have a
// separate function here that aligns the next serialised buffer to a 32-byte
// boundary in memory while writing (just skips the padding on read).
if(m_State >= WRITING || GetLogVersion() >= 0x000007)
m_pSerialiser->AlignNextBuffer(32);
SERIALISE_ELEMENT_BUF(byte *, buf, scratch, subresourceSize);
if(m_State >= WRITING)
{
RDCASSERT(record);
record->SubResources[i]->SetDataOffset(m_pSerialiser->GetOffset() - subresourceSize);
}
if(m_State == READING)
{
descs[i].pSysMem = buf;
descs[i].SysMemPitch = GetByteSize(w, 1, 1, fmt, mip);
descs[i].SysMemSlicePitch = GetByteSize(w, h, 1, fmt, mip);
}
}
if(scratch)
SAFE_DELETE_ARRAY(scratch);
return descs;
}
bool WrappedID3D11Device::Serialise_CreateTexture1D(const D3D11_TEXTURE1D_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Texture1D **ppTexture1D)
{
SERIALISE_ELEMENT_PTR(D3D11_TEXTURE1D_DESC, Descriptor, pDesc);
SERIALISE_ELEMENT(ResourceId, pTexture, GetIDForResource(*ppTexture1D));
SERIALISE_ELEMENT(bool, HasInitialData, pInitialData != NULL);
vector<D3D11_SUBRESOURCE_DATA> descs = Serialise_CreateTextureData(
ppTexture1D ? *ppTexture1D : NULL, pTexture, pInitialData, Descriptor.Width, 1, 1,
Descriptor.Format, Descriptor.MipLevels, Descriptor.ArraySize, HasInitialData);
if(m_State == READING)
{
ID3D11Texture1D *ret;
HRESULT hr = S_OK;
TextureDisplayType dispType = DispTypeForTexture(Descriptor);
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
if(HasInitialData)
hr = m_pDevice->CreateTexture1D(&Descriptor, &descs[0], &ret);
else
hr = m_pDevice->CreateTexture1D(&Descriptor, NULL, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Texture1D(ret, this, dispType);
GetResourceManager()->AddLiveResource(pTexture, ret);
}
}
for(size_t i = 0; i < descs.size(); i++)
SAFE_DELETE_ARRAY(descs[i].pSysMem);
return true;
}
HRESULT WrappedID3D11Device::CreateTexture1D(const D3D11_TEXTURE1D_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Texture1D **ppTexture1D)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppTexture1D == NULL)
return m_pDevice->CreateTexture1D(pDesc, pInitialData, NULL);
ID3D11Texture1D *real = NULL;
ID3D11Texture1D *wrapped = NULL;
HRESULT ret = m_pDevice->CreateTexture1D(pDesc, pInitialData, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Texture1D(real, this);
if(m_State >= WRITING)
{
Chunk *chunk = NULL;
{
SCOPED_SERIALISE_CONTEXT(CREATE_TEXTURE_1D);
Serialise_CreateTexture1D(pDesc, pInitialData, &wrapped);
chunk = scope.Get();
}
D3D11ResourceRecord *record =
GetResourceManager()->GetResourceRecord(GetIDForResource(wrapped));
RDCASSERT(record);
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
}
else
{
WrappedID3D11Texture1D *w = (WrappedID3D11Texture1D *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppTexture1D = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateTexture2D(const D3D11_TEXTURE2D_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Texture2D **ppTexture2D)
{
SERIALISE_ELEMENT_PTR(D3D11_TEXTURE2D_DESC, Descriptor, pDesc);
SERIALISE_ELEMENT(ResourceId, pTexture, GetIDForResource(*ppTexture2D));
SERIALISE_ELEMENT(bool, HasInitialData, pInitialData != NULL);
vector<D3D11_SUBRESOURCE_DATA> descs = Serialise_CreateTextureData(
ppTexture2D ? *ppTexture2D : NULL, pTexture, pInitialData, Descriptor.Width, Descriptor.Height,
1, Descriptor.Format, Descriptor.MipLevels, Descriptor.ArraySize, HasInitialData);
if(m_State == READING)
{
ID3D11Texture2D *ret;
HRESULT hr = S_OK;
TextureDisplayType dispType = DispTypeForTexture(Descriptor);
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
if(HasInitialData)
hr = m_pDevice->CreateTexture2D(&Descriptor, &descs[0], &ret);
else
hr = m_pDevice->CreateTexture2D(&Descriptor, NULL, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Texture2D1(ret, this, dispType);
GetResourceManager()->AddLiveResource(pTexture, ret);
}
}
for(size_t i = 0; i < descs.size(); i++)
SAFE_DELETE_ARRAY(descs[i].pSysMem);
return true;
}
HRESULT WrappedID3D11Device::CreateTexture2D(const D3D11_TEXTURE2D_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Texture2D **ppTexture2D)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppTexture2D == NULL)
return m_pDevice->CreateTexture2D(pDesc, pInitialData, NULL);
ID3D11Texture2D *real = NULL;
ID3D11Texture2D *wrapped = NULL;
HRESULT ret = m_pDevice->CreateTexture2D(pDesc, pInitialData, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Texture2D1(real, this);
if(m_State >= WRITING)
{
Chunk *chunk = NULL;
{
SCOPED_SERIALISE_CONTEXT(CREATE_TEXTURE_2D);
Serialise_CreateTexture2D(pDesc, pInitialData, &wrapped);
chunk = scope.Get();
}
D3D11ResourceRecord *record =
GetResourceManager()->GetResourceRecord(GetIDForResource(wrapped));
RDCASSERT(record);
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
}
else
{
WrappedID3D11Texture2D1 *w = (WrappedID3D11Texture2D1 *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppTexture2D = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateTexture3D(const D3D11_TEXTURE3D_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Texture3D **ppTexture3D)
{
SERIALISE_ELEMENT_PTR(D3D11_TEXTURE3D_DESC, Descriptor, pDesc);
SERIALISE_ELEMENT(ResourceId, pTexture, GetIDForResource(*ppTexture3D));
SERIALISE_ELEMENT(bool, HasInitialData, pInitialData != NULL);
vector<D3D11_SUBRESOURCE_DATA> descs = Serialise_CreateTextureData(
ppTexture3D ? *ppTexture3D : NULL, pTexture, pInitialData, Descriptor.Width, Descriptor.Height,
Descriptor.Depth, Descriptor.Format, Descriptor.MipLevels, 1, HasInitialData);
if(m_State == READING)
{
ID3D11Texture3D *ret;
HRESULT hr = S_OK;
TextureDisplayType dispType = DispTypeForTexture(Descriptor);
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
if(HasInitialData)
hr = m_pDevice->CreateTexture3D(&Descriptor, &descs[0], &ret);
else
hr = m_pDevice->CreateTexture3D(&Descriptor, NULL, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Texture3D1(ret, this, dispType);
GetResourceManager()->AddLiveResource(pTexture, ret);
}
}
for(size_t i = 0; i < descs.size(); i++)
SAFE_DELETE_ARRAY(descs[i].pSysMem);
return true;
}
HRESULT WrappedID3D11Device::CreateTexture3D(const D3D11_TEXTURE3D_DESC *pDesc,
const D3D11_SUBRESOURCE_DATA *pInitialData,
ID3D11Texture3D **ppTexture3D)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppTexture3D == NULL)
return m_pDevice->CreateTexture3D(pDesc, pInitialData, NULL);
ID3D11Texture3D *real = NULL;
ID3D11Texture3D *wrapped = NULL;
HRESULT ret = m_pDevice->CreateTexture3D(pDesc, pInitialData, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Texture3D1(real, this);
if(m_State >= WRITING)
{
Chunk *chunk = NULL;
{
SCOPED_SERIALISE_CONTEXT(CREATE_TEXTURE_3D);
Serialise_CreateTexture3D(pDesc, pInitialData, &wrapped);
chunk = scope.Get();
}
D3D11ResourceRecord *record =
GetResourceManager()->GetResourceRecord(GetIDForResource(wrapped));
RDCASSERT(record);
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
}
else
{
WrappedID3D11Texture3D1 *w = (WrappedID3D11Texture3D1 *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppTexture3D = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateShaderResourceView(ID3D11Resource *pResource,
const D3D11_SHADER_RESOURCE_VIEW_DESC *pDesc,
ID3D11ShaderResourceView **ppSRView)
{
SERIALISE_ELEMENT(ResourceId, Resource, GetIDForResource(pResource));
SERIALISE_ELEMENT(bool, HasDesc, pDesc != NULL);
SERIALISE_ELEMENT_PTR_OPT(D3D11_SHADER_RESOURCE_VIEW_DESC, Descriptor, pDesc, HasDesc);
SERIALISE_ELEMENT(ResourceId, pView, GetIDForResource(*ppSRView));
if(m_State == READING && GetResourceManager()->HasLiveResource(Resource))
{
ID3D11ShaderResourceView *ret;
D3D11_SHADER_RESOURCE_VIEW_DESC *pSRVDesc = NULL;
if(HasDesc)
pSRVDesc = &Descriptor;
ID3D11Resource *live = (ID3D11Resource *)GetResourceManager()->GetLiveResource(Resource);
WrappedID3D11Texture2D1 *tex2d = (WrappedID3D11Texture2D1 *)live;
D3D11_SHADER_RESOURCE_VIEW_DESC backbufferTypedDesc;
// need to fixup typeless backbuffer fudging, if a descriptor isn't specified then
// we need to make one to give the correct type
if(!HasDesc && WrappedID3D11Texture2D1::IsAlloc(live) && tex2d->m_RealDescriptor)
{
backbufferTypedDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
if(tex2d->m_RealDescriptor->SampleDesc.Quality > 0 ||
tex2d->m_RealDescriptor->SampleDesc.Count > 1)
backbufferTypedDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS;
backbufferTypedDesc.Format = tex2d->m_RealDescriptor->Format;
backbufferTypedDesc.Texture2D.MipLevels = 1;
backbufferTypedDesc.Texture2D.MostDetailedMip = 0;
pSRVDesc = &backbufferTypedDesc;
}
// if we have a descriptor but it specifies DXGI_FORMAT_UNKNOWN format, that means use
// the texture's format. But as above, we fudge around the typeless backbuffer so we
// have to set the correct typed format
//
// This behaviour is documented only for render targets, but seems to be used & work for
// SRVs, so apply it here too.
if(pSRVDesc && pSRVDesc->Format == DXGI_FORMAT_UNKNOWN &&
WrappedID3D11Texture2D1::IsAlloc(live) && tex2d->m_RealDescriptor)
{
pSRVDesc->Format = tex2d->m_RealDescriptor->Format;
}
HRESULT hr = m_pDevice->CreateShaderResourceView(GetResourceManager()->UnwrapResource(live),
pSRVDesc, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11ShaderResourceView1(ret, live, this);
GetResourceManager()->AddLiveResource(pView, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateShaderResourceView(ID3D11Resource *pResource,
const D3D11_SHADER_RESOURCE_VIEW_DESC *pDesc,
ID3D11ShaderResourceView **ppSRView)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppSRView == NULL)
return m_pDevice->CreateShaderResourceView(GetResourceManager()->UnwrapResource(pResource),
pDesc, NULL);
ID3D11ShaderResourceView *real = NULL;
ID3D11ShaderResourceView *wrapped = NULL;
HRESULT ret = m_pDevice->CreateShaderResourceView(GetResourceManager()->UnwrapResource(pResource),
pDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11ShaderResourceView1(real, pResource, this);
Chunk *chunk = NULL;
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_SRV);
Serialise_CreateShaderResourceView(pResource, pDesc, &wrapped);
chunk = scope.Get();
if(WrappedID3D11Texture1D::IsAlloc(pResource) || WrappedID3D11Texture2D1::IsAlloc(pResource) ||
WrappedID3D11Texture3D1::IsAlloc(pResource) || WrappedID3D11Buffer::IsAlloc(pResource))
{
D3D11ResourceRecord *parent =
GetResourceManager()->GetResourceRecord(GetIDForResource(pResource));
RDCASSERT(parent);
WrappedID3D11ShaderResourceView1 *view = (WrappedID3D11ShaderResourceView1 *)wrapped;
ResourceId id = view->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddParent(parent);
record->AddChunk(chunk);
}
else
{
RDCERR("Unexpected resource type in SRV creation");
m_DeviceRecord->AddChunk(chunk);
}
}
*ppSRView = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateUnorderedAccessView(
ID3D11Resource *pResource, const D3D11_UNORDERED_ACCESS_VIEW_DESC *pDesc,
ID3D11UnorderedAccessView **ppUAView)
{
SERIALISE_ELEMENT(ResourceId, Resource, GetIDForResource(pResource));
SERIALISE_ELEMENT(bool, HasDesc, pDesc != NULL);
SERIALISE_ELEMENT_PTR_OPT(D3D11_UNORDERED_ACCESS_VIEW_DESC, Descriptor, pDesc, HasDesc);
SERIALISE_ELEMENT(ResourceId, pView, GetIDForResource(*ppUAView));
if(m_State == READING && GetResourceManager()->HasLiveResource(Resource))
{
ID3D11UnorderedAccessView *ret;
D3D11_UNORDERED_ACCESS_VIEW_DESC *pUAVDesc = NULL;
if(HasDesc)
pUAVDesc = &Descriptor;
ID3D11Resource *live = (ID3D11Resource *)GetResourceManager()->GetLiveResource(Resource);
HRESULT hr = m_pDevice->CreateUnorderedAccessView(GetResourceManager()->UnwrapResource(live),
pUAVDesc, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11UnorderedAccessView1(ret, live, this);
GetResourceManager()->AddLiveResource(pView, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateUnorderedAccessView(ID3D11Resource *pResource,
const D3D11_UNORDERED_ACCESS_VIEW_DESC *pDesc,
ID3D11UnorderedAccessView **ppUAView)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppUAView == NULL)
return m_pDevice->CreateUnorderedAccessView(GetResourceManager()->UnwrapResource(pResource),
pDesc, NULL);
ID3D11UnorderedAccessView *real = NULL;
ID3D11UnorderedAccessView *wrapped = NULL;
HRESULT ret = m_pDevice->CreateUnorderedAccessView(
GetResourceManager()->UnwrapResource(pResource), pDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11UnorderedAccessView1(real, pResource, this);
Chunk *chunk = NULL;
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_UAV);
Serialise_CreateUnorderedAccessView(pResource, pDesc, &wrapped);
chunk = scope.Get();
if(WrappedID3D11Texture1D::IsAlloc(pResource) || WrappedID3D11Texture2D1::IsAlloc(pResource) ||
WrappedID3D11Texture3D1::IsAlloc(pResource) || WrappedID3D11Buffer::IsAlloc(pResource))
{
D3D11ResourceRecord *parent =
GetResourceManager()->GetResourceRecord(GetIDForResource(pResource));
RDCASSERT(parent);
WrappedID3D11UnorderedAccessView1 *view = (WrappedID3D11UnorderedAccessView1 *)wrapped;
ResourceId id = view->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddParent(parent);
record->AddChunk(chunk);
}
else
{
RDCERR("Unexpected resource type in UAV creation");
m_DeviceRecord->AddChunk(chunk);
}
}
*ppUAView = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateRenderTargetView(ID3D11Resource *pResource,
const D3D11_RENDER_TARGET_VIEW_DESC *pDesc,
ID3D11RenderTargetView **ppRTView)
{
SERIALISE_ELEMENT(ResourceId, Resource, GetIDForResource(pResource));
SERIALISE_ELEMENT(bool, HasDesc, pDesc != NULL);
SERIALISE_ELEMENT_PTR_OPT(D3D11_RENDER_TARGET_VIEW_DESC, Descriptor, pDesc, HasDesc);
SERIALISE_ELEMENT(ResourceId, pView, GetIDForResource(*ppRTView));
if(m_State == READING && GetResourceManager()->HasLiveResource(Resource))
{
ID3D11RenderTargetView *ret;
D3D11_RENDER_TARGET_VIEW_DESC *pRTVDesc = NULL;
if(HasDesc)
pRTVDesc = &Descriptor;
ID3D11Resource *live = (ID3D11Resource *)GetResourceManager()->GetLiveResource(Resource);
WrappedID3D11Texture2D1 *tex2d = (WrappedID3D11Texture2D1 *)live;
D3D11_RENDER_TARGET_VIEW_DESC backbufferTypedDesc;
// need to fixup typeless backbuffer fudging, if a descriptor isn't specified then
// we need to make one to give the correct type
if(!HasDesc && WrappedID3D11Texture2D1::IsAlloc(live) && tex2d->m_RealDescriptor)
{
backbufferTypedDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
if(tex2d->m_RealDescriptor->SampleDesc.Quality > 0 ||
tex2d->m_RealDescriptor->SampleDesc.Count > 1)
backbufferTypedDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS;
backbufferTypedDesc.Format = tex2d->m_RealDescriptor->Format;
backbufferTypedDesc.Texture2D.MipSlice = 0;
pRTVDesc = &backbufferTypedDesc;
}
// if we have a descriptor but it specifies DXGI_FORMAT_UNKNOWN format, that means use
// the texture's format. But as above, we fudge around the typeless backbuffer so we
// have to set the correct typed format
if(pRTVDesc && pRTVDesc->Format == DXGI_FORMAT_UNKNOWN &&
WrappedID3D11Texture2D1::IsAlloc(live) && tex2d->m_RealDescriptor)
{
pRTVDesc->Format = tex2d->m_RealDescriptor->Format;
}
HRESULT hr = m_pDevice->CreateRenderTargetView(GetResourceManager()->UnwrapResource(live),
pRTVDesc, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11RenderTargetView1(ret, live, this);
GetResourceManager()->AddLiveResource(pView, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateRenderTargetView(ID3D11Resource *pResource,
const D3D11_RENDER_TARGET_VIEW_DESC *pDesc,
ID3D11RenderTargetView **ppRTView)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppRTView == NULL)
return m_pDevice->CreateRenderTargetView(GetResourceManager()->UnwrapResource(pResource), pDesc,
NULL);
ID3D11RenderTargetView *real = NULL;
ID3D11RenderTargetView *wrapped = NULL;
HRESULT ret = m_pDevice->CreateRenderTargetView(GetResourceManager()->UnwrapResource(pResource),
pDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11RenderTargetView1(real, pResource, this);
Chunk *chunk = NULL;
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_RTV);
Serialise_CreateRenderTargetView(pResource, pDesc, &wrapped);
chunk = scope.Get();
if(WrappedID3D11Texture1D::IsAlloc(pResource) || WrappedID3D11Texture2D1::IsAlloc(pResource) ||
WrappedID3D11Texture3D1::IsAlloc(pResource) || WrappedID3D11Buffer::IsAlloc(pResource))
{
D3D11ResourceRecord *parent =
GetResourceManager()->GetResourceRecord(GetIDForResource(pResource));
RDCASSERT(parent);
WrappedID3D11RenderTargetView1 *view = (WrappedID3D11RenderTargetView1 *)wrapped;
ResourceId id = view->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddParent(parent);
record->AddChunk(chunk);
}
else
{
RDCERR("Unexpected resource type in RTV creation");
m_DeviceRecord->AddChunk(chunk);
}
}
*ppRTView = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateDepthStencilView(ID3D11Resource *pResource,
const D3D11_DEPTH_STENCIL_VIEW_DESC *pDesc,
ID3D11DepthStencilView **ppDepthStencilView)
{
SERIALISE_ELEMENT(ResourceId, Resource, GetIDForResource(pResource));
SERIALISE_ELEMENT(bool, HasDesc, pDesc != NULL);
SERIALISE_ELEMENT_PTR_OPT(D3D11_DEPTH_STENCIL_VIEW_DESC, Descriptor, pDesc, HasDesc);
SERIALISE_ELEMENT(ResourceId, pView, GetIDForResource(*ppDepthStencilView));
if(m_State == READING && GetResourceManager()->HasLiveResource(Resource))
{
ID3D11DepthStencilView *ret;
ID3D11Resource *live = (ID3D11Resource *)GetResourceManager()->GetLiveResource(Resource);
pDesc = NULL;
if(HasDesc)
pDesc = &Descriptor;
HRESULT hr =
m_pDevice->CreateDepthStencilView(GetResourceManager()->UnwrapResource(live), pDesc, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11DepthStencilView(ret, live, this);
GetResourceManager()->AddLiveResource(pView, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateDepthStencilView(ID3D11Resource *pResource,
const D3D11_DEPTH_STENCIL_VIEW_DESC *pDesc,
ID3D11DepthStencilView **ppDepthStencilView)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppDepthStencilView == NULL)
return m_pDevice->CreateDepthStencilView(GetResourceManager()->UnwrapResource(pResource), pDesc,
NULL);
ID3D11DepthStencilView *real = NULL;
ID3D11DepthStencilView *wrapped = NULL;
HRESULT ret = m_pDevice->CreateDepthStencilView(GetResourceManager()->UnwrapResource(pResource),
pDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11DepthStencilView(real, pResource, this);
Chunk *chunk = NULL;
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_DSV);
Serialise_CreateDepthStencilView(pResource, pDesc, &wrapped);
chunk = scope.Get();
if(WrappedID3D11Texture1D::IsAlloc(pResource) || WrappedID3D11Texture2D1::IsAlloc(pResource) ||
WrappedID3D11Texture3D1::IsAlloc(pResource) || WrappedID3D11Buffer::IsAlloc(pResource))
{
D3D11ResourceRecord *parent =
GetResourceManager()->GetResourceRecord(GetIDForResource(pResource));
RDCASSERT(parent);
WrappedID3D11DepthStencilView *view = (WrappedID3D11DepthStencilView *)wrapped;
ResourceId id = view->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddParent(parent);
record->AddChunk(chunk);
}
else
{
RDCERR("Unexpected resource type in DSV creation");
m_DeviceRecord->AddChunk(chunk);
}
}
*ppDepthStencilView = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateInputLayout(
const D3D11_INPUT_ELEMENT_DESC *pInputElementDescs, UINT NumElements,
const void *pShaderBytecodeWithInputSignature, SIZE_T BytecodeLength,
ID3D11InputLayout **ppInputLayout)
{
SERIALISE_ELEMENT(uint32_t, NumElems, NumElements);
D3D11_INPUT_ELEMENT_DESC *layouts = new D3D11_INPUT_ELEMENT_DESC[NumElems];
for(UINT i = 0; i < NumElems; i++)
{
SERIALISE_ELEMENT(D3D11_INPUT_ELEMENT_DESC, layout, pInputElementDescs[i]);
layouts[i] = layout;
}
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, pShaderBytecodeWithInputSignature, BytecodeLength);
SERIALISE_ELEMENT(ResourceId, pLayout, GetIDForResource(*ppInputLayout));
ID3D11InputLayout *ret = NULL;
if(m_State >= WRITING)
{
ret = *ppInputLayout;
}
else if(m_State == READING)
{
HRESULT hr =
m_pDevice->CreateInputLayout(layouts, NumElems, ShaderBytecode, (size_t)BytecodeLen, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11InputLayout(ret, this);
GetResourceManager()->AddLiveResource(pLayout, ret);
}
vector<D3D11_INPUT_ELEMENT_DESC> descvec(layouts, layouts + NumElems);
m_LayoutDescs[ret] = descvec;
if(BytecodeLen > 0 && ShaderBytecode)
m_LayoutShaders[ret] =
new WrappedShader(this, GetIDForResource(ret), ShaderBytecode, BytecodeLen);
SAFE_DELETE_ARRAY(ShaderBytecode);
}
SAFE_DELETE_ARRAY(layouts);
return true;
}
HRESULT WrappedID3D11Device::CreateInputLayout(const D3D11_INPUT_ELEMENT_DESC *pInputElementDescs,
UINT NumElements,
const void *pShaderBytecodeWithInputSignature,
SIZE_T BytecodeLength,
ID3D11InputLayout **ppInputLayout)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppInputLayout == NULL)
return m_pDevice->CreateInputLayout(pInputElementDescs, NumElements,
pShaderBytecodeWithInputSignature, BytecodeLength, NULL);
ID3D11InputLayout *real = NULL;
ID3D11InputLayout *wrapped = NULL;
HRESULT ret = m_pDevice->CreateInputLayout(
pInputElementDescs, NumElements, pShaderBytecodeWithInputSignature, BytecodeLength, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11InputLayout(real, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_INPUT_LAYOUT);
Serialise_CreateInputLayout(pInputElementDescs, NumElements,
pShaderBytecodeWithInputSignature, BytecodeLength, &wrapped);
WrappedID3D11InputLayout *lay = (WrappedID3D11InputLayout *)wrapped;
ResourceId id = lay->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
}
*ppInputLayout = wrapped;
return ret;
}
bool WrappedID3D11Device::Serialise_CreateVertexShader(const void *pShaderBytecode,
SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11VertexShader **ppVertexShader)
{
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, (void *&)pShaderBytecode, BytecodeLength);
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(pClassLinkage));
SERIALISE_ELEMENT(ResourceId, pShader, GetIDForResource(*ppVertexShader));
if(m_State == READING)
{
ID3D11ClassLinkage *linkage = NULL;
if(GetResourceManager()->HasLiveResource(pLinkage))
linkage = UNWRAP(WrappedID3D11ClassLinkage,
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage));
ID3D11VertexShader *ret;
HRESULT hr = m_pDevice->CreateVertexShader(ShaderBytecode, (size_t)BytecodeLen, linkage, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Shader<ID3D11VertexShader>(ret, ShaderBytecode, (size_t)BytecodeLen,
this);
GetResourceManager()->AddLiveResource(pShader, ret);
}
SAFE_DELETE_ARRAY(ShaderBytecode);
}
return true;
}
HRESULT WrappedID3D11Device::CreateVertexShader(const void *pShaderBytecode, SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11VertexShader **ppVertexShader)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppVertexShader == NULL)
return m_pDevice->CreateVertexShader(pShaderBytecode, BytecodeLength,
UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), NULL);
ID3D11VertexShader *real = NULL;
ID3D11VertexShader *wrapped = NULL;
HRESULT ret = m_pDevice->CreateVertexShader(
pShaderBytecode, BytecodeLength, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Shader<ID3D11VertexShader>(real, (const byte *)pShaderBytecode,
BytecodeLength, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_VERTEX_SHADER);
Serialise_CreateVertexShader(pShaderBytecode, BytecodeLength, pClassLinkage, &wrapped);
WrappedID3D11Shader<ID3D11VertexShader> *sh =
(WrappedID3D11Shader<ID3D11VertexShader> *)wrapped;
ResourceId id = sh->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
else
{
WrappedID3D11Shader<ID3D11VertexShader> *w = (WrappedID3D11Shader<ID3D11VertexShader> *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppVertexShader = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateGeometryShader(const void *pShaderBytecode,
SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11GeometryShader **ppGeometryShader)
{
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, pShaderBytecode, BytecodeLength);
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(pClassLinkage));
SERIALISE_ELEMENT(ResourceId, pShader, GetIDForResource(*ppGeometryShader));
if(m_State == READING)
{
ID3D11ClassLinkage *linkage = NULL;
if(GetResourceManager()->HasLiveResource(pLinkage))
linkage = UNWRAP(WrappedID3D11ClassLinkage,
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage));
ID3D11GeometryShader *ret;
HRESULT hr = m_pDevice->CreateGeometryShader(ShaderBytecode, (size_t)BytecodeLen, linkage, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Shader<ID3D11GeometryShader>(ret, ShaderBytecode, (size_t)BytecodeLen,
this);
GetResourceManager()->AddLiveResource(pShader, ret);
}
SAFE_DELETE_ARRAY(ShaderBytecode);
}
return true;
}
HRESULT WrappedID3D11Device::CreateGeometryShader(const void *pShaderBytecode, SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11GeometryShader **ppGeometryShader)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppGeometryShader == NULL)
return m_pDevice->CreateGeometryShader(pShaderBytecode, BytecodeLength,
UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), NULL);
ID3D11GeometryShader *real = NULL;
ID3D11GeometryShader *wrapped = NULL;
HRESULT ret = m_pDevice->CreateGeometryShader(
pShaderBytecode, BytecodeLength, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Shader<ID3D11GeometryShader>(real, (const byte *)pShaderBytecode,
BytecodeLength, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_GEOMETRY_SHADER);
Serialise_CreateGeometryShader(pShaderBytecode, BytecodeLength, pClassLinkage, &wrapped);
WrappedID3D11Shader<ID3D11GeometryShader> *sh =
(WrappedID3D11Shader<ID3D11GeometryShader> *)wrapped;
ResourceId id = sh->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
else
{
WrappedID3D11Shader<ID3D11GeometryShader> *w =
(WrappedID3D11Shader<ID3D11GeometryShader> *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppGeometryShader = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateGeometryShaderWithStreamOutput(
const void *pShaderBytecode, SIZE_T BytecodeLength,
const D3D11_SO_DECLARATION_ENTRY *pSODeclaration, UINT NumEntries, const UINT *pBufferStrides,
UINT NumStrides, UINT RasterizedStream, ID3D11ClassLinkage *pClassLinkage,
ID3D11GeometryShader **ppGeometryShader)
{
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, pShaderBytecode, BytecodeLength);
SERIALISE_ELEMENT(uint32_t, numEntries, NumEntries);
SERIALISE_ELEMENT_ARR(D3D11_SO_DECLARATION_ENTRY, SODecl, pSODeclaration, numEntries);
SERIALISE_ELEMENT(uint32_t, numStrides, NumStrides);
SERIALISE_ELEMENT_ARR(uint32_t, BufStrides, pBufferStrides, numStrides);
SERIALISE_ELEMENT(uint32_t, RastStream, RasterizedStream);
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(pClassLinkage));
SERIALISE_ELEMENT(ResourceId, pShader, GetIDForResource(*ppGeometryShader));
if(m_State == READING)
{
ID3D11ClassLinkage *linkage = NULL;
if(GetResourceManager()->HasLiveResource(pLinkage))
linkage = UNWRAP(WrappedID3D11ClassLinkage,
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage));
ID3D11GeometryShader *ret;
HRESULT hr = m_pDevice->CreateGeometryShaderWithStreamOutput(
ShaderBytecode, (size_t)BytecodeLen, SODecl, numEntries,
numStrides == 0 ? NULL : BufStrides, numStrides, RastStream, linkage, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Shader<ID3D11GeometryShader>(ret, ShaderBytecode, (size_t)BytecodeLen,
this);
GetResourceManager()->AddLiveResource(pShader, ret);
}
SAFE_DELETE_ARRAY(ShaderBytecode);
}
SAFE_DELETE_ARRAY(SODecl);
SAFE_DELETE_ARRAY(BufStrides);
return true;
}
HRESULT WrappedID3D11Device::CreateGeometryShaderWithStreamOutput(
const void *pShaderBytecode, SIZE_T BytecodeLength,
const D3D11_SO_DECLARATION_ENTRY *pSODeclaration, UINT NumEntries, const UINT *pBufferStrides,
UINT NumStrides, UINT RasterizedStream, ID3D11ClassLinkage *pClassLinkage,
ID3D11GeometryShader **ppGeometryShader)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppGeometryShader == NULL)
return m_pDevice->CreateGeometryShaderWithStreamOutput(
pShaderBytecode, BytecodeLength, pSODeclaration, NumEntries, pBufferStrides, NumStrides,
RasterizedStream, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), NULL);
ID3D11GeometryShader *real = NULL;
ID3D11GeometryShader *wrapped = NULL;
HRESULT ret = m_pDevice->CreateGeometryShaderWithStreamOutput(
pShaderBytecode, BytecodeLength, pSODeclaration, NumEntries, pBufferStrides, NumStrides,
RasterizedStream, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Shader<ID3D11GeometryShader>(real, (const byte *)pShaderBytecode,
BytecodeLength, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_GEOMETRY_SHADER_WITH_SO);
Serialise_CreateGeometryShaderWithStreamOutput(pShaderBytecode, BytecodeLength, pSODeclaration,
NumEntries, pBufferStrides, NumStrides,
RasterizedStream, pClassLinkage, &wrapped);
WrappedID3D11Shader<ID3D11GeometryShader> *sh =
(WrappedID3D11Shader<ID3D11GeometryShader> *)wrapped;
ResourceId id = sh->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
else
{
WrappedID3D11Shader<ID3D11GeometryShader> *w =
(WrappedID3D11Shader<ID3D11GeometryShader> *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppGeometryShader = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreatePixelShader(const void *pShaderBytecode,
SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11PixelShader **ppPixelShader)
{
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, pShaderBytecode, BytecodeLength);
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(pClassLinkage));
SERIALISE_ELEMENT(ResourceId, pShader, GetIDForResource(*ppPixelShader));
if(m_State == READING)
{
ID3D11ClassLinkage *linkage = NULL;
if(GetResourceManager()->HasLiveResource(pLinkage))
linkage = UNWRAP(WrappedID3D11ClassLinkage,
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage));
ID3D11PixelShader *ret;
HRESULT hr = m_pDevice->CreatePixelShader(ShaderBytecode, (size_t)BytecodeLen, linkage, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret =
new WrappedID3D11Shader<ID3D11PixelShader>(ret, ShaderBytecode, (size_t)BytecodeLen, this);
GetResourceManager()->AddLiveResource(pShader, ret);
}
SAFE_DELETE_ARRAY(ShaderBytecode);
}
return true;
}
HRESULT WrappedID3D11Device::CreatePixelShader(const void *pShaderBytecode, SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11PixelShader **ppPixelShader)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppPixelShader == NULL)
return m_pDevice->CreatePixelShader(pShaderBytecode, BytecodeLength,
UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), NULL);
ID3D11PixelShader *real = NULL;
ID3D11PixelShader *wrapped = NULL;
HRESULT ret = m_pDevice->CreatePixelShader(
pShaderBytecode, BytecodeLength, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Shader<ID3D11PixelShader>(real, (const byte *)pShaderBytecode,
BytecodeLength, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_PIXEL_SHADER);
Serialise_CreatePixelShader(pShaderBytecode, BytecodeLength, pClassLinkage, &wrapped);
WrappedID3D11Shader<ID3D11PixelShader> *sh = (WrappedID3D11Shader<ID3D11PixelShader> *)wrapped;
ResourceId id = sh->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
else
{
WrappedID3D11Shader<ID3D11PixelShader> *w = (WrappedID3D11Shader<ID3D11PixelShader> *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppPixelShader = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateHullShader(const void *pShaderBytecode,
SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11HullShader **ppHullShader)
{
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, pShaderBytecode, BytecodeLength);
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(pClassLinkage));
SERIALISE_ELEMENT(ResourceId, pShader, GetIDForResource(*ppHullShader));
if(m_State == READING)
{
ID3D11ClassLinkage *linkage = NULL;
if(GetResourceManager()->HasLiveResource(pLinkage))
linkage = UNWRAP(WrappedID3D11ClassLinkage,
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage));
ID3D11HullShader *ret;
HRESULT hr = m_pDevice->CreateHullShader(ShaderBytecode, (size_t)BytecodeLen, linkage, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Shader<ID3D11HullShader>(ret, ShaderBytecode, (size_t)BytecodeLen, this);
GetResourceManager()->AddLiveResource(pShader, ret);
}
SAFE_DELETE_ARRAY(ShaderBytecode);
}
return true;
}
HRESULT WrappedID3D11Device::CreateHullShader(const void *pShaderBytecode, SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11HullShader **ppHullShader)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppHullShader == NULL)
return m_pDevice->CreateHullShader(pShaderBytecode, BytecodeLength,
UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), NULL);
ID3D11HullShader *real = NULL;
ID3D11HullShader *wrapped = NULL;
HRESULT ret = m_pDevice->CreateHullShader(
pShaderBytecode, BytecodeLength, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Shader<ID3D11HullShader>(real, (const byte *)pShaderBytecode,
BytecodeLength, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_HULL_SHADER);
Serialise_CreateHullShader(pShaderBytecode, BytecodeLength, pClassLinkage, &wrapped);
WrappedID3D11Shader<ID3D11HullShader> *sh = (WrappedID3D11Shader<ID3D11HullShader> *)wrapped;
ResourceId id = sh->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
else
{
WrappedID3D11Shader<ID3D11HullShader> *w = (WrappedID3D11Shader<ID3D11HullShader> *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppHullShader = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateDomainShader(const void *pShaderBytecode,
SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11DomainShader **ppDomainShader)
{
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, pShaderBytecode, BytecodeLength);
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(pClassLinkage));
SERIALISE_ELEMENT(ResourceId, pShader, GetIDForResource(*ppDomainShader));
if(m_State == READING)
{
ID3D11ClassLinkage *linkage = NULL;
if(GetResourceManager()->HasLiveResource(pLinkage))
linkage = UNWRAP(WrappedID3D11ClassLinkage,
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage));
ID3D11DomainShader *ret;
HRESULT hr = m_pDevice->CreateDomainShader(ShaderBytecode, (size_t)BytecodeLen, linkage, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Shader<ID3D11DomainShader>(ret, ShaderBytecode, (size_t)BytecodeLen,
this);
GetResourceManager()->AddLiveResource(pShader, ret);
}
SAFE_DELETE_ARRAY(ShaderBytecode);
}
return true;
}
HRESULT WrappedID3D11Device::CreateDomainShader(const void *pShaderBytecode, SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11DomainShader **ppDomainShader)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppDomainShader == NULL)
return m_pDevice->CreateDomainShader(pShaderBytecode, BytecodeLength,
UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), NULL);
ID3D11DomainShader *real = NULL;
ID3D11DomainShader *wrapped = NULL;
HRESULT ret = m_pDevice->CreateDomainShader(
pShaderBytecode, BytecodeLength, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Shader<ID3D11DomainShader>(real, (const byte *)pShaderBytecode,
BytecodeLength, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_DOMAIN_SHADER);
Serialise_CreateDomainShader(pShaderBytecode, BytecodeLength, pClassLinkage, &wrapped);
WrappedID3D11Shader<ID3D11DomainShader> *sh =
(WrappedID3D11Shader<ID3D11DomainShader> *)wrapped;
ResourceId id = sh->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
else
{
WrappedID3D11Shader<ID3D11DomainShader> *w = (WrappedID3D11Shader<ID3D11DomainShader> *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppDomainShader = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateComputeShader(const void *pShaderBytecode,
SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11ComputeShader **ppComputeShader)
{
SERIALISE_ELEMENT(uint32_t, BytecodeLen, (uint32_t)BytecodeLength);
SERIALISE_ELEMENT_BUF(byte *, ShaderBytecode, pShaderBytecode, BytecodeLength);
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(pClassLinkage));
SERIALISE_ELEMENT(ResourceId, pShader, GetIDForResource(*ppComputeShader));
if(m_State == READING)
{
ID3D11ClassLinkage *linkage = NULL;
if(GetResourceManager()->HasLiveResource(pLinkage))
linkage = UNWRAP(WrappedID3D11ClassLinkage,
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage));
ID3D11ComputeShader *ret;
HRESULT hr = m_pDevice->CreateComputeShader(ShaderBytecode, (size_t)BytecodeLen, linkage, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Shader<ID3D11ComputeShader>(ret, ShaderBytecode, (size_t)BytecodeLen,
this);
GetResourceManager()->AddLiveResource(pShader, ret);
}
SAFE_DELETE_ARRAY(ShaderBytecode);
}
return true;
}
HRESULT WrappedID3D11Device::CreateComputeShader(const void *pShaderBytecode, SIZE_T BytecodeLength,
ID3D11ClassLinkage *pClassLinkage,
ID3D11ComputeShader **ppComputeShader)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppComputeShader == NULL)
return m_pDevice->CreateComputeShader(pShaderBytecode, BytecodeLength,
UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), NULL);
ID3D11ComputeShader *real = NULL;
ID3D11ComputeShader *wrapped = NULL;
HRESULT ret = m_pDevice->CreateComputeShader(
pShaderBytecode, BytecodeLength, UNWRAP(WrappedID3D11ClassLinkage, pClassLinkage), &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Shader<ID3D11ComputeShader>(real, (const byte *)pShaderBytecode,
BytecodeLength, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_COMPUTE_SHADER);
Serialise_CreateComputeShader(pShaderBytecode, BytecodeLength, pClassLinkage, &wrapped);
WrappedID3D11Shader<ID3D11ComputeShader> *sh =
(WrappedID3D11Shader<ID3D11ComputeShader> *)wrapped;
ResourceId id = sh->GetResourceID();
RDCASSERT(GetResourceManager()->GetResourceRecord(id) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
record->Length = 0;
record->AddChunk(scope.Get());
}
else
{
WrappedID3D11Shader<ID3D11ComputeShader> *w =
(WrappedID3D11Shader<ID3D11ComputeShader> *)wrapped;
GetResourceManager()->AddLiveResource(w->GetResourceID(), wrapped);
}
*ppComputeShader = wrapped;
}
return ret;
}
// Class Linkage 'fake' interfaces
bool WrappedID3D11Device::Serialise_CreateClassInstance(
LPCSTR pClassTypeName, UINT ConstantBufferOffset, UINT ConstantVectorOffset, UINT TextureOffset,
UINT SamplerOffset, WrappedID3D11ClassLinkage *linkage, ID3D11ClassInstance *inst)
{
string name = pClassTypeName ? pClassTypeName : "";
m_pSerialiser->Serialise("name", name);
SERIALISE_ELEMENT(UINT, cbOffset, ConstantBufferOffset);
SERIALISE_ELEMENT(UINT, cvOffset, ConstantVectorOffset);
SERIALISE_ELEMENT(UINT, texOffset, TextureOffset);
SERIALISE_ELEMENT(UINT, sampOffset, SamplerOffset);
SERIALISE_ELEMENT(ResourceId, pLinkage, linkage->GetResourceID());
SERIALISE_ELEMENT(ResourceId, instance, GetIDForResource(inst));
if(m_State == READING && GetResourceManager()->HasLiveResource(pLinkage))
{
ID3D11ClassLinkage *wrappedLink =
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage);
ID3D11ClassLinkage *realLink = UNWRAP(WrappedID3D11ClassLinkage, wrappedLink);
ID3D11ClassInstance *real = NULL;
ID3D11ClassInstance *wrapped = NULL;
HRESULT hr = realLink->CreateClassInstance(name.c_str(), cbOffset, cvOffset, texOffset,
sampOffset, &real);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
wrapped = new WrappedID3D11ClassInstance(real, wrappedLink, this);
GetResourceManager()->AddLiveResource(instance, wrapped);
}
}
return true;
}
ID3D11ClassInstance *WrappedID3D11Device::CreateClassInstance(
LPCSTR pClassTypeName, UINT ConstantBufferOffset, UINT ConstantVectorOffset, UINT TextureOffset,
UINT SamplerOffset, WrappedID3D11ClassLinkage *linkage, ID3D11ClassInstance *inst)
{
ID3D11ClassInstance *wrapped = NULL;
if(m_State >= WRITING)
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11ClassInstance(inst, linkage, this);
{
SCOPED_SERIALISE_CONTEXT(CREATE_CLASS_INSTANCE);
Serialise_CreateClassInstance(pClassTypeName, ConstantBufferOffset, ConstantVectorOffset,
TextureOffset, SamplerOffset, linkage, wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
return wrapped;
}
return inst;
}
bool WrappedID3D11Device::Serialise_GetClassInstance(LPCSTR pClassInstanceName, UINT InstanceIndex,
WrappedID3D11ClassLinkage *linkage,
ID3D11ClassInstance *inst)
{
string name = pClassInstanceName ? pClassInstanceName : "";
m_pSerialiser->Serialise("name", name);
SERIALISE_ELEMENT(UINT, idx, InstanceIndex);
SERIALISE_ELEMENT(ResourceId, pLinkage, linkage->GetResourceID());
SERIALISE_ELEMENT(ResourceId, instance, GetIDForResource(inst));
if(m_State == READING && GetResourceManager()->HasLiveResource(pLinkage))
{
ID3D11ClassLinkage *wrappedLink =
(ID3D11ClassLinkage *)GetResourceManager()->GetLiveResource(pLinkage);
ID3D11ClassLinkage *realLink = UNWRAP(WrappedID3D11ClassLinkage, wrappedLink);
ID3D11ClassInstance *real = NULL;
ID3D11ClassInstance *wrapped = NULL;
HRESULT hr = realLink->GetClassInstance(name.c_str(), idx, &real);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
wrapped = new WrappedID3D11ClassInstance(real, wrappedLink, this);
GetResourceManager()->AddLiveResource(instance, wrapped);
}
}
return true;
}
ID3D11ClassInstance *WrappedID3D11Device::GetClassInstance(LPCSTR pClassInstanceName,
UINT InstanceIndex,
WrappedID3D11ClassLinkage *linkage,
ID3D11ClassInstance *inst)
{
ID3D11ClassInstance *wrapped = NULL;
if(m_State >= WRITING)
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11ClassInstance(inst, linkage, this);
{
SCOPED_SERIALISE_CONTEXT(GET_CLASS_INSTANCE);
Serialise_GetClassInstance(pClassInstanceName, InstanceIndex, linkage, wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
return wrapped;
}
return inst;
}
bool WrappedID3D11Device::Serialise_CreateClassLinkage(ID3D11ClassLinkage **ppLinkage)
{
SERIALISE_ELEMENT(ResourceId, pLinkage, GetIDForResource(*ppLinkage));
if(m_State == READING)
{
ID3D11ClassLinkage *ret;
HRESULT hr = m_pDevice->CreateClassLinkage(&ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11ClassLinkage(ret, this);
GetResourceManager()->AddLiveResource(pLinkage, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateClassLinkage(ID3D11ClassLinkage **ppLinkage)
{
// get 'real' return value for NULL parameter
if(ppLinkage == NULL)
return m_pDevice->CreateClassLinkage(NULL);
ID3D11ClassLinkage *real = NULL;
ID3D11ClassLinkage *wrapped = NULL;
HRESULT ret = m_pDevice->CreateClassLinkage(&real);
if(SUCCEEDED(ret) && m_State >= WRITING)
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11ClassLinkage(real, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_CLASS_LINKAGE);
Serialise_CreateClassLinkage(&wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppLinkage = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateBlendState(const D3D11_BLEND_DESC *pBlendStateDesc,
ID3D11BlendState **ppBlendState)
{
SERIALISE_ELEMENT_PTR(D3D11_BLEND_DESC, Descriptor, pBlendStateDesc);
SERIALISE_ELEMENT(ResourceId, State, GetIDForResource(*ppBlendState));
if(m_State == READING)
{
ID3D11BlendState *ret;
HRESULT hr = m_pDevice->CreateBlendState(&Descriptor, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret = (ID3D11BlendState *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(State, ret);
}
else
{
ret = new WrappedID3D11BlendState1(ret, this);
GetResourceManager()->AddLiveResource(State, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateBlendState(const D3D11_BLEND_DESC *pBlendStateDesc,
ID3D11BlendState **ppBlendState)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppBlendState == NULL)
return m_pDevice->CreateBlendState(pBlendStateDesc, NULL);
ID3D11BlendState *real = NULL;
HRESULT ret = m_pDevice->CreateBlendState(pBlendStateDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppBlendState = (ID3D11BlendState *)GetResourceManager()->GetWrapper(real);
(*ppBlendState)->AddRef();
return ret;
}
ID3D11BlendState *wrapped = new WrappedID3D11BlendState1(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_BLEND_STATE);
Serialise_CreateBlendState(pBlendStateDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppBlendState = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateDepthStencilState(
const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc, ID3D11DepthStencilState **ppDepthStencilState)
{
SERIALISE_ELEMENT_PTR(D3D11_DEPTH_STENCIL_DESC, Descriptor, pDepthStencilDesc);
SERIALISE_ELEMENT(ResourceId, State, GetIDForResource(*ppDepthStencilState));
if(m_State == READING)
{
ID3D11DepthStencilState *ret;
HRESULT hr = m_pDevice->CreateDepthStencilState(&Descriptor, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret = (ID3D11DepthStencilState *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(State, ret);
}
else
{
ret = new WrappedID3D11DepthStencilState(ret, this);
GetResourceManager()->AddLiveResource(State, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateDepthStencilState(const D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc,
ID3D11DepthStencilState **ppDepthStencilState)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppDepthStencilState == NULL)
return m_pDevice->CreateDepthStencilState(pDepthStencilDesc, NULL);
ID3D11DepthStencilState *real = NULL;
HRESULT ret = m_pDevice->CreateDepthStencilState(pDepthStencilDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppDepthStencilState = (ID3D11DepthStencilState *)GetResourceManager()->GetWrapper(real);
(*ppDepthStencilState)->AddRef();
return ret;
}
ID3D11DepthStencilState *wrapped = new WrappedID3D11DepthStencilState(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_DEPTHSTENCIL_STATE);
Serialise_CreateDepthStencilState(pDepthStencilDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppDepthStencilState = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateRasterizerState(const D3D11_RASTERIZER_DESC *pRasterizerDesc,
ID3D11RasterizerState **ppRasterizerState)
{
SERIALISE_ELEMENT_PTR(D3D11_RASTERIZER_DESC, Descriptor, pRasterizerDesc);
SERIALISE_ELEMENT(ResourceId, State, GetIDForResource(*ppRasterizerState));
if(m_State == READING)
{
ID3D11RasterizerState *ret;
HRESULT hr = m_pDevice->CreateRasterizerState(&Descriptor, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret = (ID3D11RasterizerState *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(State, ret);
}
else
{
ret = new WrappedID3D11RasterizerState2(ret, this);
GetResourceManager()->AddLiveResource(State, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateRasterizerState(const D3D11_RASTERIZER_DESC *pRasterizerDesc,
ID3D11RasterizerState **ppRasterizerState)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppRasterizerState == NULL)
return m_pDevice->CreateRasterizerState(pRasterizerDesc, NULL);
ID3D11RasterizerState *real = NULL;
HRESULT ret = m_pDevice->CreateRasterizerState(pRasterizerDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppRasterizerState = (ID3D11RasterizerState *)GetResourceManager()->GetWrapper(real);
(*ppRasterizerState)->AddRef();
return ret;
}
ID3D11RasterizerState *wrapped = new WrappedID3D11RasterizerState2(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_RASTER_STATE);
Serialise_CreateRasterizerState(pRasterizerDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppRasterizerState = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateSamplerState(const D3D11_SAMPLER_DESC *pSamplerDesc,
ID3D11SamplerState **ppSamplerState)
{
SERIALISE_ELEMENT_PTR(D3D11_SAMPLER_DESC, Descriptor, pSamplerDesc);
SERIALISE_ELEMENT(ResourceId, State, GetIDForResource(*ppSamplerState));
if(m_State == READING)
{
ID3D11SamplerState *ret;
HRESULT hr = m_pDevice->CreateSamplerState(&Descriptor, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
if(GetResourceManager()->HasWrapper(ret))
{
ret = (ID3D11SamplerState *)GetResourceManager()->GetWrapper(ret);
ret->AddRef();
GetResourceManager()->AddLiveResource(State, ret);
}
else
{
ret = new WrappedID3D11SamplerState(ret, this);
GetResourceManager()->AddLiveResource(State, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateSamplerState(const D3D11_SAMPLER_DESC *pSamplerDesc,
ID3D11SamplerState **ppSamplerState)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppSamplerState == NULL)
return m_pDevice->CreateSamplerState(pSamplerDesc, NULL);
ID3D11SamplerState *real = NULL;
HRESULT ret = m_pDevice->CreateSamplerState(pSamplerDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
// duplicate states can be returned, if Create is called with a previous descriptor
if(GetResourceManager()->HasWrapper(real))
{
real->Release();
*ppSamplerState = (ID3D11SamplerState *)GetResourceManager()->GetWrapper(real);
(*ppSamplerState)->AddRef();
return ret;
}
ID3D11SamplerState *wrapped = new WrappedID3D11SamplerState(real, this);
CachedObjectsGarbageCollect();
{
RDCASSERT(m_CachedStateObjects.find(wrapped) == m_CachedStateObjects.end());
wrapped->AddRef();
InternalRef();
m_CachedStateObjects.insert(wrapped);
}
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_SAMPLER_STATE);
Serialise_CreateSamplerState(pSamplerDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppSamplerState = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateQuery(const D3D11_QUERY_DESC *pQueryDesc,
ID3D11Query **ppQuery)
{
SERIALISE_ELEMENT_PTR(D3D11_QUERY_DESC, Descriptor, pQueryDesc);
SERIALISE_ELEMENT(ResourceId, Query, GetIDForResource(*ppQuery));
if(m_State == READING)
{
ID3D11Query *ret;
HRESULT hr = m_pDevice->CreateQuery(&Descriptor, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Query1(ret, this);
GetResourceManager()->AddLiveResource(Query, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateQuery(const D3D11_QUERY_DESC *pQueryDesc, ID3D11Query **ppQuery)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppQuery == NULL)
return m_pDevice->CreateQuery(pQueryDesc, NULL);
ID3D11Query *real = NULL;
HRESULT ret = m_pDevice->CreateQuery(pQueryDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
*ppQuery = new WrappedID3D11Query1(real, this);
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreatePredicate(const D3D11_QUERY_DESC *pPredicateDesc,
ID3D11Predicate **ppPredicate)
{
SERIALISE_ELEMENT_PTR(D3D11_QUERY_DESC, Descriptor, pPredicateDesc);
SERIALISE_ELEMENT(ResourceId, Predicate, GetIDForResource(*ppPredicate));
if(m_State == READING)
{
ID3D11Predicate *ret;
HRESULT hr = m_pDevice->CreatePredicate(&Descriptor, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Predicate(ret, this);
GetResourceManager()->AddLiveResource(Predicate, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreatePredicate(const D3D11_QUERY_DESC *pPredicateDesc,
ID3D11Predicate **ppPredicate)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppPredicate == NULL)
return m_pDevice->CreatePredicate(pPredicateDesc, NULL);
ID3D11Predicate *real = NULL;
ID3D11Predicate *wrapped = NULL;
HRESULT ret = m_pDevice->CreatePredicate(pPredicateDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
wrapped = new WrappedID3D11Predicate(real, this);
if(m_State >= WRITING)
{
SCOPED_SERIALISE_CONTEXT(CREATE_PREDICATE);
Serialise_CreatePredicate(pPredicateDesc, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppPredicate = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateCounter(const D3D11_COUNTER_DESC *pCounterDesc,
ID3D11Counter **ppCounter)
{
SERIALISE_ELEMENT_PTR(D3D11_COUNTER_DESC, Descriptor, pCounterDesc);
SERIALISE_ELEMENT(ResourceId, Counter, GetIDForResource(*ppCounter));
if(m_State == READING)
{
ID3D11Counter *ret;
HRESULT hr = m_pDevice->CreateCounter(&Descriptor, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Counter(ret, this);
GetResourceManager()->AddLiveResource(Counter, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateCounter(const D3D11_COUNTER_DESC *pCounterDesc,
ID3D11Counter **ppCounter)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppCounter == NULL)
return m_pDevice->CreateCounter(pCounterDesc, NULL);
ID3D11Counter *real = NULL;
HRESULT ret = m_pDevice->CreateCounter(pCounterDesc, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
*ppCounter = new WrappedID3D11Counter(real, this);
}
return ret;
}
bool WrappedID3D11Device::Serialise_CreateDeferredContext(const UINT ContextFlags,
ID3D11DeviceContext **ppDeferredContext)
{
SERIALISE_ELEMENT(uint32_t, Flags, ContextFlags);
SERIALISE_ELEMENT(ResourceId, Context, GetIDForResource(*ppDeferredContext));
if(m_State == READING)
{
ID3D11DeviceContext *ret;
HRESULT hr = m_pDevice->CreateDeferredContext(Flags, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11DeviceContext(this, ret, m_pSerialiser);
AddDeferredContext((WrappedID3D11DeviceContext *)ret);
GetResourceManager()->AddLiveResource(Context, ret);
}
}
return true;
}
HRESULT WrappedID3D11Device::CreateDeferredContext(UINT ContextFlags,
ID3D11DeviceContext **ppDeferredContext)
{
// validation, returns S_FALSE for valid params, or an error code
if(ppDeferredContext == NULL)
return m_pDevice->CreateDeferredContext(ContextFlags, NULL);
ID3D11DeviceContext *real = NULL;
ID3D11DeviceContext *wrapped = NULL;
HRESULT ret = m_pDevice->CreateDeferredContext(ContextFlags, &real);
if(SUCCEEDED(ret))
{
SCOPED_LOCK(m_D3DLock);
WrappedID3D11DeviceContext *w = new WrappedID3D11DeviceContext(this, real, m_pSerialiser);
wrapped = w;
if(m_State == WRITING_CAPFRAME)
w->AttemptCapture();
if(m_State >= WRITING)
{
AddDeferredContext(w);
SCOPED_SERIALISE_CONTEXT(CREATE_DEFERRED_CONTEXT);
Serialise_CreateDeferredContext(ContextFlags, &wrapped);
m_DeviceRecord->AddChunk(scope.Get());
}
*ppDeferredContext = wrapped;
}
return ret;
}
bool WrappedID3D11Device::Serialise_OpenSharedResource(HANDLE hResource, REFIID ReturnedInterface,
void **ppResource)
{
SERIALISE_ELEMENT(ResourceType, type, IdentifyTypeByPtr((IUnknown *)*ppResource));
SERIALISE_ELEMENT(ResourceId, pResource, GetIDForResource((ID3D11DeviceChild *)*ppResource));
if(type == Resource_Buffer)
{
D3D11_BUFFER_DESC desc;
RDCEraseEl(desc);
if(m_State >= WRITING)
{
ID3D11Buffer *buf = (ID3D11Buffer *)*ppResource;
buf->GetDesc(&desc);
}
SERIALISE_ELEMENT(D3D11_BUFFER_DESC, Descriptor, desc);
char *dummy = new char[Descriptor.ByteWidth];
SERIALISE_ELEMENT_BUF(byte *, InitialData, dummy, Descriptor.ByteWidth);
delete[] dummy;
uint64_t offs = m_pSerialiser->GetOffset() - Descriptor.ByteWidth;
RDCASSERT((offs % 16) == 0);
if(m_State >= WRITING)
{
RDCASSERT(GetResourceManager()->GetResourceRecord(pResource) == NULL);
D3D11ResourceRecord *record = GetResourceManager()->AddResourceRecord(pResource);
record->SetDataOffset(offs);
record->DataInSerialiser = true;
record->Length = Descriptor.ByteWidth;
}
if(m_State == READING)
{
ID3D11Buffer *ret;
HRESULT hr = S_OK;
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
D3D11_SUBRESOURCE_DATA data;
data.pSysMem = InitialData;
data.SysMemPitch = Descriptor.ByteWidth;
data.SysMemSlicePitch = Descriptor.ByteWidth;
hr = m_pDevice->CreateBuffer(&Descriptor, &data, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Buffer(ret, Descriptor.ByteWidth, this);
GetResourceManager()->AddLiveResource(pResource, ret);
}
if(Descriptor.Usage != D3D11_USAGE_IMMUTABLE)
{
ID3D11Buffer *stage = NULL;
RDCEraseEl(desc);
desc.ByteWidth = Descriptor.ByteWidth;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
// We don't need to bind this, but IMMUTABLE requires at least one
// BindFlags.
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = 0;
desc.Usage = D3D11_USAGE_IMMUTABLE;
hr = m_pDevice->CreateBuffer(&desc, &data, &stage);
if(FAILED(hr) || stage == NULL)
{
RDCERR("Failed to create staging buffer for buffer initial contents %08x", hr);
}
else
{
m_ResourceManager->SetInitialContents(pResource, D3D11ResourceManager::InitialContentData(
stage, eInitialContents_Copy, NULL));
}
}
SAFE_DELETE_ARRAY(InitialData);
}
}
else if(type == Resource_Texture1D)
{
D3D11_TEXTURE1D_DESC desc;
RDCEraseEl(desc);
if(m_State >= WRITING)
{
ID3D11Texture1D *tex = (ID3D11Texture1D *)*ppResource;
tex->GetDesc(&desc);
}
SERIALISE_ELEMENT(D3D11_TEXTURE1D_DESC, Descriptor, desc);
Serialise_CreateTextureData(ppResource ? (ID3D11Texture1D *)*ppResource : NULL, pResource, NULL,
Descriptor.Width, 1, 1, Descriptor.Format, Descriptor.MipLevels,
Descriptor.ArraySize, false);
if(m_State == READING)
{
ID3D11Texture1D *ret;
HRESULT hr = S_OK;
TextureDisplayType dispType = DispTypeForTexture(Descriptor);
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
hr = m_pDevice->CreateTexture1D(&Descriptor, NULL, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Texture1D(ret, this, dispType);
GetResourceManager()->AddLiveResource(pResource, ret);
}
}
}
else if(type == Resource_Texture2D)
{
D3D11_TEXTURE2D_DESC desc;
RDCEraseEl(desc);
if(m_State >= WRITING)
{
ID3D11Texture2D *tex = (ID3D11Texture2D *)*ppResource;
tex->GetDesc(&desc);
}
SERIALISE_ELEMENT(D3D11_TEXTURE2D_DESC, Descriptor, desc);
Serialise_CreateTextureData(ppResource ? (ID3D11Texture2D *)*ppResource : NULL, pResource, NULL,
Descriptor.Width, Descriptor.Height, 1, Descriptor.Format,
Descriptor.MipLevels, Descriptor.ArraySize, false);
if(m_State == READING)
{
ID3D11Texture2D *ret;
HRESULT hr = S_OK;
TextureDisplayType dispType = DispTypeForTexture(Descriptor);
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
hr = m_pDevice->CreateTexture2D(&Descriptor, NULL, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Texture2D1(ret, this, dispType);
GetResourceManager()->AddLiveResource(pResource, ret);
}
}
}
else if(type == Resource_Texture3D)
{
D3D11_TEXTURE3D_DESC desc;
RDCEraseEl(desc);
if(m_State >= WRITING)
{
ID3D11Texture3D *tex = (ID3D11Texture3D *)*ppResource;
tex->GetDesc(&desc);
}
SERIALISE_ELEMENT(D3D11_TEXTURE3D_DESC, Descriptor, desc);
Serialise_CreateTextureData(ppResource ? (ID3D11Texture3D *)*ppResource : NULL, pResource, NULL,
Descriptor.Width, Descriptor.Height, Descriptor.Depth,
Descriptor.Format, Descriptor.MipLevels, 1, false);
if(m_State == READING)
{
ID3D11Texture3D *ret;
HRESULT hr = S_OK;
TextureDisplayType dispType = DispTypeForTexture(Descriptor);
// unset flags that are unimportant/problematic in replay
Descriptor.MiscFlags &=
~(D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX |
D3D11_RESOURCE_MISC_GDI_COMPATIBLE | D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
hr = m_pDevice->CreateTexture3D(&Descriptor, NULL, &ret);
if(FAILED(hr))
{
RDCERR("Failed on resource serialise-creation, HRESULT: 0x%08x", hr);
}
else
{
ret = new WrappedID3D11Texture3D1(ret, this, dispType);
GetResourceManager()->AddLiveResource(pResource, ret);
}
}
}
return true;
}
HRESULT WrappedID3D11Device::OpenSharedResource(HANDLE hResource, REFIID ReturnedInterface,
void **ppResource)
{
if(m_State < WRITING || ppResource == NULL)
return E_INVALIDARG;
bool isDXGIRes = (ReturnedInterface == __uuidof(IDXGIResource) ? true : false);
bool isRes = (ReturnedInterface == __uuidof(ID3D11Resource) ? true : false);
bool isBuf = (ReturnedInterface == __uuidof(ID3D11Buffer) ? true : false);
bool isTex1D = (ReturnedInterface == __uuidof(ID3D11Texture1D) ? true : false);
bool isTex2D = (ReturnedInterface == __uuidof(ID3D11Texture2D) ? true : false);
bool isTex3D = (ReturnedInterface == __uuidof(ID3D11Texture3D) ? true : false);
if(isDXGIRes || isRes || isBuf || isTex1D || isTex2D || isTex3D)
{
void *res = NULL;
HRESULT hr = m_pDevice->OpenSharedResource(hResource, ReturnedInterface, &res);
if(FAILED(hr))
{
IUnknown *unk = (IUnknown *)res;
SAFE_RELEASE(unk);
return hr;
}
else
{
if(isDXGIRes)
{
IDXGIResource *dxgiRes = (IDXGIResource *)res;
ID3D11Resource *d3d11Res = NULL;
hr = dxgiRes->QueryInterface(__uuidof(ID3D11Resource), (void **)&d3d11Res);
// if we can't get a d3d11Res then we can't properly wrap this resource,
// whatever it is.
if(FAILED(hr) || d3d11Res == NULL)
{
SAFE_RELEASE(d3d11Res);
SAFE_RELEASE(dxgiRes);
return E_NOINTERFACE;
}
// release this interface
SAFE_RELEASE(dxgiRes);
// and use this one, so it'll be casted back below
res = (void *)d3d11Res;
isRes = true;
}
SCOPED_LOCK(m_D3DLock);
ResourceId wrappedID;
if(isRes)
{
ID3D11Resource *resource = (ID3D11Resource *)res;
D3D11_RESOURCE_DIMENSION dim;
resource->GetType(&dim);
if(dim == D3D11_RESOURCE_DIMENSION_BUFFER)
{
res = (ID3D11Buffer *)(ID3D11Resource *)res;
isBuf = true;
}
else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE1D)
{
res = (ID3D11Texture1D *)(ID3D11Resource *)res;
isTex1D = true;
}
else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE2D)
{
res = (ID3D11Texture2D *)(ID3D11Resource *)res;
isTex2D = true;
}
else if(dim == D3D11_RESOURCE_DIMENSION_TEXTURE3D)
{
res = (ID3D11Texture3D *)(ID3D11Resource *)res;
isTex3D = true;
}
}
ID3D11Resource *realRes = NULL;
if(isBuf)
{
WrappedID3D11Buffer *w = new WrappedID3D11Buffer((ID3D11Buffer *)res, 0, this);
wrappedID = w->GetResourceID();
realRes = w->GetReal();
*ppResource = (ID3D11Buffer *)w;
}
else if(isTex1D)
{
WrappedID3D11Texture1D *w = new WrappedID3D11Texture1D((ID3D11Texture1D *)res, this);
wrappedID = w->GetResourceID();
realRes = w->GetReal();
*ppResource = (ID3D11Texture1D *)w;
}
else if(isTex2D)
{
WrappedID3D11Texture2D1 *w = new WrappedID3D11Texture2D1((ID3D11Texture2D *)res, this);
wrappedID = w->GetResourceID();
realRes = w->GetReal();
*ppResource = (ID3D11Texture2D *)w;
}
else if(isTex3D)
{
WrappedID3D11Texture3D1 *w = new WrappedID3D11Texture3D1((ID3D11Texture3D *)res, this);
wrappedID = w->GetResourceID();
realRes = w->GetReal();
*ppResource = (ID3D11Texture3D *)w;
}
Chunk *chunk = NULL;
{
SCOPED_SERIALISE_CONTEXT(OPEN_SHARED_RESOURCE);
Serialise_OpenSharedResource(hResource, ReturnedInterface, ppResource);
chunk = scope.Get();
}
// don't know where this came from or who might modify it at any point.
GetResourceManager()->MarkDirtyResource(wrappedID);
D3D11ResourceRecord *record = GetResourceManager()->GetResourceRecord(wrappedID);
RDCASSERT(record);
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
}
return S_OK;
}
return E_NOINTERFACE;
}
HRESULT WrappedID3D11Device::CheckFormatSupport(DXGI_FORMAT Format, UINT *pFormatSupport)
{
return m_pDevice->CheckFormatSupport(Format, pFormatSupport);
}
HRESULT WrappedID3D11Device::CheckMultisampleQualityLevels(DXGI_FORMAT Format, UINT SampleCount,
UINT *pNumQualityLevels)
{
return m_pDevice->CheckMultisampleQualityLevels(Format, SampleCount, pNumQualityLevels);
}
void WrappedID3D11Device::CheckCounterInfo(D3D11_COUNTER_INFO *pCounterInfo)
{
m_pDevice->CheckCounterInfo(pCounterInfo);
}
HRESULT WrappedID3D11Device::CheckCounter(const D3D11_COUNTER_DESC *pDesc, D3D11_COUNTER_TYPE *pType,
UINT *pActiveCounters, LPSTR szName, UINT *pNameLength,
LPSTR szUnits, UINT *pUnitsLength, LPSTR szDescription,
UINT *pDescriptionLength)
{
return m_pDevice->CheckCounter(pDesc, pType, pActiveCounters, szName, pNameLength, szUnits,
pUnitsLength, szDescription, pDescriptionLength);
}
HRESULT WrappedID3D11Device::CheckFeatureSupport(D3D11_FEATURE Feature, void *pFeatureSupportData,
UINT FeatureSupportDataSize)
{
return m_pDevice->CheckFeatureSupport(Feature, pFeatureSupportData, FeatureSupportDataSize);
}
HRESULT WrappedID3D11Device::GetPrivateData(REFGUID guid, UINT *pDataSize, void *pData)
{
return m_pDevice->GetPrivateData(guid, pDataSize, pData);
}
HRESULT WrappedID3D11Device::SetPrivateData(REFGUID guid, UINT DataSize, const void *pData)
{
return m_pDevice->SetPrivateData(guid, DataSize, pData);
}
HRESULT WrappedID3D11Device::SetPrivateDataInterface(REFGUID guid, const IUnknown *pData)
{
return m_pDevice->SetPrivateDataInterface(guid, pData);
}
D3D_FEATURE_LEVEL WrappedID3D11Device::GetFeatureLevel()
{
return m_pDevice->GetFeatureLevel();
}
UINT WrappedID3D11Device::GetCreationFlags()
{
return m_pDevice->GetCreationFlags();
}
HRESULT WrappedID3D11Device::GetDeviceRemovedReason()
{
return m_pDevice->GetDeviceRemovedReason();
}
void WrappedID3D11Device::GetImmediateContext(ID3D11DeviceContext **ppImmediateContext)
{
if(ppImmediateContext)
{
*ppImmediateContext = (ID3D11DeviceContext *)m_pImmediateContext;
m_pImmediateContext->AddRef();
}
}
bool WrappedID3D11Device::Serialise_SetExceptionMode(UINT RaiseFlags)
{
SERIALISE_ELEMENT(uint32_t, Flags, RaiseFlags);
if(m_State == READING)
{
m_pDevice->SetExceptionMode(Flags);
}
return true;
}
HRESULT WrappedID3D11Device::SetExceptionMode(UINT RaiseFlags)
{
HRESULT ret = m_pDevice->SetExceptionMode(RaiseFlags);
if(SUCCEEDED(ret) && m_State >= WRITING)
{
SCOPED_LOCK(m_D3DLock);
SCOPED_SERIALISE_CONTEXT(SET_EXCEPTION_MODE);
Serialise_SetExceptionMode(RaiseFlags);
m_DeviceRecord->AddChunk(scope.Get());
}
return ret;
}
UINT WrappedID3D11Device::GetExceptionMode()
{
return m_pDevice->GetExceptionMode();
}
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*============================================================================
**
** Source: test16.c
**
** Purpose:Tests sscanf_s with floats (compact notation, lowercase)
**
**
**==========================================================================*/
#include <palsuite.h>
#include "../sscanf_s.h"
PALTEST(c_runtime_sscanf_s_test16_paltest_sscanf_test16, "c_runtime/sscanf_s/test16/paltest_sscanf_test16")
{
if (PAL_Initialize(argc, argv))
{
return FAIL;
}
DoFloatTest("123.0", "%g", 123.0f);
DoFloatTest("123.0", "%2g", 12.0f);
DoFloatTest("10E1", "%g", 100.0f);
DoFloatTest("-12.01e-2", "%g", -0.1201f);
DoFloatTest("+12.01e-2", "%g", 0.1201f);
DoFloatTest("-12.01e+2", "%g", -1201.0f);
DoFloatTest("+12.01e+2", "%g", 1201.0f);
DoFloatTest("1234567890.0123456789g", "%g", 1234567936);
PAL_Terminate();
return PASS;
}
|
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
// Copyright (c) 2016 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef HPX_PROCESS_WINDOWS_INITIALIZERS_HIDE_CONSOLE_HPP
#define HPX_PROCESS_WINDOWS_INITIALIZERS_HIDE_CONSOLE_HPP
#include <hpx/config.hpp>
#if defined(HPX_WINDOWS)
#include <hpx/components/process/util/windows/initializers/initializer_base.hpp>
#include <windows.h>
namespace hpx { namespace components { namespace process { namespace windows {
namespace initializers {
class hide_console : public initializer_base
{
public:
template <class WindowsExecutor>
void on_CreateProcess_setup(WindowsExecutor &e) const
{
e.startup_info.dwFlags |= STARTF_USESHOWWINDOW;
e.startup_info.wShowWindow |= SW_HIDE;
}
};
}
}}}}
#endif
#endif
|
/**
* @file
* @copyright defined in evt/LICENSE.txt
*/
#pragma once
#include <fc/container/flat_fwd.hpp>
#include <fc/static_variant.hpp>
#include <fc/optional.hpp>
#include <fc/variant.hpp>
#include <fc/reflect/reflect.hpp>
#include <fc/crypto/sha256.hpp>
#include <evt/chain/types.hpp>
namespace evt { namespace chain { namespace contracts {
class evt_link {
public:
struct segment {
segment() = default;
segment(uint8_t key, uint32_t intv)
: key(key), intv(intv) {}
segment(uint8_t key, const std::string& strv)
: key(key), strv(strv) {}
uint8_t key;
fc::optional<uint32_t> intv;
fc::optional<std::string> strv;
};
public:
enum type_id {
timestamp = 42,
max_pay = 43,
symbol_id = 44,
domain = 91,
token = 92,
max_pay_str = 94,
address = 95,
link_id = 156
};
enum flag {
version1 = 1,
everiPass = 2,
everiPay = 4,
destroy = 8
};
public:
static evt_link parse_from_evtli(const std::string& str);
std::string to_string(int prefix = 0) const;
public:
uint16_t get_header() const { return header_; }
const segment& get_segment(uint8_t key) const;
bool has_segment(uint8_t key) const;
const link_id_type& get_link_id() const;
const fc::flat_map<uint8_t, segment>& get_segments() const { return segments_; }
const fc::flat_set<signature_type>& get_signatures() const {return signatures_; }
public:
void set_header(uint16_t header) { header_ = header; }
void add_segment(const segment&);
void add_signature(const signature_type&);
void clear_signatures() { signatures_.clear(); }
void sign(const private_key_type&);
public:
fc::sha256 digest() const;
fc::flat_set<public_key_type> restore_keys() const;
private:
uint16_t header_;
fc::flat_map<uint8_t, segment> segments_;
fc::flat_set<signature_type> signatures_;
private:
friend struct fc::reflector<evt_link>;
};
}}} // namespac evt::chain::contracts
namespace fc {
class variant;
void to_variant(const evt::chain::contracts::evt_link& link, fc::variant& v);
void from_variant(const fc::variant& v, evt::chain::contracts::evt_link& link);
} // namespace fc
FC_REFLECT(evt::chain::contracts::evt_link::segment, (key)(intv)(strv));
FC_REFLECT(evt::chain::contracts::evt_link, (header_)(segments_)(signatures_));
|
// EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois,
// The Regents of the University of California, through Lawrence Berkeley National Laboratory
// (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge
// National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other
// contributors. All rights reserved.
//
// NOTICE: This Software was developed under funding from the U.S. Department of Energy and the
// U.S. Government consequently retains certain rights. As such, the U.S. Government has been
// granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable,
// worldwide license in the Software to reproduce, distribute copies to the public, prepare
// derivative works, and perform publicly and display publicly, and to permit others to do so.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory,
// the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form
// without changes from the version obtained under this License, or (ii) Licensee makes a
// reference solely to the software portion of its product, Licensee must refer to the
// software as "EnergyPlus version X" software, where "X" is the version number Licensee
// obtained under this License and may not use a different name for the software. Except as
// specifically required in this Section (4), Licensee shall not use in a company name, a
// product name, in advertising, publicity, or other promotional activities any name, trade
// name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly
// similar designation, without the U.S. Department of Energy's prior written consent.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ObjexxFCL Headers
#include <ObjexxFCL/string.functions.hh>
// EnergyPlus Headers
#include <DataPrecisionGlobals.hh>
#include <DataRuntimeLanguage.hh>
#include <UtilityRoutines.hh>
namespace EnergyPlus {
// Data only module for EMS runtime language
namespace DataRuntimeLanguage {
// MODULE INFORMATION:
// AUTHOR Peter Graham Ellis
// DATE WRITTEN June 2006
// MODIFIED Brent Griffith, May 2009
// RE-ENGINEERED na
// PURPOSE OF THIS MODULE:
// METHODOLOGY EMPLOYED: na
// Using/Aliasing
using namespace DataPrecisionGlobals;
// Data
// module should be available to other modules and routines.
// Thus, all variables in this module must be PUBLIC.
// MODULE PARAMETER DEFINITIONS:
int const ValueNull(0); // Erl entity type, "Null" value
int const ValueNumber(1); // Erl entity type, hard numeric value
int const ValueString(2); // Erl entity type, character data
int const ValueArray(3); // Erl entity type, not used yet, for future array type
int const ValueVariable(4); // Erl entity type, Erl variable
int const ValueExpression(5); // Erl entity type, Erl expression
int const ValueTrend(6); // Erl entity type, Erl trend variable
int const ValueError(7); // Erl entity type, processing of an expression failed, returned error
int const PntrReal(301); // data type for overloaded pointer management, double real
int const PntrInteger(302); // data type for overloaded pointer management, integer
int const PntrLogical(303); // data type for overloaded pointer management, logical
int const MaxWhileLoopIterations(1000000); // protect from infinite loop in WHILE loops
// Parameters for identifying operator types in Erl
// The number of these parameters indicates the order of precedence
int const OperatorLiteral(1); // Just stores a literal value
int const OperatorNegative(2); // - (unary) No LHS?
int const OperatorDivide(3); // /
int const OperatorMultiply(4); // *
int const OperatorSubtract(5); // - (binary)
int const OperatorAdd(6); // + (binary)
int const OperatorEqual(7); // ==
int const OperatorNotEqual(8); // <>
int const OperatorLessOrEqual(9); // <=
int const OperatorGreaterOrEqual(10); // >=
int const OperatorLessThan(11); // <
int const OperatorGreaterThan(12); // >
int const OperatorRaiseToPower(13); // ^
int const OperatorLogicalAND(14); // &&
int const OperatiorLogicalOR(15); // ||
// note there is an important check "> 15" to distinguish operators from functions
// so becareful if renumber these parameters. Binary operator additions should get inserted here rather than appended
// parameters for built-in Erl functions, these are processed like operators and numbering
// must be sequential with the operators.
// math functions
int const FuncRound(16); // accessor for Fortran's DNINT()
int const FuncMod(17); // accessor for Fortran's MOD()
int const FuncSin(18); // accessor for Fortran's SIN()
int const FuncCos(19); // accessor for Fortran's COS()
int const FuncArcSin(20); // accessor for Fortran's ASIN()
int const FuncArcCos(21); // accessor for Fortran's ACOS()
int const FuncDegToRad(22); // Multiplies degrees by DegToRad
int const FuncRadToDeg(23); // Divides radians by DegToRad
int const FuncExp(24); // accessor for Fortran's EXP()
int const FuncLn(25); // accessor for Fortran's LOG()
int const FuncMax(26); // accessor for Fortran's MAX()
int const FuncMin(27); // accessor for Fortran's MIN()
int const FuncABS(28); // accessor for Fortran's ABS()
int const FuncRandU(29); // accessor for Fortran's Random_Number() intrinsic, uniform distribution
int const FuncRandG(30); // accessor for Gaussian/normal distribution random number
int const FuncRandSeed(31); // accessor for Fortran's Random_Seed() intrinsic
// begin psychrometric routines
int const FuncRhoAirFnPbTdbW(32); // accessor for E+ psych routine
int const FuncCpAirFnWTdb(33); // accessor for E+ psych routine
int const FuncHfgAirFnWTdb(34); // accessor for E+ psych routine
int const FuncHgAirFnWTdb(35); // accessor for E+ psych routine
int const FuncTdpFnTdbTwbPb(36); // accessor for E+ psych routine
int const FuncTdpFnWPb(37); // accessor for E+ psych routine
int const FuncHFnTdbW(38); // accessor for E+ psych routine
int const FuncHFnTdbRhPb(39); // accessor for E+ psych routine
int const FuncTdbFnHW(40); // accessor for E+ psych routine
int const FuncRhovFnTdbRh(41); // accessor for E+ psych routine
int const FuncRhovFnTdbRhLBnd0C(42); // accessor for E+ psych routine
int const FuncRhovFnTdbWPb(43); // accessor for E+ psych routine
int const FuncRhFnTdbRhov(44); // accessor for E+ psych routine
int const FuncRhFnTdbRhovLBnd0C(45); // accessor for E+ psych routine
int const FuncRhFnTdbWPb(46); // accessor for E+ psych routine
int const FuncTwbFnTdbWPb(47); // accessor for E+ psych routine
int const FuncVFnTdbWPb(48); // accessor for E+ psych routine
int const FuncWFnTdpPb(49); // accessor for E+ psych routine
int const FuncWFnTdbH(50); // accessor for E+ psych routine
int const FuncWFnTdbTwbPb(51); // accessor for E+ psych routine
int const FuncWFnTdbRhPb(52); // accessor for E+ psych routine
int const FuncPsatFnTemp(53); // accessor for E+ psych routine
int const FuncTsatFnHPb(54); // accessor for E+ psych routine
int const FuncTsatFnPb(55); // not public in PsychRoutines.cc so not really available in EMS.
int const FuncCpCW(56); // accessor for E+ psych routine
int const FuncCpHW(57); // accessor for E+ psych routine
int const FuncRhoH2O(58); // accessor for E+ psych routine
// Simulation Management Functions
int const FuncFatalHaltEp(59); // accessor for E+ error management, "Fatal" level
int const FuncSevereWarnEp(60); // accessor for E+ error management, "Severe" level
int const FuncWarnEp(61); // accessor for E+ error management, "Warning" level
// Trend variable handling Functions
int const FuncTrendValue(62); // accessor for Erl Trend variables, instance value
int const FuncTrendAverage(63); // accessor for Erl Trend variables, average value
int const FuncTrendMax(64); // accessor for Erl Trend variables, max value
int const FuncTrendMin(65); // accessor for Erl Trend variables, min value
int const FuncTrendDirection(66); // accessor for Erl Trend variables, slope value
int const FuncTrendSum(67); // accessor for Erl Trend variables, sum value
// Curve and Table access function
int const FuncCurveValue(68);
int const NumPossibleOperators(68); // total number of operators and built-in functions
// DERIVED TYPE DEFINITIONS:
// MODULE VARIABLE TYPE DECLARATIONS:
// INTERFACE BLOCK SPECIFICATIONS: na
// MODULE VARIABLE DECLARATIONS:
Array1D_int EMSProgram;
int NumProgramCallManagers(0); // count of Erl program managers with calling points
int NumSensors(0); // count of EMS sensors used in model (data from output variables)
int numActuatorsUsed(0); // count of EMS actuators used in model
int numEMSActuatorsAvailable(0); // count of EMS actuators available for use in such a model
int maxEMSActuatorsAvailable(0); // count of EMS current maximum actuators available for use in such a model
int NumInternalVariablesUsed(0); // count of EMS internal variables used in model
int numEMSInternalVarsAvailable(0); // count of EMS internal variables available for use in such a model
int maxEMSInternalVarsAvailable(0); // count of EMS current maximum internal variables available for use in such a model
int varsAvailableAllocInc(1000); // allocation increment for variable arrays
int NumErlPrograms(0); // count of Erl programs in model
int NumErlSubroutines(0); // count of Erl subroutines in model
int NumUserGlobalVariables(0); // count of global EMS variables defined by user
int NumErlVariables(0); // count of Erl variables
int NumErlStacks(0); // count of Erl program stacks in model. sum of programs and subroutines
int NumExpressions(0); // count of Erl expressions
int NumEMSOutputVariables(0); // count of EMS output variables, custom output variables from Erl
int NumEMSMeteredOutputVariables(0); // count of EMS metered output variables, custom meters from Erl
int NumErlTrendVariables(0); // count of EMS trend variables in model
int NumEMSCurveIndices(0); // count of EMS curve index variables in model
int NumEMSConstructionIndices(0); // count of EMS construction index variables in model
//######################################################################################################################################
// code for ExternalInterface
int NumExternalInterfaceGlobalVariables(0); // count of ExternalInterface runtime variable
int NumExternalInterfaceFunctionalMockupUnitImportGlobalVariables(0); // count of ExternalInterface runtime variable for FMUImport
// will be updated with values from ExternalInterface
int NumExternalInterfaceFunctionalMockupUnitExportGlobalVariables(0); // count of ExternalInterface runtime variable for FMUExport
// will be updated with values from ExternalInterface
int NumExternalInterfaceActuatorsUsed(0); // count of ExternalInterface Actuators
int NumExternalInterfaceFunctionalMockupUnitImportActuatorsUsed(0); // count of ExternalInterface Actuators for FMUImport
int NumExternalInterfaceFunctionalMockupUnitExportActuatorsUsed(0); // count of ExternalInterface Actuators for FMUExport
//######################################################################################################################################
int OutputEMSFileUnitNum(0); // file lun handle for open EMS output file
bool OutputEDDFile(false); // set to true if user requests EDD output file be written
bool OutputFullEMSTrace(false); // how much to write out to trace, if true do verbose for each line
bool OutputEMSErrors(false); // how much to write out to trace, if true include Erl error messages
bool OutputEMSActuatorAvailFull(false); // how much to write out to EDD file, if true dump full combinatorial actuator list
bool OutputEMSActuatorAvailSmall(false); // how much to write out to EDD file, if true dump actuator list without key names
bool OutputEMSInternalVarsFull(false); // how much to write out to EDD file, if true dump full combinatorial internal list
bool OutputEMSInternalVarsSmall(false); // how much to write out to EDD file, if true dump internal list without key names
Array2D_bool EMSConstructActuatorChecked;
Array2D_bool EMSConstructActuatorIsOkay;
// Object Data
Array1D<ErlVariableType> ErlVariable; // holds Erl variables in a structure array
Array1D<ErlStackType> ErlStack; // holds Erl programs in separate "stacks"
Array1D<ErlExpressionType> ErlExpression; // holds Erl expressions in structure array
Array1D<OperatorType> PossibleOperators; // hard library of available operators and functions
Array1D<TrendVariableType> TrendVariable; // holds Erl trend varialbes in a structure array
Array1D<OutputVarSensorType> Sensor; // EMS:SENSOR objects used (from output variables)
Array1D<EMSActuatorAvailableType> EMSActuatorAvailable; // actuators that could be used
Array1D<ActuatorUsedType> EMSActuatorUsed; // actuators that are used
Array1D<InternalVarsAvailableType> EMSInternalVarsAvailable; // internal data that could be used
Array1D<InternalVarsUsedType> EMSInternalVarsUsed; // internal data that are used
Array1D<EMSProgramCallManagementType> EMSProgramCallManager; // program calling managers
ErlValueType Null(0, 0.0, "", 0, 0, false, 0, "", true); // special "null" Erl variable value instance
ErlValueType False(0, 0.0, "", 0, 0, false, 0, "", true); // special "false" Erl variable value instance
ErlValueType True(0, 0.0, "", 0, 0, false, 0, "", true); // special "True" Erl variable value instance, gets reset
// EMS Actuator fast duplicate check lookup support
std::unordered_set<std::tuple<std::string, std::string, std::string>, EMSActuatorKey_hash> EMSActuator_lookup; // Fast duplicate lookup structure
// Functions
void clear_state()
{
EMSProgram.deallocate();
NumProgramCallManagers = 0;
NumSensors = 0;
numActuatorsUsed = 0;
numEMSActuatorsAvailable = 0;
maxEMSActuatorsAvailable = 0;
NumInternalVariablesUsed = 0;
numEMSInternalVarsAvailable = 0;
maxEMSInternalVarsAvailable = 0;
varsAvailableAllocInc = 1000;
NumErlPrograms = 0;
NumErlSubroutines = 0;
NumUserGlobalVariables = 0;
NumErlVariables = 0;
NumErlStacks = 0;
NumExpressions = 0;
NumEMSOutputVariables = 0;
NumEMSMeteredOutputVariables = 0;
NumErlTrendVariables = 0;
NumEMSCurveIndices = 0;
NumEMSConstructionIndices = 0;
NumExternalInterfaceGlobalVariables = 0;
NumExternalInterfaceFunctionalMockupUnitImportGlobalVariables = 0;
NumExternalInterfaceFunctionalMockupUnitExportGlobalVariables = 0;
NumExternalInterfaceActuatorsUsed = 0;
NumExternalInterfaceFunctionalMockupUnitImportActuatorsUsed = 0;
NumExternalInterfaceFunctionalMockupUnitExportActuatorsUsed = 0;
OutputEMSFileUnitNum = 0;
OutputEDDFile = false;
OutputFullEMSTrace = false;
OutputEMSErrors = false;
OutputEMSActuatorAvailFull = false;
OutputEMSActuatorAvailSmall = false;
OutputEMSInternalVarsFull = false;
OutputEMSInternalVarsSmall = false;
EMSConstructActuatorChecked.deallocate();
EMSConstructActuatorIsOkay.deallocate();
ErlVariable.deallocate(); // holds Erl variables in a structure array
ErlStack.deallocate(); // holds Erl programs in separate "stacks"
ErlExpression.deallocate(); // holds Erl expressions in structure array
PossibleOperators.deallocate(); // hard library of available operators and functions
TrendVariable.deallocate(); // holds Erl trend varialbes in a structure array
Sensor.deallocate(); // EMS:SENSOR objects used (from output variables)
EMSActuatorAvailable.deallocate(); // actuators that could be used
EMSActuatorUsed.deallocate(); // actuators that are used
EMSInternalVarsAvailable.deallocate(); // internal data that could be used
EMSInternalVarsUsed.deallocate(); // internal data that are used
EMSProgramCallManager.deallocate(); // program calling managers
EMSActuator_lookup.clear(); // Fast duplicate lookup structure
}
void ValidateEMSVariableName(std::string const &cModuleObject, // the current object name
std::string const &cFieldValue, // the field value
std::string const &cFieldName, // the current field name
bool &errFlag, // true if errors found in this routine.
bool &ErrorsFound // true if errors found in this routine.
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda Lawrie
// DATE WRITTEN May 2012
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// Consolidate error checking on EMS variable names.
// METHODOLOGY EMPLOYED:
// na
// REFERENCES:
// na
// Using/Aliasing
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
static std::string const InvalidStartCharacters("0123456789");
// INTERFACE BLOCK SPECIFICATIONS:
// na
// DERIVED TYPE DEFINITIONS:
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
errFlag = false;
if (has(cFieldValue, ' ')) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used as EMS variables cannot contain spaces");
errFlag = true;
ErrorsFound = true;
}
if (has(cFieldValue, '-')) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used as EMS variables cannot contain \"-\" characters.");
errFlag = true;
ErrorsFound = true;
}
if (has(cFieldValue, '+')) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used as EMS variables cannot contain \"+\" characters.");
errFlag = true;
ErrorsFound = true;
}
if (has(cFieldValue, '.')) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used as EMS variables cannot contain \".\" characters.");
errFlag = true;
ErrorsFound = true;
}
if ((cFieldValue.length() > 0) && (has_any_of(cFieldValue[0], InvalidStartCharacters))) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used as EMS variables cannot start with numeric characters.");
errFlag = true;
ErrorsFound = true;
}
}
void ValidateEMSProgramName(std::string const &cModuleObject, // the current object name
std::string const &cFieldValue, // the field value
std::string const &cFieldName, // the current field name
std::string const &cSubType, // sub type = Program or Subroutine
bool &errFlag, // true if errors found in this routine.
bool &ErrorsFound // true if errors found in this routine.
)
{
// SUBROUTINE INFORMATION:
// AUTHOR Linda Lawrie
// DATE WRITTEN May 2012
// MODIFIED na
// RE-ENGINEERED na
// PURPOSE OF THIS SUBROUTINE:
// Consolidate error checking on EMS variable names.
// METHODOLOGY EMPLOYED:
// na
// REFERENCES:
// na
// Using/Aliasing
// Locals
// SUBROUTINE ARGUMENT DEFINITIONS:
// SUBROUTINE PARAMETER DEFINITIONS:
static std::string const InvalidStartCharacters("0123456789");
// INTERFACE BLOCK SPECIFICATIONS:
// na
// DERIVED TYPE DEFINITIONS:
// na
// SUBROUTINE LOCAL VARIABLE DECLARATIONS:
// INTEGER :: pos
errFlag = false;
if (has(cFieldValue, ' ')) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used for EMS " + cSubType + " cannot contain spaces");
errFlag = true;
ErrorsFound = true;
}
if (has(cFieldValue, '-')) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used for EMS " + cSubType + " cannot contain \"-\" characters.");
errFlag = true;
ErrorsFound = true;
}
if (has(cFieldValue, '+')) {
ShowSevereError(cModuleObject + "=\"" + cFieldValue + "\", Invalid variable name entered.");
ShowContinueError("..." + cFieldName + "; Names used for EMS " + cSubType + " cannot contain \"+\" characters.");
errFlag = true;
ErrorsFound = true;
}
// pos=SCAN(cFieldValue(1:1),InvalidStartCharacters)
// IF (pos > 0) THEN
// CALL ShowSevereError(TRIM(cModuleObject)//'="'//TRIM(cFieldValue)//'", Invalid variable name entered.')
// CALL ShowContinueError('...'//TRIM(cFieldName)//'; Names used as EMS variables cannot start with numeric characters.')
// errFlag=.TRUE.
// ErrorsFound = .TRUE.
// ENDIF
}
} // namespace DataRuntimeLanguage
} // namespace EnergyPlus
|
#include <gtest/gtest.h>
#include <ecfw/world.hpp>
TEST(world, is_valid)
{
ecfw::world world{};
auto valid_entity = world.create();
ASSERT_TRUE(world.is_valid(valid_entity));
uint32_t invalid_entity = 0xDEADBEEF;
ASSERT_FALSE(world.is_valid(invalid_entity));
}
|
#include <iostream>
#include <Transformer.h>
#include <boost/test/unit_test.hpp>
using namespace esrocos::transformer;
typedef AcyclicTransformer<> atf20_20;
BOOST_AUTO_TEST_SUITE(transformation_tests)
BOOST_AUTO_TEST_CASE(transform_construction)
{
atf20_20::Transformation t;
BOOST_CHECK_EQUAL(0,std::strcmp(t.a(),""));
BOOST_CHECK_EQUAL(0,std::strcmp(t.b(),""));
BOOST_CHECK_EQUAL(0,std::strcmp(t.id(),""));
BOOST_CHECK_EQUAL(true,identity.isApprox(t.atob()));
BOOST_CHECK_EQUAL(true,identity.isApprox(t.atob()));
}
BOOST_AUTO_TEST_CASE(transform_initialization)
{
const char * a = "from";
const char * b = "to";
const char * id = "some_id";
atf20_20::Transformation t(a,b,id);
BOOST_CHECK_EQUAL(0,std::strcmp(t.a(),a));
BOOST_CHECK_EQUAL(0,std::strcmp(t.b(),b));
BOOST_CHECK_EQUAL(0,std::strcmp(t.id(),id));
BOOST_CHECK_EQUAL(true,identity.isApprox(t.atob()));
BOOST_CHECK_EQUAL(true,identity.isApprox(t.atob()));
}
BOOST_AUTO_TEST_SUITE_END()
|
/**
* \file PnlWznmMtdList_blks.cpp
* job handler for job PnlWznmMtdList (implementation of blocks)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class PnlWznmMtdList::VecVDo
******************************************************************************/
uint PnlWznmMtdList::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "butminimizeclick") return BUTMINIMIZECLICK;
if (s == "butregularizeclick") return BUTREGULARIZECLICK;
if (s == "butnewclick") return BUTNEWCLICK;
if (s == "butdeleteclick") return BUTDELETECLICK;
if (s == "butfilterclick") return BUTFILTERCLICK;
if (s == "butrefreshclick") return BUTREFRESHCLICK;
return(0);
};
string PnlWznmMtdList::VecVDo::getSref(
const uint ix
) {
if (ix == BUTMINIMIZECLICK) return("ButMinimizeClick");
if (ix == BUTREGULARIZECLICK) return("ButRegularizeClick");
if (ix == BUTNEWCLICK) return("ButNewClick");
if (ix == BUTDELETECLICK) return("ButDeleteClick");
if (ix == BUTFILTERCLICK) return("ButFilterClick");
if (ix == BUTREFRESHCLICK) return("ButRefreshClick");
return("");
};
/******************************************************************************
class PnlWznmMtdList::ContIac
******************************************************************************/
PnlWznmMtdList::ContIac::ContIac(
const uint numFTos
) :
Block()
{
this->numFTos = numFTos;
mask = {NUMFTOS};
};
bool PnlWznmMtdList::ContIac::readJSON(
Json::Value& sup
, bool addbasetag
) {
clear();
bool basefound;
Json::Value& me = sup;
if (addbasetag) me = sup["ContIacWznmMtdList"];
basefound = (me != Json::nullValue);
if (basefound) {
if (me.isMember("numFTos")) {numFTos = me["numFTos"].asUInt(); add(NUMFTOS);};
};
return basefound;
};
bool PnlWznmMtdList::ContIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContIacWznmMtdList");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemIacWznmMtdList";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFTos", numFTos)) add(NUMFTOS);
};
return basefound;
};
void PnlWznmMtdList::ContIac::writeJSON(
Json::Value& sup
, string difftag
) {
if (difftag.length() == 0) difftag = "ContIacWznmMtdList";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
me["numFTos"] = numFTos;
};
void PnlWznmMtdList::ContIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContIacWznmMtdList";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemIacWznmMtdList";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "numFTos", numFTos);
xmlTextWriterEndElement(wr);
};
set<uint> PnlWznmMtdList::ContIac::comm(
const ContIac* comp
) {
set<uint> items;
if (numFTos == comp->numFTos) insert(items, NUMFTOS);
return(items);
};
set<uint> PnlWznmMtdList::ContIac::diff(
const ContIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFTOS};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmMtdList::ContInf
******************************************************************************/
PnlWznmMtdList::ContInf::ContInf(
const string& TxtFor
, const string& TxtPre
, const bool ButFilterOn
, const uint numFCsiQst
) :
Block()
{
this->TxtFor = TxtFor;
this->TxtPre = TxtPre;
this->ButFilterOn = ButFilterOn;
this->numFCsiQst = numFCsiQst;
mask = {TXTFOR, TXTPRE, BUTFILTERON, NUMFCSIQST};
};
void PnlWznmMtdList::ContInf::writeJSON(
Json::Value& sup
, string difftag
) {
if (difftag.length() == 0) difftag = "ContInfWznmMtdList";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
me["TxtFor"] = TxtFor;
me["TxtPre"] = TxtPre;
me["ButFilterOn"] = ButFilterOn;
me["numFCsiQst"] = numFCsiQst;
};
void PnlWznmMtdList::ContInf::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "ContInfWznmMtdList";
string itemtag;
if (shorttags) itemtag = "Ci";
else itemtag = "ContitemInfWznmMtdList";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeStringAttr(wr, itemtag, "sref", "TxtFor", TxtFor);
writeStringAttr(wr, itemtag, "sref", "TxtPre", TxtPre);
writeBoolAttr(wr, itemtag, "sref", "ButFilterOn", ButFilterOn);
writeUintAttr(wr, itemtag, "sref", "numFCsiQst", numFCsiQst);
xmlTextWriterEndElement(wr);
};
set<uint> PnlWznmMtdList::ContInf::comm(
const ContInf* comp
) {
set<uint> items;
if (TxtFor == comp->TxtFor) insert(items, TXTFOR);
if (TxtPre == comp->TxtPre) insert(items, TXTPRE);
if (ButFilterOn == comp->ButFilterOn) insert(items, BUTFILTERON);
if (numFCsiQst == comp->numFCsiQst) insert(items, NUMFCSIQST);
return(items);
};
set<uint> PnlWznmMtdList::ContInf::diff(
const ContInf* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {TXTFOR, TXTPRE, BUTFILTERON, NUMFCSIQST};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmMtdList::StatShr
******************************************************************************/
PnlWznmMtdList::StatShr::StatShr(
const uint ixWznmVExpstate
, const bool ButDeleteActive
) :
Block()
{
this->ixWznmVExpstate = ixWznmVExpstate;
this->ButDeleteActive = ButDeleteActive;
mask = {IXWZNMVEXPSTATE, BUTDELETEACTIVE};
};
void PnlWznmMtdList::StatShr::writeJSON(
Json::Value& sup
, string difftag
) {
if (difftag.length() == 0) difftag = "StatShrWznmMtdList";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
me["srefIxWznmVExpstate"] = VecWznmVExpstate::getSref(ixWznmVExpstate);
me["ButDeleteActive"] = ButDeleteActive;
};
void PnlWznmMtdList::StatShr::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "StatShrWznmMtdList";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StatitemShrWznmMtdList";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeStringAttr(wr, itemtag, "sref", "srefIxWznmVExpstate", VecWznmVExpstate::getSref(ixWznmVExpstate));
writeBoolAttr(wr, itemtag, "sref", "ButDeleteActive", ButDeleteActive);
xmlTextWriterEndElement(wr);
};
set<uint> PnlWznmMtdList::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (ixWznmVExpstate == comp->ixWznmVExpstate) insert(items, IXWZNMVEXPSTATE);
if (ButDeleteActive == comp->ButDeleteActive) insert(items, BUTDELETEACTIVE);
return(items);
};
set<uint> PnlWznmMtdList::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {IXWZNMVEXPSTATE, BUTDELETEACTIVE};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmMtdList::StgIac
******************************************************************************/
PnlWznmMtdList::StgIac::StgIac(
const uint TcoSrfWidth
, const uint TcoJobWidth
, const uint TcoExsWidth
) :
Block()
{
this->TcoSrfWidth = TcoSrfWidth;
this->TcoJobWidth = TcoJobWidth;
this->TcoExsWidth = TcoExsWidth;
mask = {TCOSRFWIDTH, TCOJOBWIDTH, TCOEXSWIDTH};
};
bool PnlWznmMtdList::StgIac::readJSON(
Json::Value& sup
, bool addbasetag
) {
clear();
bool basefound;
Json::Value& me = sup;
if (addbasetag) me = sup["StgIacWznmMtdList"];
basefound = (me != Json::nullValue);
if (basefound) {
if (me.isMember("TcoSrfWidth")) {TcoSrfWidth = me["TcoSrfWidth"].asUInt(); add(TCOSRFWIDTH);};
if (me.isMember("TcoJobWidth")) {TcoJobWidth = me["TcoJobWidth"].asUInt(); add(TCOJOBWIDTH);};
if (me.isMember("TcoExsWidth")) {TcoExsWidth = me["TcoExsWidth"].asUInt(); add(TCOEXSWIDTH);};
};
return basefound;
};
bool PnlWznmMtdList::StgIac::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StgIacWznmMtdList");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StgitemIacWznmMtdList";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoSrfWidth", TcoSrfWidth)) add(TCOSRFWIDTH);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoJobWidth", TcoJobWidth)) add(TCOJOBWIDTH);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoExsWidth", TcoExsWidth)) add(TCOEXSWIDTH);
};
return basefound;
};
void PnlWznmMtdList::StgIac::writeJSON(
Json::Value& sup
, string difftag
) {
if (difftag.length() == 0) difftag = "StgIacWznmMtdList";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
me["TcoSrfWidth"] = TcoSrfWidth;
me["TcoJobWidth"] = TcoJobWidth;
me["TcoExsWidth"] = TcoExsWidth;
};
void PnlWznmMtdList::StgIac::writeXML(
xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "StgIacWznmMtdList";
string itemtag;
if (shorttags) itemtag = "Si";
else itemtag = "StgitemIacWznmMtdList";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
writeUintAttr(wr, itemtag, "sref", "TcoSrfWidth", TcoSrfWidth);
writeUintAttr(wr, itemtag, "sref", "TcoJobWidth", TcoJobWidth);
writeUintAttr(wr, itemtag, "sref", "TcoExsWidth", TcoExsWidth);
xmlTextWriterEndElement(wr);
};
set<uint> PnlWznmMtdList::StgIac::comm(
const StgIac* comp
) {
set<uint> items;
if (TcoSrfWidth == comp->TcoSrfWidth) insert(items, TCOSRFWIDTH);
if (TcoJobWidth == comp->TcoJobWidth) insert(items, TCOJOBWIDTH);
if (TcoExsWidth == comp->TcoExsWidth) insert(items, TCOEXSWIDTH);
return(items);
};
set<uint> PnlWznmMtdList::StgIac::diff(
const StgIac* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {TCOSRFWIDTH, TCOJOBWIDTH, TCOEXSWIDTH};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class PnlWznmMtdList::Tag
******************************************************************************/
void PnlWznmMtdList::Tag::writeJSON(
const uint ixWznmVLocale
, Json::Value& sup
, string difftag
) {
if (difftag.length() == 0) difftag = "TagWznmMtdList";
Json::Value& me = sup[difftag] = Json::Value(Json::objectValue);
if (ixWznmVLocale == VecWznmVLocale::ENUS) {
me["Cpt"] = "Methods";
me["TcoSrf"] = "Identifier";
me["TcoJob"] = "Job";
me["TcoExs"] = "Execute in server";
};
me["TxtFor"] = VecWznmVTag::getTitle(VecWznmVTag::FOR, ixWznmVLocale);
me["TxtRecord1"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::REC, ixWznmVLocale));
me["TxtRecord2"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::EMPLONG, ixWznmVLocale));
me["Trs"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::GOTO, ixWznmVLocale)) + " ...";
me["TxtShowing1"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::SHOWLONG, ixWznmVLocale));
me["TxtShowing2"] = StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::EMPLONG, ixWznmVLocale));
};
void PnlWznmMtdList::Tag::writeXML(
const uint ixWznmVLocale
, xmlTextWriter* wr
, string difftag
, bool shorttags
) {
if (difftag.length() == 0) difftag = "TagWznmMtdList";
string itemtag;
if (shorttags) itemtag = "Ti";
else itemtag = "TagitemWznmMtdList";
xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
if (ixWznmVLocale == VecWznmVLocale::ENUS) {
writeStringAttr(wr, itemtag, "sref", "Cpt", "Methods");
writeStringAttr(wr, itemtag, "sref", "TcoSrf", "Identifier");
writeStringAttr(wr, itemtag, "sref", "TcoJob", "Job");
writeStringAttr(wr, itemtag, "sref", "TcoExs", "Execute in server");
};
writeStringAttr(wr, itemtag, "sref", "TxtFor", VecWznmVTag::getTitle(VecWznmVTag::FOR, ixWznmVLocale));
writeStringAttr(wr, itemtag, "sref", "TxtRecord1", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::REC, ixWznmVLocale)));
writeStringAttr(wr, itemtag, "sref", "TxtRecord2", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::EMPLONG, ixWznmVLocale)));
writeStringAttr(wr, itemtag, "sref", "Trs", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::GOTO, ixWznmVLocale)) + " ...");
writeStringAttr(wr, itemtag, "sref", "TxtShowing1", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::SHOWLONG, ixWznmVLocale)));
writeStringAttr(wr, itemtag, "sref", "TxtShowing2", StrMod::cap(VecWznmVTag::getTitle(VecWznmVTag::EMPLONG, ixWznmVLocale)));
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class PnlWznmMtdList::DpchAppData
******************************************************************************/
PnlWznmMtdList::DpchAppData::DpchAppData() :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMMTDLISTDATA)
{
};
string PnlWznmMtdList::DpchAppData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(STGIAC)) ss.push_back("stgiac");
if (has(STGIACQRY)) ss.push_back("stgiacqry");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmMtdList::DpchAppData::readJSON(
Json::Value& sup
, bool addbasetag
) {
clear();
bool basefound;
Json::Value& me = sup;
if (addbasetag) me = sup["DpchAppWznmMtdListData"];
basefound = (me != Json::nullValue);
if (basefound) {
if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);};
if (contiac.readJSON(me, true)) add(CONTIAC);
if (stgiac.readJSON(me, true)) add(STGIAC);
if (stgiacqry.readJSON(me, true)) add(STGIACQRY);
} else {
contiac = ContIac();
stgiac = StgIac();
stgiacqry = QryWznmMtdList::StgIac();
};
};
void PnlWznmMtdList::DpchAppData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string scrJref;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppWznmMtdListData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) {
jref = Scr::descramble(scrJref);
add(JREF);
};
if (contiac.readXML(docctx, basexpath, true)) add(CONTIAC);
if (stgiac.readXML(docctx, basexpath, true)) add(STGIAC);
if (stgiacqry.readXML(docctx, basexpath, true)) add(STGIACQRY);
} else {
contiac = ContIac();
stgiac = StgIac();
stgiacqry = QryWznmMtdList::StgIac();
};
};
/******************************************************************************
class PnlWznmMtdList::DpchAppDo
******************************************************************************/
PnlWznmMtdList::DpchAppDo::DpchAppDo() :
DpchAppWznm(VecWznmVDpch::DPCHAPPWZNMMTDLISTDO)
{
ixVDo = 0;
};
string PnlWznmMtdList::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmMtdList::DpchAppDo::readJSON(
Json::Value& sup
, bool addbasetag
) {
clear();
bool basefound;
Json::Value& me = sup;
if (addbasetag) me = sup["DpchAppWznmMtdListDo"];
basefound = (me != Json::nullValue);
if (basefound) {
if (me.isMember("scrJref")) {jref = Scr::descramble(me["scrJref"].asString()); add(JREF);};
if (me.isMember("srefIxVDo")) {ixVDo = VecVDo::getIx(me["srefIxVDo"].asString()); add(IXVDO);};
} else {
};
};
void PnlWznmMtdList::DpchAppDo::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string scrJref;
string srefIxVDo;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchAppWznmMtdListDo");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) {
jref = Scr::descramble(scrJref);
add(JREF);
};
if (extractStringUclc(docctx, basexpath, "srefIxVDo", "", srefIxVDo)) {
ixVDo = VecVDo::getIx(srefIxVDo);
add(IXVDO);
};
} else {
};
};
/******************************************************************************
class PnlWznmMtdList::DpchEngData
******************************************************************************/
PnlWznmMtdList::DpchEngData::DpchEngData(
const ubigint jref
, ContIac* contiac
, ContInf* continf
, Feed* feedFCsiQst
, Feed* feedFTos
, StatShr* statshr
, StgIac* stgiac
, ListWznmQMtdList* rst
, QryWznmMtdList::StatShr* statshrqry
, QryWznmMtdList::StgIac* stgiacqry
, const set<uint>& mask
) :
DpchEngWznm(VecWznmVDpch::DPCHENGWZNMMTDLISTDATA, jref)
{
if (find(mask, ALL)) this->mask = {JREF, CONTIAC, CONTINF, FEEDFCSIQST, FEEDFTOS, STATSHR, STGIAC, TAG, RST, STATAPPQRY, STATSHRQRY, STGIACQRY};
else this->mask = mask;
if (find(this->mask, CONTIAC) && contiac) this->contiac = *contiac;
if (find(this->mask, CONTINF) && continf) this->continf = *continf;
if (find(this->mask, FEEDFCSIQST) && feedFCsiQst) this->feedFCsiQst = *feedFCsiQst;
if (find(this->mask, FEEDFTOS) && feedFTos) this->feedFTos = *feedFTos;
if (find(this->mask, STATSHR) && statshr) this->statshr = *statshr;
if (find(this->mask, STGIAC) && stgiac) this->stgiac = *stgiac;
if (find(this->mask, RST) && rst) this->rst = *rst;
if (find(this->mask, STATSHRQRY) && statshrqry) this->statshrqry = *statshrqry;
if (find(this->mask, STGIACQRY) && stgiacqry) this->stgiacqry = *stgiacqry;
};
string PnlWznmMtdList::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(JREF)) ss.push_back("jref");
if (has(CONTIAC)) ss.push_back("contiac");
if (has(CONTINF)) ss.push_back("continf");
if (has(FEEDFCSIQST)) ss.push_back("feedFCsiQst");
if (has(FEEDFTOS)) ss.push_back("feedFTos");
if (has(STATSHR)) ss.push_back("statshr");
if (has(STGIAC)) ss.push_back("stgiac");
if (has(TAG)) ss.push_back("tag");
if (has(RST)) ss.push_back("rst");
if (has(STATAPPQRY)) ss.push_back("statappqry");
if (has(STATSHRQRY)) ss.push_back("statshrqry");
if (has(STGIACQRY)) ss.push_back("stgiacqry");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void PnlWznmMtdList::DpchEngData::merge(
DpchEngWznm* dpcheng
) {
DpchEngData* src = (DpchEngData*) dpcheng;
if (src->has(JREF)) {jref = src->jref; add(JREF);};
if (src->has(CONTIAC)) {contiac = src->contiac; add(CONTIAC);};
if (src->has(CONTINF)) {continf = src->continf; add(CONTINF);};
if (src->has(FEEDFCSIQST)) {feedFCsiQst = src->feedFCsiQst; add(FEEDFCSIQST);};
if (src->has(FEEDFTOS)) {feedFTos = src->feedFTos; add(FEEDFTOS);};
if (src->has(STATSHR)) {statshr = src->statshr; add(STATSHR);};
if (src->has(STGIAC)) {stgiac = src->stgiac; add(STGIAC);};
if (src->has(TAG)) add(TAG);
if (src->has(RST)) {rst = src->rst; add(RST);};
if (src->has(STATAPPQRY)) add(STATAPPQRY);
if (src->has(STATSHRQRY)) {statshrqry = src->statshrqry; add(STATSHRQRY);};
if (src->has(STGIACQRY)) {stgiacqry = src->stgiacqry; add(STGIACQRY);};
};
void PnlWznmMtdList::DpchEngData::writeJSON(
const uint ixWznmVLocale
, Json::Value& sup
) {
Json::Value& me = sup["DpchEngWznmMtdListData"] = Json::Value(Json::objectValue);
if (has(JREF)) me["scrJref"] = Scr::scramble(jref);
if (has(CONTIAC)) contiac.writeJSON(me);
if (has(CONTINF)) continf.writeJSON(me);
if (has(FEEDFCSIQST)) feedFCsiQst.writeJSON(me);
if (has(FEEDFTOS)) feedFTos.writeJSON(me);
if (has(STATSHR)) statshr.writeJSON(me);
if (has(STGIAC)) stgiac.writeJSON(me);
if (has(TAG)) Tag::writeJSON(ixWznmVLocale, me);
if (has(RST)) rst.writeJSON(me);
if (has(STATAPPQRY)) QryWznmMtdList::StatApp::writeJSON(me);
if (has(STATSHRQRY)) statshrqry.writeJSON(me);
if (has(STGIACQRY)) stgiacqry.writeJSON(me);
};
void PnlWznmMtdList::DpchEngData::writeXML(
const uint ixWznmVLocale
, xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchEngWznmMtdListData");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wznm");
if (has(JREF)) writeString(wr, "scrJref", Scr::scramble(jref));
if (has(CONTIAC)) contiac.writeXML(wr);
if (has(CONTINF)) continf.writeXML(wr);
if (has(FEEDFCSIQST)) feedFCsiQst.writeXML(wr);
if (has(FEEDFTOS)) feedFTos.writeXML(wr);
if (has(STATSHR)) statshr.writeXML(wr);
if (has(STGIAC)) stgiac.writeXML(wr);
if (has(TAG)) Tag::writeXML(ixWznmVLocale, wr);
if (has(RST)) rst.writeXML(wr);
if (has(STATAPPQRY)) QryWznmMtdList::StatApp::writeXML(wr);
if (has(STATSHRQRY)) statshrqry.writeXML(wr);
if (has(STGIACQRY)) stgiacqry.writeXML(wr);
xmlTextWriterEndElement(wr);
};
|
#include "open_cdm_ext.h"
#include "open_cdm_impl.h"
#define ASSERT_NOT_EXECUTED() \
{ \
fprintf(stderr, "Error: didn't expect to use %s (%s:%d)!!\n", \
__PRETTY_FUNCTION__, __FILE__, __LINE__); \
abort(); \
}
DEPRECATED struct OpenCDMSystem* opencdm_create_system(const char keySystem[])
{
struct OpenCDMSystem* result = nullptr;
opencdm_create_system_extended(keySystem, &result);
return result;
}
OpenCDMError opencdm_create_system_extended(const char keySystem[], struct OpenCDMSystem** system)
{
ASSERT(system != nullptr);
*system = nullptr;
std::string metadata;
OpenCDMError result = static_cast<OpenCDMError>(OpenCDMAccessor::Instance()->Metadata(std::string(keySystem), metadata));
if( result == OpenCDMError::ERROR_NONE ) {
*system = new OpenCDMSystem(keySystem, metadata);
}
return result;
}
OpenCDMError opencdm_system_get_version(struct OpenCDMSystem* system,
char versionStr[])
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
versionStr[0] = '\0';
std::string versionStdStr = accessor->GetVersionExt(system->keySystem());
assert(versionStdStr.length() < 64);
strcpy(versionStr, versionStdStr.c_str());
return ERROR_NONE;
}
OpenCDMError opencdm_system_ext_get_ldl_session_limit(OpenCDMSystem* system,
uint32_t* ldlLimit)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
std::string keySystem = system->keySystem();
*ldlLimit = accessor->GetLdlSessionLimit(keySystem);
return ERROR_NONE;
}
uint32_t opencdm_system_ext_is_secure_stop_enabled(
struct OpenCDMSystem* system)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
return (OpenCDMError)accessor->IsSecureStopEnabled(system->keySystem());
}
OpenCDMError
opencdm_system_ext_enable_secure_stop(struct OpenCDMSystem* system,
uint32_t use)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
return (OpenCDMError)accessor->EnableSecureStop(system->keySystem(),
use != 0);
}
uint32_t opencdm_system_ext_reset_secure_stop(struct OpenCDMSystem* system)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
return (OpenCDMError)accessor->ResetSecureStops(system->keySystem());
}
OpenCDMError opencdm_system_ext_get_secure_stop_ids(OpenCDMSystem* system,
uint8_t ids[],
uint8_t idSize,
uint32_t* count)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
return (OpenCDMError)accessor->GetSecureStopIds(system->keySystem(), ids,
idSize, *count);
}
OpenCDMError opencdm_system_ext_get_secure_stop(OpenCDMSystem* system,
const uint8_t sessionID[],
uint32_t sessionIDLength,
uint8_t rawData[],
uint16_t* rawSize)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
return (OpenCDMError)accessor->GetSecureStop(
system->keySystem(), sessionID, sessionIDLength, rawData, *rawSize);
}
OpenCDMError opencdm_system_ext_commit_secure_stop(
OpenCDMSystem* system, const uint8_t sessionID[],
uint32_t sessionIDLength, const uint8_t serverResponse[],
uint32_t serverResponseLength)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
return (OpenCDMError)accessor->CommitSecureStop(
system->keySystem(), sessionID, sessionIDLength, serverResponse,
serverResponseLength);
}
OpenCDMError opencdm_system_get_drm_time(struct OpenCDMSystem* system,
uint64_t* time)
{
ASSERT(system != nullptr);
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
OpenCDMError result(ERROR_INVALID_ACCESSOR);
if (system != nullptr) {
*time = accessor->GetDrmSystemTime(system->keySystem());
result = ERROR_NONE;
}
return (result);
}
uint32_t
opencdm_session_get_session_id_ext(struct OpenCDMSession* opencdmSession)
{
uint32_t result = OpenCDMError::ERROR_INVALID_SESSION;
ASSERT(opencdmSession != nullptr);
if (opencdmSession != nullptr) {
result = opencdmSession->SessionIdExt();
}
return result;
}
OpenCDMError opencdm_destruct_session_ext(OpenCDMSession* opencdmSession)
{
OpenCDMError result(OpenCDMError::ERROR_INVALID_SESSION);
ASSERT(opencdmSession != nullptr);
if (opencdmSession != nullptr) {
result = OpenCDMError::ERROR_NONE;
opencdmSession->Release();
}
return (result);
}
OpenCDMError
opencdm_session_set_drm_header(struct OpenCDMSession* opencdmSession,
const uint8_t drmHeader[],
uint32_t drmHeaderSize)
{
ASSERT(opencdmSession != nullptr);
return (OpenCDMError)opencdmSession->SetDrmHeader(drmHeader, drmHeaderSize);
}
OpenCDMError
opencdm_session_get_challenge_data(struct OpenCDMSession* mOpenCDMSession,
uint8_t* challenge, uint32_t* challengeSize,
uint32_t isLDL)
{
ASSERT(mOpenCDMSession != nullptr);
return (OpenCDMError)mOpenCDMSession->GetChallengeDataExt(challenge,
*challengeSize, isLDL);
}
OpenCDMError
opencdm_session_cancel_challenge_data(struct OpenCDMSession* mOpenCDMSession)
{
ASSERT(mOpenCDMSession != nullptr);
return (OpenCDMError)mOpenCDMSession->CancelChallengeDataExt();
}
OpenCDMError opencdm_session_store_license_data(
struct OpenCDMSession* mOpenCDMSession, const uint8_t licenseData[],
uint32_t licenseDataSize, uint8_t* secureStopId)
{
ASSERT(mOpenCDMSession != nullptr);
return (OpenCDMError)mOpenCDMSession->StoreLicenseData(
licenseData, licenseDataSize, secureStopId);
}
OpenCDMError opencdm_session_select_key_id(
struct OpenCDMSession* mOpenCDMSession, uint8_t keyLenght, const uint8_t keyId[])
{
ASSERT(mOpenCDMSession != nullptr);
OpenCDMError output = (OpenCDMError)mOpenCDMSession->SelectKeyId(keyLenght, keyId);
return output;
}
OpenCDMError opencdm_session_clean_decrypt_context(struct OpenCDMSession* mOpenCDMSession)
{
ASSERT(mOpenCDMSession != nullptr);
return (OpenCDMError)mOpenCDMSession->CleanDecryptContext();
}
OpenCDMError opencdm_delete_key_store(struct OpenCDMSystem* system)
{
ASSERT(system != nullptr);
OpenCDMError result(ERROR_INVALID_ACCESSOR);
if (system != nullptr) {
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
std::string keySystem = system->keySystem();
result = (OpenCDMError)accessor->DeleteKeyStore(keySystem);
}
return (result);
}
OpenCDMError opencdm_delete_secure_store(struct OpenCDMSystem* system)
{
ASSERT(system != nullptr);
OpenCDMError result(ERROR_INVALID_ACCESSOR);
if (system != nullptr) {
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
std::string keySystem = system->keySystem();
result = (OpenCDMError)accessor->DeleteSecureStore(keySystem);
}
return (result);
}
OpenCDMError opencdm_get_key_store_hash_ext(struct OpenCDMSystem* system,
uint8_t keyStoreHash[],
uint32_t keyStoreHashLength)
{
ASSERT(system != nullptr);
OpenCDMError result(ERROR_INVALID_ACCESSOR);
if (system != nullptr) {
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
std::string keySystem = system->keySystem();
result = (OpenCDMError)accessor->GetKeyStoreHash(keySystem, keyStoreHash,
keyStoreHashLength);
}
return (result);
}
OpenCDMError opencdm_get_secure_store_hash_ext(struct OpenCDMSystem* system,
uint8_t secureStoreHash[],
uint32_t secureStoreHashLength)
{
ASSERT(system != nullptr);
OpenCDMError result(ERROR_INVALID_ACCESSOR);
if (system != nullptr) {
OpenCDMAccessor* accessor = OpenCDMAccessor::Instance();
std::string keySystem = system->keySystem();
result = (OpenCDMError)accessor->GetSecureStoreHash(
keySystem, secureStoreHash, secureStoreHashLength);
}
return (result);
}
/**
* \brief Create DRM session (for actual decrypting of data).
*
* Creates an instance of \ref OpenCDMSession using initialization data.
* \param keySystem DRM system to create the session for.
* \param licenseType DRM specifc signed integer selecting License Type (e.g.
* "Limited Duration" for PlayReady).
* \param initDataType Type of data passed in \ref initData.
* \param initData Initialization data.
* \param initDataLength Length (in bytes) of initialization data.
* \param CDMData CDM data.
* \param CDMDataLength Length (in bytes) of \ref CDMData.
* \param session Output parameter that will contain pointer to instance of \ref
* OpenCDMSession.
* \return Zero on success, non-zero on error.
*/
OpenCDMError
opencdm_construct_session(struct OpenCDMSystem* system,
const LicenseType licenseType, const char initDataType[],
const uint8_t initData[], const uint16_t initDataLength,
const uint8_t CDMData[], const uint16_t CDMDataLength,
OpenCDMSessionCallbacks* callbacks, void* userData,
struct OpenCDMSession** session)
{
ASSERT(system != nullptr);
OpenCDMError result(ERROR_INVALID_ACCESSOR);
TRACE_L1("Creating a Session for %s", system->keySystem().c_str());
if (system != nullptr) {
*session = new OpenCDMSession(system, std::string(initDataType),
initData, initDataLength, CDMData,
CDMDataLength, licenseType, callbacks, userData);
result = (*session != nullptr ? OpenCDMError::ERROR_NONE
: OpenCDMError::ERROR_INVALID_SESSION);
}
TRACE_L1("Created a Session, result %p, %d", *session, result);
return (result);
}
|
// Copyright (c) 2011-2018 The Limracoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/limracoin-config.h>
#endif
#include <qt/addressbookpage.h>
#include <qt/forms/ui_addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/limracoingui.h>
#include <qt/csvmodelwriter.h>
#include <qt/editaddressdialog.h>
#include <qt/guiutil.h>
#include <qt/platformstyle.h>
#include <QIcon>
#include <QMenu>
#include <QMessageBox>
#include <QSortFilterProxyModel>
class AddressBookSortFilterProxyModel final : public QSortFilterProxyModel
{
const QString m_type;
public:
AddressBookSortFilterProxyModel(const QString& type, QObject* parent)
: QSortFilterProxyModel(parent)
, m_type(type)
{
setDynamicSortFilter(true);
setFilterCaseSensitivity(Qt::CaseInsensitive);
setSortCaseSensitivity(Qt::CaseInsensitive);
}
protected:
bool filterAcceptsRow(int row, const QModelIndex& parent) const
{
auto model = sourceModel();
auto label = model->index(row, AddressTableModel::Label, parent);
if (model->data(label, AddressTableModel::TypeRole).toString() != m_type) {
return false;
}
auto address = model->index(row, AddressTableModel::Address, parent);
if (filterRegExp().indexIn(model->data(address).toString()) < 0 &&
filterRegExp().indexIn(model->data(label).toString()) < 0) {
return false;
}
return true;
}
};
AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode, Tabs _tab, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddressBookPage),
model(0),
mode(_mode),
tab(_tab)
{
ui->setupUi(this);
if (!platformStyle->getImagesOnButtons()) {
ui->newAddress->setIcon(QIcon());
ui->copyAddress->setIcon(QIcon());
ui->deleteAddress->setIcon(QIcon());
ui->exportButton->setIcon(QIcon());
} else {
ui->newAddress->setIcon(platformStyle->SingleColorIcon(":/icons/add"));
ui->copyAddress->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy"));
ui->deleteAddress->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/export"));
}
switch(mode)
{
case ForSelection:
switch(tab)
{
case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break;
case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break;
}
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept()));
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tableView->setFocus();
ui->closeButton->setText(tr("C&hoose"));
ui->exportButton->hide();
break;
case ForEditing:
switch(tab)
{
case SendingTab: setWindowTitle(tr("Sending addresses")); break;
case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break;
}
break;
}
switch(tab)
{
case SendingTab:
ui->labelExplanation->setText(tr("These are your Limracoin addresses for sending payments. Always check the amount and the receiving address before sending coins."));
ui->deleteAddress->setVisible(true);
ui->newAddress->setVisible(true);
break;
case ReceivingTab:
ui->labelExplanation->setText(tr("These are your Limracoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction."));
ui->deleteAddress->setVisible(false);
ui->newAddress->setVisible(false);
break;
}
// Context menu actions
QAction *copyAddressAction = new QAction(tr("&Copy Address"), this);
QAction *copyLabelAction = new QAction(tr("Copy &Label"), this);
QAction *editAction = new QAction(tr("&Edit"), this);
deleteAction = new QAction(ui->deleteAddress->text(), this);
// Build context menu
contextMenu = new QMenu(this);
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyLabelAction);
contextMenu->addAction(editAction);
if(tab == SendingTab)
contextMenu->addAction(deleteAction);
contextMenu->addSeparator();
// Connect signals for context menu actions
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked()));
connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction()));
connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction()));
connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept()));
}
AddressBookPage::~AddressBookPage()
{
delete ui;
}
void AddressBookPage::setModel(AddressTableModel *_model)
{
this->model = _model;
if(!_model)
return;
auto type = tab == ReceivingTab ? AddressTableModel::Receive : AddressTableModel::Send;
proxyModel = new AddressBookSortFilterProxyModel(type, this);
proxyModel->setSourceModel(_model);
connect(ui->searchLineEdit, SIGNAL(textChanged(QString)), proxyModel, SLOT(setFilterWildcard(QString)));
ui->tableView->setModel(proxyModel);
ui->tableView->sortByColumn(0, Qt::AscendingOrder);
// Set column widths
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch);
ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created address
connect(_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int)));
selectionChanged();
}
void AddressBookPage::on_copyAddress_clicked()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address);
}
void AddressBookPage::onCopyLabelAction()
{
GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label);
}
void AddressBookPage::onEditAction()
{
if(!model)
return;
if(!ui->tableView->selectionModel())
return;
QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows();
if(indexes.isEmpty())
return;
EditAddressDialog dlg(
tab == SendingTab ?
EditAddressDialog::EditSendingAddress :
EditAddressDialog::EditReceivingAddress, this);
dlg.setModel(model);
QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0));
dlg.loadRow(origIndex.row());
dlg.exec();
}
void AddressBookPage::on_newAddress_clicked()
{
if(!model)
return;
if (tab == ReceivingTab) {
return;
}
EditAddressDialog dlg(EditAddressDialog::NewSendingAddress, this);
dlg.setModel(model);
if(dlg.exec())
{
newAddressToSelect = dlg.getAddress();
}
}
void AddressBookPage::on_deleteAddress_clicked()
{
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
QModelIndexList indexes = table->selectionModel()->selectedRows();
if(!indexes.isEmpty())
{
table->model()->removeRow(indexes.at(0).row());
}
}
void AddressBookPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
switch(tab)
{
case SendingTab:
// In sending tab, allow deletion of selection
ui->deleteAddress->setEnabled(true);
ui->deleteAddress->setVisible(true);
deleteAction->setEnabled(true);
break;
case ReceivingTab:
// Deleting receiving addresses, however, is not allowed
ui->deleteAddress->setEnabled(false);
ui->deleteAddress->setVisible(false);
deleteAction->setEnabled(false);
break;
}
ui->copyAddress->setEnabled(true);
}
else
{
ui->deleteAddress->setEnabled(false);
ui->copyAddress->setEnabled(false);
}
}
void AddressBookPage::done(int retval)
{
QTableView *table = ui->tableView;
if(!table->selectionModel() || !table->model())
return;
// Figure out which address was selected, and return it
QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address);
for (const QModelIndex& index : indexes) {
QVariant address = table->model()->data(index);
returnValue = address.toString();
}
if(returnValue.isEmpty())
{
// If no address entry selected, return rejected
retval = Rejected;
}
QDialog::done(retval);
}
void AddressBookPage::on_exportButton_clicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(this,
tr("Export Address List"), QString(),
tr("Comma separated file (*.csv)"), nullptr);
if (filename.isNull())
return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole);
writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole);
if(!writer.write()) {
QMessageBox::critical(this, tr("Exporting Failed"),
tr("There was an error trying to save the address list to %1. Please try again.").arg(filename));
}
}
void AddressBookPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
}
void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect))
{
// Select row of newly created address, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newAddressToSelect.clear();
}
}
|
#include "fs/impl/memory/fs_memory_file_system.hpp"
#include "fs/impl/memory/fs_memory_file.hpp"
#include "fs/impl/memory/fs_memory_folder.hpp"
#include "exception/ih/exc_internal_error.hpp"
#include <memory>
#include <std_fs>
//------------------------------------------------------------------------------
namespace fs::memory
{
//------------------------------------------------------------------------------
MemoryFileSystem::FilePtr MemoryFileSystem::openFile( const Path & _path ) const
{
const Path path = toAbsolutePath( _path );
FolderPtr dirPtr = getFolder( path.parent_path() );
if( !dirPtr )
{
return nullptr;
}
const Path fileName = _path.filename();
return dirPtr->getFile( fileName.string() );
}
//------------------------------------------------------------------------------
MemoryFileSystem::FilePtr MemoryFileSystem::createFile( const Path & _path )
{
const Path path = toAbsolutePath( _path );
MemoryFolder & folder = ensureFolder( path.parent_path() );
const Path fileName = _path.filename();
return folder.ensureFile( fileName.string() );
}
//------------------------------------------------------------------------------
bool MemoryFileSystem::isExistFile( const Path & _path ) const
{
return openFile( _path ).get() != nullptr;
}
//------------------------------------------------------------------------------
MemoryFileSystem::Path MemoryFileSystem::getCurrentPath() const
{
return "/tmp/";
}
//------------------------------------------------------------------------------
MemoryFileSystem::Path MemoryFileSystem::toAbsolute( const Path & _path ) const
{
return getCurrentPath() / _path;
}
//------------------------------------------------------------------------------
void MemoryFileSystem::forEachItem(
const Path & _dirPath, ItemCallback _callback ) const
{
FolderPtr folderPtr = getFolder( _dirPath );
INTERNAL_CHECK_WARRING( folderPtr != nullptr );
if( folderPtr == nullptr )
{
return;
}
MemoryFolder & folder = *folderPtr;
folder.forEachItem( [&]( std::string_view _name, ItemType _type ) {
Path path = _dirPath / _name;
_callback( path, _type );
} );
}
//------------------------------------------------------------------------------
MemoryFolder & MemoryFileSystem::ensureRoot( const Path & _path )
{
auto pair = m_roots.try_emplace(
_path,
FolderPtr{ std::make_shared< MemoryFolder >( _path.string() ) } );
auto it = pair.first;
FolderPtr & rootPtr = it->second;
INTERNAL_CHECK_ERROR( rootPtr );
return *rootPtr;
}
//------------------------------------------------------------------------------
MemoryFileSystem::FolderPtr
MemoryFileSystem::getRoot( const Path & _path ) const
{
if( auto it = m_roots.find( _path ); it != m_roots.end() )
{
return it->second;
}
return nullptr;
}
//------------------------------------------------------------------------------
MemoryFileSystem::FolderPtr
MemoryFileSystem::getFolder( const Path & _path ) const
{
FolderPtr rootPtr = getRoot( _path.root_directory() );
if( !rootPtr )
{
return nullptr;
}
FolderPtr currentFolder = rootPtr;
const Path pathWitoutRoot = _path.relative_path();
for( const auto & currentName: pathWitoutRoot )
{
if( stdfs::is_dir_filename( currentName ) )
{
continue;
}
INTERNAL_CHECK_ERROR( currentFolder );
auto subDirPtr = currentFolder->getSubFolder( currentName.string() );
currentFolder = subDirPtr;
if( !currentFolder )
{
break;
}
}
return currentFolder;
}
//------------------------------------------------------------------------------
MemoryFolder & MemoryFileSystem::ensureFolder( const Path & _path )
{
Path pathWitoutRoot = _path.relative_path();
MemoryFolder & root = ensureRoot( _path.root_directory() );
MemoryFolder * currentFolder = &root;
for( const auto & currentName: pathWitoutRoot )
{
const std::string folderName = currentName.string();
if( folderName.empty() )
{
continue;
}
INTERNAL_CHECK_ERROR( currentFolder );
auto subDirPtr = currentFolder->ensureSubFolder( currentName.string() );
currentFolder = subDirPtr.get();
}
INTERNAL_CHECK_ERROR( currentFolder );
return *currentFolder;
}
//------------------------------------------------------------------------------
MemoryFileSystem::Path
MemoryFileSystem::toAbsolutePath( const Path & _path ) const
{
if( !_path.is_absolute() )
{
return getCurrentPath() / _path;
}
return _path;
}
//------------------------------------------------------------------------------
}
|
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include <armnn/BackendId.hpp>
#include <backendsCommon/test/JsonPrinterTestImpl.hpp>
#include <boost/test/unit_test.hpp>
#include <vector>
BOOST_AUTO_TEST_SUITE(RefJsonPrinter)
BOOST_AUTO_TEST_CASE(SoftmaxProfilerJsonPrinterCpuRefTest)
{
std::vector<armnn::BackendId> backends = {armnn::Compute::CpuRef};
RunSoftmaxProfilerJsonPrinterTest(backends);
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "random.h"
#include "scheduler.h"
#include "test/test_madcoin.h"
#include <boost/bind.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(scheduler_tests)
static void microTask(CScheduler& s, boost::mutex& mutex, int& counter, int delta, boost::chrono::system_clock::time_point rescheduleTime)
{
{
boost::unique_lock<boost::mutex> lock(mutex);
counter += delta;
}
boost::chrono::system_clock::time_point noTime = boost::chrono::system_clock::time_point::min();
if (rescheduleTime != noTime) {
CScheduler::Function f = boost::bind(µTask, boost::ref(s), boost::ref(mutex), boost::ref(counter), -delta + 1, noTime);
s.schedule(f, rescheduleTime);
}
}
static void MicroSleep(uint64_t n)
{
#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
boost::this_thread::sleep_for(boost::chrono::microseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
boost::this_thread::sleep(boost::posix_time::microseconds(n));
#else
//should never get here
#error missing boost sleep implementation
#endif
}
BOOST_AUTO_TEST_CASE(manythreads)
{
seed_insecure_rand(false);
// Stress test: hundreds of microsecond-scheduled tasks,
// serviced by 10 threads.
//
// So... ten shared counters, which if all the tasks execute
// properly will sum to the number of tasks done.
// Each task adds or subtracts from one of the counters a
// random amount, and then schedules another task 0-1000
// microseconds in the future to subtract or add from
// the counter -random_amount+1, so in the end the shared
// counters should sum to the number of initial tasks performed.
CScheduler microTasks;
boost::mutex counterMutex[10];
int counter[10] = { 0 };
boost::random::mt19937 rng(insecure_rand());
boost::random::uniform_int_distribution<> zeroToNine(0, 9);
boost::random::uniform_int_distribution<> randomMsec(-11, 1000);
boost::random::uniform_int_distribution<> randomDelta(-1000, 1000);
boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
boost::chrono::system_clock::time_point now = start;
boost::chrono::system_clock::time_point first, last;
size_t nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 0);
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
nTasks = microTasks.getQueueInfo(first, last);
BOOST_CHECK(nTasks == 100);
BOOST_CHECK(first < last);
BOOST_CHECK(last > now);
// As soon as these are created they will start running and servicing the queue
boost::thread_group microThreads;
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
MicroSleep(600);
now = boost::chrono::system_clock::now();
// More threads and more tasks:
for (int i = 0; i < 5; i++)
microThreads.create_thread(boost::bind(&CScheduler::serviceQueue, µTasks));
for (int i = 0; i < 100; i++) {
boost::chrono::system_clock::time_point t = now + boost::chrono::microseconds(randomMsec(rng));
boost::chrono::system_clock::time_point tReschedule = now + boost::chrono::microseconds(500 + randomMsec(rng));
int whichCounter = zeroToNine(rng);
CScheduler::Function f = boost::bind(µTask, boost::ref(microTasks),
boost::ref(counterMutex[whichCounter]), boost::ref(counter[whichCounter]),
randomDelta(rng), tReschedule);
microTasks.schedule(f, t);
}
// Drain the task queue then exit threads
microTasks.stop(true);
microThreads.join_all(); // ... wait until all the threads are done
int counterSum = 0;
for (int i = 0; i < 10; i++) {
BOOST_CHECK(counter[i] != 0);
counterSum += counter[i];
}
BOOST_CHECK_EQUAL(counterSum, 200);
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "TreeNode.h"
#include <stdio.h>
TreeNode::TreeNode(int value)
{
m_value = value;
}
TreeNode::TreeNode()
{
}
TreeNode::~TreeNode()
{
}
void TreeNode::draw(int x, int y, bool selected)
{
static char buffer[10];
Color color;
DrawCircle(x, y, 30, BLUE);
sprintf_s(buffer, "%d", m_value);
if (selected)
{
DrawCircle(x, y, 28, ORANGE);
}
else
{
DrawCircle(x, y, 28, BLACK);
}
DrawText(buffer, (x - 12), (y - 10), 20, WHITE);
}
|
// Copyright (c) 2006-2008 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/string_util.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/automation/url_request_failed_dns_job.h"
#include "net/url_request/url_request_unittest.h"
class ErrorPageTest : public UITest {
};
TEST_F(ErrorPageTest, DNSError) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
std::wstring test_host = UTF8ToWide(test_url.host());
NavigateToURL(test_url);
// Verify that the url is in the title. Since it's set via Javascript, we
// need to give it a chance to run.
int i;
std::wstring title;
for (i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
title = GetActiveTabTitle();
if (title.find(test_host) != std::wstring::npos) {
// Success, bail out.
break;
}
}
if (i == 10) {
FAIL() << "failed to get error page title; got " << title;
}
};
TEST_F(ErrorPageTest, IFrame404) {
// iframes that have 404 pages should not trigger an alternate error page.
// In this test, the iframe sets the title of the parent page to "SUCCESS"
// when the iframe loads. If the iframe fails to load (because an alternate
// error page loads instead), then the title will remain as "FAIL".
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(L"chrome/test/data", NULL);
ASSERT_TRUE(NULL != server.get());
GURL test_url = server->TestServerPage("files/iframe404.html");
NavigateToURL(test_url);
// Verify that the url is in the title. Since it's set via Javascript, we
// need to give it a chance to run.
int i;
std::wstring title;
for (i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
title = GetActiveTabTitle();
if (title == L"SUCCESS") {
// Success, bail out.
break;
}
}
if (i == 10) {
FAIL() << "iframe 404 didn't load properly";
}
};
|
/**********************************************************************
* Copyright (c) 2008-2015, Alliance for Sustainable Energy.
* All rights reserved.
*
* 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
**********************************************************************/
#ifndef MODEL_SCHEDULEFIXEDINTERVAL_HPP
#define MODEL_SCHEDULEFIXEDINTERVAL_HPP
#include "ModelAPI.hpp"
#include "ScheduleInterval.hpp"
namespace openstudio {
namespace model {
namespace detail {
class ScheduleFixedInterval_Impl;
} // detail
/** ScheduleFixedInterval is a ScheduleInterval that wraps the OpenStudio IDD object
* 'OS_Schedule_FixedInterval'. */
class MODEL_API ScheduleFixedInterval : public ScheduleInterval {
public:
/** @name Constructors and Destructors */
//@{
explicit ScheduleFixedInterval(const Model& model);
virtual ~ScheduleFixedInterval() {}
//@}
static IddObjectType iddObjectType();
/** @name Getters */
//@{
bool interpolatetoTimestep() const;
bool isInterpolatetoTimestepDefaulted() const;
double intervalLength() const;
double outOfRangeValue() const;
bool isOutOfRangeValueDefaulted() const;
int startMonth() const;
int startDay() const;
//@}
/** @name Setters */
//@{
void setInterpolatetoTimestep(bool interpolatetoTimestep);
void resetInterpolatetoTimestep();
bool setIntervalLength(double intervalLength);
void setOutOfRangeValue(double outOfRangeValue);
void resetOutOfRangeValue();
bool setStartMonth(int startMonth);
bool setStartDay(int startDay);
//@}
protected:
/// @cond
typedef detail::ScheduleFixedInterval_Impl ImplType;
friend class Model;
friend class openstudio::IdfObject;
friend class detail::ScheduleFixedInterval_Impl;
explicit ScheduleFixedInterval(std::shared_ptr<detail::ScheduleFixedInterval_Impl> impl);
/// @endcond
private:
REGISTER_LOGGER("openstudio.model.ScheduleFixedInterval");
};
/** \relates ScheduleFixedInterval*/
typedef boost::optional<ScheduleFixedInterval> OptionalScheduleFixedInterval;
/** \relates ScheduleFixedInterval*/
typedef std::vector<ScheduleFixedInterval> ScheduleFixedIntervalVector;
} // model
} // openstudio
#endif // MODEL_SCHEDULEFIXEDINTERVAL_HPP
|
#include <cosma/local_multiply.hpp>
#include <cosma/mpi_mapper.hpp>
#include <cosma/multiply.hpp>
#include <complex>
#include <random>
using namespace cosma;
template <typename T>
void fill_matrix(T* ptr, size_t size) {
std::random_device dev; // seed
std::mt19937 rng(dev()); // generator
std::uniform_real_distribution<T> dist(1.); // distribution
for (unsigned i = 0; i < size; ++i) {
ptr[i] = T{dist(rng)};
}
}
template <typename T>
void fill_matrix(std::complex<T>* ptr, size_t size) {
std::random_device dev; // seed
std::mt19937 rng(dev()); // generator
std::uniform_real_distribution<T> dist(1.); // distribution
for (unsigned i = 0; i < size; ++i) {
ptr[i] = std::complex<T>{dist(rng), dist(rng)};
}
}
template <typename Scalar>
bool run(Strategy &s,
context<Scalar> &ctx,
MPI_Comm comm = MPI_COMM_WORLD,
bool overlap = false) {
constexpr auto epsilon = std::numeric_limits<float>::epsilon();
int rank;
int size;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &size);
auto mpi_type = cosma::mpi_mapper<Scalar>::getType();
s.overlap_comm_and_comp = overlap;
int m = s.m;
int n = s.n;
int k = s.k;
int P = s.P;
// Declare A,B and C COSMA matrices objects
// CosmaMatrix<Scalar> A(ctx, 'A', s, rank);
// CosmaMatrix<Scalar> B(ctx, 'B', s, rank);
// CosmaMatrix<Scalar> C(ctx, 'C', s, rank);
CosmaMatrix<Scalar> A('A', s, rank);
CosmaMatrix<Scalar> B('B', s, rank);
CosmaMatrix<Scalar> C('C', s, rank);
// initial sizes
auto sizeA = A.matrix_size();
auto sizeB = B.matrix_size();
auto sizeC = C.matrix_size();
// fill the matrices with random data
srand48(rank);
fill_matrix(A.matrix_pointer(), sizeA);
fill_matrix(B.matrix_pointer(), sizeB);
#ifdef DEBUG
std::cout << "Initial data in A and B:" << std::endl;
for (int i = 0; i < P; i++) {
if (rank == i) {
printf("(%d) A: ", i);
for (auto j = 0; j < sizeA; j++)
printf("%5.3f ", A.matrix_pointer()[j]);
printf("\n");
printf("(%d) B: ", i);
for (auto j = 0; j < sizeB; j++)
printf("%5.3f ", B.matrix_pointer()[j]);
printf("\n");
}
MPI_Barrier(comm);
}
#endif // DEBUG
bool isOK;
// Then rank0 ask for other ranks data
std::vector<Scalar> As, Bs;
if (rank == 0) {
As = std::vector<Scalar>(m * k);
std::memcpy(As.data(), A.matrix_pointer(), A.matrix_size()*sizeof(Scalar));
Bs = std::vector<Scalar>(k * n);
std::memcpy(Bs.data(), B.matrix_pointer(), B.matrix_size()*sizeof(Scalar));
int offsetA = sizeA;
int offsetB = sizeB;
for (int i = 1; i < P; i++) {
int receive_size_A = A.matrix_size(i);
int receive_size_B = B.matrix_size(i);
// Rank 0 receive data
MPI_Recv(As.data() + offsetA,
receive_size_A,
mpi_type,
i,
0,
comm,
MPI_STATUSES_IGNORE);
MPI_Recv(Bs.data() + offsetB,
receive_size_B,
mpi_type,
i,
0,
comm,
MPI_STATUSES_IGNORE);
offsetA += receive_size_A;
offsetB += receive_size_B;
}
}
// Rank i send data
if (rank > 0) {
MPI_Send(A.matrix_pointer(), sizeA, mpi_type, 0, 0, comm);
MPI_Send(B.matrix_pointer(), sizeB, mpi_type, 0, 0, comm);
}
MPI_Barrier(comm);
// Then rank 0 must reorder data locally
std::vector<Scalar> globA;
std::vector<Scalar> globB;
std::vector<Scalar> globCcheck;
if (rank == 0) {
globA.resize(m * k);
globB.resize(k * n);
globCcheck.resize(m * n);
int offsetA = 0;
int offsetB = 0;
for (int i = 0; i < P; i++) {
int local_size_A = A.matrix_size(i);
int local_size_B = B.matrix_size(i);
for (int j = 0; j < local_size_A; j++) {
int y, x;
std::tie(y, x) = A.global_coordinates(j, i);
if (y >= 0 && x >= 0) {
globA.at(x * m + y) = As.at(offsetA + j);
}
}
for (int j = 0; j < local_size_B; j++) {
int y, x;
std::tie(y, x) = B.global_coordinates(j, i);
// std::cout << "Mapped successfully!\n";
if (y >= 0 && x >= 0) {
// globB.at(x*n+y)=Bs.at(i*sizeB+j);
// std::cout << "Retrieved Bs value successfully!\n";
globB.at(x * k + y) = Bs.at(offsetB + j);
}
}
offsetA += local_size_A;
offsetB += local_size_B;
}
// Now compute the result
cosma::local_multiply(globA.data(),
globB.data(),
globCcheck.data(),
m,
n,
k,
Scalar{1.0},
Scalar{0.0});
#ifdef DEBUG
std::cout << "Complete matrix A: " << std::endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < k; j++) {
std::cout << globA[j * m + i] << " ";
}
std::cout << "\n";
}
std::cout << "\n";
std::cout << "Complete matrix B: " << std::endl;
for (int i = 0; i < k; i++) {
for (int j = 0; j < n; j++) {
std::cout << globB[j * k + i] << " ";
}
std::cout << "\n";
}
std::cout << "Complete matrix C: " << std::endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
std::cout << globCcheck[j * m + i] << " ";
}
std::cout << "\n";
}
std::cout << "\n";
#endif
}
multiply(A, B, C, s, comm, Scalar{1}, Scalar{0});
// Then rank0 ask for other ranks data
std::vector<Scalar> Cs;
if (rank == 0) {
Cs = std::vector<Scalar>(m * n);
std::memcpy(Cs.data(), C.matrix_pointer(), C.matrix_size()*sizeof(Scalar));
int offsetC = sizeC;
for (int i = 1; i < P; i++) {
int receive_size_C = C.matrix_size(i);
// Rank 0 receive data
MPI_Recv(Cs.data() + offsetC,
receive_size_C,
mpi_type,
i,
0,
comm,
MPI_STATUSES_IGNORE);
offsetC += receive_size_C;
}
}
// Rank i send data
if (rank > 0) {
MPI_Send(C.matrix_pointer(), sizeC, mpi_type, 0, 0, comm);
}
MPI_Barrier(comm);
// Then rank 0 must reorder data locally
std::vector<Scalar> globC;
if (rank == 0) {
globC.resize(m * n);
int offsetC = 0;
for (int i = 0; i < P; i++) {
int local_size_C = C.matrix_size(i);
for (int j = 0; j < local_size_C; j++) {
int y, x;
std::tie(y, x) = C.global_coordinates(j, i);
if (y >= 0 && x >= 0) {
globC.at(x * m + y) = Cs.at(offsetC + j);
}
}
offsetC += local_size_C;
}
// Now Check result
isOK = globCcheck.size() == globC.size();
for (int i = 0; i < globC.size(); ++i) {
isOK = isOK && (std::abs(globC[i] - globCcheck[i]) < epsilon);
}
if (!isOK) {
std::cout << "Result is NOT OK" << std::endl;
for (int i = 0; i < m * n; i++) {
if (globCcheck[i] != globC[i]) {
int x = i % m;
int y = i / m;
int locidx, rank;
std::tie(locidx, rank) = C.local_coordinates(x, y);
std::cout << "global(" << x << ", " << y
<< ") = (loc = " << locidx << ", rank = " << rank
<< ") = " << globC.at(i) << " and should be "
<< globCcheck.at(i) << std::endl;
}
}
}
else {
std::cout <<"Result is OK"<<std::endl;
}
}
#ifdef DEBUG
for (int i = 0; i < P; i++) {
if (rank == i) {
printf("(%d) A: ", i);
for (auto j = 0; j < sizeA; j++)
printf("%5.3f ", A.matrix_pointer()[j]);
printf("\n");
printf("(%d) B: ", i);
for (auto j = 0; j < sizeB; j++)
printf("%5.3f ", B.matrix_pointer()[j]);
printf("\n");
printf("(%d) C: ", i);
for (auto j = 0; j < sizeC; j++)
printf("%5.3f ", C.matrix_pointer()[j]);
printf("\n");
}
MPI_Barrier(comm);
}
#endif // DEBUG
return rank > 0 || isOK;
}
|
/**
* @file XmlUtils.hpp
* @brief XmlUtils class prototype.
* @author zer0
* @date 2019-08-05
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_DOM_XML_XMLUTILS_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_DOM_XML_XMLUTILS_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <libtbag/Err.hpp>
#include <libtbag/dom/xml/tinyxml2/tinyxml2.h>
#include <string>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace dom {
namespace xml {
using Document = tinyxml2::XMLDocument;
using Element = tinyxml2::XMLElement;
using Node = tinyxml2::XMLNode;
TBAG_API std::string name(Element const & elem);
TBAG_API std::string text(Element const & element);
TBAG_API void text(Element & element, std::string const & value);
TBAG_API void text(Element & element, char const * value);
TBAG_API void text(Element & element, bool value);
TBAG_API void text(Element & element, int value);
TBAG_API void text(Element & element, unsigned int value);
TBAG_API void text(Element & element, float value);
TBAG_API void text(Element & element, double value);
TBAG_API bool existsChildElement(Element const & element, std::string const & tag);
TBAG_API bool existsAttribute(Element const & element, std::string const & key);
TBAG_API Err opt(Element const & element, std::string const & key, std::string & result, std::string const & default_value = std::string());
TBAG_API Err opt(Element const & element, std::string const & key, bool & result, bool default_value = false);
TBAG_API Err opt(Element const & element, std::string const & key, int & result, int default_value = 0);
TBAG_API Err opt(Element const & element, std::string const & key, unsigned int & result, unsigned int default_value = 0);
TBAG_API Err opt(Element const & element, std::string const & key, float & result, float default_value = 0.0);
TBAG_API Err opt(Element const & element, std::string const & key, double & result, double default_value = 0.0);
TBAG_API Element & set(Element & element, std::string const & key, std::string const & value);
TBAG_API Element & set(Element & element, std::string const & key, char const * value);
TBAG_API Element & set(Element & element, std::string const & key, bool value);
TBAG_API Element & set(Element & element, std::string const & key, int value);
TBAG_API Element & set(Element & element, std::string const & key, unsigned int value);
TBAG_API Element & set(Element & element, std::string const & key, float value);
TBAG_API Element & set(Element & element, std::string const & key, double value);
TBAG_API Err optAttr(Element const & element, std::string const & key, std::string & result, std::string const & default_value = std::string());
TBAG_API Err optAttr(Element const & element, std::string const & key, bool & result, bool default_value = false);
TBAG_API Err optAttr(Element const & element, std::string const & key, int & result, int default_value = 0);
TBAG_API Err optAttr(Element const & element, std::string const & key, unsigned int & result, unsigned int default_value = 0);
TBAG_API Err optAttr(Element const & element, std::string const & key, std::int64_t & result, std::int64_t default_value = 0);
TBAG_API Err optAttr(Element const & element, std::string const & key, float & result, float default_value = 0.0);
TBAG_API Err optAttr(Element const & element, std::string const & key, double & result, double default_value = 0.0);
TBAG_API Element & setAttr(Element & element, std::string const & key, std::string const & value);
TBAG_API Element & setAttr(Element & element, std::string const & key, char const * value);
TBAG_API Element & setAttr(Element & element, std::string const & key, bool value);
TBAG_API Element & setAttr(Element & element, std::string const & key, int value);
TBAG_API Element & setAttr(Element & element, std::string const & key, unsigned int value);
TBAG_API Element & setAttr(Element & element, std::string const & key, std::int64_t value);
TBAG_API Element & setAttr(Element & element, std::string const & key, float value);
TBAG_API Element & setAttr(Element & element, std::string const & key, double value);
TBAG_API Element * newElement(Document & doc, std::string const & tag);
TBAG_API Element * newElement(Element & element, std::string const & tag);
TBAG_API Node * insertElement(Document & doc, Node * node);
TBAG_API Node * insertElement(Element & element, Node * node);
TBAG_API Err readDocumentFromXmlText(Document & doc, std::string const & xml);
TBAG_API Err writeDocumentToXmlText(Document const & doc, std::string & xml, bool compact = false, int depth = 0);
TBAG_API Err writeElementToXmlText(Element const & elem, std::string & xml, bool compact = false, int depth = 0);
TBAG_API Err writeElementToXmlElement(Element const & elem, Element & output);
} // namespace xml
} // namespace dom
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_DOM_XML_XMLUTILS_HPP__
|
//$Id$
//------------------------------------------------------------------------------
// ParameterCreateDialog
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool
//
// Copyright (c) 2002 - 2018 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other 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.
//
// Author: Linda Jun
// Created: 2004/02/25
//
/**
* Implements ParameterCreateDialog class. This class shows dialog window where a
* user parameter can be created.
*
*/
//------------------------------------------------------------------------------
#include "ParameterCreateDialog.hpp"
#include "ParameterSelectDialog.hpp"
#include "GmatMainFrame.hpp"
#include "FileManager.hpp"
#include "FileUtil.hpp"
#include "GmatStaticBoxSizer.hpp"
#include "GmatAppData.hpp" // for GetResourceTree()
#include "ResourceTree.hpp"
#include "RgbColor.hpp"
#include "ParameterInfo.hpp" // for GetDepObjectType()
#include "StringUtil.hpp" // for GmatStringUtil::
#include "MessageInterface.hpp"
#include "StringTokenizer.hpp"
#include "Array.hpp"
#include "gmatdefs.hpp"
#include "ArraySetupDialog.hpp"
#include "bitmaps/Erase.xpm"
#include <wx/help.h>
#include <wx/tglbtn.h>
#include <wx/notebook.h>
#include <wx/config.h>
#include <wx/variant.h> // for wxVariant()
//#define DEBUG_PARAM_CREATE
//#define DEBUG_PARAM_CREATE_VAR
//#define DEBUG_PARAM_CREATE_LOAD
//#define DEBUG_PARAM_CREATE_SAVE
//#define DEBUG_PAGE_CHANGED
//------------------------------------------------------------------------------
// event tables and other macros for wxWindows
//------------------------------------------------------------------------------
BEGIN_EVENT_TABLE(ParameterCreateDialog, GmatDialog)
EVT_BUTTON(ID_BUTTON_OK, ParameterCreateDialog::OnOK)
EVT_BUTTON(ID_CREATE_BUTTON, ParameterCreateDialog::OnCreateButton)
EVT_BUTTON(ID_SELECT_BUTTON, ParameterCreateDialog::OnSelectButtonClick)
EVT_BUTTON(ID_EDITARRAY_BUTTON, ParameterCreateDialog::OnEditArrayButtonClick)
EVT_BUTTON(ID_CLEAR_VAR_BUTTON, ParameterCreateDialog::OnClearButtonClick)
EVT_BUTTON(ID_CLEAR_ARR_BUTTON, ParameterCreateDialog::OnClearButtonClick)
EVT_BUTTON(ID_CLEAR_STR_BUTTON, ParameterCreateDialog::OnClearButtonClick)
EVT_TEXT(ID_VARTEXTCTRL, ParameterCreateDialog::OnVarTextUpdate)
EVT_TEXT_ENTER(ID_VARTEXTCTRL, ParameterCreateDialog::OnTextEnter)
EVT_TEXT(ID_ARYTEXTCTRL, ParameterCreateDialog::OnAryTextUpdate)
EVT_TEXT_ENTER(ID_ARYTEXTCTRL, ParameterCreateDialog::OnTextEnter)
EVT_TEXT(ID_STRTEXTCTRL, ParameterCreateDialog::OnStrTextUpdate)
EVT_TEXT_ENTER(ID_STRTEXTCTRL, ParameterCreateDialog::OnTextEnter)
EVT_NOTEBOOK_PAGE_CHANGED(ID_NOTEBOOK, ParameterCreateDialog::OnPageChanged)
EVT_LISTBOX(ID_LISTBOX, ParameterCreateDialog::OnListboxClick)
END_EVENT_TABLE()
//------------------------------------------------------------------------------
// ParameterCreateDialog(wxWindow *parent, int paramType)
//------------------------------------------------------------------------------
/*
* @param paramType 1 = Variable, 2 = Array, 3 = String
*/
//------------------------------------------------------------------------------
ParameterCreateDialog::ParameterCreateDialog(wxWindow *parent, ParameterType paramType)
: GmatDialog(parent, -1, wxString(_T("New Variable, Array, or String")))
{
#ifdef DEBUG_PARAM_CREATE
MessageInterface::ShowMessage
("ParameterCreateDialog() entered, paramType=%d\n", paramType);
#endif
mParamType = paramType;
mCurrParam = NULL;
mParamNames.Clear();
mIsParamCreated = false;
mPageChangedByUser = false;
mArrayChanged = false;
mVariableChanged = false;
mStringChanged = false;
mSelectVarStrings.Add("Spacecraft");
mSelectVarStrings.Add("SpacePoint");
mSelectVarStrings.Add("ImpulsiveBurn");
Create();
SetParameterType( paramType );
ShowData();
mPageChangedByUser = true;
}
//------------------------------------------------------------------------------
// ParameterCreateDialog(wxWindow *parent, string paramName)
//------------------------------------------------------------------------------
/*
*/
//------------------------------------------------------------------------------
ParameterCreateDialog::ParameterCreateDialog(wxWindow *parent, const wxString paramName)
: GmatDialog(parent, -1, wxString(_T("New Variable, Array, or String")))
{
#ifdef DEBUG_PARAM_CREATE
MessageInterface::ShowMessage
("ParameterCreateDialog() entered, paramName='%s'\n", paramName.c_str());
#endif
mObjectName = paramName.c_str();
mCurrParam = (Parameter*)theGuiInterpreter->GetConfiguredObject(mObjectName);
if (!mCurrParam)
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "Cannot find the parameter object named " + mObjectName);
}
else
{
mParamNames.Clear();
mIsParamCreated = false;
mPageChangedByUser = false;
mSelectVarStrings.Add("Spacecraft");
mSelectVarStrings.Add("SpacePoint");
mSelectVarStrings.Add("ImpulsiveBurn");
Create();
std::string s = mCurrParam->GetTypeName();
if (s == "String")
mParamType = STRING;
else if (s == "Array")
mParamType = ARRAY;
else
mParamType = VARIABLE;
SetParameterType( mParamType );
ShowData();
mPageChangedByUser = true;
}
}
//------------------------------------------------------------------------------
// ~ParameterCreateDialog()
//------------------------------------------------------------------------------
ParameterCreateDialog::~ParameterCreateDialog()
{
mSelectVarStrings.Clear();
}
//------------------------------------------------------------------------------
// void OnOK()
//------------------------------------------------------------------------------
/**
* Closes the page
*/
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnOK(wxCommandEvent &event)
{
Close();
}
//------------------------------------------------------------------------------
// virtual void Create()
//------------------------------------------------------------------------------
void ParameterCreateDialog::Create()
{
#ifdef DEBUG_PARAM_CREATE
MessageInterface::ShowMessage("ParameterCreateDialog::Create() entered\n");
#endif
#if __WXMAC__
int buttonWidth = 40;
#else
int buttonWidth = 25;
#endif
int bsize = 2;
std::string CreateLabel = "=" GUI_ACCEL_KEY ">";
wxBitmap clearBitmap = wxBitmap(Erase_xpm);
// get the config object
wxConfigBase *pConfig = wxConfigBase::Get();
// SetPath() understands ".."
pConfig->SetPath(wxT("/Parameter"));
notebook = new wxNotebook(this, ID_NOTEBOOK);
wxPanel *varPanel = new wxPanel(notebook);
wxPanel *arrPanel = new wxPanel(notebook);
wxPanel *strPanel = new wxPanel(notebook);
//wxStaticText
wxStaticText *varNameStaticText =
new wxStaticText(varPanel, ID_TEXT, "Variable " GUI_ACCEL_KEY "Name",
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *expStaticText =
new wxStaticText(varPanel, ID_TEXT, "Variable " GUI_ACCEL_KEY "Value",
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *varEqualSignStaticText =
new wxStaticText(varPanel, ID_TEXT, wxT("="),
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *arrNameStaticText =
new wxStaticText(arrPanel, ID_TEXT, "Array " GUI_ACCEL_KEY "Name",
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *arr1RowStaticText =
new wxStaticText(arrPanel, ID_TEXT, GUI_ACCEL_KEY"Row",
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *arr1ColStaticText =
new wxStaticText(arrPanel, ID_TEXT, GUI_ACCEL_KEY"Column",
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *arrEqualSignStaticText =
new wxStaticText(arrPanel, ID_TEXT, wxT("="),
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *arrTimesStaticText =
new wxStaticText(arrPanel, ID_TEXT, wxT(" X"),
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *stringNameLabel =
new wxStaticText(strPanel, ID_TEXT, "String " GUI_ACCEL_KEY "Name",
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *stringEqualSignStaticText =
new wxStaticText(strPanel, ID_TEXT, wxT("="),
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *stringValueLabel =
new wxStaticText(strPanel, ID_TEXT, "String " GUI_ACCEL_KEY "Value",
wxDefaultPosition, wxDefaultSize, 0);
wxStaticText *configStringLabel =
new wxStaticText(strPanel, ID_TEXT, GUI_ACCEL_KEY"Strings",
wxDefaultPosition, wxDefaultSize, 0);
// wxTextCtrl
mVarClearButton =
new wxBitmapButton(varPanel, ID_CLEAR_VAR_BUTTON, clearBitmap, wxDefaultPosition,
wxSize(buttonWidth, -1));
mVarClearButton->SetToolTip(pConfig->Read(_T("ClearVariableHint"), "Clear Variable Fields"));
mVarNameTextCtrl = new wxTextCtrl(varPanel, ID_VARTEXTCTRL, wxT(""),
wxDefaultPosition, wxSize(130,-1), wxTE_PROCESS_ENTER);
mVarNameTextCtrl->SetToolTip(pConfig->Read(_T("VariableNameHint")));
// Only numeric value is allowed (LOJ: 2010.11.24)
mVarValueTextCtrl = new wxTextCtrl(varPanel, ID_VARTEXTCTRL, wxT(""),
wxDefaultPosition, wxSize(280,-1), wxTE_PROCESS_ENTER,
wxTextValidator(wxGMAT_FILTER_NUMERIC));
mVarValueTextCtrl->SetToolTip(pConfig->Read(_T("VariableValueHint")));
mArrClearButton =
new wxBitmapButton(arrPanel, ID_CLEAR_ARR_BUTTON, clearBitmap, wxDefaultPosition,
wxSize(buttonWidth, -1));
mArrClearButton->SetToolTip(pConfig->Read(_T("ClearArrayHint"), "Clear Array Fields"));
mArrNameTextCtrl = new wxTextCtrl(arrPanel, ID_ARYTEXTCTRL, wxT(""),
wxDefaultPosition, wxSize(102,-1), wxTE_PROCESS_ENTER);
mArrNameTextCtrl->SetToolTip(pConfig->Read(_T("ArrayNameHint")));
mArrRowTextCtrl = new wxTextCtrl(arrPanel, ID_ARYTEXTCTRL, wxT(""),
wxDefaultPosition, wxSize(50,-1), wxTE_PROCESS_ENTER,
wxTextValidator(wxGMAT_FILTER_NUMERIC));
mArrRowTextCtrl->SetToolTip(pConfig->Read(_T("ArrayRowValueHint")));
mArrColTextCtrl = new wxTextCtrl(arrPanel, ID_ARYTEXTCTRL, wxT(""),
wxDefaultPosition, wxSize(50,-1), wxTE_PROCESS_ENTER,
wxTextValidator(wxGMAT_FILTER_NUMERIC));
mArrColTextCtrl->SetToolTip(pConfig->Read(_T("ArrayColumnValueHint")));
mStrClearButton =
new wxBitmapButton(strPanel, ID_CLEAR_STR_BUTTON, clearBitmap, wxDefaultPosition,
wxSize(buttonWidth, -1));
mStrClearButton->SetToolTip(pConfig->Read(_T("ClearStringHint"), "Clear String Fields"));
mStringNameTextCtrl = new wxTextCtrl(strPanel, ID_STRTEXTCTRL, wxT(""),
wxDefaultPosition, wxSize(80,-1), wxTE_PROCESS_ENTER);
mStringNameTextCtrl->SetToolTip(pConfig->Read(_T("StringNameHint")));
mStringValueTextCtrl = new wxTextCtrl(strPanel, ID_STRTEXTCTRL, wxT(""),
wxDefaultPosition, wxSize(110,-1), wxTE_PROCESS_ENTER);
mStringValueTextCtrl->SetToolTip(pConfig->Read(_T("StringValueHint")));
// wxButton
mCreateVariableButton = new wxButton(varPanel, ID_CREATE_BUTTON, wxString(CreateLabel.c_str()),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
mCreateVariableButton->SetToolTip(pConfig->Read(_T("CreateVariableHint")));
mCreateVariableButton->Disable();
mSelectButton = new wxButton(varPanel, ID_SELECT_BUTTON, wxT("Select"),
wxDefaultPosition, wxDefaultSize, 0);
mSelectButton->SetToolTip(pConfig->Read(_T("SelectHint")));
mCreateArrayButton = new wxButton(arrPanel, ID_CREATE_BUTTON, wxString(CreateLabel.c_str()),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
mCreateArrayButton->SetToolTip(pConfig->Read(_T("CreateArrayHint")));
mCreateArrayButton->Disable();
mEditArrayButton = new wxButton(arrPanel, ID_EDITARRAY_BUTTON, wxT("Edit"),
wxDefaultPosition, wxDefaultSize, 0);
mEditArrayButton->Disable();
mEditArrayButton->SetToolTip(pConfig->Read(_T("EditArrayHint")));
mCreateStringButton = new wxButton(strPanel, ID_CREATE_BUTTON, wxString(CreateLabel.c_str()),
wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT);
mCreateStringButton->SetToolTip(pConfig->Read(_T("CreateStringHint")));
mCreateStringButton->Disable();
//wxArrayString
wxArrayString emptyArray;
// wxListBox
mUserVarListBox =
theGuiManager->GetUserVariableListBox(varPanel, ID_LISTBOX, wxSize(170, 125), "");
mUserVarListBox->SetToolTip(pConfig->Read(_T("VariableListHint")));
mUserArrayListBox =
theGuiManager->GetUserArrayListBox(arrPanel, ID_LISTBOX, wxSize(170, 125), "");
mUserArrayListBox->SetToolTip(pConfig->Read(_T("ArrayListHint")));
mUserStringListBox =
theGuiManager->GetUserStringListBox(strPanel, ID_LISTBOX, wxSize(170, 125), "");
mUserStringListBox->SetToolTip(pConfig->Read(_T("StringListHint")));
// wxSizers
mDetailsBoxSizer = new wxBoxSizer(wxHORIZONTAL);
wxFlexGridSizer *top1FlexGridSizer = new wxFlexGridSizer(5, 0, 0);
wxFlexGridSizer *objPropertyFlexGridSizer = new wxFlexGridSizer(4, 0, 0);
wxFlexGridSizer *arr1FlexGridSizer = new wxFlexGridSizer(7, 0, 0);
wxFlexGridSizer *stringFlexGridSizer = new wxFlexGridSizer(6, 0, 0);
GmatStaticBoxSizer *variableStaticBoxSizer =
new GmatStaticBoxSizer(wxHORIZONTAL, varPanel);
GmatStaticBoxSizer *arrayStaticBoxSizer =
new GmatStaticBoxSizer(wxHORIZONTAL, arrPanel);
GmatStaticBoxSizer *stringStaticBoxSizer =
new GmatStaticBoxSizer(wxVERTICAL, strPanel);
// Add to wx*Sizers
//-------------------------------------------------------
// for Variable
//-------------------------------------------------------
top1FlexGridSizer->Add(0, 0, 0, bsize);
top1FlexGridSizer->Add(varNameStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
top1FlexGridSizer->Add(0, 0, 0, bsize);
top1FlexGridSizer->Add(expStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
top1FlexGridSizer->Add(0, 0, 0, bsize);
top1FlexGridSizer->Add(mVarClearButton, 0, wxALIGN_CENTER|wxALL, bsize);
top1FlexGridSizer->Add(mVarNameTextCtrl, 0, wxALIGN_CENTER|wxALL, bsize);
top1FlexGridSizer->Add(varEqualSignStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
top1FlexGridSizer->Add(mVarValueTextCtrl, 0, wxALIGN_CENTER|wxALL, bsize);
top1FlexGridSizer->Add(mCreateVariableButton, 0, wxALIGN_CENTRE|wxALL, bsize);
top1FlexGridSizer->Add(0, 0, wxALIGN_CENTER|wxALL, bsize);
top1FlexGridSizer->Add(0, 0, wxALIGN_CENTRE|wxALL, bsize);
top1FlexGridSizer->Add(0, 0, wxALIGN_CENTRE|wxALL, bsize);
top1FlexGridSizer->Add(mSelectButton, 0, wxALIGN_LEFT|wxALL, bsize);
top1FlexGridSizer->Add(0, 0, wxALIGN_CENTRE|wxALL, bsize);
objPropertyFlexGridSizer->Add(mUserVarListBox, 0, wxALIGN_CENTER|wxALL, bsize);
variableStaticBoxSizer->Add(top1FlexGridSizer, 0, wxALIGN_TOP|wxALL, bsize);
variableStaticBoxSizer->Add(objPropertyFlexGridSizer, 0, wxALIGN_TOP|wxALL, bsize);
stringFlexGridSizer->Add(0, 0, 0, bsize);
stringFlexGridSizer->Add(stringNameLabel, 0, wxALIGN_CENTER|wxALL, bsize);
stringFlexGridSizer->Add(0, 0, 0, bsize);
stringFlexGridSizer->Add(stringValueLabel, 1, wxALIGN_CENTER|wxALL, bsize);
stringFlexGridSizer->Add(0, 0, 0, bsize);
stringFlexGridSizer->Add(configStringLabel, 0, wxALIGN_CENTER|wxALL, bsize);
stringFlexGridSizer->Add(mStrClearButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, bsize);
stringFlexGridSizer->Add(mStringNameTextCtrl, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, bsize);
stringFlexGridSizer->Add(stringEqualSignStaticText, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, bsize);
stringFlexGridSizer->Add(mStringValueTextCtrl, 1, wxALIGN_CENTER_HORIZONTAL|wxALL, bsize);
stringFlexGridSizer->Add(mCreateStringButton, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, bsize);
stringFlexGridSizer->Add(mUserStringListBox, 0, wxALIGN_CENTER|wxALL, bsize);
stringStaticBoxSizer->Add(stringFlexGridSizer, 0, wxALIGN_TOP|wxALL, bsize);
//-------------------------------------------------------
// for Array Creation
//-------------------------------------------------------
// 1st row
arr1FlexGridSizer->Add(0, 0, 0, bsize);
arr1FlexGridSizer->Add(arrNameStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(0, 0, 0, bsize);
arr1FlexGridSizer->Add(arr1RowStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(0, 0, 0, bsize);
arr1FlexGridSizer->Add(arr1ColStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(0, 0, 0, bsize);
//arr1FlexGridSizer->Add(configArrStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
// 2nd row
arr1FlexGridSizer->Add(mArrClearButton, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(mArrNameTextCtrl, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(arrEqualSignStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(mArrRowTextCtrl, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(arrTimesStaticText, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(mArrColTextCtrl, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(mCreateArrayButton, 0, wxALIGN_CENTER|wxALL, bsize);
//arr1FlexGridSizer->Add(mUserArrayListBox, 0, wxALIGN_CENTER|wxALL, bsize);
arr1FlexGridSizer->Add(0, 0, 0, bsize);
arr1FlexGridSizer->Add(mEditArrayButton, 0, wxALIGN_LEFT, bsize);
arrayStaticBoxSizer->Add(arr1FlexGridSizer, 0, wxALIGN_TOP|wxALL, bsize);
arrayStaticBoxSizer->Add(mUserArrayListBox, 0, wxALIGN_TOP|wxALL, bsize);
varPanel->SetSizer(variableStaticBoxSizer);
arrPanel->SetSizer(arrayStaticBoxSizer);
strPanel->SetSizer(stringStaticBoxSizer);
//-------------------------------------------------------
// add to parent sizer
//-------------------------------------------------------
notebook->AddPage(varPanel, GUI_ACCEL_KEY"Variable", true);
notebook->AddPage(arrPanel, GUI_ACCEL_KEY"Array", false);
notebook->AddPage(strPanel, GUI_ACCEL_KEY"String", false);
theMiddleSizer->Add(notebook, 0, wxALIGN_LEFT|wxGROW, 0);
theCancelButton->SetLabel("Cancel");
theOkButton->SetLabel("Close"); // OK button acts like Close
// Only numbers and string literals are allowed for initial values, so hide
mSelectButton->Hide();
#ifdef DEBUG_PARAM_CREATE
MessageInterface::ShowMessage("ParameterCreateDialog::Create() exiting\n");
#endif
}
//------------------------------------------------------------------------------
// virtual void LoadData()
//------------------------------------------------------------------------------
void ParameterCreateDialog::LoadData()
{
#ifdef DEBUG_PARAM_CREATE_LOAD
MessageInterface::ShowMessage
("ParameterCreateDialog::LoadData() entering, mObjectName='%s'\n", mObjectName.c_str());
#endif
wxString str;
int mNumRows;
int mNumCols;
// Real rval;
if (mObjectName != "")
{
mCurrParam =
(Parameter*)theGuiInterpreter->GetConfiguredObject(mObjectName.c_str());
// Set the pointer for the "Show Script" button
mObject = mCurrParam;
if (mCurrParam == NULL)
return;
switch (mParamType)
{
case VARIABLE:
mVarNameTextCtrl->SetValue(mObjectName.c_str());
// We no longer allow expression (LOJ: 2010.11.24)
//mVarValueTextCtrl->SetValue(mCurrParam->GetStringParameter("Expression").c_str());
mVarValueTextCtrl->SetValue(wxVariant(mCurrParam->GetRealParameter("Value")));
mCreateVariableButton->Disable();
mUserVarListBox->SetStringSelection(mObjectName.c_str());
mVariableChanged = false;
break;
case ARRAY:
mArrNameTextCtrl->SetValue(mObjectName.c_str());
mNumRows = mCurrParam->GetIntegerParameter("NumRows");
mNumCols = mCurrParam->GetIntegerParameter("NumCols");
str << mNumRows;
mArrRowTextCtrl->SetValue(str);
str = "";
str << mNumCols;
mArrColTextCtrl->SetValue(str);
mCreateArrayButton->Disable();
mEditArrayButton->Enable(mCurrParam != NULL);
mUserArrayListBox->SetStringSelection(mObjectName.c_str());
mArrayChanged = false;
break;
case STRING:
mStringNameTextCtrl->SetValue(mObjectName.c_str());
mStringValueTextCtrl->SetValue(mCurrParam->GetStringParameter("Expression").c_str());
mCreateStringButton->Disable();
mUserStringListBox->SetStringSelection(mObjectName.c_str());
mStringChanged = false;
break;
}
}
#ifdef DEBUG_PARAM_CREATE_LOAD
MessageInterface::ShowMessage("ParameterCreateDialog::LoadData() exiting\n");
#endif
}
//------------------------------------------------------------------------------
// virtual void SaveData()
//------------------------------------------------------------------------------
void ParameterCreateDialog::SaveData()
{
std::string s;
Integer mNumCols;
Integer mNumRows;
canClose = true;
wxString paramName;
#ifdef DEBUG_PARAM_CREATE_SAVE
MessageInterface::ShowMessage
("ParameterCreateDialog::SaveData() entered, mParamType=%d, mCurrParam=<%p>\n"
" mArrayChanged=%d, mVariableChanged=%d, mStringChanged=%d\n", mParamType,
mCurrParam, mArrayChanged, mVariableChanged, mStringChanged);
#endif
// Check for the existing name
switch (mParamType)
{
case VARIABLE:
paramName = mVarNameTextCtrl->GetValue();
if ((mCurrParam == NULL) || (mObjectName.c_str() != paramName))
{
CreateVariable();
}
else
{
std::string expr = mVarValueTextCtrl->GetValue().WX_TO_STD_STRING;
Real rval;
CheckReal(rval, expr, "Expression", "Real Number");
#ifdef DEBUG_PARAM_CREATE_SAVE
MessageInterface::ShowMessage
(" Setting %s to variable '%s'\n", expr.c_str(), mCurrParam->GetName().c_str());
#endif
mCurrParam->SetStringParameter("Expression", expr);
ResetControls();
}
break;
case ARRAY:
paramName = mArrNameTextCtrl->GetValue();
if ((mCurrParam == NULL) || (mObjectName.c_str() != paramName))
{
#ifdef DEBUG_PARAM_CREATE_SAVE
MessageInterface::ShowMessage
(" Creating new Array '%s'\n", paramName.c_str());
#endif
CreateArray();
}
else
{
#ifdef DEBUG_PARAM_CREATE_SAVE
MessageInterface::ShowMessage
(" Modifying existing Array '%s'\n", paramName.c_str());
#endif
s = mArrRowTextCtrl->GetValue().c_str();
CheckIntegerRange(mNumRows, s, "Rows", 1, 1000, true, true, true, true);
s = mArrColTextCtrl->GetValue().c_str();
CheckIntegerRange(mNumCols, s, "Columns", 1, 1000, true, true, true, true);
// Reset size if columns and rows are valid
if (canClose)
{
#ifdef DEBUG_PARAM_CREATE_SAVE
MessageInterface::ShowMessage
(" Resetting size of Array '%s' to rows=%d, cols=%d\n",
paramName.c_str(), mNumRows, mNumCols);
#endif
((Array *) mCurrParam)->SetSize(mNumRows, mNumCols, false);
}
if (canClose)
ResetControls();
}
break;
case STRING:
paramName = mStringNameTextCtrl->GetValue();
if ((mCurrParam == NULL) || (mObjectName.c_str() != paramName))
{
CreateString();
}
else
{
std::string expr = mStringValueTextCtrl->GetValue().WX_TO_STD_STRING;
mCurrParam->SetStringParameter("Expression", expr);
ResetControls();
}
break;
}
if (!canClose) return;
EnableUpdate( mCreateVariableButton->IsEnabled() ||
mCreateArrayButton->IsEnabled() ||
mCreateStringButton->IsEnabled() );
#ifdef DEBUG_PARAM_CREATE_SAVE
MessageInterface::ShowMessage
("ParameterCreateDialog::SaveData() leaving, mParamType=%d, mCurrParam=<%p>\n"
" mArrayChanged=%d, mVariableChanged=%d, mStringChanged=%d\n", mParamType,
mCurrParam, mArrayChanged, mVariableChanged, mStringChanged);
#endif
}
//------------------------------------------------------------------------------
// virtual void ResetData()
//------------------------------------------------------------------------------
void ParameterCreateDialog::ResetData()
{
mIsParamCreated = false;
}
//------------------------------------------------------------------------------
// virtual void ResetControls()
//------------------------------------------------------------------------------
void ParameterCreateDialog::ResetControls()
{
switch (mParamType)
{
case VARIABLE:
mCreateVariableButton->Disable();
mVarValueTextCtrl->SetValue("");
mVarNameTextCtrl->SetValue("");
mVariableChanged = false;
mUserVarListBox->Deselect(mUserVarListBox->GetSelection());
break;
case ARRAY:
mCreateArrayButton->Disable();
mArrNameTextCtrl->SetValue("");
mArrRowTextCtrl->SetValue("");
mArrColTextCtrl->SetValue("");
mEditArrayButton->Disable();
mUserArrayListBox->Deselect(mUserArrayListBox->GetSelection());
mArrayChanged = false;
break;
case STRING:
mCreateStringButton->Disable();
mStringNameTextCtrl->SetValue("");
mStringValueTextCtrl->SetValue("");
mUserStringListBox->Deselect(mUserStringListBox->GetSelection());
mStringChanged = false;
break;
}
}
//---------------------------------
// event handling
//---------------------------------
//------------------------------------------------------------------------------
// void OnVarTextUpdate(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnVarTextUpdate(wxCommandEvent& event)
{
mCreateVariableButton->Disable();
if ((mVarNameTextCtrl->IsModified() &&
mVarNameTextCtrl->GetValue().Trim() != "") ||
(mVarValueTextCtrl->IsModified() &&
mVarValueTextCtrl->GetValue().Trim() != ""))
{
mCreateVariableButton->Enable();
EnableUpdate(true);
mVariableChanged = true;
}
}
//------------------------------------------------------------------------------
// void OnTextEnter(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnTextEnter(wxCommandEvent& event)
{
((wxWindow *) event.GetEventObject())->GetNextSibling()->SetFocus();
}
//------------------------------------------------------------------------------
// void OnAryTextUpdate(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnAryTextUpdate(wxCommandEvent& event)
{
mCreateArrayButton->Disable();
if ((mArrNameTextCtrl->IsModified() &&
mArrNameTextCtrl->GetValue().Trim() != "") ||
(mArrRowTextCtrl->IsModified() &&
mArrRowTextCtrl->GetValue().Trim() != "") ||
(mArrColTextCtrl->IsModified() &&
mArrColTextCtrl->GetValue().Trim() != ""))
{
mCreateArrayButton->Enable();
EnableUpdate(true);
mArrayChanged = true;
}
}
//------------------------------------------------------------------------------
// void OnStrTextUpdate(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnStrTextUpdate(wxCommandEvent& event)
{
mCreateStringButton->Disable();
if ((mStringNameTextCtrl->IsModified() &&
mStringNameTextCtrl->GetValue().Trim() != "") ||
mStringValueTextCtrl->IsModified())
{
mCreateStringButton->Enable();
EnableUpdate(true);
mStringChanged = true;
}
}
//------------------------------------------------------------------------------
// void OnCreateButton(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnCreateButton(wxCommandEvent& event)
{
SaveData();
switch (mParamType)
{
case VARIABLE:
mVarNameTextCtrl->SetFocus();
break;
case ARRAY:
mArrNameTextCtrl->SetFocus();
break;
case STRING:
mStringNameTextCtrl->SetFocus();
break;
}
}
//------------------------------------------------------------------------------
// void SetParameterType(ParameterType paramType)
//------------------------------------------------------------------------------
void ParameterCreateDialog::SetParameterType( ParameterType paramType )
{
mParamType = paramType;
#ifdef DEBUG_PARAM_CREATE
MessageInterface::ShowMessage
("SetParameterType() entered, mParamType=%d, mObjectName='%s'\n",
mParamType, mObjectName.c_str());
#endif
// This SetSelection() is deprecated and should not be used in new code.
// So used the ChangeSelection() function instead. (LOJ: 2010.11.29)
notebook->ChangeSelection( (size_t) mParamType );
}
//------------------------------------------------------------------------------
// void OnPageChanged(wxNotebookEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnPageChanged(wxNotebookEvent& event)
{
#ifdef DEBUG_PAGE_CHANGED
MessageInterface::ShowMessage
("OnPageChanged() entered, mPageChangedByUser=%d, mArrayChanged=%d, "
"mVariableChanged=%d, mStringChanged=%d\n", mPageChangedByUser, mArrayChanged,
mVariableChanged, mStringChanged);
#endif
if (mPageChangedByUser)
{
// Show current selection data when page chaged by user
mParamType = (ParameterType) event.GetSelection();
switch (mParamType)
{
case VARIABLE:
mObjectName = mUserVarListBox->GetStringSelection();
if (!mVariableChanged)
LoadData();
break;
case ARRAY:
mObjectName = mUserArrayListBox->GetStringSelection();
if (!mArrayChanged)
LoadData();
break;
case STRING:
mObjectName = mUserStringListBox->GetStringSelection();
if (!mStringChanged)
LoadData();
break;
}
}
// Show current selection data when page chages
switch (mParamType)
{
case VARIABLE:
mVarNameTextCtrl->SetFocus();
break;
case ARRAY:
mArrNameTextCtrl->SetFocus();
break;
case STRING:
mStringNameTextCtrl->SetFocus();
break;
}
}
//------------------------------------------------------------------------------
// void OnClearButtonClick(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnClearButtonClick(wxCommandEvent& event)
{
switch (mParamType)
{
case VARIABLE:
mVarNameTextCtrl->Clear();
mVarValueTextCtrl->Clear();
mUserVarListBox->Deselect(mUserVarListBox->GetSelection());
break;
case ARRAY:
mArrNameTextCtrl->Clear();
mArrRowTextCtrl->Clear();
mArrColTextCtrl->Clear();
mUserArrayListBox->Deselect(mUserArrayListBox->GetSelection());
break;
case STRING:
mStringNameTextCtrl->Clear();
mStringValueTextCtrl->Clear();
mUserStringListBox->Deselect(mUserStringListBox->GetSelection());
break;
}
}
//------------------------------------------------------------------------------
// void OnEditArrayButtonClick(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnEditArrayButtonClick(wxCommandEvent& event)
{
#ifdef DEBUG_EDIT_ARRAY
MessageInterface::ShowMessage
("ParameterCreateDialog::OnEditArrayButtonClick() paramName='%s'\n",
mArrNameTextCtrl->GetValue().c_str());
#endif
ArraySetupDialog paramDlg(this, mArrNameTextCtrl->GetValue());
paramDlg.ShowModal();
}
//------------------------------------------------------------------------------
// void OnSelectButtonClick(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnSelectButtonClick(wxCommandEvent& event)
{
ParameterSelectDialog paramDlg(this, mSelectVarStrings,
GuiItemManager::SHOW_PLOTTABLE, false, true);
paramDlg.SetParamNameArray(mSelectVarStrings);
paramDlg.ShowModal();
if (paramDlg.HasSelectionChanged())
{
wxArrayString selectVarStrings = paramDlg.GetParamNameArray();
if (selectVarStrings.Count() > 0)
{
mVarValueTextCtrl->Clear();
for (unsigned int i=0; i<selectVarStrings.Count(); i++)
mVarValueTextCtrl->AppendText(selectVarStrings[i]);
}
else // no selections
{
mVarValueTextCtrl->Clear();
}
}
}
//------------------------------------------------------------------------------
// void OnHelp(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnHelp(wxCommandEvent &event)
{
#ifdef DEBUG_GMAT_DIALOG_HELP
MessageInterface::ShowMessage
("GmatDialog::OnHelp() entered, mObject=<%p><%s>'%s'\n", mObject,
mObject ? mObject->GetTypeName().c_str() : "NULL",
mObject ? mObject->GetName().c_str() : "NULL");
#endif
wxString objLink;
wxString sHTML;
wxString baseHelpLink;
char msgBuffer[255];
// get the config object
wxConfigBase *pConfig = wxConfigBase::Get();
pConfig->SetPath(wxT("/Help"));
objLink = "VariableArrayString";
wxHelpController *theHelpController = GmatAppData::Instance()->GetMainFrame()->GetHelpController();
if (theHelpController != NULL)
{
#ifdef DEBUG_GMAT_DIALOG_HELP
MessageInterface::ShowMessage
("GmatPanel::OnHelp() theHelpController=<%p>\n "
"File to display=%s\n", theHelpController,
s);
#endif
// displays chm, not html
// see if there is an override for panel (e.g., PropSetupKeyword=Propagator)
sHTML = objLink+".html";
objLink = pConfig->Read(objLink+"Keyword", sHTML);
// work around for wxWidgets bug: http://trac.wxwidgets.org/ticket/14888
// chm help fails for Windows 8,10.
// solution taken from: https://stackoverflow.com/questions/29944745/
bool useHelpController = true;
#ifdef _WIN32 // All Win platforms define this, even when 64-bit
//For Windows 8 is dwMajorVersion = 6, dwMinorVersion = 2.
OSVERSIONINFOEX info;
ZeroMemory(&info, sizeof(OSVERSIONINFOEX));
info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx((LPOSVERSIONINFO)&info);//info requires typecasting
Real winVersion = (Real)info.dwMajorVersion + (Real)info.dwMinorVersion / 10.0;
if (winVersion > 6.1)
useHelpController = false;
#endif
if (useHelpController)
theHelpController->DisplaySection(objLink);
else
theHelpController->DisplayContents();
}
else
{
// get base help link if available
baseHelpLink = pConfig->Read(_T("BaseHelpLink"),_T("http://gmat.sourceforge.net/docs/latest/html/%s.html"));
sprintf( msgBuffer, baseHelpLink.c_str(), objLink.WX_TO_C_STRING);
#ifdef DEBUG_GMAT_DIALOG_HELP
MessageInterface::ShowMessage
(" objLink = '%s', baseHelpLink = '%s'\n helpLink = '%s'\n",
objLink.c_str(), baseHelpLink.c_str(), msgBuffer);
#endif
// open separate window to show help
objLink = pConfig->Read(objLink, wxString(&msgBuffer[0]));
#ifdef DEBUG_GMAT_DIALOG_HELP
MessageInterface::ShowMessage(" actual help Link = '%s'\n", objLink.c_str());
#endif
// if path is relative, try to append it to gmat root
if (GmatFileUtil::IsPathRelative(objLink.c_str()))
{
FileManager *fm = FileManager::Instance();
if (GmatStringUtil::EndsWithPathSeparator(fm->GetRootPath()))
objLink = fm->GetRootPath().c_str() + objLink;
else
{
wxString pathSep = GmatFileUtil::GetPathSeparator().c_str();
objLink = fm->GetRootPath().c_str() + pathSep + objLink;
}
}
wxLaunchDefaultBrowser(objLink);
}
#ifdef DEBUG_GMAT_DIALOG_HELP
MessageInterface::ShowMessage("GmatDialog::OnHelp() leaving\n");
#endif
}
//------------------------------------------------------------------------------
// void OnListboxClick(wxCommandEvent& event)
//------------------------------------------------------------------------------
void ParameterCreateDialog::OnListboxClick(wxCommandEvent& event)
{
wxString currObject = mObjectName.c_str();
wxString nextObject = event.GetString();
mObjectName = event.GetString();
#ifdef DEBUG_LIST_BOX
MessageInterface::ShowMessage
("OnListboxClick() entered, currObject='%s', nextObject='%s'\n "
"mArrayChanged=%d, mVariableChanged=%d, mStringChanged=%d\n", currObject.c_str(),
nextObject.c_str(), mArrayChanged, mVariableChanged, mStringChanged);
#endif
#if 0
bool objectChanged = false;
if (event.GetEventObject() == mUserVarListBox)
objectChanged = mVariableChanged;
else if (event.GetEventObject() == mUserArrayListBox)
objectChanged = mArrayChanged;
else if (event.GetEventObject() == mUserStringListBox)
objectChanged = mStringChanged;
#endif
// Prompt user for saving current object before switching to other of the same type
//if (objectChanged)
if (mVariableChanged || mArrayChanged || mStringChanged)
{
if (currObject != nextObject)
{
wxString paramTypeName = "Variable";
if (mArrayChanged)
paramTypeName = "Array";
else if (mStringChanged)
paramTypeName = "String";
//wxString msg = "The value change made to will be lost, do you want to save it first?";
wxString msg = "Do you want to save the new value before switching to "
" other " + paramTypeName + "?";
wxMessageDialog *msgDlg = new wxMessageDialog
(this, msg, "Save...", wxYES_NO |wxICON_QUESTION, wxDefaultPosition);
int result = msgDlg->ShowModal();
if (result == wxID_YES)
{
// Save current object before switching to other
mObjectName = currObject;
SaveData();
mObjectName = nextObject;
}
else if (result == wxID_NO)
{
if (mVariableChanged)
mVariableChanged = false;
else if (mArrayChanged)
mArrayChanged = false;
else if (mStringChanged)
mStringChanged = false;
}
}
}
LoadData();
#ifdef DEBUG_LIST_BOX
MessageInterface::ShowMessage
("OnListboxClick() leaving, currObject='%s', mObjectName='%s'\n "
"mArrayChanged=%d, mVariableChanged=%d, mStringChanged=%d\n", currObject.c_str(),
mObjectName.c_str(), mArrayChanged, mVariableChanged, mStringChanged);
#endif
}
//------------------------------------------------------------------------------
// Parameter* CreateParameter(const wxString ¶mName)
//------------------------------------------------------------------------------
/*
* @return newly created parameter pointer if it does not exist,
* return existing parameter pointer otherwise
*/
//------------------------------------------------------------------------------
Parameter* ParameterCreateDialog::CreateParameter(const wxString &name)
{
#ifdef DEBUG_PARAM_CREATE
MessageInterface::ShowMessage
("ParameterCreateDialog::CreateParameter() name:%s\n", name.c_str());
#endif
std::string paramName(name.c_str());
//std::string ownerName(mObjectListBox->GetStringSelection().c_str());
//std::string propName(mPropertyListBox->GetStringSelection().c_str());
//std::string depObjName = "";
//if (mCentralBodyComboBox->IsShown())
//{
// depObjName = std::string(mCentralBodyComboBox->GetStringSelection().c_str());
//}
//else if (mCoordSysComboBox->IsShown())
//{
// depObjName = std::string(mCoordSysComboBox->GetStringSelection().c_str());
//}
Parameter *param = theGuiInterpreter->GetParameter(paramName);
// create a parameter if it does not exist
if (param == NULL)
{
//param = theGuiInterpreter->CreateParameter(propName, paramName);
//param->SetRefObjectName(Gmat::SPACECRAFT, ownerName);
//if (depObjName != "")
// param->SetStringParameter("DepObject", depObjName);
}
#ifdef DEBUG_PARAM_CREATE
MessageInterface::ShowMessage("ParameterCreateDialog::CreateParameter() exiting\n");
#endif
return param;
}
//------------------------------------------------------------------------------
// void CreateVariable()
//------------------------------------------------------------------------------
/*
* This method creates a variable after going through validation.
*/
//------------------------------------------------------------------------------
void ParameterCreateDialog::CreateVariable()
{
wxString wxvarName = mVarNameTextCtrl->GetValue().Trim();
std::string varName = std::string(wxvarName.c_str());
wxString wxvarExpr = mVarValueTextCtrl->GetValue().Trim();
std::string varExpr = std::string(wxvarExpr.c_str());
Real realNum;
bool isRealNumber = true;
#ifdef DEBUG_PARAM_CREATE_VAR
MessageInterface::ShowMessage
("ParameterCreateDialog::CreateVariable() entered, varName = " + varName +
" varExpr = " + varExpr + "\n");
#endif
// check if it has blank variable name or expression
if (varName == "" || varExpr == "")
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "Variable name or value cannot be blank");
canClose = false;
return;
}
// Trim blank spaces
varName = GmatStringUtil::Trim(varName);
// Check if name starts with number or contains non-alphanumeric character
// Warning message is displayed from UserInputValidator::IsValidName()
if (!IsValidName(varName.c_str()))
return;
// Check if name is any command type name
if (theGuiInterpreter->IsCommandType(varName.c_str()))
{
std::string format = GmatStringUtil::GetInvalidNameMessageFormat();
MessageInterface::PopupMessage
(Gmat::ERROR_, format.c_str(), varName.c_str());
canClose = false;
return;
}
// check if rhs is a number
if (!GmatStringUtil::ToReal(varExpr, realNum))
isRealNumber = false;
Parameter *param = NULL;
// check if variable name already exist
//if (theGuiInterpreter->GetParameter(varName) != NULL)
if (theGuiInterpreter->GetConfiguredObject(varName) != NULL)
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "The variable: \"%s\" cannot be created. "
"The name already exists.", varName.c_str());
canClose = false;
return;
}
try
{
// create a variable if rhs is a number
if (isRealNumber)
{
param = theGuiInterpreter->CreateParameter("Variable", varName);
param->SetStringParameter("Expression", varExpr);
}
else
{
#ifdef __ALLOW_SETTING_TO_ANOTHER_OBJECT__
SetVariableToAnotherObject(varExpr);
#else
MessageInterface::PopupMessage
(Gmat::ERROR_, "\"%s\" is not a valid number", varExpr.c_str());
canClose = false;
return;
#endif
}
#ifdef DEBUG_PARAM_CREATE_VAR
MessageInterface::ShowMessage
("ParameterCreateDialog::CreateVariable() The variable \"%s\" added\n",
varName.c_str());
#endif
mParamNames.Add(varName.c_str());
mIsParamCreated = true;
theGuiManager->UpdateParameter();
GmatAppData::Instance()->GetResourceTree()->UpdateVariable();
mUserVarListBox->Append(varName.c_str());
for (unsigned int i=0; i<mUserVarListBox->GetCount(); i++)
{
if (mUserVarListBox->GetString(i).IsSameAs(varName.c_str()))
{
mUserVarListBox->SetSelection(i);
break;
}
}
// reset values
ResetControls();
#ifdef DEBUG_PARAM_CREATE_VAR
MessageInterface::ShowMessage
("ParameterCreateDialog::CreateVariable() leaving\n");
#endif
}
catch (BaseException &e)
{
MessageInterface::PopupMessage(Gmat::ERROR_, e.GetFullMessage());
}
}
//------------------------------------------------------------------------------
// void CreateString()
//------------------------------------------------------------------------------
void ParameterCreateDialog::CreateString()
{
wxString wxstrName = mStringNameTextCtrl->GetValue().Trim();
std::string strName = std::string(wxstrName);
std::string strValue = std::string(mStringValueTextCtrl->GetValue().c_str());
try
{
// if new user string to create
if (theGuiInterpreter->GetConfiguredObject(strName) == NULL)
{
// check if it has blank variable name
if (strName == "")
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "String name cannot be blank");
canClose = false;
return;
}
// Trim blank spaces
strName = GmatStringUtil::Trim(strName);
// check if it has valid variable name
if (!GmatStringUtil::IsValidName(strName))
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "Invalid string name: \"%s.\" String name must "
"follow GMAT variable name rules (start with an alphabetic character, "
"only alphanumerics and underscores, no reserved words)", strName.c_str());
canClose = false;
return;
}
Parameter *param;
param = theGuiInterpreter->CreateParameter("String", strName);
param->SetStringParameter("Expression", strValue);
mParamNames.Add(strName.c_str());
mIsParamCreated = true;
theGuiManager->UpdateParameter();
GmatAppData::Instance()->GetResourceTree()->UpdateVariable();
mUserStringListBox->Append(strName.c_str());
for (unsigned int i=0; i<mUserStringListBox->GetCount(); i++)
{
if (mUserStringListBox->GetString(i).IsSameAs(strName.c_str()))
{
mUserStringListBox->SetSelection(i);
break;
}
}
EnableUpdate(true);
}
else
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "The string: \"%s\" cannot be created. "
"The name already exists.", strName.c_str());
}
ResetControls();
}
catch (BaseException &e)
{
MessageInterface::PopupMessage(Gmat::ERROR_, e.GetFullMessage());
}
}
//------------------------------------------------------------------------------
// void CreateArray()
//------------------------------------------------------------------------------
void ParameterCreateDialog::CreateArray()
{
std::string s;
long row, col;
Integer mNumCols, mNumRows;
s = mArrRowTextCtrl->GetValue().c_str();
CheckIntegerRange(mNumRows, s, "Rows", 1, 1000, true, true, true, true);
s = mArrColTextCtrl->GetValue().c_str();
CheckIntegerRange(mNumCols, s, "Columns", 1, 1000, true, true, true, true);
if (!(mArrRowTextCtrl->GetValue().ToLong(&row)) ||
!(mArrColTextCtrl->GetValue().ToLong(&col)))
{
wxLogError(wxT("Row or Column is not a number"));
wxLog::FlushActive();
canClose = false;
return;
}
// Check for maximum array size of 1000x1000
if (row > 1000 || col > 1000)
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "The array size %d x %d is too big. The maximum "
"allowed size is 1000 x 1000", row, col);
canClose = false;
return;
}
if (!canClose)
return;
try
{
wxString wxarrName = mArrNameTextCtrl->GetValue().Trim();
std::string arrName = std::string(wxarrName.c_str());
// if new user array to create
if (theGuiInterpreter->GetConfiguredObject(arrName) == NULL)
{
// check if it has blank variable name or expression
if (arrName == "")
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "Array name cannot be blank");
canClose = false;
return;
}
// Trim blank spaces
arrName = GmatStringUtil::Trim(arrName);
// check if it has valid variable name
if (!GmatStringUtil::IsValidName(arrName))
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "Invalid array name: \"%s.\" Array name must "
"follow GMAT variable name rules (start with an alphabetic character, "
"only alphanumerics and underscores, no reserved words)", arrName.c_str());
canClose = false;
return;
}
Parameter *param;
param = theGuiInterpreter->CreateParameter("Array", arrName);
param->SetIntegerParameter("NumRows", row);
param->SetIntegerParameter("NumCols", col);
mParamNames.Add(arrName.c_str());
mIsParamCreated = true;
theGuiManager->UpdateParameter();
GmatAppData::Instance()->GetResourceTree()->UpdateVariable();
mUserArrayListBox->Append(arrName.c_str());
for (unsigned int i=0; i<mUserArrayListBox->GetCount(); i++)
{
if (mUserArrayListBox->GetString(i).IsSameAs(arrName.c_str()))
{
mUserArrayListBox->SetSelection(i);
break;
}
}
EnableUpdate(true);
}
else
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "The array: \"%s\" cannot be created. "
"The name already exists.", arrName.c_str());
}
ResetControls();
}
catch (BaseException &e)
{
MessageInterface::PopupMessage(Gmat::ERROR_, e.GetFullMessage());
}
}
//------------------------------------------------------------------------------
// void SetVariableToAnotherObject(const std::string &varName,
// const std::string &varExpr)
//------------------------------------------------------------------------------
void ParameterCreateDialog::SetVariableToAnotherObject(const std::string &varName,
const std::string &varExpr)
{
// Parse the Parameter
//StringTokenizer st(varExpr, "()*/+-^ ");
// tokenize nothing, we want no expressions, 04/2010 TGG
StringTokenizer st(varExpr, "");
StringArray tokens = st.GetAllTokens();
StringArray paramArray;
Real realNum;
Parameter *param = NULL;
// Check if unexisting varibles used in expression
for (unsigned int i=0; i<tokens.size(); i++)
{
#ifdef DEBUG_PARAM_CREATE_VAR
MessageInterface::ShowMessage(" token:<%s> \n", tokens[i].c_str());
#endif
if (!GmatStringUtil::ToReal(tokens[i], realNum))
{
// Check for the valid name
if (!GmatStringUtil::IsValidName(tokens[i]))
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "\"%s\" is not a valid number or variable name",
tokens[i].c_str());
canClose = false;
return;
}
// create system parameter if it is NULL
if (theGuiInterpreter->GetParameter(tokens[i]) == NULL)
{
// check if it is system parameter
std::string type, owner, depObj;
GmatStringUtil::ParseParameter(tokens[i], type, owner, depObj);
if (theGuiInterpreter->IsParameter(type))
{
#ifdef DEBUG_PARAM_CREATE_VAR
MessageInterface::ShowMessage
("type:%s is a system parameter\n", type.c_str());
#endif
Parameter *sysParam =
theGuiInterpreter->CreateParameter(type, tokens[i]);
// set ref. object name
sysParam->SetRefObjectName(sysParam->GetOwnerType(), owner);
// set dependent object name
if (depObj != "")
sysParam->SetStringParameter("DepObject", depObj);
}
else
{
MessageInterface::PopupMessage
(Gmat::ERROR_, "The variable \"%s\" does not exist. "
"It must be created first.", tokens[i].c_str());
canClose = false;
return;
}
}
// create a variable
param = theGuiInterpreter->CreateParameter("Variable", varName);
param->SetStringParameter("Expression", varExpr);
// set parameter names used in expression
param->SetRefObjectName(Gmat::PARAMETER, tokens[i]);
}
}
}
|
// Copyright (C) 2013 Jimmie Bergmann - jimmiebergmann@gmail.com
//
// This software is provided 'as-is', without any express or
// implied warranty. In no event will the authors be held
// liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute
// it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but
// is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any
// source distribution.
// ///////////////////////////////////////////////////////////////////////////
#ifndef BIT_NETWORK_TCP_LISTENER_BASE_HPP
#define BIT_NETWORK_TCP_LISTENER_BASE_HPP
#include <Bit/Build.hpp>
#include <Bit/Network/TcpSocket.hpp>
namespace Bit
{
namespace Private
{
////////////////////////////////////////////////////////////////
/// \ingroup Network
/// \brief Tcp listener base class.
///
////////////////////////////////////////////////////////////////
class BIT_API TcpListenerBase : private Socket
{
public:
////////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////////
virtual ~TcpListenerBase( ) { }
////////////////////////////////////////////////////////////////
/// \brief Start the listener.
///
/// \param p_Port The server port.
///
////////////////////////////////////////////////////////////////
virtual Bool Start( const Uint16 p_Port ) = 0;
////////////////////////////////////////////////////////////////
/// \brief Stop the listener
///
////////////////////////////////////////////////////////////////
virtual void Stop( ) = 0;
////////////////////////////////////////////////////////////////
/// \brief Listen for incoming connections
///
/// This is a modal function.
///
/// \param p_TcpSocket The returned connected socket.
///
////////////////////////////////////////////////////////////////
virtual Bool Listen( TcpSocket & p_Connection ) = 0;
////////////////////////////////////////////////////////////////
/// \brief Checks if the listener is hosted.
///
/// \return True if hosted, else false.
///
////////////////////////////////////////////////////////////////
virtual Bool IsRunning( ) const = 0;
};
}
}
#endif
|
// Copyright (c) 2012 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <stdint.h>
#include <cassert>
#include <algorithm>
#include "storage.hpp"
#include "convert_endian.hpp"
namespace sak
{
/// The idea behind the endian_stream is to provide a stream-like interface
/// for accessing a fixed-size buffer.
/// All complexity regarding endianness is encapsulated.
class endian_stream
{
public:
/// Creates an endian stream on top of a pre-allocated buffer of the
/// specified size
/// @param buffer a pointer to the buffer
/// @param size the size of the buffer in bytes
endian_stream(uint8_t* buffer, uint32_t size);
/// Creates an endian stream on top of a mutable storage that has
/// a fixed size
/// @param storage the mutable storage
endian_stream(const mutable_storage& storage);
/// Writes a value of the size of ValueType to the stream
/// @param value the value to write
template<class ValueType>
void write(ValueType value)
{
// Make sure there is enough space in the underlying buffer
assert(m_size >= m_position + sizeof(ValueType));
// Write the value at the current position
big_endian::put<ValueType>(value, &m_buffer[m_position]);
// Advance the current position
m_position += sizeof(ValueType);
}
/// Writes the contents of a sak::storage container to the stream.
/// Note that this function is provided only for convenience and
/// it does not perform any endian conversions. Furthermore, the length
/// of the container is not written to the stream.
/// @param storage the storage to write
void write(const mutable_storage& storage)
{
write(const_storage(storage));
}
/// Writes the contents of a sak::storage container to the stream.
/// Note that this function is provided only for convenience and
/// it does not perform any endian conversions. Furthermore, the length
/// of the container is not written to the stream.
/// @param storage the storage to write
void write(const const_storage& storage)
{
// Make sure there is enough space in the underlying buffer
assert(m_size >= m_position + storage.m_size);
// Copy the data to the buffer
std::copy_n(storage.m_data, storage.m_size, &m_buffer[m_position]);
// Advance the current position
m_position += storage.m_size;
}
/// Reads from the stream and moves the read position.
/// @param value reference to the value to be read
template<class ValueType>
void read(ValueType& value)
{
// Make sure there is enough data to read in the underlying buffer
assert(m_size >= m_position + sizeof(ValueType));
// Read the value at the current position
value = big_endian::get<ValueType>(&m_buffer[m_position]);
// Advance the current position
m_position += sizeof(ValueType);
}
/// Reads data from the stream to fill a mutable storage
/// Note that this function is provided only for convenience and
/// it does not perform any endian conversions. Furthermore, the length
/// of the storage is not read from the stream. Therefore, the
/// mutable storage must resized before it can be filled.
/// @param storage the storage to be filled
void read(const mutable_storage& storage)
{
// Make sure there is enough data to read in the underlying buffer
assert(m_size >= m_position + storage.m_size);
// Copy the data from the buffer to the storage
std::copy_n(&m_buffer[m_position], storage.m_size, storage.m_data);
// Advance the current position
m_position += storage.m_size;
}
/// Gets the size of the underlying buffer
/// @return the size of the buffer
uint32_t size() const;
/// Gets the current read/write position in the stream
/// @return the current position
uint32_t position() const;
/// Changes the current read/write position in the stream
/// @param new_position the new position
void seek(uint32_t new_position);
private:
/// Pointer to the buffer
uint8_t* m_buffer;
/// The size of the buffer
uint32_t m_size;
/// The current position
uint32_t m_position;
};
}
|
//*****************************************************************************
/*!
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************
*
* \file evqueue.h
*
* \brief A queue of events.
*
* \version
* - S Panyam 18/02/2009
* Created
*
*****************************************************************************/
#include "event.h"
// overloaded to do comparison between 2 events
bool operator<(const SEvent &a, const SEvent &b)
{
return a.priority < b.priority;
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: BeatmapDifficultyMask
#include "GlobalNamespace/BeatmapDifficultyMask.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: MultiplayerModeSettings
class MultiplayerModeSettings : public ::Il2CppObject {
public:
// public System.Int32 createServerPlayersCount
// Size: 0x4
// Offset: 0x10
int createServerPlayersCount;
// Field size check
static_assert(sizeof(int) == 0x4);
// public BeatmapDifficultyMask quickPlayBeatmapDifficulty
// Size: 0x1
// Offset: 0x14
GlobalNamespace::BeatmapDifficultyMask quickPlayBeatmapDifficulty;
// Field size check
static_assert(sizeof(GlobalNamespace::BeatmapDifficultyMask) == 0x1);
// Padding between fields: quickPlayBeatmapDifficulty and: quickPlaySongPackMaskSerializedName
char __padding1[0x3] = {};
// public System.String quickPlaySongPackMaskSerializedName
// Size: 0x8
// Offset: 0x18
::Il2CppString* quickPlaySongPackMaskSerializedName;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: MultiplayerModeSettings
MultiplayerModeSettings(int createServerPlayersCount_ = {}, GlobalNamespace::BeatmapDifficultyMask quickPlayBeatmapDifficulty_ = {}, ::Il2CppString* quickPlaySongPackMaskSerializedName_ = {}) noexcept : createServerPlayersCount{createServerPlayersCount_}, quickPlayBeatmapDifficulty{quickPlayBeatmapDifficulty_}, quickPlaySongPackMaskSerializedName{quickPlaySongPackMaskSerializedName_} {}
// public System.Void .ctor()
// Offset: 0x23DB1DC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MultiplayerModeSettings* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MultiplayerModeSettings::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MultiplayerModeSettings*, creationType>()));
}
}; // MultiplayerModeSettings
#pragma pack(pop)
static check_size<sizeof(MultiplayerModeSettings), 24 + sizeof(::Il2CppString*)> __GlobalNamespace_MultiplayerModeSettingsSizeCheck;
static_assert(sizeof(MultiplayerModeSettings) == 0x20);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MultiplayerModeSettings*, "", "MultiplayerModeSettings");
|
#include "lunarlady/Game.hpp"
#include "lunarlady/System.hpp"
#include "lunarlady/StringFormat.hpp"
namespace lunarlady {
class StringFormatSystem : public System {
public:
StringFormatSystem() : System("Font format"), mFormat( Registrator().getGeneralStringPath() ) {
}
~StringFormatSystem() {
}
void step(real iTime) {
}
StringFormat mFormat;
};
LL_SYSTEM(StringFormatSystem, 400);
}
|
/*
* Copyright (c) 2015 The WebRTC 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.
*/
#define MS_CLASS "webrtc::TransportFeedbackAdapter"
// #define MS_LOG_DEV_LEVEL 3
#include "modules/congestion_controller/rtp/transport_feedback_adapter.h"
#include "api/units/timestamp.h"
#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "system_wrappers/source/field_trial.h"
#include "mediasoup_helpers.h"
#include "Logger.hpp"
#include "RTC/RTCP/FeedbackRtpTransport.hpp"
#include <stdlib.h>
#include <algorithm>
#include <cmath>
#include <utility>
namespace webrtc {
namespace {
PacketResult NetworkPacketFeedbackFromRtpPacketFeedback(
const webrtc::PacketFeedback& pf) {
PacketResult feedback;
if (pf.arrival_time_ms == webrtc::PacketFeedback::kNotReceived) {
feedback.receive_time = Timestamp::PlusInfinity();
} else {
feedback.receive_time = Timestamp::ms(pf.arrival_time_ms);
}
feedback.sent_packet.sequence_number = pf.long_sequence_number;
feedback.sent_packet.send_time = Timestamp::ms(pf.send_time_ms);
feedback.sent_packet.size = DataSize::bytes(pf.payload_size);
feedback.sent_packet.pacing_info = pf.pacing_info;
feedback.sent_packet.prior_unacked_data =
DataSize::bytes(pf.unacknowledged_data);
return feedback;
}
} // namespace
const int64_t kNoTimestamp = -1;
const int64_t kSendTimeHistoryWindowMs = 60000;
TransportFeedbackAdapter::TransportFeedbackAdapter()
: allow_duplicates_(field_trial::IsEnabled(
"WebRTC-TransportFeedbackAdapter-AllowDuplicates")),
send_time_history_(kSendTimeHistoryWindowMs),
current_offset_ms_(kNoTimestamp),
last_timestamp_us_(kNoTimestamp),
local_net_id_(0),
remote_net_id_(0) {}
TransportFeedbackAdapter::~TransportFeedbackAdapter() {
}
void TransportFeedbackAdapter::AddPacket(const RtpPacketSendInfo& packet_info,
size_t overhead_bytes,
Timestamp creation_time) {
{
PacketFeedback packet_feedback(
creation_time.ms(), packet_info.transport_sequence_number,
packet_info.length + overhead_bytes, local_net_id_, remote_net_id_,
packet_info.pacing_info);
if (packet_info.has_rtp_sequence_number) {
packet_feedback.ssrc = packet_info.ssrc;
packet_feedback.rtp_sequence_number = packet_info.rtp_sequence_number;
}
// MS_NOTE: TODO remove.
// MS_DUMP("packet_feedback.arrival_time_ms: %" PRIi64, packet_feedback.arrival_time_ms);
// MS_DUMP("packet_feedback.send_time_ms: %" PRIi64, packet_feedback.send_time_ms);
// MS_DUMP("packet_feedback.sequence_number: %" PRIu16, packet_feedback.sequence_number);
// MS_DUMP("packet_feedback.long_sequence_number: %" PRIi64, packet_feedback.long_sequence_number);
// MS_DUMP("packet_feedback.payload_size: %zu", packet_feedback.payload_size);
// MS_DUMP("packet_feedback.unacknowledged_data: %zu", packet_feedback.unacknowledged_data);
// MS_DUMP("packet_feedback.local_net_id: %" PRIu16, packet_feedback.local_net_id);
// MS_DUMP("packet_feedback.remote_net_id: %" PRIu16, packet_feedback.remote_net_id);
// MS_DUMP("packet_feedback.ssrc: %" PRIu32, packet_feedback.ssrc.value());
// MS_DUMP("packet_feedback.rtp_sequence_number: %" PRIu16, packet_feedback.rtp_sequence_number);
send_time_history_.RemoveOld(creation_time.ms());
send_time_history_.AddNewPacket(std::move(packet_feedback));
}
{
for (auto* observer : observers_) {
observer->OnPacketAdded(packet_info.ssrc,
packet_info.transport_sequence_number);
}
}
}
absl::optional<SentPacket> TransportFeedbackAdapter::ProcessSentPacket(
const rtc::SentPacket& sent_packet) {
// TODO(srte): Only use one way to indicate that packet feedback is used.
if (sent_packet.info.included_in_feedback || sent_packet.packet_id != -1) {
SendTimeHistory::Status send_status = send_time_history_.OnSentPacket(
sent_packet.packet_id, sent_packet.send_time_ms);
absl::optional<PacketFeedback> packet;
if (allow_duplicates_ ||
send_status != SendTimeHistory::Status::kDuplicate) {
packet = send_time_history_.GetPacket(sent_packet.packet_id);
}
if (packet) {
SentPacket msg;
msg.size = DataSize::bytes(packet->payload_size);
msg.send_time = Timestamp::ms(packet->send_time_ms);
msg.sequence_number = packet->long_sequence_number;
msg.prior_unacked_data = DataSize::bytes(packet->unacknowledged_data);
msg.data_in_flight =
send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_);
return msg;
}
} else if (sent_packet.info.included_in_allocation) {
send_time_history_.AddUntracked(sent_packet.info.packet_size_bytes,
sent_packet.send_time_ms);
}
return absl::nullopt;
}
absl::optional<TransportPacketsFeedback>
TransportFeedbackAdapter::ProcessTransportFeedback(
const RTC::RTCP::FeedbackRtpTransportPacket& feedback,
Timestamp feedback_receive_time) {
DataSize prior_in_flight = GetOutstandingData();
last_packet_feedback_vector_ =
GetPacketFeedbackVector(feedback, feedback_receive_time);
{
for (auto* observer : observers_) {
observer->OnPacketFeedbackVector(last_packet_feedback_vector_);
}
}
std::vector<PacketFeedback> feedback_vector = last_packet_feedback_vector_;
if (feedback_vector.empty())
return absl::nullopt;
TransportPacketsFeedback msg;
for (const PacketFeedback& rtp_feedback : feedback_vector) {
if (rtp_feedback.send_time_ms != PacketFeedback::kNoSendTime) {
auto feedback = NetworkPacketFeedbackFromRtpPacketFeedback(rtp_feedback);
msg.packet_feedbacks.push_back(feedback);
} else if (rtp_feedback.arrival_time_ms == PacketFeedback::kNotReceived) {
msg.sendless_arrival_times.push_back(Timestamp::PlusInfinity());
} else {
msg.sendless_arrival_times.push_back(
Timestamp::ms(rtp_feedback.arrival_time_ms));
}
}
{
absl::optional<int64_t> first_unacked_send_time_ms =
send_time_history_.GetFirstUnackedSendTime();
if (first_unacked_send_time_ms)
msg.first_unacked_send_time = Timestamp::ms(*first_unacked_send_time_ms);
}
msg.feedback_time = feedback_receive_time;
msg.prior_in_flight = prior_in_flight;
msg.data_in_flight = GetOutstandingData();
return msg;
}
DataSize TransportFeedbackAdapter::GetOutstandingData() const {
return send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_);
}
std::vector<PacketFeedback> TransportFeedbackAdapter::GetPacketFeedbackVector(
const RTC::RTCP::FeedbackRtpTransportPacket& feedback,
Timestamp feedback_time) {
// Add timestamp deltas to a local time base selected on first packet arrival.
// This won't be the true time base, but makes it easier to manually inspect
// time stamps.
if (last_timestamp_us_ == kNoTimestamp) {
current_offset_ms_ = feedback_time.ms();
} else {
current_offset_ms_ +=
mediasoup_helpers::FeedbackRtpTransport::GetBaseDeltaUs(&feedback, last_timestamp_us_) / 1000;
}
last_timestamp_us_ =
mediasoup_helpers::FeedbackRtpTransport::GetBaseTimeUs(&feedback);
std::vector<PacketFeedback> packet_feedback_vector;
if (feedback.GetPacketStatusCount() == 0) {
MS_WARN_DEV("empty transport feedback packet received");
return packet_feedback_vector;
}
packet_feedback_vector.reserve(feedback.GetPacketStatusCount());
{
size_t failed_lookups = 0;
int64_t offset_us = 0;
int64_t timestamp_ms = 0;
uint16_t seq_num = feedback.GetBaseSequenceNumber();
for (const auto& packet : mediasoup_helpers::FeedbackRtpTransport::GetReceivedPackets(&feedback)) {
// Insert into the vector those unreceived packets which precede this
// iteration's received packet.
for (; seq_num != packet.sequence_number(); ++seq_num) {
PacketFeedback packet_feedback(PacketFeedback::kNotReceived, seq_num);
// Note: Element not removed from history because it might be reported
// as received by another feedback.
if (!send_time_history_.GetFeedback(&packet_feedback, false))
++failed_lookups;
if (packet_feedback.local_net_id == local_net_id_ &&
packet_feedback.remote_net_id == remote_net_id_) {
packet_feedback_vector.push_back(packet_feedback);
}
}
// Handle this iteration's received packet.
offset_us += packet.delta_us();
timestamp_ms = current_offset_ms_ + (offset_us / 1000);
PacketFeedback packet_feedback(timestamp_ms, packet.sequence_number());
if (!send_time_history_.GetFeedback(&packet_feedback, true))
++failed_lookups;
if (packet_feedback.local_net_id == local_net_id_ &&
packet_feedback.remote_net_id == remote_net_id_) {
packet_feedback_vector.push_back(packet_feedback);
}
++seq_num;
}
if (failed_lookups > 0) {
MS_WARN_DEV("failed to lookup send time for %zu"
" packet%s, send time history too small?",
failed_lookups,
(failed_lookups > 1 ? "s" : ""));
}
}
return packet_feedback_vector;
}
std::vector<PacketFeedback>
TransportFeedbackAdapter::GetTransportFeedbackVector() const {
return last_packet_feedback_vector_;
}
} // namespace webrtc
|
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Heiko Strathmann, Dhruv Arya
*/
#include <gtest/gtest.h>
#include <shogun/evaluation/SigmoidCalibration.h>
using namespace shogun;
TEST(SigmoidCalibrationTest, binary_calibration)
{
SGVector<float64_t> preds(10), labs(10);
preds.vector[0] = 0.6;
preds.vector[1] = -0.2;
preds.vector[2] = 0.7;
preds.vector[3] = 0.9;
preds.vector[4] = -0.1;
preds.vector[5] = -0.3;
preds.vector[6] = 0.9;
preds.vector[7] = 0.6;
preds.vector[8] = -0.3;
preds.vector[9] = 0.7;
labs.vector[0] = 1;
labs.vector[1] = -1;
labs.vector[2] = 1;
labs.vector[3] = 1;
labs.vector[4] = -1;
labs.vector[5] = -1;
labs.vector[6] = 1;
labs.vector[7] = 1;
labs.vector[8] = -1;
labs.vector[9] = -1;
CBinaryLabels* predictions = new CBinaryLabels(preds);
CBinaryLabels* labels = new CBinaryLabels(labs);
SG_REF(predictions)
CSigmoidCalibration* sigmoid_calibration = new CSigmoidCalibration();
auto calibrated = sigmoid_calibration->fit_binary(predictions, labels);
EXPECT_EQ(calibrated, true);
auto calibrated_labels = sigmoid_calibration->calibrate_binary(predictions);
auto values = calibrated_labels->get_values();
EXPECT_EQ(values[0], 0.656628663983293337);
EXPECT_EQ(values[1], 0.159375349583615822);
EXPECT_EQ(values[2], 0.718534704684106407);
EXPECT_EQ(values[3], 0.819801347075004516);
EXPECT_EQ(values[4], 0.201976857736835741);
EXPECT_EQ(values[5], 0.124359200656053326);
EXPECT_EQ(values[6], 0.819801347075004516);
EXPECT_EQ(values[7], 0.656628663983293337);
EXPECT_EQ(values[8], 0.124359200656053326);
EXPECT_EQ(values[9], 0.718534704684106407);
SG_UNREF(sigmoid_calibration)
SG_UNREF(predictions)
SG_UNREF(labels)
SG_UNREF(calibrated_labels)
}
TEST(SigmoidCalibrationTest, multiclass_calibration)
{
index_t num_vec = 10;
index_t num_class = 3;
double preds[] = {
3.58412386, -1.85426031, -3.01727279, 3.26476717, -4.29277837,
-0.97842984, 3.71045102, -2.87473617, -2.39465561, 0.50210539,
-0.90306753, -0.96823852, -0.23000778, 0.8901302, -1.60981499,
-0.82280503, -6.85573966, 4.49250544, 2.51249731, -1.9841395,
-1.97320905, -2.51812929, 2.75936145, -0.9259119, -0.92123693,
1.95678501, -1.76459559, -1.30939982, 1.79817245, -1.30609521};
SGVector<float64_t> tgt({0, 0, 0, 0, 1, 2, 0, 1, 1, 1});
CMulticlassLabels* predictions = new CMulticlassLabels(tgt);
CMulticlassLabels* targets = new CMulticlassLabels(tgt);
predictions->allocate_confidences_for(num_class);
for (index_t i = 0; i < num_vec; i++)
{
SGVector<float64_t> confs(num_class);
for (index_t j = 0; j < num_class; j++)
{
confs[j] = preds[i * num_class + j];
}
predictions->set_multiclass_confidences(i, confs);
}
auto calibration_method = new CSigmoidCalibration();
auto calibrated = calibration_method->fit_multiclass(predictions, targets);
EXPECT_EQ(calibrated, true);
auto calib_result = calibration_method->calibrate_multiclass(predictions);
float64_t expected_probs[] = {
0.75674645, 0.20144443, 0.04180912, 0.82689269, 0.05965391, 0.11345341,
0.81409222, 0.12715657, 0.05875121, 0.48765218, 0.38500051, 0.12734731,
0.31003506, 0.60319518, 0.08676976, 0.26630134, 0.01476002, 0.71893864,
0.72470815, 0.20387599, 0.07141586, 0.074445, 0.80897488, 0.11658012,
0.20620103, 0.71452701, 0.07927195, 0.16983872, 0.72947987, 0.10068142};
for (index_t i = 0; i < num_vec; i++)
{
auto vals = calib_result->get_multiclass_confidences(i);
for (index_t j = 0; j < vals.size(); j++)
{
EXPECT_NEAR(vals[j], expected_probs[i * num_class + j], 1E-5);
}
}
SG_UNREF(predictions);
SG_UNREF(targets);
SG_UNREF(calibration_method);
SG_UNREF(calib_result);
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "InitCollisionFinder.h"
#include "DexUtil.h"
/**
* Some optimizations want to change the prototypes of many methods. Sometimes,
* changing those method prototypes will collide with another method. For most
* method collisions we rename the new method to avoid the collision. But we
* cannot rename <init> methods.
*
* This utility works around the init collision problem by finding the types
* that cause the init collision. This allows an optimization to exclude these
* types before it makes any changes.
*/
namespace init_collision_finder {
/**
* Given a method, return the new DexMethodSpec that the optimization wants to
* change this method to (returning boost::none if it does not want to make a
* change). In the process, this method should fill the vector argument with any
* DexTypes that were replaced in the method's prototype.
*
* This function is supplied by the user of the Init Collision Finder.
*/
using GetNewSpec = std::function<boost::optional<DexMethodSpec>(
const DexMethod*, std::vector<DexType*>*)>;
std::vector<DexType*> find(const Scope& scope, const GetNewSpec& get_new_spec) {
// Compute what the new prototypes will be after we convert a method. Check
// the prototypes against existing methods and other prototypes created by
// this method.
std::vector<DexType*> result;
for (const DexClass* cls : scope) {
std::unordered_set<DexMethodSpec> new_specs;
for (const DexMethod* m : cls->get_dmethods()) {
if (method::is_init(m)) {
std::vector<DexType*> unsafe_refs;
const auto& new_spec = get_new_spec(m, &unsafe_refs);
if (new_spec) {
const auto& pair = new_specs.emplace(*new_spec);
bool already_there = !pair.second;
if (already_there || DexMethod::get_method(*new_spec)) {
always_assert_log(
!unsafe_refs.empty(),
"unsafe_refs should be filled with the types that will be "
"replaced on this <init> method's prototype");
result.insert(result.end(), unsafe_refs.begin(), unsafe_refs.end());
}
}
}
}
}
return result;
}
} // namespace init_collision_finder
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_SK_PopOutCake_AnimBlueprint_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function SK_PopOutCake_AnimBlueprint.SK_PopOutCake_AnimBlueprint_C.EvaluateGraphExposedInputs_ExecuteUbergraph_SK_PopOutCake_AnimBlueprint_AnimGraphNode_BlendListByBool_4352
struct USK_PopOutCake_AnimBlueprint_C_EvaluateGraphExposedInputs_ExecuteUbergraph_SK_PopOutCake_AnimBlueprint_AnimGraphNode_BlendListByBool_4352_Params
{
};
// Function SK_PopOutCake_AnimBlueprint.SK_PopOutCake_AnimBlueprint_C.BlueprintUpdateAnimation
struct USK_PopOutCake_AnimBlueprint_C_BlueprintUpdateAnimation_Params
{
float* DeltaTimeX; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function SK_PopOutCake_AnimBlueprint.SK_PopOutCake_AnimBlueprint_C.ExecuteUbergraph_SK_PopOutCake_AnimBlueprint
struct USK_PopOutCake_AnimBlueprint_C_ExecuteUbergraph_SK_PopOutCake_AnimBlueprint_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
/****************************************************************************************************************************************************
* Copyright (c) 2014 Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the Freescale Semiconductor, Inc. nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************************************************************************************/
#include <FslDemoApp/Base/Host/DemoHostFeatureUtil.hpp>
#include <limits>
namespace Fsl
{
uint32_t DemoHostFeatureUtil::EncodeOpenGLESVersion(const uint16_t major)
{
// a minor value of 0xFFFF means we only care about the major version
return (major << 16) | 0xFFFF;
}
uint32_t DemoHostFeatureUtil::EncodeOpenGLESVersion(const uint16_t major, const uint16_t minor)
{
return (major << 16) | minor;
}
void DemoHostFeatureUtil::DecodeOpenGLESVersion(uint32_t encodedValue, int& rMajor, int& rMinor)
{
rMajor = (encodedValue >> 16) & 0xFFFF;
uint16_t minor = encodedValue & 0xFFFF;
rMinor = minor != 0xFFFF ? minor : -1;
}
uint32_t DemoHostFeatureUtil::EncodeOpenVGVersion(const uint16_t major)
{
// a minor value of 0xFFFF means we only care about the major version
return (major << 16) | 0xFFFF;
}
uint32_t DemoHostFeatureUtil::EncodeOpenVGVersion(const uint16_t major, const uint16_t minor)
{
return (major << 16) | minor;
}
void DemoHostFeatureUtil::DecodeOpenVGVersion(uint32_t encodedValue, int& rMajor, int& rMinor)
{
rMajor = (encodedValue >> 16) & 0xFFFF;
uint16_t minor = encodedValue & 0xFFFF;
rMinor = minor != 0xFFFF ? minor : -1;
}
uint32_t DemoHostFeatureUtil::EncodeG2DVersion(const uint16_t major)
{
// a minor value of 0xFFFF means we only care about the major version
return (major << 16) | 0xFFFF;
}
uint32_t DemoHostFeatureUtil::EncodeG2DVersion(const uint16_t major, const uint16_t minor)
{
return (major << 16) | minor;
}
void DemoHostFeatureUtil::DecodeG2DVersion(uint32_t encodedValue, int& rMajor, int& rMinor)
{
rMajor = (encodedValue >> 16) & 0xFFFF;
uint16_t minor = encodedValue & 0xFFFF;
rMinor = minor != 0xFFFF ? minor : -1;
}
uint32_t DemoHostFeatureUtil::EncodeVersion(const uint16_t major)
{
// a minor value of 0xFFFF means we only care about the major version
return (major << 16) | 0xFFFF;
}
uint32_t DemoHostFeatureUtil::EncodeVersion(const uint16_t major, const uint16_t minor)
{
return (major << 16) | minor;
}
void DemoHostFeatureUtil::DecodeVersion(uint32_t encodedValue, int& rMajor, int& rMinor)
{
rMajor = (encodedValue >> 16) & 0xFFFF;
uint16_t minor = encodedValue & 0xFFFF;
rMinor = minor != 0xFFFF ? minor : -1;
}
}
|
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int parent[N], size[N];
void UNION (int x, int y) {
if (size[x] > size[y])
swap(x, y);
size[x] += size[y];
parent[y] = parent[x];
}
int FIND (const int x) {
if (x != parent[x])
parent[x] = FIND(parent[x]);
return parent[x];
}
int main () {
int n, q; scanf("%d %d", &n, &q);
for (int i = 0; i < n; ++i)
parent[i] = i, size[i] = 1;
while (q-- > 0) {
int type, x, y; scanf("%d %d %d", &type, &x, &y);
x = FIND(x), y = FIND(y);
if (type == 1)
puts(x == y ? "Yes" : "No");
else
UNION(x, y);
}
return 0;
}
|
// Copyright Aleksey Gurtovoy 2001-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /physbam_repository/External_Libraries/Archives/boost/boost/mpl/list/aux_/include_preprocessed.hpp,v $
// $Date: 2007/02/12 18:25:37 $
// $Revision: 1.1 $
// NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION!
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
# define AUX778076_HEADER \
aux_/preprocessed/plain/BOOST_MPL_PREPROCESSED_HEADER \
/**/
# include BOOST_PP_STRINGIZE(boost/mpl/list/AUX778076_HEADER)
# undef AUX778076_HEADER
#undef BOOST_MPL_PREPROCESSED_HEADER
|
#include "duckdb/execution/physical_plan_generator.hpp"
#include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp"
#include "duckdb/execution/column_binding_resolver.hpp"
#include "duckdb/main/client_context.hpp"
#include "duckdb/planner/expression/bound_function_expression.hpp"
namespace duckdb {
class DependencyExtractor : public LogicalOperatorVisitor {
public:
explicit DependencyExtractor(unordered_set<CatalogEntry *> &dependencies) : dependencies(dependencies) {
}
protected:
unique_ptr<Expression> VisitReplace(BoundFunctionExpression &expr, unique_ptr<Expression> *expr_ptr) override {
// extract dependencies from the bound function expression
if (expr.function.dependency) {
expr.function.dependency(expr, dependencies);
}
return nullptr;
}
private:
unordered_set<CatalogEntry *> &dependencies;
};
unique_ptr<PhysicalOperator> PhysicalPlanGenerator::CreatePlan(unique_ptr<LogicalOperator> op) {
// first resolve column references
context.profiler.StartPhase("column_binding");
ColumnBindingResolver resolver;
resolver.VisitOperator(*op);
context.profiler.EndPhase();
// now resolve types of all the operators
context.profiler.StartPhase("resolve_types");
op->ResolveOperatorTypes(); //op->types is updated
context.profiler.EndPhase();
// extract dependencies from the logical plan
DependencyExtractor extractor(dependencies);
extractor.VisitOperator(*op);
// then create the main physical plan
context.profiler.StartPhase("create_plan");
auto plan = CreatePlan(*op); //op->estimated_cardinality is updated
context.profiler.EndPhase();
return plan;
}
unique_ptr<PhysicalOperator> PhysicalPlanGenerator::CreatePlanRL(LogicalOperator* op) {
// first resolve column references
context.profiler.StartPhase("column_binding");
ColumnBindingResolver resolver;
resolver.VisitOperator(*op);
context.profiler.EndPhase();
// now resolve types of all the operators
context.profiler.StartPhase("resolve_types");
op->ResolveOperatorTypes();
context.profiler.EndPhase();
// extract dependencies from the logical plan
DependencyExtractor extractor(dependencies);
extractor.VisitOperator(*op);
// then create the main physical plan
context.profiler.StartPhase("create_plan");
auto plan = CreatePlan(*op);
context.profiler.EndPhase();
return plan;
}
unique_ptr<PhysicalOperator> PhysicalPlanGenerator::CreatePlan(LogicalOperator &op) {
op.estimated_cardinality = op.EstimateCardinality(context);
switch (op.type) {
case LogicalOperatorType::LOGICAL_GET:
return CreatePlan((LogicalGet &)op);
case LogicalOperatorType::LOGICAL_PROJECTION:
return CreatePlan((LogicalProjection &)op);
case LogicalOperatorType::LOGICAL_EMPTY_RESULT:
return CreatePlan((LogicalEmptyResult &)op);
case LogicalOperatorType::LOGICAL_FILTER:
return CreatePlan((LogicalFilter &)op);
case LogicalOperatorType::LOGICAL_AGGREGATE_AND_GROUP_BY:
return CreatePlan((LogicalAggregate &)op);
case LogicalOperatorType::LOGICAL_WINDOW:
return CreatePlan((LogicalWindow &)op);
case LogicalOperatorType::LOGICAL_UNNEST:
return CreatePlan((LogicalUnnest &)op);
case LogicalOperatorType::LOGICAL_LIMIT:
return CreatePlan((LogicalLimit &)op);
case LogicalOperatorType::LOGICAL_SAMPLE:
return CreatePlan((LogicalSample &)op);
case LogicalOperatorType::LOGICAL_ORDER_BY:
return CreatePlan((LogicalOrder &)op);
case LogicalOperatorType::LOGICAL_TOP_N:
return CreatePlan((LogicalTopN &)op);
case LogicalOperatorType::LOGICAL_COPY_TO_FILE:
return CreatePlan((LogicalCopyToFile &)op);
case LogicalOperatorType::LOGICAL_DUMMY_SCAN:
return CreatePlan((LogicalDummyScan &)op);
case LogicalOperatorType::LOGICAL_ANY_JOIN:
return CreatePlan((LogicalAnyJoin &)op);
case LogicalOperatorType::LOGICAL_DELIM_JOIN:
return CreatePlan((LogicalDelimJoin &)op);
case LogicalOperatorType::LOGICAL_COMPARISON_JOIN:
return CreatePlan((LogicalComparisonJoin &)op);
case LogicalOperatorType::LOGICAL_CROSS_PRODUCT:
return CreatePlan((LogicalCrossProduct &)op);
case LogicalOperatorType::LOGICAL_UNION:
case LogicalOperatorType::LOGICAL_EXCEPT:
case LogicalOperatorType::LOGICAL_INTERSECT:
return CreatePlan((LogicalSetOperation &)op);
case LogicalOperatorType::LOGICAL_INSERT:
return CreatePlan((LogicalInsert &)op);
case LogicalOperatorType::LOGICAL_DELETE:
return CreatePlan((LogicalDelete &)op);
case LogicalOperatorType::LOGICAL_CHUNK_GET:
return CreatePlan((LogicalChunkGet &)op);
case LogicalOperatorType::LOGICAL_DELIM_GET:
return CreatePlan((LogicalDelimGet &)op);
case LogicalOperatorType::LOGICAL_EXPRESSION_GET:
return CreatePlan((LogicalExpressionGet &)op);
case LogicalOperatorType::LOGICAL_UPDATE:
return CreatePlan((LogicalUpdate &)op);
case LogicalOperatorType::LOGICAL_CREATE_TABLE:
return CreatePlan((LogicalCreateTable &)op);
case LogicalOperatorType::LOGICAL_CREATE_INDEX:
return CreatePlan((LogicalCreateIndex &)op);
case LogicalOperatorType::LOGICAL_EXPLAIN:
return CreatePlan((LogicalExplain &)op);
case LogicalOperatorType::LOGICAL_SHOW:
return CreatePlan((LogicalShow &)op);
case LogicalOperatorType::LOGICAL_DISTINCT:
return CreatePlan((LogicalDistinct &)op);
case LogicalOperatorType::LOGICAL_PREPARE:
return CreatePlan((LogicalPrepare &)op);
case LogicalOperatorType::LOGICAL_EXECUTE:
return CreatePlan((LogicalExecute &)op);
case LogicalOperatorType::LOGICAL_CREATE_VIEW:
case LogicalOperatorType::LOGICAL_CREATE_SEQUENCE:
case LogicalOperatorType::LOGICAL_CREATE_SCHEMA:
case LogicalOperatorType::LOGICAL_CREATE_MACRO:
return CreatePlan((LogicalCreate &)op);
case LogicalOperatorType::LOGICAL_PRAGMA:
return CreatePlan((LogicalPragma &)op);
case LogicalOperatorType::LOGICAL_TRANSACTION:
case LogicalOperatorType::LOGICAL_ALTER:
case LogicalOperatorType::LOGICAL_DROP:
case LogicalOperatorType::LOGICAL_VACUUM:
case LogicalOperatorType::LOGICAL_LOAD:
return CreatePlan((LogicalSimple &)op);
case LogicalOperatorType::LOGICAL_RECURSIVE_CTE:
return CreatePlan((LogicalRecursiveCTE &)op);
case LogicalOperatorType::LOGICAL_CTE_REF:
return CreatePlan((LogicalCTERef &)op);
case LogicalOperatorType::LOGICAL_EXPORT:
return CreatePlan((LogicalExport &)op);
case LogicalOperatorType::LOGICAL_SET:
return CreatePlan((LogicalSet &)op);
default:
throw NotImplementedException("Unimplemented logical operator type!");
}
}
} // namespace duckdb
|
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2021 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include <miopen/config.h>
#include <miopen/solver/gemm_common.hpp>
#include <tuple> // std::ignore
/// This W/A disables all GEMM convolution solvers for xDLOPs
/// targets when MIOpenGEMM is used (OCL BE). More info at
/// https://github.com/ROCmSoftwarePlatform/MIOpen/issues/1315.
///
/// W/A affects ROCm releases starting from 4.5 and also
/// pre-5.0 Mainline HIP builds, e.g. 9148.
#define WORKAROUND_ISSUE_1315 (MIOPEN_USE_MIOPENGEMM && (HIP_PACKAGE_VERSION_FLAT >= 4004000000ULL))
namespace miopen {
namespace conv {
namespace solver {
namespace gemm {
bool IsWorkaroundIssue1315(const miopen::ExecutionContext& ctx)
{
#if WORKAROUND_ISSUE_1315
const auto device = ctx.GetStream().GetTargetProperties().Name();
return (device == "gfx908") || (device == "gfx90a");
#else
std::ignore = ctx;
return false;
#endif
}
} // namespace gemm
} // namespace solver
} // namespace conv
} // namespace miopen
|
/*
* Copyright (C) 2018 The Android Open Source Project
* Copyright (C) 2020 The LineageOS Project
*
* 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.
*/
// Author := dev_harsh1998, Isaac Chen
#define LOG_TAG "android.hardware.light@2.0-impl.xiaomi_twolip"
/* #define LOG_NDEBUG 0 */
#include "Light.h"
#include <android-base/file.h>
#include <android-base/logging.h>
#include <unistd.h>
namespace {
#define PPCAT_NX(A, B) A/B
#define PPCAT(A, B) PPCAT_NX(A, B)
#define STRINGIFY_INNER(x) #x
#define STRINGIFY(x) STRINGIFY_INNER(x)
#define LEDS(x) PPCAT(/sys/class/leds, x)
#define LCD_ATTR(x) STRINGIFY(PPCAT(LEDS(lcd-backlight), x))
#define WHITE_ATTR(x) STRINGIFY(PPCAT(LEDS(red), x))
using ::android::base::ReadFileToString;
using ::android::base::WriteStringToFile;
// Default max brightness
constexpr auto kDefaultMaxLedBrightness = 255;
constexpr auto kDefaultMaxScreenBrightness = 4095;
// Write value to path and close file.
bool WriteToFile(const std::string& path, uint32_t content) {
return WriteStringToFile(std::to_string(content), path);
}
uint32_t RgbaToBrightness(uint32_t color) {
// Extract brightness from AARRGGBB.
uint32_t alpha = (color >> 24) & 0xFF;
// Retrieve each of the RGB colors
uint32_t red = (color >> 16) & 0xFF;
uint32_t green = (color >> 8) & 0xFF;
uint32_t blue = color & 0xFF;
// Scale RGB colors if a brightness has been applied by the user
if (alpha != 0xFF) {
red = red * alpha / 0xFF;
green = green * alpha / 0xFF;
blue = blue * alpha / 0xFF;
}
return (77 * red + 150 * green + 29 * blue) >> 8;
}
inline uint32_t RgbaToBrightness(uint32_t color, uint32_t max_brightness) {
return RgbaToBrightness(color) * max_brightness / 0xFF;
}
inline bool IsLit(uint32_t color) {
return color & 0x00ffffff;
}
} // anonymous namespace
namespace android {
namespace hardware {
namespace light {
namespace V2_0 {
namespace implementation {
Light::Light() {
std::string buf;
if (ReadFileToString(LCD_ATTR(max_brightness), &buf)) {
max_screen_brightness_ = std::stoi(buf);
} else {
max_screen_brightness_ = kDefaultMaxScreenBrightness;
LOG(ERROR) << "Failed to read max screen brightness, fallback to "
<< kDefaultMaxScreenBrightness;
}
if (ReadFileToString(WHITE_ATTR(max_brightness), &buf)) {
max_led_brightness_ = std::stoi(buf);
} else {
max_led_brightness_ = kDefaultMaxLedBrightness;
LOG(ERROR) << "Failed to read max LED brightness, fallback to " << kDefaultMaxLedBrightness;
}
}
Return<Status> Light::setLight(Type type, const LightState& state) {
auto it = lights_.find(type);
if (it == lights_.end()) {
return Status::LIGHT_NOT_SUPPORTED;
}
it->second(type, state);
return Status::SUCCESS;
}
Return<void> Light::getSupportedTypes(getSupportedTypes_cb _hidl_cb) {
std::vector<Type> types;
for (auto&& light : lights_) types.emplace_back(light.first);
_hidl_cb(types);
return Void();
}
void Light::setLightBacklight(Type /*type*/, const LightState& state) {
uint32_t brightness = RgbaToBrightness(state.color, max_screen_brightness_);
WriteToFile(LCD_ATTR(brightness), brightness);
}
void Light::setLightNotification(Type type, const LightState& state) {
bool found = false;
for (auto&& [cur_type, cur_state] : notif_states_) {
if (cur_type == type) {
cur_state = state;
}
// Fallback to battery light
if (!found && (cur_type == Type::BATTERY || IsLit(cur_state.color))) {
found = true;
LOG(DEBUG) << __func__ << ": type=" << toString(cur_type);
applyNotificationState(cur_state);
}
}
}
void Light::applyNotificationState(const LightState& state) {
uint32_t white_brightness = RgbaToBrightness(state.color, max_led_brightness_);
// Turn off the leds (initially)
WriteToFile(WHITE_ATTR(breath), 0);
if (state.flashMode == Flash::TIMED && state.flashOnMs > 0 && state.flashOffMs > 0) {
LOG(DEBUG) << __func__ << ": color=" << std::hex << state.color << std::dec
<< " onMs=" << state.flashOnMs << " offMs=" << state.flashOffMs;
// White
WriteToFile(WHITE_ATTR(delay_off), static_cast<uint32_t>(state.flashOffMs));
WriteToFile(WHITE_ATTR(delay_on), static_cast<uint32_t>(state.flashOnMs));
WriteToFile(WHITE_ATTR(breath), 1);
} else {
WriteToFile(WHITE_ATTR(brightness), white_brightness);
}
}
} // namespace implementation
} // namespace V2_0
} // namespace light
} // namespace hardware
} // namespace android
|
//=================================================================================================
/*!
// \file src/mathtest/dvecdvecouter/V4bV3b.cpp
// \brief Source file for the V4bV3b dense vector/dense vector outer product math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/StaticVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecdvecouter/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'V4bV3b'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
using V4b = blaze::StaticVector<TypeB,4UL>;
using V3b = blaze::StaticVector<TypeB,3UL>;
// Creator type definitions
using CV4b = blazetest::Creator<V4b>;
using CV3b = blazetest::Creator<V3b>;
// Running the tests
RUN_DVECDVECOUTER_OPERATION_TEST( CV4b(), CV3b() );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector outer product:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
#include "pps_timer.h"
#include "pipes.h"
#include "pps_sysapi.h"
#include "pps_message.h"
#include "pps_service.h"
#include <thread>
#include <chrono>
#define TIMER_QUEUE_LEN 4096
#define TIMER_TASK_POOL_CAP 4096
#define TIMER_TASK_SLOT_NUM 65536
#define TIMER_MAX_TASK TIMER_TASK_SLOT_NUM-1000
struct timer_task
{
int32_t poolIdx;
struct pps_timer* timer;
struct timer_msg msg;
};
static inline void cond_init(struct timer_cond& cond);
static inline void cond_notify(struct timer_cond& cond);
static inline void cond_waitfor(struct timer_cond& cond,
int64_t delay, int64_t tmNow,
struct pipes* pipes, int64_t& dbgCost);
static inline void cond_deinit(struct timer_cond& cond);
static void thread_work(struct pps_timer* tmr)
{
printf("timer(%d) start\n", tmr->index);
struct pipes* pipes = tmr->pipes;
uint32_t totalLoopNum = pipes->totalLoopThread.load();
std::atomic<bool>& idle = tmr->idle;
idle.store(false);
//
cond_init(tmr->idleCond);
// incr loop started num
pipes->loopStartedNum.fetch_add(1);
// wait all loop started
while(pipes->loopStartedNum.load() < totalLoopNum) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
printf("timer(%d) will loop\n", tmr->index);
//
struct tw_timer<struct timer_task*>* twTimer = tmr->twTimer;
struct mq_mpsc<int32_t>* queTask = tmr->queTask;
struct pool_linked<struct timer_task*>* plkReAddTask = tmr->plkReAddTask;
struct pool_linked<struct timer_msg>* plkUnRspTask = tmr->plkUnRspTask;
uint32_t& reAddTaskNum = tmr->reAddTask;
uint32_t& unRspTaskNum = tmr->unRspTask;
std::atomic<uint32_t>& taskBakNum = tmr->taskBakNum;
struct timer_msg* pMsg;
struct timer_task* pTask;
struct timer_task* pTaskSlot = tmr->taskSlots;
std::atomic<uint32_t>& unAddTask = tmr->unAddTask;
struct timer_cond& idleCond = tmr->idleCond;
int64_t tmNow, delay;
int32_t addCnt, reAddCnt, reRspCnt;
int32_t idxTask;
const int32_t stepMsgMax = 2000;
bool shutdown = false;
// debug
int64_t tmDbg1, tmDbg2, tmDbg3, tmDbg4,
dbgLastDelay, dbgLastDelayReal, dbgTmLastAdvance,
dbgDelayCost, dbgDelayCost2;
// start loop
while(true) {
reAddCnt = 0;
tmNow = timer_clock_now_ms(pipes);
// tm debug begin
tmDbg1 = tmNow;
tmDbg2 = tmDbg3 = tmDbg4 = 0;
// tm debug end
// check reAdd task
if(reAddTaskNum > 0) {
while (plk_pop(plkReAddTask, &pTask)) {
--reAddTaskNum;
++reAddCnt;
//tmNow = sysapi_clock_now_ms(); // debug
tmwheel_add(pTask->msg.expiration,
tmNow,
pTask,
twTimer);
}
tmNow = timer_clock_now_ms(pipes);
tmDbg2 = tmNow; // debug
}
// check unRsp task
reRspCnt = 0;
if (unRspTaskNum > 0) {
const plk_iterator<struct timer_msg> it = plk_it_init(plkUnRspTask);
for (; plk_it_loop(it);) {
pMsg = *it;
int32_t ret = svc_send_timermsg(pMsg->svcIdx, pMsg, tmr);
if (ret != 0) {
// send succ || dst has gone
plk_erase(it);
--unRspTaskNum;
}
++reRspCnt;
}
tmNow = timer_clock_now_ms(pipes);
tmDbg3 = tmNow; // debug
}
// check task queue
addCnt = 0;
while (mpsc_pop(queTask, &idxTask)) {
if(idxTask == -1){
shutdown = true;
break;
}
pTask = &pTaskSlot[idxTask];
//tmNow = sysapi_clock_now_ms(); // debug
tmwheel_add(pTask->msg.expiration, tmNow, pTask, twTimer);
if (++addCnt >= stepMsgMax) {
break;
}
}
if(shutdown){
break;
}
if (taskBakNum.load(std::memory_order_relaxed) > 0) { // has bak task
uint32_t tNum = 0;
while (true) {
pTask = nullptr;
{
std::unique_lock<std::mutex> lock(tmr->mtxTaskBak);
plk_pop(tmr->plkTaskBak, &pTask);
}
if (pTask) {
++tNum;
//tmNow = sysapi_clock_now_ms(); // debug
tmwheel_add(pTask->msg.expiration, tmNow, pTask, twTimer);
if (++addCnt >= stepMsgMax + stepMsgMax) {
break;
}
}
else {
break;
}
}
taskBakNum.fetch_sub(tNum, std::memory_order_relaxed);
}
//
if(addCnt > 0 || reAddCnt > 0 || reRspCnt > 0) {
unAddTask.fetch_sub(addCnt);
tmNow = timer_clock_now_ms(pipes); // has act, update tmNow for accurate
tmDbg4 = tmNow; // debug
}
//tmNow = sysapi_clock_now_ms(); // debug
// advance clock
delay = tmwheel_advance_clock(tmNow, twTimer);
dbgLastDelay = delay; // debug
dbgTmLastAdvance = tmNow; // debug
//
if(addCnt < 1 && reAddTaskNum < 1 && unRspTaskNum < 1) {
// no act this loop, check idle
idle.store(true);
if (unAddTask.load() < 1) {
if (delay <= 0 || delay >= 10000) {
delay = 10000;
}
int64_t tm1 = timer_clock_now_ms(pipes); // debug
cond_waitfor(idleCond, delay, tmNow, pipes, dbgDelayCost2);
dbgDelayCost = timer_clock_now_ms(pipes) - tm1; // debug
}
idle.store(false);
}
}
// wait all extthread done
pps_wait_ext_thread_done(pipes);
//
exclusive_mgr_waitalldone(pipes->exclusiveMgr);
// decr loopExited num
pipes->loopExitedNum.fetch_add(1);
// wait all loop exit
while(pipes->loopExitedNum.load() < totalLoopNum) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
//
cond_deinit(tmr->idleCond);
printf("timer(%d) end\n", tmr->index);
}
#if defined(USE_LINUX_TIMER)
void* timer_thread(void* arg)
{
struct pps_timer* tmr = (struct pps_timer*)arg;
thread_work(tmr);
return NULL;
}
#else
void timer_thread(struct pps_timer* tmr)
{
thread_work(tmr);
}
#endif
static void on_timeout(struct timer_task* task, int64_t tmNow)
{
//printf("timer exec on_timeout\n"); // debug
struct pps_timer* tmr = task->timer;
struct timer_msg* m = &task->msg;
m->session = -m->session;
// debug begin
int64_t realNow = timer_clock_now_ms(tmr->pipes);
int64_t off = realNow - m->expiration;
if(off > 4) {
printf("timeout delayed, off=%ld\n", off);
}
m->expiration = tmNow;
// debug end
int32_t ret = svc_send_timermsg(m->svcIdx, m, tmr);
if (ret == 0) { // dst mq is full, add to waitsend
plk_push_ptr(tmr->plkUnRspTask, m);
++tmr->unRspTask;
}
if (--m->repeat >= 0 && ret >= 0) { // schedule not complete, readd
m->session = -m->session;
m->expiration = tmNow + m->delay;
++tmr->reAddTask;
plk_push(tmr->plkReAddTask, task);
}
else { //back task
if(task->poolIdx >= 0) { // from taskPool
mpmc_push(tmr->freeTaskPool, task->poolIdx);
}else { // from taskBak
delete task;
}
}
}
int timer_add_task(struct timer_msg*m, struct pps_timer* timer)
{
int32_t idxTask;
if (mpmc_pop(timer->freeTaskPool, &idxTask)) {
struct timer_task* t = &timer->taskSlots[idxTask];
t->msg = *m;
mpsc_push(timer->queTask, idxTask);
}
else { // no free slot
struct timer_task* t = new struct timer_task;
t->poolIdx = -1;
t->timer = timer;
t->msg = *m;
{
std::unique_lock<std::mutex> lock(timer->mtxTaskBak);
plk_push(timer->plkTaskBak, t);
}
timer->taskBakNum.fetch_add(1);
}
//
timer->unAddTask.fetch_add(1);
if (timer->idle.load()) {// notify
cond_notify(timer->idleCond);
}
return 1;
}
void timer_shutdown(struct pipes* pipes)
{
for(int i=0; i<pipes->config->timer_num; ++i) {
struct pps_timer* timer = &pipes->timers[i];
while(!mpsc_push(timer->queTask, -1)){
}
cond_notify(timer->idleCond);
}
}
//
static inline void cond_init(struct timer_cond& cond)
{
#ifdef USE_LINUX_TIMER
pthread_mutex_init(&cond.mtx, NULL);
assert(pthread_condattr_init(&cond.condAttr) == 0);
assert(pthread_condattr_setclock(&cond.condAttr, CLOCK_MONOTONIC) == 0);
assert(pthread_cond_init(&cond.cond, &cond.condAttr) == 0);
#endif
}
static inline void cond_deinit(struct timer_cond& cond)
{
#ifdef USE_LINUX_TIMER
pthread_mutex_destroy(&cond.mtx);
pthread_condattr_destroy(&cond.condAttr);
pthread_cond_destroy(&cond.cond);
#endif
}
static inline void cond_notify(struct timer_cond& cond)
{
#ifdef USE_LINUX_TIMER
pthread_mutex_lock(&cond.mtx);
pthread_cond_signal(&cond.cond);
pthread_mutex_unlock(&cond.mtx);
#else
std::unique_lock<std::mutex> lock(cond.mtx);
cond.cv.notify_one();
#endif
}
static inline void cond_waitfor(struct timer_cond& cond, int64_t delay,
int64_t tmNow, struct pipes* pipes, int64_t& dbgCost)
{
#ifdef USE_LINUX_TIMER
delay -= 1;
if (delay <= 0) {
dbgCost = 0;
return;
}
struct timespec ts;
//struct timespec ts2, ts3; // debug
//
struct timespec* pTmStart = &pipes->tmStart->tm;
ts.tv_sec = pTmStart->tv_sec;
ts.tv_nsec = pTmStart->tv_nsec;
int64_t ns = ts.tv_nsec + (tmNow + delay) * 1000000;
ts.tv_nsec = ns % 1000000000;
ts.tv_sec += ns / 1000000000;
pthread_mutex_t* pMtx = &cond.mtx;
pthread_mutex_lock(pMtx);
//clock_gettime(CLOCK_MONOTONIC, &ts2); // debug
pthread_cond_timedwait(&cond.cond, pMtx, &ts);
//clock_gettime(CLOCK_MONOTONIC, &ts3); // debug
//dbgCost = (ts3.tv_sec - ts2.tv_sec) * 1000 + (ts3.tv_nsec - ts2.tv_nsec) / 1000000; // debug
pthread_mutex_unlock(pMtx);
#else
std::unique_lock<std::mutex> lock(cond.mtx);
cond.cv.wait_for(lock, std::chrono::milliseconds(delay));
#endif
}
//
int timer_init_main_thread(struct pps_timer* tmr, struct pipes* pipes, uint32_t index)
{
tmr->pipes = pipes;
tmr->index = index;
tmr->unAddTask.store(0);
//
tmr->reAddTask = 0;
tmr->plkReAddTask = const_cast<struct pool_linked<struct timer_task*>*>(plk_create<struct timer_task*>(TIMER_MAX_TASK));
//
tmr->unRspTask = 0;
tmr->plkUnRspTask = const_cast<struct pool_linked<struct timer_msg>*>(plk_create<struct timer_msg>(4096));
//
tmr->taskBakNum.store(0);
tmr->plkTaskBak = const_cast<struct pool_linked<struct timer_task*>*>(plk_create<struct timer_task*>(4096));
//
tmr->twTimer = tmwheel_create<struct timer_task*>(
2,
500,
0,
on_timeout,
10000,
10000);
//
tmr->taskSlots = new struct timer_task[TIMER_TASK_SLOT_NUM];
tmr->freeTaskPool = const_cast<struct mq_mpmc<int32_t>*>(mpmc_create<int32_t>(TIMER_TASK_SLOT_NUM));
tmr->queTask = const_cast<struct mq_mpsc<int32_t>*>(mpsc_create<int32_t>(TIMER_TASK_SLOT_NUM));
for (int32_t i = 0; i < TIMER_TASK_SLOT_NUM; ++i) {
struct timer_task* t = &tmr->taskSlots[i];
t->poolIdx = i;
t->timer = tmr;
if (i < TIMER_MAX_TASK) {
mpmc_push(tmr->freeTaskPool, i);
}
}
return 1;
}
int timer_deinit_main_thread(struct pps_timer* tmr)
{
delete[] tmr->taskSlots;
plk_destroy(tmr->plkReAddTask);
plk_destroy(tmr->plkUnRspTask);
plk_destroy(tmr->plkTaskBak);
mpmc_destroy(tmr->freeTaskPool);
mpsc_destroy(tmr->queTask);
//
tmwheel_destroy(tmr->twTimer);
return 1;
}
|
#include "easypr.h"
#include "easypr/util/switch.hpp"
#include "accuracy.hpp"
#include "chars.hpp"
#include "plate.hpp"
// %OPENCV%\x86\vc12\lib opencv_world300d.lib;
namespace easypr {
namespace demo {
// interactions
int accuracyTestMain() {
std::shared_ptr<easypr::Kv> kv(new easypr::Kv);
kv->load("resources/text/chinese_mapping");
bool isExit = false;
while (!isExit) {
easypr::Utils::print_file_lines("resources/text/batch_test_menu");
std::cout << kv->get("make_a_choice") << ":";
int select = -1;
bool isRepeat = true;
Result result;
while (isRepeat) {
std::cin >> select;
isRepeat = false;
switch (select) {
case 1:
accuracyTest("resources/image/general_test", result);
break;
case 2:
accuracyTest("resources/image/native_test", result);
break;
case 3:
gridSearchTest("resources/image/general_test");
break;
case 4:
isExit = true;
break;
default:
std::cout << kv->get("input_error") << ":";
isRepeat = true;
break;
}
}
}
return 0;
}
int trainChineseMain() {
std::shared_ptr<easypr::Kv> kv(new easypr::Kv);
kv->load("resources/text/chinese_mapping");
bool isExit = false;
while (!isExit) {
easypr::Utils::print_file_lines("resources/text/train_menu");
std::cout << kv->get("make_a_choice") << ":";
int select = -1;
bool isRepeat = true;
while (isRepeat) {
std::cin >> select;
isRepeat = false;
switch (select) {
case 1:
{
easypr::AnnChTrain ann("tmp/annCh", "tmp/annCh.xml");
ann.setNumberForCount(100);
ann.train();
}
break;
case 2:
{
easypr::AnnChTrain ann("tmp/annCh", "tmp/annCh.xml");
ann.setNumberForCount(350);
ann.train();
}
break;
case 3:
{
easypr::AnnChTrain ann("tmp/annCh", "tmp/annCh.xml");
ann.setNumberForCount(700);
ann.train();
}
break;
case 4:
{
easypr::AnnChTrain ann("tmp/annCh", "tmp/annCh.xml");
ann.setNumberForCount(1000);
ann.train();
}
break;
case 5:
{
easypr::AnnChTrain ann("tmp/annCh", "tmp/annCh.xml");
ann.setNumberForCount(1500);
ann.train();
}
break;
case 6:
isExit = true;
break;
default:
std::cout << kv->get("input_error") << ":";
isRepeat = true;
break;
}
}
}
return 0;
}
int testMain() {
std::shared_ptr<easypr::Kv> kv(new easypr::Kv);
kv->load("resources/text/chinese_mapping");
bool isExit = false;
while (!isExit) {
Utils::print_file_lines("resources/text/test_menu");
std::cout << kv->get("make_a_choice") << ":";
int select = -1;
bool isRepeat = true;
while (isRepeat) {
std::cin >> select;
isRepeat = false;
switch (select) {
case 1:
assert(test_plate_locate() == 0);
break;
case 2:
assert(test_plate_judge() == 0);
break;
case 3:
assert(test_plate_detect() == 0);
break;
case 4:
assert(test_chars_segment() == 0);
break;
case 5:
assert(test_chars_identify() == 0);
break;
case 6:
assert(test_chars_recognise() == 0);
break;
case 7:
assert(test_plate_recognize() == 0);
break;
case 8:
assert(test_plate_locate() == 0);
assert(test_plate_judge() == 0);
assert(test_plate_detect() == 0);
assert(test_chars_segment() == 0);
assert(test_chars_identify() == 0);
assert(test_chars_recognise() == 0);
assert(test_plate_recognize() == 0);
break;
case 9:
isExit = true;
break;
default:
std::cout << kv->get("input_error") << ":";
isRepeat = true;
break;
}
}
}
return 0;
}
} // namespace demo
} // namespace easypr
void command_line_handler(int argc, const char* argv[]) {
program_options::Generator options;
options.add_subroutine("svm", "svm operations").make_usage("Usage:");
{
/* ------------------------------------------
| SVM Training operations
| ------------------------------------------
|
| $ demo svm --plates=path/to/plates/ [--test] --svm=save/to/svm.xml
|
| ------------------------------------------
*/
options("h,help", "show help information");
options(",plates", "",
"a folder contains both forward data and inverse data in the "
"separated subfolders");
options(",svm", easypr::kDefaultSvmPath, "the svm model file");
options("t,test", "run tests in --plates");
}
options.add_subroutine("ann", "ann operation").make_usage("Usages:");
{
/* ------------------------------------------
| ANN_MLP Training operations
| ------------------------------------------
|
| $ demo ann --zh-chars=zhchars/ --en-chars=enchars/ --ann=save/to/ann.xml
|
| ------------------------------------------
*/
options("h,help", "show help information");
options(",chars", "",
"the folder contains character sub-folders, with each folder"
"named by label defined in include/easypr/config.h");
options(",ann", easypr::kDefaultAnnPath,
"the ann model file you want to save");
options("t,test", "run test in --chars");
}
options.add_subroutine("locate", "locate plates in an image")
.make_usage("Usage:");
{
/* ------------------------------------------
| Plate locating operations
| ------------------------------------------
|
| $ demo locate -f file
|
| ------------------------------------------
*/
options("h,help", "show help information");
options("f,file", "",
"the target picture which contains one or more plates");
}
options.add_subroutine(
"judge", "determine whether an image block is the license plate")
.make_usage("Usage:");
{
/* ------------------------------------------
| Plate judge operations
| ------------------------------------------
|
| $ demo judge -f file --svm model/svm.xml
|
| ------------------------------------------
*/
options("h,help", "show help information");
options("f,file", "the target image block");
options(",svm", easypr::kDefaultSvmPath, "the svm model file");
}
options.add_subroutine("recognize", "plate recognition").make_usage("Usage:");
{
/* ------------------------------------------
| Plate recognize operations
| ------------------------------------------
|
| $ demo recognize -p file --svm model/svm.xml
| --ann model/ann.xml
| $ demo recognize -pb dir/ --svm model/svm.xml
| --ann model/ann.xml
|
| ------------------------------------------
*/
options("h,help", "show help information");
options("p,path", "", "where is the target picture or target folder");
options("b,batch", "do batch recognition, if set, --path means a folder");
options("c,color", "returns the plate color, blue or yellow");
options(",svm", easypr::kDefaultSvmPath, "the svm model file");
options(",ann", easypr::kDefaultAnnPath, "the ann model file");
}
auto parser = options.make_parser();
try {
parser->parse(argc, argv);
} catch (const std::exception &err) {
std::cout << err.what() << std::endl;
return;
}
auto subname = parser->get_subroutine_name();
program_options::select(subname)
.found("svm",
[&]() {
if (parser->has("help") || argc <= 2) {
std::cout << options("svm");
return;
}
easypr::SvmTrain svm(parser->get("plates")->c_str(),
parser->get("svm")->c_str());
if (parser->has("test")) {
svm.test();
} else {
svm.train();
}
})
.found("ann",
[&]() {
if (parser->has("help") || argc <= 2) {
std::cout << options("ann");
return;
}
assert(parser->has("chars"));
assert(parser->has("ann"));
easypr::AnnTrain ann(parser->get("chars")->c_str(),
parser->get("ann")->c_str());
if (parser->has("test")) {
ann.test();
} else {
ann.train();
}
})
.found("locate",
[&]() {
if (parser->has("help") || argc <= 2) {
std::cout << options("locate");
return;
}
if (parser->has("file")) {
easypr::api::plate_locate(parser->get("file")->val().c_str());
std::cout << "finished, results can be found in tmp/"
<< std::endl;
}
})
.found("judge",
[&]() {
if (parser->has("help") || argc <= 2) {
std::cout << options("judge");
std::cout << "Note that the input image's size should "
<< "be the same as the one you gived to svm train."
<< std::endl;
return;
}
if (parser->has("file")) {
assert(parser->has("file"));
assert(parser->has("svm"));
auto image = parser->get("file")->val();
auto svm = parser->get("svm")->val();
const char* true_or_false[2] = {"false", "true"};
std::cout << true_or_false[easypr::api::plate_judge(
image.c_str(), svm.c_str())]
<< std::endl;
}
})
.found("recognize",
[&]() {
if (parser->has("help") || argc <= 2) {
std::cout << options("recognize");
return;
}
if (parser->has("path")) {
if (parser->has("batch")) {
// batch testing
auto folder = parser->get("path")->val();
easypr::demo::Result result;
easypr::demo::accuracyTest(folder.c_str(), result);
} else {
// single testing
auto image = parser->get("path")->val();
if (parser->has("color")) {
// return plate color
const char* colors[2] = {"blue", "yellow"};
std::cout
<< colors[easypr::api::get_plate_color(image.c_str())]
<< std::endl;
} else {
// return strings
auto svm = parser->get("svm")->val();
auto ann = parser->get("ann")->val();
auto results = easypr::api::plate_recognize(
image.c_str(), svm.c_str(), ann.c_str());
for (auto s : results) {
std::cout << s << std::endl;
}
}
}
} else {
std::cout << "option 'file' cannot be empty." << std::endl;
}
})
.others([&]() {
// no case matched, print all commands.
std::cout << "There are several sub commands listed below, "
<< "choose one by typing:\n\n"
<< " " << easypr::utils::getFileName(argv[0])
<< " command [options]\n\n"
<< "The commands are:\n" << std::endl;
auto subs = options.get_subroutine_list();
for (auto sub : subs) {
fprintf(stdout, "%s %s\n", sub.first.c_str(), sub.second.c_str());
}
std::cout << std::endl;
});
}
int main(int argc, const char* argv[]) {
if (setenv ("DISPLAY", ":0", 0) == -1) {
return -1;
}
std::shared_ptr<easypr::Kv> kv(new easypr::Kv);
kv->load("resources/text/chinese_mapping");
if (argc > 1) {
// handle command line execution.
command_line_handler(argc, argv);
return 0;
}
bool isExit = false;
while (!isExit) {
easypr::Utils::print_file_lines("resources/text/main_menu");
std::cout << kv->get("make_a_choice") << ":";
int select = -1;
bool isRepeat = true;
while (isRepeat) {
std::cin >> select;
isRepeat = false;
switch (select) {
case 1:
easypr::demo::testMain();
break;
case 2:
easypr::demo::accuracyTestMain();
break;
case 3:
std::cout << "Run \"demo svm\" for more usage." << std::endl;
{
easypr::SvmTrain svm("tmp/svm", "tmp/svm.xml");
svm.train();
}
break;
case 4:
std::cout << "Run \"demo ann\" for more usage." << std::endl;
{
easypr::AnnTrain ann("tmp/ann", "tmp/ann.xml");
ann.train();
}
break;
case 5:
easypr::demo::trainChineseMain();
break;
case 6: {
//TODO: genenrate gray characters
easypr::demo::accuracyCharRecognizeTest("resources/image/tmp/plates_200k");
break;
}
case 7:
isExit = true;
break;
default:
std::cout << kv->get("input_error") << ":";
isRepeat = true;
break;
}
}
}
return 0;
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "gtest/gtest.h"
#include "Basics/CpuUsageSnapshot.h"
using namespace arangodb;
TEST(CpuUsageSnapshotTest, testEmpty) {
CpuUsageSnapshot s;
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
ASSERT_EQ(0.0, s.userPercent());
ASSERT_EQ(0.0, s.systemPercent());
ASSERT_EQ(0.0, s.idlePercent());
ASSERT_EQ(0.0, s.iowaitPercent());
}
TEST(CpuUsageSnapshotTest, testFromString) {
{
std::string input("");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
}
{
std::string input("quetzalcoatl");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
}
{
std::string input("1");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
}
{
std::string input("1 2 3445");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
}
{
std::string input("19999999999999999999999999999999999999999999999999999999999999999999999999999999999999");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
}
{
std::string input("1234 48868 939949 439995 2030223 02232");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
}
{
std::string input("1 2 3 4 5 6 7 8 9 10");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
uint64_t total = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
ASSERT_TRUE(s.valid());
ASSERT_EQ(total, s.total());
ASSERT_EQ(1, s.user);
ASSERT_EQ(2, s.nice);
ASSERT_EQ(3, s.system);
ASSERT_EQ(4, s.idle);
ASSERT_EQ(5, s.iowait);
ASSERT_EQ(6, s.irq);
ASSERT_EQ(7, s.softirq);
ASSERT_EQ(8, s.steal);
ASSERT_EQ(9, s.guest);
ASSERT_EQ(10, s.guestnice);
ASSERT_DOUBLE_EQ(100. * (1.+ 2.) / double(total), s.userPercent());
ASSERT_DOUBLE_EQ(100. * 3. / double(total), s.systemPercent());
ASSERT_DOUBLE_EQ(100. * 4. / double(total), s.idlePercent());
ASSERT_DOUBLE_EQ(100. * 5. / double(total), s.iowaitPercent());
}
{
std::string input("1 0 0 0 0 0 0 0 0 0");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
uint64_t total = 1;
ASSERT_TRUE(s.valid());
ASSERT_EQ(total, s.total());
ASSERT_EQ(1, s.user);
ASSERT_EQ(0, s.nice);
ASSERT_EQ(0, s.system);
ASSERT_EQ(0, s.idle);
ASSERT_EQ(0, s.iowait);
ASSERT_EQ(0, s.irq);
ASSERT_EQ(0, s.softirq);
ASSERT_EQ(0, s.steal);
ASSERT_EQ(0, s.guest);
ASSERT_EQ(0, s.guestnice);
ASSERT_DOUBLE_EQ(100. * 1. / double(total), s.userPercent());
ASSERT_DOUBLE_EQ(100. * 0. / double(total), s.systemPercent());
ASSERT_DOUBLE_EQ(100. * 0. / double(total), s.idlePercent());
ASSERT_DOUBLE_EQ(100. * 0. / double(total), s.iowaitPercent());
}
{
std::string input("578816 390 54632 4019475 2523 0 275 0 0 0");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
uint64_t total = 578816 + 390 + 54632 + 4019475 + 2523 + 0 + 275 + 0 + 0 + 0;
ASSERT_TRUE(s.valid());
ASSERT_EQ(total, s.total());
ASSERT_EQ(578816, s.user);
ASSERT_EQ(390, s.nice);
ASSERT_EQ(54632, s.system);
ASSERT_EQ(4019475, s.idle);
ASSERT_EQ(2523, s.iowait);
ASSERT_EQ(0, s.irq);
ASSERT_EQ(275, s.softirq);
ASSERT_EQ(0, s.steal);
ASSERT_EQ(0, s.guest);
ASSERT_EQ(0, s.guestnice);
ASSERT_DOUBLE_EQ(100. * (578816. + 390.) / double(total), s.userPercent());
ASSERT_DOUBLE_EQ(100. * 54632. / double(total), s.systemPercent());
ASSERT_DOUBLE_EQ(100. * 4019475. / double(total), s.idlePercent());
ASSERT_DOUBLE_EQ(100. * 2523. / double(total), s.iowaitPercent());
}
{
std::string input("304866003 5720038 69726754 4732078787 130352063 0 7621266 0 0 0");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
uint64_t total = 304866003 + 5720038 + 69726754 + 4732078787 + 130352063 + 0 + 7621266 + 0 + 0 + 0;
ASSERT_TRUE(s.valid());
ASSERT_EQ(total, s.total());
ASSERT_EQ(304866003, s.user);
ASSERT_EQ(5720038, s.nice);
ASSERT_EQ(69726754, s.system);
ASSERT_EQ(4732078787, s.idle);
ASSERT_EQ(130352063, s.iowait);
ASSERT_EQ(0, s.irq);
ASSERT_EQ(7621266, s.softirq);
ASSERT_EQ(0, s.steal);
ASSERT_EQ(0, s.guest);
ASSERT_EQ(0, s.guestnice);
ASSERT_DOUBLE_EQ(100. * (304866003. + 5720038.) / double(total), s.userPercent());
ASSERT_DOUBLE_EQ(100. * 69726754. / double(total), s.systemPercent());
ASSERT_DOUBLE_EQ(100. * 4732078787. / double(total), s.idlePercent());
ASSERT_DOUBLE_EQ(100. * 130352063. / double(total), s.iowaitPercent());
}
{
std::string input("624582 562 63837 5793524 3165 0 361 0 0 0\ncpu0 51303 38 7370 749474 378 0 216 0 0 0");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
uint64_t total = 624582 + 562 + 63837 + 5793524 + 3165 + 0 + 361 + 0 + 0 + 0;
ASSERT_TRUE(s.valid());
ASSERT_EQ(total, s.total());
ASSERT_EQ(624582, s.user);
ASSERT_EQ(562, s.nice);
ASSERT_EQ(63837, s.system);
ASSERT_EQ(5793524, s.idle);
ASSERT_EQ(3165, s.iowait);
ASSERT_EQ(0, s.irq);
ASSERT_EQ(361, s.softirq);
ASSERT_EQ(0, s.steal);
ASSERT_EQ(0, s.guest);
ASSERT_EQ(0, s.guestnice);
ASSERT_DOUBLE_EQ(100. * (624582. + 562.) / double(total), s.userPercent());
ASSERT_DOUBLE_EQ(100. * 63837. / double(total), s.systemPercent());
ASSERT_DOUBLE_EQ(100. * 5793524. / double(total), s.idlePercent());
ASSERT_DOUBLE_EQ(100. * 3165. / double(total), s.iowaitPercent());
}
}
TEST(CpuUsageSnapshotTest, testClear) {
std::string input("1 2 3 4 5 6 7 8 9 10");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_TRUE(s.valid());
s.clear();
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
ASSERT_EQ(0.0, s.userPercent());
ASSERT_EQ(0.0, s.systemPercent());
ASSERT_EQ(0.0, s.idlePercent());
ASSERT_EQ(0.0, s.iowaitPercent());
}
TEST(CpuUsageSnapshotTest, testSubtract) {
{
// subtract snapshot with the same data
std::string input("1 2 3 4 5 6 7 8 9 10");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_TRUE(s.valid());
CpuUsageSnapshot o = CpuUsageSnapshot::fromString(input.data(), input.size());
ASSERT_TRUE(o.valid());
s.subtract(o);
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
ASSERT_EQ(0, s.user);
ASSERT_EQ(0, s.nice);
ASSERT_EQ(0, s.system);
ASSERT_EQ(0, s.idle);
ASSERT_EQ(0, s.iowait);
ASSERT_EQ(0, s.irq);
ASSERT_EQ(0, s.softirq);
ASSERT_EQ(0, s.steal);
ASSERT_EQ(0, s.guest);
ASSERT_EQ(0, s.guestnice);
}
{
std::string input1("624582 562 63837 5793524 3165 0 361 0 0 0");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input1.data(), input1.size());
ASSERT_TRUE(s.valid());
std::string input2("578816 390 54632 4019475 2523 0 275 0 0 0");
CpuUsageSnapshot o = CpuUsageSnapshot::fromString(input2.data(), input2.size());
ASSERT_TRUE(o.valid());
s.subtract(o);
ASSERT_TRUE(s.valid());
ASSERT_EQ(624582 + 562 + 63837 + 5793524 + 3165 + 0 + 361 + 0 + 0 + 0 - 578816 - 390 - 54632 - 4019475 - 2523 - 0 - 275 - 0 -0 - 0, s.total());
ASSERT_EQ(624582 - 578816, s.user);
ASSERT_EQ(562 - 390, s.nice);
ASSERT_EQ(63837 - 54632, s.system);
ASSERT_EQ(5793524 - 4019475, s.idle);
ASSERT_EQ(3165 - 2523, s.iowait);
ASSERT_EQ(0, s.irq);
ASSERT_EQ(361 - 275, s.softirq);
ASSERT_EQ(0, s.steal);
ASSERT_EQ(0, s.guest);
ASSERT_EQ(0, s.guestnice);
}
{
// underflow
std::string input1("578816 390 54632 4019475 2523 0 275 0 0 0");
CpuUsageSnapshot s = CpuUsageSnapshot::fromString(input1.data(), input1.size());
ASSERT_TRUE(s.valid());
std::string input2("624582 562 63837 5793524 3165 0 361 0 0 0");
CpuUsageSnapshot o = CpuUsageSnapshot::fromString(input2.data(), input2.size());
ASSERT_TRUE(o.valid());
s.subtract(o);
ASSERT_FALSE(s.valid());
ASSERT_EQ(0, s.total());
ASSERT_EQ(0, s.total());
ASSERT_EQ(0, s.user);
ASSERT_EQ(0, s.nice);
ASSERT_EQ(0, s.system);
ASSERT_EQ(0, s.idle);
ASSERT_EQ(0, s.iowait);
ASSERT_EQ(0, s.irq);
ASSERT_EQ(0, s.softirq);
ASSERT_EQ(0, s.steal);
ASSERT_EQ(0, s.guest);
ASSERT_EQ(0, s.guestnice);
ASSERT_EQ(0, s.user);
}
}
|
//===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements induction variable simplification. It does
// not define any actual pass or policy, but provides a single function to
// simplify a loop's induction variables based on ScalarEvolution.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/SimplifyIndVar.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
using namespace llvm;
#define DEBUG_TYPE "indvars"
STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
STATISTIC(NumElimOperand, "Number of IV operands folded into a use");
STATISTIC(NumFoldedUser, "Number of IV users folded into a constant");
STATISTIC(NumElimRem , "Number of IV remainder operations eliminated");
STATISTIC(
NumSimplifiedSDiv,
"Number of IV signed division operations converted to unsigned division");
STATISTIC(
NumSimplifiedSRem,
"Number of IV signed remainder operations converted to unsigned remainder");
STATISTIC(NumElimCmp , "Number of IV comparisons eliminated");
namespace {
/// This is a utility for simplifying induction variables
/// based on ScalarEvolution. It is the primary instrument of the
/// IndvarSimplify pass, but it may also be directly invoked to cleanup after
/// other loop passes that preserve SCEV.
class SimplifyIndvar {
Loop *L;
LoopInfo *LI;
ScalarEvolution *SE;
DominatorTree *DT;
const TargetTransformInfo *TTI;
SCEVExpander &Rewriter;
SmallVectorImpl<WeakTrackingVH> &DeadInsts;
bool Changed;
public:
SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
LoopInfo *LI, const TargetTransformInfo *TTI,
SCEVExpander &Rewriter,
SmallVectorImpl<WeakTrackingVH> &Dead)
: L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter),
DeadInsts(Dead), Changed(false) {
assert(LI && "IV simplification requires LoopInfo");
}
bool hasChanged() const { return Changed; }
/// Iteratively perform simplification on a worklist of users of the
/// specified induction variable. This is the top-level driver that applies
/// all simplifications to users of an IV.
void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
bool eliminateTrunc(TruncInst *TI);
bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
bool IsSigned);
void replaceRemWithNumerator(BinaryOperator *Rem);
void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
void replaceSRemWithURem(BinaryOperator *Rem);
bool eliminateSDiv(BinaryOperator *SDiv);
bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
};
}
/// Find a point in code which dominates all given instructions. We can safely
/// assume that, whatever fact we can prove at the found point, this fact is
/// also true for each of the given instructions.
static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions,
DominatorTree &DT) {
Instruction *CommonDom = nullptr;
for (auto *Insn : Instructions)
if (!CommonDom || DT.dominates(Insn, CommonDom))
CommonDom = Insn;
else if (!DT.dominates(CommonDom, Insn))
// If there is no dominance relation, use common dominator.
CommonDom =
DT.findNearestCommonDominator(CommonDom->getParent(),
Insn->getParent())->getTerminator();
assert(CommonDom && "Common dominator not found?");
return CommonDom;
}
/// Fold an IV operand into its use. This removes increments of an
/// aligned IV when used by a instruction that ignores the low bits.
///
/// IVOperand is guaranteed SCEVable, but UseInst may not be.
///
/// Return the operand of IVOperand for this induction variable if IVOperand can
/// be folded (in case more folding opportunities have been exposed).
/// Otherwise return null.
Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
Value *IVSrc = nullptr;
const unsigned OperIdx = 0;
const SCEV *FoldedExpr = nullptr;
bool MustDropExactFlag = false;
switch (UseInst->getOpcode()) {
default:
return nullptr;
case Instruction::UDiv:
case Instruction::LShr:
// We're only interested in the case where we know something about
// the numerator and have a constant denominator.
if (IVOperand != UseInst->getOperand(OperIdx) ||
!isa<ConstantInt>(UseInst->getOperand(1)))
return nullptr;
// Attempt to fold a binary operator with constant operand.
// e.g. ((I + 1) >> 2) => I >> 2
if (!isa<BinaryOperator>(IVOperand)
|| !isa<ConstantInt>(IVOperand->getOperand(1)))
return nullptr;
IVSrc = IVOperand->getOperand(0);
// IVSrc must be the (SCEVable) IV, since the other operand is const.
assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
if (UseInst->getOpcode() == Instruction::LShr) {
// Get a constant for the divisor. See createSCEV.
uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
if (D->getValue().uge(BitWidth))
return nullptr;
D = ConstantInt::get(UseInst->getContext(),
APInt::getOneBitSet(BitWidth, D->getZExtValue()));
}
FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
// We might have 'exact' flag set at this point which will no longer be
// correct after we make the replacement.
if (UseInst->isExact() &&
SE->getSCEV(IVSrc) != SE->getMulExpr(FoldedExpr, SE->getSCEV(D)))
MustDropExactFlag = true;
}
// We have something that might fold it's operand. Compare SCEVs.
if (!SE->isSCEVable(UseInst->getType()))
return nullptr;
// Bypass the operand if SCEV can prove it has no effect.
if (SE->getSCEV(UseInst) != FoldedExpr)
return nullptr;
LLVM_DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
<< " -> " << *UseInst << '\n');
UseInst->setOperand(OperIdx, IVSrc);
assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
if (MustDropExactFlag)
UseInst->dropPoisonGeneratingFlags();
++NumElimOperand;
Changed = true;
if (IVOperand->use_empty())
DeadInsts.emplace_back(IVOperand);
return IVSrc;
}
bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
Value *IVOperand) {
unsigned IVOperIdx = 0;
ICmpInst::Predicate Pred = ICmp->getPredicate();
if (IVOperand != ICmp->getOperand(0)) {
// Swapped
assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
IVOperIdx = 1;
Pred = ICmpInst::getSwappedPredicate(Pred);
}
// Get the SCEVs for the ICmp operands (in the specific context of the
// current loop)
const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
auto *PN = dyn_cast<PHINode>(IVOperand);
if (!PN)
return false;
auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L);
if (!LIP)
return false;
ICmpInst::Predicate InvariantPredicate = LIP->Pred;
const SCEV *InvariantLHS = LIP->LHS;
const SCEV *InvariantRHS = LIP->RHS;
// Rewrite the comparison to a loop invariant comparison if it can be done
// cheaply, where cheaply means "we don't need to emit any new
// instructions".
SmallDenseMap<const SCEV*, Value*> CheapExpansions;
CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
// TODO: Support multiple entry loops? (We currently bail out of these in
// the IndVarSimplify pass)
if (auto *BB = L->getLoopPredecessor()) {
const int Idx = PN->getBasicBlockIndex(BB);
if (Idx >= 0) {
Value *Incoming = PN->getIncomingValue(Idx);
const SCEV *IncomingS = SE->getSCEV(Incoming);
CheapExpansions[IncomingS] = Incoming;
}
}
Value *NewLHS = CheapExpansions[InvariantLHS];
Value *NewRHS = CheapExpansions[InvariantRHS];
if (!NewLHS)
if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
NewLHS = ConstLHS->getValue();
if (!NewRHS)
if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
NewRHS = ConstRHS->getValue();
if (!NewLHS || !NewRHS)
// We could not find an existing value to replace either LHS or RHS.
// Generating new instructions has subtler tradeoffs, so avoid doing that
// for now.
return false;
LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
ICmp->setPredicate(InvariantPredicate);
ICmp->setOperand(0, NewLHS);
ICmp->setOperand(1, NewRHS);
return true;
}
/// SimplifyIVUsers helper for eliminating useless
/// comparisons against an induction variable.
void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
unsigned IVOperIdx = 0;
ICmpInst::Predicate Pred = ICmp->getPredicate();
ICmpInst::Predicate OriginalPred = Pred;
if (IVOperand != ICmp->getOperand(0)) {
// Swapped
assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
IVOperIdx = 1;
Pred = ICmpInst::getSwappedPredicate(Pred);
}
// Get the SCEVs for the ICmp operands (in the specific context of the
// current loop)
const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
// If the condition is always true or always false in the given context,
// replace it with a constant value.
SmallVector<Instruction *, 4> Users;
for (auto *U : ICmp->users())
Users.push_back(cast<Instruction>(U));
const Instruction *CtxI = findCommonDominator(Users, *DT);
if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, CtxI)) {
ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev));
DeadInsts.emplace_back(ICmp);
LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
} else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
// fallthrough to end of function
} else if (ICmpInst::isSigned(OriginalPred) &&
SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
// If we were unable to make anything above, all we can is to canonicalize
// the comparison hoping that it will open the doors for other
// optimizations. If we find out that we compare two non-negative values,
// we turn the instruction's predicate to its unsigned version. Note that
// we cannot rely on Pred here unless we check if we have swapped it.
assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
<< '\n');
ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
} else
return;
++NumElimCmp;
Changed = true;
}
bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
// Get the SCEVs for the ICmp operands.
auto *N = SE->getSCEV(SDiv->getOperand(0));
auto *D = SE->getSCEV(SDiv->getOperand(1));
// Simplify unnecessary loops away.
const Loop *L = LI->getLoopFor(SDiv->getParent());
N = SE->getSCEVAtScope(N, L);
D = SE->getSCEVAtScope(D, L);
// Replace sdiv by udiv if both of the operands are non-negative
if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
auto *UDiv = BinaryOperator::Create(
BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
SDiv->getName() + ".udiv", SDiv);
UDiv->setIsExact(SDiv->isExact());
SDiv->replaceAllUsesWith(UDiv);
LLVM_DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
++NumSimplifiedSDiv;
Changed = true;
DeadInsts.push_back(SDiv);
return true;
}
return false;
}
// i %s n -> i %u n if i >= 0 and n >= 0
void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
Rem->getName() + ".urem", Rem);
Rem->replaceAllUsesWith(URem);
LLVM_DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
++NumSimplifiedSRem;
Changed = true;
DeadInsts.emplace_back(Rem);
}
// i % n --> i if i is in [0,n).
void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
Rem->replaceAllUsesWith(Rem->getOperand(0));
LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
++NumElimRem;
Changed = true;
DeadInsts.emplace_back(Rem);
}
// (i+1) % n --> (i+1)==n?0:(i+1) if i is in [0,n).
void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
auto *T = Rem->getType();
auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
SelectInst *Sel =
SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
Rem->replaceAllUsesWith(Sel);
LLVM_DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
++NumElimRem;
Changed = true;
DeadInsts.emplace_back(Rem);
}
/// SimplifyIVUsers helper for eliminating useless remainder operations
/// operating on an induction variable or replacing srem by urem.
void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
bool IsSigned) {
auto *NValue = Rem->getOperand(0);
auto *DValue = Rem->getOperand(1);
// We're only interested in the case where we know something about
// the numerator, unless it is a srem, because we want to replace srem by urem
// in general.
bool UsedAsNumerator = IVOperand == NValue;
if (!UsedAsNumerator && !IsSigned)
return;
const SCEV *N = SE->getSCEV(NValue);
// Simplify unnecessary loops away.
const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
N = SE->getSCEVAtScope(N, ICmpLoop);
bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
// Do not proceed if the Numerator may be negative
if (!IsNumeratorNonNegative)
return;
const SCEV *D = SE->getSCEV(DValue);
D = SE->getSCEVAtScope(D, ICmpLoop);
if (UsedAsNumerator) {
auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
if (SE->isKnownPredicate(LT, N, D)) {
replaceRemWithNumerator(Rem);
return;
}
auto *T = Rem->getType();
const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
if (SE->isKnownPredicate(LT, NLessOne, D)) {
replaceRemWithNumeratorOrZero(Rem);
return;
}
}
// Try to replace SRem with URem, if both N and D are known non-negative.
// Since we had already check N, we only need to check D now
if (!IsSigned || !SE->isKnownNonNegative(D))
return;
replaceSRemWithURem(Rem);
}
bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
const SCEV *LHS = SE->getSCEV(WO->getLHS());
const SCEV *RHS = SE->getSCEV(WO->getRHS());
if (!SE->willNotOverflow(WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
return false;
// Proved no overflow, nuke the overflow check and, if possible, the overflow
// intrinsic as well.
BinaryOperator *NewResult = BinaryOperator::Create(
WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO);
if (WO->isSigned())
NewResult->setHasNoSignedWrap(true);
else
NewResult->setHasNoUnsignedWrap(true);
SmallVector<ExtractValueInst *, 4> ToDelete;
for (auto *U : WO->users()) {
if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
if (EVI->getIndices()[0] == 1)
EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
else {
assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
EVI->replaceAllUsesWith(NewResult);
}
ToDelete.push_back(EVI);
}
}
for (auto *EVI : ToDelete)
EVI->eraseFromParent();
if (WO->use_empty())
WO->eraseFromParent();
Changed = true;
return true;
}
bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
const SCEV *LHS = SE->getSCEV(SI->getLHS());
const SCEV *RHS = SE->getSCEV(SI->getRHS());
if (!SE->willNotOverflow(SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
return false;
BinaryOperator *BO = BinaryOperator::Create(
SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI);
if (SI->isSigned())
BO->setHasNoSignedWrap();
else
BO->setHasNoUnsignedWrap();
SI->replaceAllUsesWith(BO);
DeadInsts.emplace_back(SI);
Changed = true;
return true;
}
bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
// It is always legal to replace
// icmp <pred> i32 trunc(iv), n
// with
// icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
// Or with
// icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
// Or with either of these if pred is an equality predicate.
//
// If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
// every comparison which uses trunc, it means that we can replace each of
// them with comparison of iv against sext/zext(n). We no longer need trunc
// after that.
//
// TODO: Should we do this if we can widen *some* comparisons, but not all
// of them? Sometimes it is enough to enable other optimizations, but the
// trunc instruction will stay in the loop.
Value *IV = TI->getOperand(0);
Type *IVTy = IV->getType();
const SCEV *IVSCEV = SE->getSCEV(IV);
const SCEV *TISCEV = SE->getSCEV(TI);
// Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
// get rid of trunc
bool DoesSExtCollapse = false;
bool DoesZExtCollapse = false;
if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
DoesSExtCollapse = true;
if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
DoesZExtCollapse = true;
// If neither sext nor zext does collapse, it is not profitable to do any
// transform. Bail.
if (!DoesSExtCollapse && !DoesZExtCollapse)
return false;
// Collect users of the trunc that look like comparisons against invariants.
// Bail if we find something different.
SmallVector<ICmpInst *, 4> ICmpUsers;
for (auto *U : TI->users()) {
// We don't care about users in unreachable blocks.
if (isa<Instruction>(U) &&
!DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
continue;
ICmpInst *ICI = dyn_cast<ICmpInst>(U);
if (!ICI) return false;
assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
!(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
return false;
// If we cannot get rid of trunc, bail.
if (ICI->isSigned() && !DoesSExtCollapse)
return false;
if (ICI->isUnsigned() && !DoesZExtCollapse)
return false;
// For equality, either signed or unsigned works.
ICmpUsers.push_back(ICI);
}
auto CanUseZExt = [&](ICmpInst *ICI) {
// Unsigned comparison can be widened as unsigned.
if (ICI->isUnsigned())
return true;
// Is it profitable to do zext?
if (!DoesZExtCollapse)
return false;
// For equality, we can safely zext both parts.
if (ICI->isEquality())
return true;
// Otherwise we can only use zext when comparing two non-negative or two
// negative values. But in practice, we will never pass DoesZExtCollapse
// check for a negative value, because zext(trunc(x)) is non-negative. So
// it only make sense to check for non-negativity here.
const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
};
// Replace all comparisons against trunc with comparisons against IV.
for (auto *ICI : ICmpUsers) {
bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
Instruction *Ext = nullptr;
// For signed/unsigned predicate, replace the old comparison with comparison
// of immediate IV against sext/zext of the invariant argument. If we can
// use either sext or zext (i.e. we are dealing with equality predicate),
// then prefer zext as a more canonical form.
// TODO: If we see a signed comparison which can be turned into unsigned,
// we can do it here for canonicalization purposes.
ICmpInst::Predicate Pred = ICI->getPredicate();
if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
if (CanUseZExt(ICI)) {
assert(DoesZExtCollapse && "Unprofitable zext?");
Ext = new ZExtInst(Op1, IVTy, "zext", ICI);
Pred = ICmpInst::getUnsignedPredicate(Pred);
} else {
assert(DoesSExtCollapse && "Unprofitable sext?");
Ext = new SExtInst(Op1, IVTy, "sext", ICI);
assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
}
bool Changed;
L->makeLoopInvariant(Ext, Changed);
(void)Changed;
ICmpInst *NewICI = new ICmpInst(ICI, Pred, IV, Ext);
ICI->replaceAllUsesWith(NewICI);
DeadInsts.emplace_back(ICI);
}
// Trunc no longer needed.
TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
DeadInsts.emplace_back(TI);
return true;
}
/// Eliminate an operation that consumes a simple IV and has no observable
/// side-effect given the range of IV values. IVOperand is guaranteed SCEVable,
/// but UseInst may not be.
bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
Instruction *IVOperand) {
if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
eliminateIVComparison(ICmp, IVOperand);
return true;
}
if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
bool IsSRem = Bin->getOpcode() == Instruction::SRem;
if (IsSRem || Bin->getOpcode() == Instruction::URem) {
simplifyIVRemainder(Bin, IVOperand, IsSRem);
return true;
}
if (Bin->getOpcode() == Instruction::SDiv)
return eliminateSDiv(Bin);
}
if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
if (eliminateOverflowIntrinsic(WO))
return true;
if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
if (eliminateSaturatingIntrinsic(SI))
return true;
if (auto *TI = dyn_cast<TruncInst>(UseInst))
if (eliminateTrunc(TI))
return true;
if (eliminateIdentitySCEV(UseInst, IVOperand))
return true;
return false;
}
static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
if (auto *BB = L->getLoopPreheader())
return BB->getTerminator();
return Hint;
}
/// Replace the UseInst with a loop invariant expression if it is safe.
bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
if (!SE->isSCEVable(I->getType()))
return false;
// Get the symbolic expression for this instruction.
const SCEV *S = SE->getSCEV(I);
if (!SE->isLoopInvariant(S, L))
return false;
// Do not generate something ridiculous even if S is loop invariant.
if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I))
return false;
auto *IP = GetLoopInvariantInsertPosition(L, I);
if (!isSafeToExpandAt(S, IP, *SE)) {
LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I
<< " with non-speculable loop invariant: " << *S << '\n');
return false;
}
auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
I->replaceAllUsesWith(Invariant);
LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
<< " with loop invariant: " << *S << '\n');
++NumFoldedUser;
Changed = true;
DeadInsts.emplace_back(I);
return true;
}
/// Eliminate any operation that SCEV can prove is an identity function.
bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
Instruction *IVOperand) {
if (!SE->isSCEVable(UseInst->getType()) ||
(UseInst->getType() != IVOperand->getType()) ||
(SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
return false;
// getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
// dominator tree, even if X is an operand to Y. For instance, in
//
// %iv = phi i32 {0,+,1}
// br %cond, label %left, label %merge
//
// left:
// %X = add i32 %iv, 0
// br label %merge
//
// merge:
// %M = phi (%X, %iv)
//
// getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
// %M.replaceAllUsesWith(%X) would be incorrect.
if (isa<PHINode>(UseInst))
// If UseInst is not a PHI node then we know that IVOperand dominates
// UseInst directly from the legality of SSA.
if (!DT || !DT->dominates(IVOperand, UseInst))
return false;
if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
return false;
LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
UseInst->replaceAllUsesWith(IVOperand);
++NumElimIdentity;
Changed = true;
DeadInsts.emplace_back(UseInst);
return true;
}
/// Annotate BO with nsw / nuw if it provably does not signed-overflow /
/// unsigned-overflow. Returns true if anything changed, false otherwise.
bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
Value *IVOperand) {
SCEV::NoWrapFlags Flags;
bool Deduced;
std::tie(Flags, Deduced) = SE->getStrengthenedNoWrapFlagsFromBinOp(
cast<OverflowingBinaryOperator>(BO));
if (!Deduced)
return Deduced;
BO->setHasNoUnsignedWrap(ScalarEvolution::maskFlags(Flags, SCEV::FlagNUW) ==
SCEV::FlagNUW);
BO->setHasNoSignedWrap(ScalarEvolution::maskFlags(Flags, SCEV::FlagNSW) ==
SCEV::FlagNSW);
// The getStrengthenedNoWrapFlagsFromBinOp() check inferred additional nowrap
// flags on addrecs while performing zero/sign extensions. We could call
// forgetValue() here to make sure those flags also propagate to any other
// SCEV expressions based on the addrec. However, this can have pathological
// compile-time impact, see https://bugs.llvm.org/show_bug.cgi?id=50384.
return Deduced;
}
/// Annotate the Shr in (X << IVOperand) >> C as exact using the
/// information from the IV's range. Returns true if anything changed, false
/// otherwise.
bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
Value *IVOperand) {
using namespace llvm::PatternMatch;
if (BO->getOpcode() == Instruction::Shl) {
bool Changed = false;
ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
for (auto *U : BO->users()) {
const APInt *C;
if (match(U,
m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
match(U,
m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
BinaryOperator *Shr = cast<BinaryOperator>(U);
if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
Shr->setIsExact(true);
Changed = true;
}
}
}
return Changed;
}
return false;
}
/// Add all uses of Def to the current IV's worklist.
static void pushIVUsers(
Instruction *Def, Loop *L,
SmallPtrSet<Instruction*,16> &Simplified,
SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
for (User *U : Def->users()) {
Instruction *UI = cast<Instruction>(U);
// Avoid infinite or exponential worklist processing.
// Also ensure unique worklist users.
// If Def is a LoopPhi, it may not be in the Simplified set, so check for
// self edges first.
if (UI == Def)
continue;
// Only change the current Loop, do not change the other parts (e.g. other
// Loops).
if (!L->contains(UI))
continue;
// Do not push the same instruction more than once.
if (!Simplified.insert(UI).second)
continue;
SimpleIVUsers.push_back(std::make_pair(UI, Def));
}
}
/// Return true if this instruction generates a simple SCEV
/// expression in terms of that IV.
///
/// This is similar to IVUsers' isInteresting() but processes each instruction
/// non-recursively when the operand is already known to be a simpleIVUser.
///
static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
if (!SE->isSCEVable(I->getType()))
return false;
// Get the symbolic expression for this instruction.
const SCEV *S = SE->getSCEV(I);
// Only consider affine recurrences.
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
if (AR && AR->getLoop() == L)
return true;
return false;
}
/// Iteratively perform simplification on a worklist of users
/// of the specified induction variable. Each successive simplification may push
/// more users which may themselves be candidates for simplification.
///
/// This algorithm does not require IVUsers analysis. Instead, it simplifies
/// instructions in-place during analysis. Rather than rewriting induction
/// variables bottom-up from their users, it transforms a chain of IVUsers
/// top-down, updating the IR only when it encounters a clear optimization
/// opportunity.
///
/// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
///
void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
if (!SE->isSCEVable(CurrIV->getType()))
return;
// Instructions processed by SimplifyIndvar for CurrIV.
SmallPtrSet<Instruction*,16> Simplified;
// Use-def pairs if IV users waiting to be processed for CurrIV.
SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
// Push users of the current LoopPhi. In rare cases, pushIVUsers may be
// called multiple times for the same LoopPhi. This is the proper thing to
// do for loop header phis that use each other.
pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
while (!SimpleIVUsers.empty()) {
std::pair<Instruction*, Instruction*> UseOper =
SimpleIVUsers.pop_back_val();
Instruction *UseInst = UseOper.first;
// If a user of the IndVar is trivially dead, we prefer just to mark it dead
// rather than try to do some complex analysis or transformation (such as
// widening) basing on it.
// TODO: Propagate TLI and pass it here to handle more cases.
if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
DeadInsts.emplace_back(UseInst);
continue;
}
// Bypass back edges to avoid extra work.
if (UseInst == CurrIV) continue;
// Try to replace UseInst with a loop invariant before any other
// simplifications.
if (replaceIVUserWithLoopInvariant(UseInst))
continue;
Instruction *IVOperand = UseOper.second;
for (unsigned N = 0; IVOperand; ++N) {
assert(N <= Simplified.size() && "runaway iteration");
Value *NewOper = foldIVUser(UseInst, IVOperand);
if (!NewOper)
break; // done folding
IVOperand = dyn_cast<Instruction>(NewOper);
}
if (!IVOperand)
continue;
if (eliminateIVUser(UseInst, IVOperand)) {
pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
continue;
}
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
if ((isa<OverflowingBinaryOperator>(BO) &&
strengthenOverflowingOperation(BO, IVOperand)) ||
(isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
// re-queue uses of the now modified binary operator and fall
// through to the checks that remain.
pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
}
}
CastInst *Cast = dyn_cast<CastInst>(UseInst);
if (V && Cast) {
V->visitCast(Cast);
continue;
}
if (isSimpleIVUser(UseInst, L, SE)) {
pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
}
}
}
namespace llvm {
void IVVisitor::anchor() { }
/// Simplify instructions that use this induction variable
/// by using ScalarEvolution to analyze the IV's recurrence.
bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
LoopInfo *LI, const TargetTransformInfo *TTI,
SmallVectorImpl<WeakTrackingVH> &Dead,
SCEVExpander &Rewriter, IVVisitor *V) {
SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI,
Rewriter, Dead);
SIV.simplifyUsers(CurrIV, V);
return SIV.hasChanged();
}
/// Simplify users of induction variables within this
/// loop. This does not actually change or add IVs.
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
LoopInfo *LI, const TargetTransformInfo *TTI,
SmallVectorImpl<WeakTrackingVH> &Dead) {
SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
#ifndef NDEBUG
Rewriter.setDebugType(DEBUG_TYPE);
#endif
bool Changed = false;
for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
Changed |=
simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter);
}
return Changed;
}
} // namespace llvm
//===----------------------------------------------------------------------===//
// Widen Induction Variables - Extend the width of an IV to cover its
// widest uses.
//===----------------------------------------------------------------------===//
class WidenIV {
// Parameters
PHINode *OrigPhi;
Type *WideType;
// Context
LoopInfo *LI;
Loop *L;
ScalarEvolution *SE;
DominatorTree *DT;
// Does the module have any calls to the llvm.experimental.guard intrinsic
// at all? If not we can avoid scanning instructions looking for guards.
bool HasGuards;
bool UsePostIncrementRanges;
// Statistics
unsigned NumElimExt = 0;
unsigned NumWidened = 0;
// Result
PHINode *WidePhi = nullptr;
Instruction *WideInc = nullptr;
const SCEV *WideIncExpr = nullptr;
SmallVectorImpl<WeakTrackingVH> &DeadInsts;
SmallPtrSet<Instruction *,16> Widened;
enum ExtendKind { ZeroExtended, SignExtended, Unknown };
// A map tracking the kind of extension used to widen each narrow IV
// and narrow IV user.
// Key: pointer to a narrow IV or IV user.
// Value: the kind of extension used to widen this Instruction.
DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
// A map with control-dependent ranges for post increment IV uses. The key is
// a pair of IV def and a use of this def denoting the context. The value is
// a ConstantRange representing possible values of the def at the given
// context.
DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
Optional<ConstantRange> getPostIncRangeInfo(Value *Def,
Instruction *UseI) {
DefUserPair Key(Def, UseI);
auto It = PostIncRangeInfos.find(Key);
return It == PostIncRangeInfos.end()
? Optional<ConstantRange>(None)
: Optional<ConstantRange>(It->second);
}
void calculatePostIncRanges(PHINode *OrigPhi);
void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
DefUserPair Key(Def, UseI);
auto It = PostIncRangeInfos.find(Key);
if (It == PostIncRangeInfos.end())
PostIncRangeInfos.insert({Key, R});
else
It->second = R.intersectWith(It->second);
}
public:
/// Record a link in the Narrow IV def-use chain along with the WideIV that
/// computes the same value as the Narrow IV def. This avoids caching Use*
/// pointers.
struct NarrowIVDefUse {
Instruction *NarrowDef = nullptr;
Instruction *NarrowUse = nullptr;
Instruction *WideDef = nullptr;
// True if the narrow def is never negative. Tracking this information lets
// us use a sign extension instead of a zero extension or vice versa, when
// profitable and legal.
bool NeverNegative = false;
NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
bool NeverNegative)
: NarrowDef(ND), NarrowUse(NU), WideDef(WD),
NeverNegative(NeverNegative) {}
};
WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
bool HasGuards, bool UsePostIncrementRanges = true);
PHINode *createWideIV(SCEVExpander &Rewriter);
unsigned getNumElimExt() { return NumElimExt; };
unsigned getNumWidened() { return NumWidened; };
protected:
Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
Instruction *Use);
Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
const SCEVAddRecExpr *WideAR);
Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
ExtendKind getExtendKind(Instruction *I);
using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
unsigned OpCode) const;
Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
bool widenLoopCompare(NarrowIVDefUse DU);
bool widenWithVariantUse(NarrowIVDefUse DU);
void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
private:
SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
};
/// Determine the insertion point for this user. By default, insert immediately
/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
/// common dominator for the incoming blocks. A nullptr can be returned if no
/// viable location is found: it may happen if User is a PHI and Def only comes
/// to this PHI from unreachable blocks.
static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
DominatorTree *DT, LoopInfo *LI) {
PHINode *PHI = dyn_cast<PHINode>(User);
if (!PHI)
return User;
Instruction *InsertPt = nullptr;
for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
if (PHI->getIncomingValue(i) != Def)
continue;
BasicBlock *InsertBB = PHI->getIncomingBlock(i);
if (!DT->isReachableFromEntry(InsertBB))
continue;
if (!InsertPt) {
InsertPt = InsertBB->getTerminator();
continue;
}
InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
InsertPt = InsertBB->getTerminator();
}
// If we have skipped all inputs, it means that Def only comes to Phi from
// unreachable blocks.
if (!InsertPt)
return nullptr;
auto *DefI = dyn_cast<Instruction>(Def);
if (!DefI)
return InsertPt;
assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
auto *L = LI->getLoopFor(DefI->getParent());
assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
if (LI->getLoopFor(DTN->getBlock()) == L)
return DTN->getBlock()->getTerminator();
llvm_unreachable("DefI dominates InsertPt!");
}
WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
bool HasGuards, bool UsePostIncrementRanges)
: OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges),
DeadInsts(DI) {
assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
}
Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
bool IsSigned, Instruction *Use) {
// Set the debug location and conservative insertion point.
IRBuilder<> Builder(Use);
// Hoist the insertion point into loop preheaders as far as possible.
for (const Loop *L = LI->getLoopFor(Use->getParent());
L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper);
L = L->getParentLoop())
Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
Builder.CreateZExt(NarrowOper, WideType);
}
/// Instantiate a wide operation to replace a narrow operation. This only needs
/// to handle operations that can evaluation to SCEVAddRec. It can safely return
/// 0 for any operation we decide not to clone.
Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU,
const SCEVAddRecExpr *WideAR) {
unsigned Opcode = DU.NarrowUse->getOpcode();
switch (Opcode) {
default:
return nullptr;
case Instruction::Add:
case Instruction::Mul:
case Instruction::UDiv:
case Instruction::Sub:
return cloneArithmeticIVUser(DU, WideAR);
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
return cloneBitwiseIVUser(DU);
}
}
Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) {
Instruction *NarrowUse = DU.NarrowUse;
Instruction *NarrowDef = DU.NarrowDef;
Instruction *WideDef = DU.WideDef;
LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
// Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
// about the narrow operand yet so must insert a [sz]ext. It is probably loop
// invariant and will be folded or hoisted. If it actually comes from a
// widened IV, it should be removed during a future call to widenIVUse.
bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
? WideDef
: createExtendInst(NarrowUse->getOperand(0), WideType,
IsSigned, NarrowUse);
Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
? WideDef
: createExtendInst(NarrowUse->getOperand(1), WideType,
IsSigned, NarrowUse);
auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
NarrowBO->getName());
IRBuilder<> Builder(NarrowUse);
Builder.Insert(WideBO);
WideBO->copyIRFlags(NarrowBO);
return WideBO;
}
Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,
const SCEVAddRecExpr *WideAR) {
Instruction *NarrowUse = DU.NarrowUse;
Instruction *NarrowDef = DU.NarrowDef;
Instruction *WideDef = DU.WideDef;
LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
// We're trying to find X such that
//
// Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
//
// We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
// and check using SCEV if any of them are correct.
// Returns true if extending NonIVNarrowDef according to `SignExt` is a
// correct solution to X.
auto GuessNonIVOperand = [&](bool SignExt) {
const SCEV *WideLHS;
const SCEV *WideRHS;
auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
if (SignExt)
return SE->getSignExtendExpr(S, Ty);
return SE->getZeroExtendExpr(S, Ty);
};
if (IVOpIdx == 0) {
WideLHS = SE->getSCEV(WideDef);
const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
WideRHS = GetExtend(NarrowRHS, WideType);
} else {
const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
WideLHS = GetExtend(NarrowLHS, WideType);
WideRHS = SE->getSCEV(WideDef);
}
// WideUse is "WideDef `op.wide` X" as described in the comment.
const SCEV *WideUse =
getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode());
return WideUse == WideAR;
};
bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
if (!GuessNonIVOperand(SignExtend)) {
SignExtend = !SignExtend;
if (!GuessNonIVOperand(SignExtend))
return nullptr;
}
Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
? WideDef
: createExtendInst(NarrowUse->getOperand(0), WideType,
SignExtend, NarrowUse);
Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
? WideDef
: createExtendInst(NarrowUse->getOperand(1), WideType,
SignExtend, NarrowUse);
auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
NarrowBO->getName());
IRBuilder<> Builder(NarrowUse);
Builder.Insert(WideBO);
WideBO->copyIRFlags(NarrowBO);
return WideBO;
}
WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
auto It = ExtendKindMap.find(I);
assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
return It->second;
}
const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
unsigned OpCode) const {
switch (OpCode) {
case Instruction::Add:
return SE->getAddExpr(LHS, RHS);
case Instruction::Sub:
return SE->getMinusSCEV(LHS, RHS);
case Instruction::Mul:
return SE->getMulExpr(LHS, RHS);
case Instruction::UDiv:
return SE->getUDivExpr(LHS, RHS);
default:
llvm_unreachable("Unsupported opcode.");
};
}
/// No-wrap operations can transfer sign extension of their result to their
/// operands. Generate the SCEV value for the widened operation without
/// actually modifying the IR yet. If the expression after extending the
/// operands is an AddRec for this loop, return the AddRec and the kind of
/// extension used.
WidenIV::WidenedRecTy
WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) {
// Handle the common case of add<nsw/nuw>
const unsigned OpCode = DU.NarrowUse->getOpcode();
// Only Add/Sub/Mul instructions supported yet.
if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
OpCode != Instruction::Mul)
return {nullptr, Unknown};
// One operand (NarrowDef) has already been extended to WideDef. Now determine
// if extending the other will lead to a recurrence.
const unsigned ExtendOperIdx =
DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
const SCEV *ExtendOperExpr = nullptr;
const OverflowingBinaryOperator *OBO =
cast<OverflowingBinaryOperator>(DU.NarrowUse);
ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
ExtendOperExpr = SE->getSignExtendExpr(
SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
ExtendOperExpr = SE->getZeroExtendExpr(
SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
else
return {nullptr, Unknown};
// When creating this SCEV expr, don't apply the current operations NSW or NUW
// flags. This instruction may be guarded by control flow that the no-wrap
// behavior depends on. Non-control-equivalent instructions can be mapped to
// the same SCEV expression, and it would be incorrect to transfer NSW/NUW
// semantics to those operations.
const SCEV *lhs = SE->getSCEV(DU.WideDef);
const SCEV *rhs = ExtendOperExpr;
// Let's swap operands to the initial order for the case of non-commutative
// operations, like SUB. See PR21014.
if (ExtendOperIdx == 0)
std::swap(lhs, rhs);
const SCEVAddRecExpr *AddRec =
dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
if (!AddRec || AddRec->getLoop() != L)
return {nullptr, Unknown};
return {AddRec, ExtKind};
}
/// Is this instruction potentially interesting for further simplification after
/// widening it's type? In other words, can the extend be safely hoisted out of
/// the loop with SCEV reducing the value to a recurrence on the same loop. If
/// so, return the extended recurrence and the kind of extension used. Otherwise
/// return {nullptr, Unknown}.
WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) {
if (!SE->isSCEVable(DU.NarrowUse->getType()))
return {nullptr, Unknown};
const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
SE->getTypeSizeInBits(WideType)) {
// NarrowUse implicitly widens its operand. e.g. a gep with a narrow
// index. So don't follow this use.
return {nullptr, Unknown};
}
const SCEV *WideExpr;
ExtendKind ExtKind;
if (DU.NeverNegative) {
WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
if (isa<SCEVAddRecExpr>(WideExpr))
ExtKind = SignExtended;
else {
WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
ExtKind = ZeroExtended;
}
} else if (getExtendKind(DU.NarrowDef) == SignExtended) {
WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
ExtKind = SignExtended;
} else {
WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
ExtKind = ZeroExtended;
}
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
if (!AddRec || AddRec->getLoop() != L)
return {nullptr, Unknown};
return {AddRec, ExtKind};
}
/// This IV user cannot be widened. Replace this use of the original narrow IV
/// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
static void truncateIVUse(WidenIV::NarrowIVDefUse DU, DominatorTree *DT,
LoopInfo *LI) {
auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
if (!InsertPt)
return;
LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
<< *DU.NarrowUse << "\n");
IRBuilder<> Builder(InsertPt);
Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
}
/// If the narrow use is a compare instruction, then widen the compare
// (and possibly the other operand). The extend operation is hoisted into the
// loop preheader as far as possible.
bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) {
ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
if (!Cmp)
return false;
// We can legally widen the comparison in the following two cases:
//
// - The signedness of the IV extension and comparison match
//
// - The narrow IV is always positive (and thus its sign extension is equal
// to its zero extension). For instance, let's say we're zero extending
// %narrow for the following use
//
// icmp slt i32 %narrow, %val ... (A)
//
// and %narrow is always positive. Then
//
// (A) == icmp slt i32 sext(%narrow), sext(%val)
// == icmp slt i32 zext(%narrow), sext(%val)
bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
return false;
Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
unsigned IVWidth = SE->getTypeSizeInBits(WideType);
assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
// Widen the compare instruction.
auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
if (!InsertPt)
return false;
IRBuilder<> Builder(InsertPt);
DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
// Widen the other operand of the compare, if necessary.
if (CastWidth < IVWidth) {
Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
}
return true;
}
// The widenIVUse avoids generating trunc by evaluating the use as AddRec, this
// will not work when:
// 1) SCEV traces back to an instruction inside the loop that SCEV can not
// expand, eg. add %indvar, (load %addr)
// 2) SCEV finds a loop variant, eg. add %indvar, %loopvariant
// While SCEV fails to avoid trunc, we can still try to use instruction
// combining approach to prove trunc is not required. This can be further
// extended with other instruction combining checks, but for now we handle the
// following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext")
//
// Src:
// %c = sub nsw %b, %indvar
// %d = sext %c to i64
// Dst:
// %indvar.ext1 = sext %indvar to i64
// %m = sext %b to i64
// %d = sub nsw i64 %m, %indvar.ext1
// Therefore, as long as the result of add/sub/mul is extended to wide type, no
// trunc is required regardless of how %b is generated. This pattern is common
// when calculating address in 64 bit architecture
bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) {
Instruction *NarrowUse = DU.NarrowUse;
Instruction *NarrowDef = DU.NarrowDef;
Instruction *WideDef = DU.WideDef;
// Handle the common case of add<nsw/nuw>
const unsigned OpCode = NarrowUse->getOpcode();
// Only Add/Sub/Mul instructions are supported.
if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
OpCode != Instruction::Mul)
return false;
// The operand that is not defined by NarrowDef of DU. Let's call it the
// other operand.
assert((NarrowUse->getOperand(0) == NarrowDef ||
NarrowUse->getOperand(1) == NarrowDef) &&
"bad DU");
const OverflowingBinaryOperator *OBO =
cast<OverflowingBinaryOperator>(NarrowUse);
ExtendKind ExtKind = getExtendKind(NarrowDef);
bool CanSignExtend = ExtKind == SignExtended && OBO->hasNoSignedWrap();
bool CanZeroExtend = ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap();
auto AnotherOpExtKind = ExtKind;
// Check that all uses are either:
// - narrow def (in case of we are widening the IV increment);
// - single-input LCSSA Phis;
// - comparison of the chosen type;
// - extend of the chosen type (raison d'etre).
SmallVector<Instruction *, 4> ExtUsers;
SmallVector<PHINode *, 4> LCSSAPhiUsers;
SmallVector<ICmpInst *, 4> ICmpUsers;
for (Use &U : NarrowUse->uses()) {
Instruction *User = cast<Instruction>(U.getUser());
if (User == NarrowDef)
continue;
if (!L->contains(User)) {
auto *LCSSAPhi = cast<PHINode>(User);
// Make sure there is only 1 input, so that we don't have to split
// critical edges.
if (LCSSAPhi->getNumOperands() != 1)
return false;
LCSSAPhiUsers.push_back(LCSSAPhi);
continue;
}
if (auto *ICmp = dyn_cast<ICmpInst>(User)) {
auto Pred = ICmp->getPredicate();
// We have 3 types of predicates: signed, unsigned and equality
// predicates. For equality, it's legal to widen icmp for either sign and
// zero extend. For sign extend, we can also do so for signed predicates,
// likeweise for zero extend we can widen icmp for unsigned predicates.
if (ExtKind == ZeroExtended && ICmpInst::isSigned(Pred))
return false;
if (ExtKind == SignExtended && ICmpInst::isUnsigned(Pred))
return false;
ICmpUsers.push_back(ICmp);
continue;
}
if (ExtKind == SignExtended)
User = dyn_cast<SExtInst>(User);
else
User = dyn_cast<ZExtInst>(User);
if (!User || User->getType() != WideType)
return false;
ExtUsers.push_back(User);
}
if (ExtUsers.empty()) {
DeadInsts.emplace_back(NarrowUse);
return true;
}
// We'll prove some facts that should be true in the context of ext users. If
// there is no users, we are done now. If there are some, pick their common
// dominator as context.
const Instruction *CtxI = findCommonDominator(ExtUsers, *DT);
if (!CanSignExtend && !CanZeroExtend) {
// Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we
// will most likely not see it. Let's try to prove it.
if (OpCode != Instruction::Add)
return false;
if (ExtKind != ZeroExtended)
return false;
const SCEV *LHS = SE->getSCEV(OBO->getOperand(0));
const SCEV *RHS = SE->getSCEV(OBO->getOperand(1));
// TODO: Support case for NarrowDef = NarrowUse->getOperand(1).
if (NarrowUse->getOperand(0) != NarrowDef)
return false;
if (!SE->isKnownNegative(RHS))
return false;
bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS,
SE->getNegativeSCEV(RHS), CtxI);
if (!ProvedSubNUW)
return false;
// In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as
// neg(zext(neg(op))), which is basically sext(op).
AnotherOpExtKind = SignExtended;
}
// Verifying that Defining operand is an AddRec
const SCEV *Op1 = SE->getSCEV(WideDef);
const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
if (!AddRecOp1 || AddRecOp1->getLoop() != L)
return false;
LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
// Generating a widening use instruction.
Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
? WideDef
: createExtendInst(NarrowUse->getOperand(0), WideType,
AnotherOpExtKind, NarrowUse);
Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
? WideDef
: createExtendInst(NarrowUse->getOperand(1), WideType,
AnotherOpExtKind, NarrowUse);
auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
NarrowBO->getName());
IRBuilder<> Builder(NarrowUse);
Builder.Insert(WideBO);
WideBO->copyIRFlags(NarrowBO);
ExtendKindMap[NarrowUse] = ExtKind;
for (Instruction *User : ExtUsers) {
assert(User->getType() == WideType && "Checked before!");
LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
<< *WideBO << "\n");
++NumElimExt;
User->replaceAllUsesWith(WideBO);
DeadInsts.emplace_back(User);
}
for (PHINode *User : LCSSAPhiUsers) {
assert(User->getNumOperands() == 1 && "Checked before!");
Builder.SetInsertPoint(User);
auto *WidePN =
Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide");
BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor();
assert(LoopExitingBlock && L->contains(LoopExitingBlock) &&
"Not a LCSSA Phi?");
WidePN->addIncoming(WideBO, LoopExitingBlock);
Builder.SetInsertPoint(&*User->getParent()->getFirstInsertionPt());
auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType());
User->replaceAllUsesWith(TruncPN);
DeadInsts.emplace_back(User);
}
for (ICmpInst *User : ICmpUsers) {
Builder.SetInsertPoint(User);
auto ExtendedOp = [&](Value * V)->Value * {
if (V == NarrowUse)
return WideBO;
if (ExtKind == ZeroExtended)
return Builder.CreateZExt(V, WideBO->getType());
else
return Builder.CreateSExt(V, WideBO->getType());
};
auto Pred = User->getPredicate();
auto *LHS = ExtendedOp(User->getOperand(0));
auto *RHS = ExtendedOp(User->getOperand(1));
auto *WideCmp =
Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide");
User->replaceAllUsesWith(WideCmp);
DeadInsts.emplace_back(User);
}
return true;
}
/// Determine whether an individual user of the narrow IV can be widened. If so,
/// return the wide clone of the user.
Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU, SCEVExpander &Rewriter) {
assert(ExtendKindMap.count(DU.NarrowDef) &&
"Should already know the kind of extension used to widen NarrowDef");
// Stop traversing the def-use chain at inner-loop phis or post-loop phis.
if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
if (LI->getLoopFor(UsePhi->getParent()) != L) {
// For LCSSA phis, sink the truncate outside the loop.
// After SimplifyCFG most loop exit targets have a single predecessor.
// Otherwise fall back to a truncate within the loop.
if (UsePhi->getNumOperands() != 1)
truncateIVUse(DU, DT, LI);
else {
// Widening the PHI requires us to insert a trunc. The logical place
// for this trunc is in the same BB as the PHI. This is not possible if
// the BB is terminated by a catchswitch.
if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
return nullptr;
PHINode *WidePhi =
PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
UsePhi);
WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
UsePhi->replaceAllUsesWith(Trunc);
DeadInsts.emplace_back(UsePhi);
LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
<< *WidePhi << "\n");
}
return nullptr;
}
}
// This narrow use can be widened by a sext if it's non-negative or its narrow
// def was widended by a sext. Same for zext.
auto canWidenBySExt = [&]() {
return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
};
auto canWidenByZExt = [&]() {
return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
};
// Our raison d'etre! Eliminate sign and zero extension.
if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
(isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
Value *NewDef = DU.WideDef;
if (DU.NarrowUse->getType() != WideType) {
unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
unsigned IVWidth = SE->getTypeSizeInBits(WideType);
if (CastWidth < IVWidth) {
// The cast isn't as wide as the IV, so insert a Trunc.
IRBuilder<> Builder(DU.NarrowUse);
NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
}
else {
// A wider extend was hidden behind a narrower one. This may induce
// another round of IV widening in which the intermediate IV becomes
// dead. It should be very rare.
LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
<< " not wide enough to subsume " << *DU.NarrowUse
<< "\n");
DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
NewDef = DU.NarrowUse;
}
}
if (NewDef != DU.NarrowUse) {
LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
<< " replaced by " << *DU.WideDef << "\n");
++NumElimExt;
DU.NarrowUse->replaceAllUsesWith(NewDef);
DeadInsts.emplace_back(DU.NarrowUse);
}
// Now that the extend is gone, we want to expose it's uses for potential
// further simplification. We don't need to directly inform SimplifyIVUsers
// of the new users, because their parent IV will be processed later as a
// new loop phi. If we preserved IVUsers analysis, we would also want to
// push the uses of WideDef here.
// No further widening is needed. The deceased [sz]ext had done it for us.
return nullptr;
}
// Does this user itself evaluate to a recurrence after widening?
WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
if (!WideAddRec.first)
WideAddRec = getWideRecurrence(DU);
assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown));
if (!WideAddRec.first) {
// If use is a loop condition, try to promote the condition instead of
// truncating the IV first.
if (widenLoopCompare(DU))
return nullptr;
// We are here about to generate a truncate instruction that may hurt
// performance because the scalar evolution expression computed earlier
// in WideAddRec.first does not indicate a polynomial induction expression.
// In that case, look at the operands of the use instruction to determine
// if we can still widen the use instead of truncating its operand.
if (widenWithVariantUse(DU))
return nullptr;
// This user does not evaluate to a recurrence after widening, so don't
// follow it. Instead insert a Trunc to kill off the original use,
// eventually isolating the original narrow IV so it can be removed.
truncateIVUse(DU, DT, LI);
return nullptr;
}
// Assume block terminators cannot evaluate to a recurrence. We can't to
// insert a Trunc after a terminator if there happens to be a critical edge.
assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
"SCEV is not expected to evaluate a block terminator");
// Reuse the IV increment that SCEVExpander created as long as it dominates
// NarrowUse.
Instruction *WideUse = nullptr;
if (WideAddRec.first == WideIncExpr &&
Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
WideUse = WideInc;
else {
WideUse = cloneIVUser(DU, WideAddRec.first);
if (!WideUse)
return nullptr;
}
// Evaluation of WideAddRec ensured that the narrow expression could be
// extended outside the loop without overflow. This suggests that the wide use
// evaluates to the same expression as the extended narrow use, but doesn't
// absolutely guarantee it. Hence the following failsafe check. In rare cases
// where it fails, we simply throw away the newly created wide use.
if (WideAddRec.first != SE->getSCEV(WideUse)) {
LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
<< *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
<< "\n");
DeadInsts.emplace_back(WideUse);
return nullptr;
}
// if we reached this point then we are going to replace
// DU.NarrowUse with WideUse. Reattach DbgValue then.
replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT);
ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
// Returning WideUse pushes it on the worklist.
return WideUse;
}
/// Add eligible users of NarrowDef to NarrowIVUsers.
void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
bool NonNegativeDef =
SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
SE->getZero(NarrowSCEV->getType()));
for (User *U : NarrowDef->users()) {
Instruction *NarrowUser = cast<Instruction>(U);
// Handle data flow merges and bizarre phi cycles.
if (!Widened.insert(NarrowUser).second)
continue;
bool NonNegativeUse = false;
if (!NonNegativeDef) {
// We might have a control-dependent range information for this context.
if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
}
NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
NonNegativeDef || NonNegativeUse);
}
}
/// Process a single induction variable. First use the SCEVExpander to create a
/// wide induction variable that evaluates to the same recurrence as the
/// original narrow IV. Then use a worklist to forward traverse the narrow IV's
/// def-use chain. After widenIVUse has processed all interesting IV users, the
/// narrow IV will be isolated for removal by DeleteDeadPHIs.
///
/// It would be simpler to delete uses as they are processed, but we must avoid
/// invalidating SCEV expressions.
PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
// Is this phi an induction variable?
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
if (!AddRec)
return nullptr;
// Widen the induction variable expression.
const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
? SE->getSignExtendExpr(AddRec, WideType)
: SE->getZeroExtendExpr(AddRec, WideType);
assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
"Expect the new IV expression to preserve its type");
// Can the IV be extended outside the loop without overflow?
AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
if (!AddRec || AddRec->getLoop() != L)
return nullptr;
// An AddRec must have loop-invariant operands. Since this AddRec is
// materialized by a loop header phi, the expression cannot have any post-loop
// operands, so they must dominate the loop header.
assert(
SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
"Loop header phi recurrence inputs do not dominate the loop");
// Iterate over IV uses (including transitive ones) looking for IV increments
// of the form 'add nsw %iv, <const>'. For each increment and each use of
// the increment calculate control-dependent range information basing on
// dominating conditions inside of the loop (e.g. a range check inside of the
// loop). Calculated ranges are stored in PostIncRangeInfos map.
//
// Control-dependent range information is later used to prove that a narrow
// definition is not negative (see pushNarrowIVUsers). It's difficult to do
// this on demand because when pushNarrowIVUsers needs this information some
// of the dominating conditions might be already widened.
if (UsePostIncrementRanges)
calculatePostIncRanges(OrigPhi);
// The rewriter provides a value for the desired IV expression. This may
// either find an existing phi or materialize a new one. Either way, we
// expect a well-formed cyclic phi-with-increments. i.e. any operand not part
// of the phi-SCC dominates the loop entry.
Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt();
Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
// If the wide phi is not a phi node, for example a cast node, like bitcast,
// inttoptr, ptrtoint, just skip for now.
if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) {
// if the cast node is an inserted instruction without any user, we should
// remove it to make sure the pass don't touch the function as we can not
// wide the phi.
if (ExpandInst->hasNUses(0) &&
Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst)))
DeadInsts.emplace_back(ExpandInst);
return nullptr;
}
// Remembering the WideIV increment generated by SCEVExpander allows
// widenIVUse to reuse it when widening the narrow IV's increment. We don't
// employ a general reuse mechanism because the call above is the only call to
// SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
if (BasicBlock *LatchBlock = L->getLoopLatch()) {
WideInc =
cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
WideIncExpr = SE->getSCEV(WideInc);
// Propagate the debug location associated with the original loop increment
// to the new (widened) increment.
auto *OrigInc =
cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
WideInc->setDebugLoc(OrigInc->getDebugLoc());
}
LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
++NumWidened;
// Traverse the def-use chain using a worklist starting at the original IV.
assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
Widened.insert(OrigPhi);
pushNarrowIVUsers(OrigPhi, WidePhi);
while (!NarrowIVUsers.empty()) {
WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
// Process a def-use edge. This may replace the use, so don't hold a
// use_iterator across it.
Instruction *WideUse = widenIVUse(DU, Rewriter);
// Follow all def-use edges from the previous narrow use.
if (WideUse)
pushNarrowIVUsers(DU.NarrowUse, WideUse);
// widenIVUse may have removed the def-use edge.
if (DU.NarrowDef->use_empty())
DeadInsts.emplace_back(DU.NarrowDef);
}
// Attach any debug information to the new PHI.
replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT);
return WidePhi;
}
/// Calculates control-dependent range for the given def at the given context
/// by looking at dominating conditions inside of the loop
void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
Instruction *NarrowUser) {
using namespace llvm::PatternMatch;
Value *NarrowDefLHS;
const APInt *NarrowDefRHS;
if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
m_APInt(NarrowDefRHS))) ||
!NarrowDefRHS->isNonNegative())
return;
auto UpdateRangeFromCondition = [&] (Value *Condition,
bool TrueDest) {
CmpInst::Predicate Pred;
Value *CmpRHS;
if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
m_Value(CmpRHS))))
return;
CmpInst::Predicate P =
TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
auto CmpConstrainedLHSRange =
ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
*NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap);
updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
};
auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
if (!HasGuards)
return;
for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
Ctx->getParent()->rend())) {
Value *C = nullptr;
if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
UpdateRangeFromCondition(C, /*TrueDest=*/true);
}
};
UpdateRangeFromGuards(NarrowUser);
BasicBlock *NarrowUserBB = NarrowUser->getParent();
// If NarrowUserBB is statically unreachable asking dominator queries may
// yield surprising results. (e.g. the block may not have a dom tree node)
if (!DT->isReachableFromEntry(NarrowUserBB))
return;
for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
L->contains(DTB->getBlock());
DTB = DTB->getIDom()) {
auto *BB = DTB->getBlock();
auto *TI = BB->getTerminator();
UpdateRangeFromGuards(TI);
auto *BI = dyn_cast<BranchInst>(TI);
if (!BI || !BI->isConditional())
continue;
auto *TrueSuccessor = BI->getSuccessor(0);
auto *FalseSuccessor = BI->getSuccessor(1);
auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
return BBE.isSingleEdge() &&
DT->dominates(BBE, NarrowUser->getParent());
};
if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
}
}
/// Calculates PostIncRangeInfos map for the given IV
void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
SmallPtrSet<Instruction *, 16> Visited;
SmallVector<Instruction *, 6> Worklist;
Worklist.push_back(OrigPhi);
Visited.insert(OrigPhi);
while (!Worklist.empty()) {
Instruction *NarrowDef = Worklist.pop_back_val();
for (Use &U : NarrowDef->uses()) {
auto *NarrowUser = cast<Instruction>(U.getUser());
// Don't go looking outside the current loop.
auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
continue;
if (!Visited.insert(NarrowUser).second)
continue;
Worklist.push_back(NarrowUser);
calculatePostIncRange(NarrowDef, NarrowUser);
}
}
}
PHINode *llvm::createWideIV(const WideIVInfo &WI,
LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter,
DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts,
unsigned &NumElimExt, unsigned &NumWidened,
bool HasGuards, bool UsePostIncrementRanges) {
WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
PHINode *WidePHI = Widener.createWideIV(Rewriter);
NumElimExt = Widener.getNumElimExt();
NumWidened = Widener.getNumWidened();
return WidePHI;
}
|
#include "rejit_preprocessor.h"
#include "stats.h"
#include "logger.h"
#include "debugger_members.h"
namespace trace
{
// RejitPreprocessor
template <class RejitRequestDefinition>
RejitPreprocessor<RejitRequestDefinition>::RejitPreprocessor(std::shared_ptr<RejitHandler> rejit_handler,
std::shared_ptr<RejitWorkOffloader> work_offloader) :
m_rejit_handler(std::move(rejit_handler)), m_work_offloader(std::move(work_offloader))
{
}
template <class RejitRequestDefinition>
void RejitPreprocessor<RejitRequestDefinition>::ProcessTypeDefForRejit(const RejitRequestDefinition& definition,
ComPtr<IMetaDataImport2>& metadataImport,
ComPtr<IMetaDataEmit2>& metadataEmit,
ComPtr<IMetaDataAssemblyImport>& assemblyImport,
ComPtr<IMetaDataAssemblyEmit>& assemblyEmit, const ModuleInfo& moduleInfo,
const mdTypeDef typeDef, std::vector<ModuleID>& vtModules,
std::vector<mdMethodDef>& vtMethodDefs)
{
auto target_method = GetTargetMethod(definition);
Logger::Debug(" Looking for '", target_method.type.name, ".", target_method.method_name,
"(", (target_method.signature_types.size() - 1), " params)' method implementation.");
// Now we enumerate all methods with the same target method name. (All overloads of the method)
auto enumMethods = Enumerator<mdMethodDef>(
[&metadataImport, target_method, typeDef](HCORENUM* ptr, mdMethodDef arr[], ULONG max, ULONG* cnt) -> HRESULT {
return metadataImport->EnumMethodsWithName(ptr, typeDef, target_method.method_name.c_str(), arr,
max, cnt);
},
[&metadataImport](HCORENUM ptr) -> void { metadataImport->CloseEnum(ptr); });
auto corProfilerInfo = m_rejit_handler->GetCorProfilerInfo();
auto pCorAssemblyProperty = m_rejit_handler->GetCorAssemblyProperty();
auto enable_by_ref_instrumentation = m_rejit_handler->GetEnableByRefInstrumentation();
auto enable_calltarget_state_by_ref = m_rejit_handler->GetEnableCallTargetStateByRef();
auto enumIterator = enumMethods.begin();
for (; enumIterator != enumMethods.end(); enumIterator = ++enumIterator)
{
auto methodDef = *enumIterator;
// Extract the function info from the mdMethodDef
const auto caller = GetFunctionInfo(metadataImport, methodDef);
if (!caller.IsValid())
{
Logger::Warn(" * The caller for the methoddef: ", shared::TokenStr(&methodDef), " is not valid!");
continue;
}
// We create a new function info into the heap from the caller functionInfo in the stack, to
// be used later in the ReJIT process
auto functionInfo = FunctionInfo(caller);
auto hr = functionInfo.method_signature.TryParse();
if (FAILED(hr))
{
Logger::Warn(" * The method signature: ", functionInfo.method_signature.str(), " cannot be parsed.");
continue;
}
// Compare if the current mdMethodDef contains the same number of arguments as the
// instrumentation target
const auto numOfArgs = functionInfo.method_signature.NumberOfArguments();
if (numOfArgs != target_method.signature_types.size() - 1)
{
Logger::Debug(" * The caller for the methoddef: ", caller.name,
" doesn't have the right number of arguments (", numOfArgs, " arguments).");
continue;
}
// Compare each mdMethodDef argument type to the instrumentation target
bool argumentsMismatch = false;
const auto& methodArguments = functionInfo.method_signature.GetMethodArguments();
Logger::Debug(" * Comparing signature for method: ", caller.type.name, ".", caller.name);
for (unsigned int i = 0; i < numOfArgs; i++)
{
const auto argumentTypeName = methodArguments[i].GetTypeTokName(metadataImport);
const auto integrationArgumentTypeName = target_method.signature_types[i + 1];
Logger::Debug(" -> ", argumentTypeName, " = ", integrationArgumentTypeName);
if (argumentTypeName != integrationArgumentTypeName && integrationArgumentTypeName != WStr("_"))
{
argumentsMismatch = true;
break;
}
}
if (argumentsMismatch)
{
Logger::Debug(" * The caller for the methoddef: ", target_method.method_name,
" doesn't have the right type of arguments.");
continue;
}
// As we are in the right method, we gather all information we need and stored it in to the
// ReJIT handler.
auto moduleHandler = m_rejit_handler->GetOrAddModule(moduleInfo.id);
if (moduleHandler == nullptr)
{
Logger::Warn("Module handler is null, this only happens if the RejitHandler has been shutdown.");
break;
}
if (moduleHandler->GetModuleMetadata() == nullptr)
{
Logger::Debug("Creating ModuleMetadata...");
const auto moduleMetadata =
new ModuleMetadata(metadataImport, metadataEmit, assemblyImport, assemblyEmit, moduleInfo.assembly.name,
moduleInfo.assembly.app_domain_id, pCorAssemblyProperty,
enable_by_ref_instrumentation, enable_calltarget_state_by_ref);
Logger::Info("ReJIT handler stored metadata for ", moduleInfo.id, " ", moduleInfo.assembly.name,
" AppDomain ", moduleInfo.assembly.app_domain_id, " ", moduleInfo.assembly.app_domain_name);
moduleHandler->SetModuleMetadata(moduleMetadata);
}
RejitHandlerModuleMethodCreatorFunc creator = [=, request = definition, functionInfo = functionInfo](
const mdMethodDef method, RejitHandlerModule* module) {
return CreateMethod(method, module, functionInfo, request);
};
moduleHandler->CreateMethodIfNotExists(methodDef, creator);
// Store module_id and methodDef to request the ReJIT after analyzing all integrations.
vtModules.push_back(moduleInfo.id);
vtMethodDefs.push_back(methodDef);
Logger::Debug(" * Enqueue for ReJIT [ModuleId=", moduleInfo.id, ", MethodDef=", shared::TokenStr(&methodDef),
", AppDomainId=", moduleHandler->GetModuleMetadata()->app_domain_id,
", Assembly=", moduleHandler->GetModuleMetadata()->assemblyName, ", Type=", caller.type.name,
", Method=", caller.name, "(", numOfArgs, " params), Signature=", caller.signature.str(), "]");
}
}
template <class RejitRequestDefinition>
ULONG RejitPreprocessor<RejitRequestDefinition>::RequestRejitForLoadedModules(
const std::vector<ModuleID>& modules,
const std::vector<RejitRequestDefinition>& definitions,
bool enqueueInSameThread)
{
if (m_rejit_handler->IsShutdownRequested())
{
return 0;
}
auto corProfilerInfo = m_rejit_handler->GetCorProfilerInfo();
std::vector<ModuleID> vtModules;
std::vector<mdMethodDef> vtMethodDefs;
// Preallocate with size => 15 due this is the current max of method interceptions in a single module
// (see InstrumentationDefinitions.Generated.cs)
vtModules.reserve(15);
vtMethodDefs.reserve(15);
for (const auto& module : modules)
{
auto _ = trace::Stats::Instance()->CallTargetRequestRejitMeasure();
const ModuleInfo& moduleInfo = GetModuleInfo(corProfilerInfo, module);
Logger::Debug("Requesting Rejit for Module: ", moduleInfo.assembly.name);
ComPtr<IUnknown> metadataInterfaces;
ComPtr<IMetaDataImport2> metadataImport;
ComPtr<IMetaDataEmit2> metadataEmit;
ComPtr<IMetaDataAssemblyImport> assemblyImport;
ComPtr<IMetaDataAssemblyEmit> assemblyEmit;
std::unique_ptr<AssemblyMetadata> assemblyMetadata = nullptr;
for (const RejitRequestDefinition& definition : definitions)
{
const auto target_method = GetTargetMethod(definition);
const auto is_derived = GetIsDerived(definition);
if (is_derived)
{
// Abstract methods handling.
if (assemblyMetadata == nullptr)
{
Logger::Debug(" Loading Assembly Metadata...");
auto hr = corProfilerInfo->GetModuleMetaData(moduleInfo.id, ofRead | ofWrite, IID_IMetaDataImport2,
metadataInterfaces.GetAddressOf());
if (FAILED(hr))
{
Logger::Warn("CallTarget_RequestRejitForModule failed to get metadata interface for ",
moduleInfo.id, " ", moduleInfo.assembly.name);
break;
}
metadataImport = metadataInterfaces.As<IMetaDataImport2>(IID_IMetaDataImport);
metadataEmit = metadataInterfaces.As<IMetaDataEmit2>(IID_IMetaDataEmit);
assemblyImport = metadataInterfaces.As<IMetaDataAssemblyImport>(IID_IMetaDataAssemblyImport);
assemblyEmit = metadataInterfaces.As<IMetaDataAssemblyEmit>(IID_IMetaDataAssemblyEmit);
assemblyMetadata = std::make_unique<AssemblyMetadata>(GetAssemblyImportMetadata(assemblyImport));
Logger::Debug(" Assembly Metadata loaded for: ", assemblyMetadata->name, "(",
assemblyMetadata->version.str(), ").");
}
// If the integration is in a different assembly than the target method
if (assemblyMetadata->name != target_method.type.assembly.name)
{
// Check if the current module contains a reference to the assembly of the integration
auto assemblyRefEnum = EnumAssemblyRefs(assemblyImport);
auto assemblyRefIterator = assemblyRefEnum.begin();
bool assemblyRefFound = false;
for (; assemblyRefIterator != assemblyRefEnum.end(); assemblyRefIterator = ++assemblyRefIterator)
{
auto assemblyRef = *assemblyRefIterator;
const auto& assemblyRefMetadata = GetReferencedAssemblyMetadata(assemblyImport, assemblyRef);
if (assemblyRefMetadata.name == target_method.type.assembly.name &&
target_method.type.min_version <= assemblyRefMetadata.version &&
target_method.type.max_version >= assemblyRefMetadata.version)
{
assemblyRefFound = true;
break;
}
}
// If the assembly reference was not found we skip the integration
if (!assemblyRefFound)
{
continue;
}
}
// Enumerate the types of the module in search of types implementing the integration
auto typeDefEnum = EnumTypeDefs(metadataImport);
auto typeDefIterator = typeDefEnum.begin();
for (; typeDefIterator != typeDefEnum.end(); typeDefIterator = ++typeDefIterator)
{
auto typeDef = *typeDefIterator;
const auto typeInfo = GetTypeInfo(metadataImport, typeDef);
bool rewriteType = false;
auto ancestorTypeInfo = typeInfo.extend_from.get();
// Check if the type has ancestors
int maxDepth = 1;
while (ancestorTypeInfo != nullptr && maxDepth > 0)
{
// Validate the type name we already have
if (ancestorTypeInfo->name == target_method.type.name)
{
// Validate assembly data (scopeToken has the assemblyRef of the ancestor type)
if (ancestorTypeInfo->scopeToken != mdTokenNil)
{
const auto tokenType = TypeFromToken(ancestorTypeInfo->scopeToken);
if (tokenType == mdtAssemblyRef)
{
const auto& ancestorAssemblyMetadata =
GetReferencedAssemblyMetadata(assemblyImport, ancestorTypeInfo->scopeToken);
// We check the assembly name and version
if (ancestorAssemblyMetadata.name == target_method.type.assembly.name &&
target_method.type.min_version <=
ancestorAssemblyMetadata.version &&
target_method.type.max_version >= ancestorAssemblyMetadata.version)
{
rewriteType = true;
break;
}
}
else
{
Logger::Warn("Unknown token type (Not supported)");
}
}
else
{
// Check module name and version
if (moduleInfo.assembly.name == target_method.type.assembly.name &&
target_method.type.min_version <= assemblyMetadata->version &&
target_method.type.max_version >= assemblyMetadata->version)
{
rewriteType = true;
break;
}
}
}
// Go up
ancestorTypeInfo = ancestorTypeInfo->extend_from.get();
if (ancestorTypeInfo != nullptr)
{
if (ancestorTypeInfo->name == WStr("System.ValueType") ||
ancestorTypeInfo->name == WStr("System.Object") ||
ancestorTypeInfo->name == WStr("System.Enum"))
{
ancestorTypeInfo = nullptr;
}
}
maxDepth--;
}
if (rewriteType)
{
//
// Looking for the method to rewrite
//
ProcessTypeDefForRejit(definition, metadataImport, metadataEmit, assemblyImport, assemblyEmit,
moduleInfo, typeDef, vtModules, vtMethodDefs);
}
}
}
else
{
// If the integration is not for the current assembly we skip.
if (target_method.type.assembly.name != moduleInfo.assembly.name)
{
continue;
}
if (assemblyMetadata == nullptr)
{
Logger::Debug(" Loading Assembly Metadata...");
auto hr = corProfilerInfo->GetModuleMetaData(moduleInfo.id, ofRead | ofWrite, IID_IMetaDataImport2,
metadataInterfaces.GetAddressOf());
if (FAILED(hr))
{
Logger::Warn("CallTarget_RequestRejitForModule failed to get metadata interface for ",
moduleInfo.id, " ", moduleInfo.assembly.name);
break;
}
metadataImport = metadataInterfaces.As<IMetaDataImport2>(IID_IMetaDataImport);
metadataEmit = metadataInterfaces.As<IMetaDataEmit2>(IID_IMetaDataEmit);
assemblyImport = metadataInterfaces.As<IMetaDataAssemblyImport>(IID_IMetaDataAssemblyImport);
assemblyEmit = metadataInterfaces.As<IMetaDataAssemblyEmit>(IID_IMetaDataAssemblyEmit);
assemblyMetadata = std::make_unique<AssemblyMetadata>(GetAssemblyImportMetadata(assemblyImport));
Logger::Debug(" Assembly Metadata loaded for: ", assemblyMetadata->name, "(",
assemblyMetadata->version.str(), ").");
}
// Check min version
if (target_method.type.min_version > assemblyMetadata->version)
{
continue;
}
// Check max version
if (target_method.type.max_version < assemblyMetadata->version)
{
continue;
}
// We are in the right module, so we try to load the mdTypeDef from the integration target type name.
mdTypeDef typeDef = mdTypeDefNil;
auto foundType = FindTypeDefByName(target_method.type.name, moduleInfo.assembly.name,
metadataImport, typeDef);
if (!foundType)
{
continue;
}
//
// Looking for the method to rewrite
//
ProcessTypeDefForRejit(definition, metadataImport, metadataEmit, assemblyImport, assemblyEmit,
moduleInfo, typeDef, vtModules, vtMethodDefs);
}
}
}
const auto rejitCount = (ULONG) vtMethodDefs.size();
// Request the ReJIT for all integrations found in the module.
if (rejitCount > 0)
{
if (enqueueInSameThread)
{
m_rejit_handler->RequestRejit(vtModules, vtMethodDefs);
}
else
{
m_rejit_handler->EnqueueForRejit(vtModules, vtMethodDefs);
}
}
return rejitCount;
}
template <class RejitRequestDefinition>
void RejitPreprocessor<RejitRequestDefinition>::EnqueueRequestRejitForLoadedModules(
const std::vector<ModuleID>& modulesVector, const std::vector<RejitRequestDefinition>& definitions,
std::promise<ULONG>* promise)
{
if (m_rejit_handler->IsShutdownRequested())
{
if (promise != nullptr)
{
promise->set_value(0);
}
return;
}
if (modulesVector.size() == 0 || definitions.size() == 0)
{
return;
}
Logger::Debug("RejitHandler::EnqueueRequestRejitForLoadedModules");
std::function<void()> action = [=, modules = std::move(modulesVector), definitions = std::move(definitions),
promise = promise]() mutable {
// Process modules for rejit
const auto rejitCount = RequestRejitForLoadedModules(modules, definitions, true);
// Resolve promise
if (promise != nullptr)
{
promise->set_value(rejitCount);
}
};
// Enqueue
m_work_offloader->Enqueue(std::make_unique<RejitWorkItem>(std::move(action)));
}
// TraceIntegrationRejitPreprocessor
const MethodReference& TracerRejitPreprocessor::GetTargetMethod(const IntegrationDefinition& integrationDefinition)
{
return integrationDefinition.target_method;
}
const bool TracerRejitPreprocessor::GetIsDerived(const IntegrationDefinition& integrationDefinition)
{
return integrationDefinition.is_derived;
}
const std::unique_ptr<RejitHandlerModuleMethod> TracerRejitPreprocessor::CreateMethod(const mdMethodDef methodDef, RejitHandlerModule* module,
const FunctionInfo& functionInfo,
const IntegrationDefinition& integrationDefinition)
{
return std::make_unique<TracerRejitHandlerModuleMethod>(methodDef,
module,
functionInfo,
integrationDefinition);
}
template class RejitPreprocessor<debugger::MethodProbeDefinition>;
template class RejitPreprocessor<IntegrationDefinition>;
} // namespace trace
|
/*
UniformSphereRandomTroughFinder.cpp
Li-Yi Wei
09/06/2009
*/
#include "UniformSphereRandomTroughFinder.hpp"
#include "Random.hpp"
#include "Math.hpp"
#include "Exception.hpp"
UniformSphereRandomTroughFinder::UniformSphereRandomTroughFinder(const int num_class, const int num_trials, const bool greedy) : _num_class(num_class), _num_trials(num_trials), _greedy(greedy), _radius(num_class, Math::INF)
{
// nothing to do
}
UniformSphereRandomTroughFinder::UniformSphereRandomTroughFinder(const int num_class, const int num_trials, const bool greedy, const vector<float> & radius) : _num_class(num_class), _num_trials(num_trials), _greedy(greedy), _radius(radius)
{
if(radius.size() != num_class)
{
throw Exception("UniformSphereRandomTroughFinder::UniformSphereRandomTroughFinder(): radius.size() != num_class");
}
}
UniformSphereRandomTroughFinder::~UniformSphereRandomTroughFinder(void)
{
// nothing to do
}
int UniformSphereRandomTroughFinder::SetRadius(const vector<float> & radius)
{
_radius = radius;
return (_radius.size() == _num_class);
}
int UniformSphereRandomTroughFinder::Find(const EnergyField & energy_field, Sample & answer) const
{
if((answer.id < 0) || (answer.id >= _radius.size()))
{
throw Exception("UniformSphereRandomTroughFinder::Find(): illegal class id");
return 0;
}
const Domain & domain = energy_field.GetDomain();
float min_energy = Math::INF;
#if 1
try
{
min_energy = energy_field.Get(answer);
}
catch(Exception e)
{
min_energy = Math::INF;
}
#endif
const float peak_energy = min_energy;
const bool greedy = _greedy && (peak_energy < Math::INF);
_query = answer;
for(int i = 0; i < _num_trials; i++)
{
if(! SphereRandom(domain, _query, _radius[_query.id], _sample))
{
return 0;
}
_sample.id = answer.id;
const float energy = energy_field.Get(_sample);
if(energy < min_energy)
{
min_energy = energy;
answer = _sample;
}
if(greedy && (energy < peak_energy))
{
break;
}
if(energy < _threshold_energy)
{
break;
}
}
return (min_energy < Math::INF);
}
int UniformSphereRandomTroughFinder::SphereRandom(const Domain & domain, const Sample & query, const float radius, Sample & answer)
{
answer = query;
float distance2 = Math::INF;
do
{
for(int i = 0; i < answer.coordinate.Dimension(); i++)
{
answer.coordinate[i] = Random::UniformRandom()*2-1;
}
distance2 = 0;
for(int i = 0; i < answer.coordinate.Dimension(); i++)
{
distance2 += answer.coordinate[i]*answer.coordinate[i];
}
}
while(distance2 > 1.0);
for(int i = 0; i < answer.coordinate.Dimension(); i++)
{
answer.coordinate[i] = query.coordinate[i] + answer.coordinate[i]*radius;
}
// assuming toroidal domain for now
// could be fixed by repeated trials
if(! domain.Adopt(answer, answer))
{
throw Exception("UniformSphereRandomTroughFinder::SphereRandom(): cannot adopt sample back into domain");
return 0;
}
// done
return 1;
}
|
// -------------------------------------------------------------------------------------------------
// Copyright 2016 - NumScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
// -------------------------------------------------------------------------------------------------
/// bench for functor tanh in scalar mode for double type with no decorator (regular call).
#include <simd_bench.hpp>
#include <boost/simd/function/tanh.hpp>
namespace nsb = ns::bench;
namespace bs = boost::simd;
DEFINE_BENCH_MAIN()
{
using T = double;
run<T>(bs::tanh, nsbg::rand<T>(-10, 10));
}
|
// Copyright 2018 The Chromium OS 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 "cros-disks/drivefs_helper.h"
#include <base/files/file_path.h>
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
#include <base/strings/string_util.h>
#include "cros-disks/fuse_mounter.h"
#include "cros-disks/mount_options.h"
#include "cros-disks/platform.h"
#include "cros-disks/system_mounter.h"
#include "cros-disks/uri.h"
namespace cros_disks {
namespace {
const char kDataDirOptionPrefix[] = "datadir=";
const char kIdentityOptionPrefix[] = "identity=";
const char kUserName[] = "fuse-drivefs";
const char kHelperTool[] = "/opt/google/drive-file-stream/drivefs";
const char kSeccompPolicyFile[] =
"/opt/google/drive-file-stream/drivefs-seccomp.policy";
const char kType[] = "drivefs";
} // namespace
DrivefsHelper::DrivefsHelper(const Platform* platform)
: FUSEHelper(kType, platform, base::FilePath(kHelperTool), kUserName) {}
DrivefsHelper::~DrivefsHelper() = default;
std::unique_ptr<FUSEMounter> DrivefsHelper::CreateMounter(
const base::FilePath& working_dir,
const Uri& source,
const base::FilePath& target_path,
const std::vector<std::string>& options) const {
const std::string& identity = source.path();
// Enforced by FUSEHelper::CanMount().
DCHECK(!identity.empty());
auto data_dir = GetValidatedDataDir(options);
if (data_dir.empty()) {
return nullptr;
}
uid_t files_uid;
gid_t files_gid;
if (!platform()->GetUserAndGroupId(kFilesUser, &files_uid, nullptr) ||
!platform()->GetGroupId(kFilesGroup, &files_gid)) {
LOG(ERROR) << "Invalid user configuration.";
return nullptr;
}
if (!SetupDirectoryForFUSEAccess(data_dir) ||
!BindMount(data_dir, working_dir)) {
return nullptr;
}
MountOptions mount_options;
mount_options.EnforceOption(kDataDirOptionPrefix + working_dir.value());
mount_options.EnforceOption(kIdentityOptionPrefix + identity);
mount_options.Initialize(options, true, base::IntToString(files_uid),
base::IntToString(files_gid));
// TODO(crbug.com/859802): Make seccomp mandatory when testing done.
std::string seccomp =
platform()->PathExists(kSeccompPolicyFile) ? kSeccompPolicyFile : "";
return std::make_unique<FUSEMounter>(
"", target_path.value(), type(), mount_options, platform(),
program_path().value(), user(), seccomp, true);
}
base::FilePath DrivefsHelper::GetValidatedDataDir(
const std::vector<std::string>& options) const {
for (const auto& option : options) {
if (base::StartsWith(option, kDataDirOptionPrefix,
base::CompareCase::SENSITIVE)) {
std::string path_string = option.substr(strlen(kDataDirOptionPrefix));
base::FilePath data_dir(path_string);
if (data_dir.empty() || !data_dir.IsAbsolute() ||
data_dir.ReferencesParent()) {
LOG(ERROR) << "Invalid DriveFS option datadir=" << path_string;
return {};
}
base::FilePath suffix_component;
// If the datadir doesn't exist, canonicalize the parent directory
// instead, and append the last path component to that path.
if (!platform()->DirectoryExists(data_dir.value())) {
suffix_component = data_dir.BaseName();
data_dir = data_dir.DirName();
}
if (!platform()->GetRealPath(data_dir.value(), &path_string)) {
return {};
}
return base::FilePath(path_string).Append(suffix_component);
}
}
return {};
}
bool DrivefsHelper::SetupDirectoryForFUSEAccess(
const base::FilePath& dir) const {
CHECK(dir.IsAbsolute() && !dir.ReferencesParent())
<< "unsafe path '" << dir.value() << "'";
uid_t files_uid, mounter_uid;
gid_t files_gid;
if (!platform()->GetUserAndGroupId(user(), &mounter_uid, nullptr) ||
!platform()->GetUserAndGroupId(kFilesUser, &files_uid, nullptr) ||
!platform()->GetGroupId(kFilesGroup, &files_gid)) {
LOG(ERROR) << "Invalid user configuration.";
return false;
}
std::string path = dir.value();
if (platform()->DirectoryExists(path)) {
uid_t current_uid;
gid_t current_gid;
if (!platform()->GetOwnership(path, ¤t_uid, ¤t_gid)) {
LOG(WARNING) << "Can't access datadir '" << path << "'";
return false;
}
if (current_uid == mounter_uid && current_gid == files_gid) {
return true;
}
if (!platform()->RemoveEmptyDirectory(path)) {
LOG(WARNING) << "Existing datadir '" << path << "' has unexpected owner "
<< current_uid << ":" << current_gid;
return false;
}
}
if (!platform()->CreateDirectory(path)) {
LOG(ERROR) << "Failed to create datadir '" << path << "'";
return false;
}
if (!platform()->SetPermissions(path, 0770)) {
LOG(ERROR) << "Can't chmod datadir '" << path << "'";
return false;
}
if (!platform()->SetOwnership(path, mounter_uid, files_gid)) {
LOG(ERROR) << "Can't chown datadir '" << path << "'";
return false;
}
return true;
}
bool DrivefsHelper::BindMount(const base::FilePath& source,
const base::FilePath& target) const {
std::vector<std::string> options = {MountOptions::kOptionBind,
MountOptions::kOptionReadWrite};
MountOptions mount_options;
mount_options.Initialize(options, false, "", "");
return SystemMounter(source.value(), target.value(), "", mount_options,
platform())
.Mount() == MOUNT_ERROR_NONE;
}
} // namespace cros_disks
|
/* Copyright 2015-2018 Egor Yusov
*
* 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
*
* 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 OF ANY PROPRIETARY RIGHTS.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
// EngineSandbox.cpp : Defines the entry point for the application.
//
#include "pch.h"
#include <math.h>
#include "TestBufferAccess.h"
#include "MapHelper.h"
#include "BasicShaderSourceStreamFactory.h"
using namespace Diligent;
TestBufferAccess::TestBufferAccess() :
UnitTestBase("Buffer access test"),
m_fXExtent(0),
m_fYExtent(0)
{}
void TestBufferAccess::Init( IRenderDevice *pDevice, IDeviceContext *pContext, ISwapChain *pSwapChain, float fMinXCoord, float fMinYCoord, float fXExtent, float fYExtent )
{
m_pRenderDevice = pDevice;
m_pDeviceContext = pContext;
auto DevType = m_pRenderDevice->GetDeviceCaps().DevType;
bool bUseGLSL = DevType == DeviceType::OpenGL || DevType == DeviceType::OpenGLES || DevType == DeviceType::Vulkan;
m_fXExtent = fXExtent;
m_fYExtent = fYExtent;
float vertices[] = { 0.0f,0.0f,0.0f, 0.5f, 0.9f, 0.1f,
0.5f,1.f,0.0f, 0.9f, 0.3f, 0.7f,
1.f,0.0f,0.0f, 0.2f, 0.4f, 0.9f };
for(int iVert=0; iVert < 3; ++iVert)
{
vertices[iVert*6] = (vertices[iVert*6]) / (float)(NumRows+1) * fXExtent + fMinXCoord;
vertices[iVert*6+1] = (vertices[iVert*6+1]) / (float)(NumRows+1) * fYExtent + fMinYCoord;
}
{
Diligent::BufferDesc BuffDesc;
BuffDesc.uiSizeInBytes = sizeof(vertices);
BuffDesc.BindFlags = BIND_VERTEX_BUFFER;
Diligent::BufferData BuffData;
BuffData.pData = vertices;
BuffData.DataSize = BuffDesc.uiSizeInBytes;
m_pRenderDevice->CreateBuffer(BuffDesc, BuffData, &m_pVertexBuff);
}
for(int InstBuff = 0; InstBuff < _countof(m_pInstBuff); ++InstBuff)
{
float instance_offsets[NumInstances*2] =
{
1.f * fXExtent / (float)(NumRows+1), InstBuff*fYExtent / (float)(NumRows+1),
2.f * fXExtent / (float)(NumRows+1), InstBuff*fYExtent / (float)(NumRows+1),
3.f * fXExtent / (float)(NumRows+1), InstBuff*fYExtent / (float)(NumRows+1),
};
Diligent::BufferDesc BuffDesc;
BuffDesc.uiSizeInBytes = sizeof(instance_offsets);
BuffDesc.BindFlags = BIND_VERTEX_BUFFER;
if( InstBuff == 3 )
{
BuffDesc.Usage = USAGE_DYNAMIC;
BuffDesc.CPUAccessFlags = CPU_ACCESS_WRITE;
}
else if( InstBuff == 4 )
{
BuffDesc.Usage = USAGE_CPU_ACCESSIBLE;
BuffDesc.BindFlags = BIND_NONE;
BuffDesc.CPUAccessFlags = CPU_ACCESS_READ;
}
else if( InstBuff == 5 )
{
BuffDesc.Usage = USAGE_CPU_ACCESSIBLE;
BuffDesc.BindFlags = BIND_NONE;
BuffDesc.CPUAccessFlags = CPU_ACCESS_WRITE;
}
else if( InstBuff == 6 )
{
BuffDesc.Usage = USAGE_CPU_ACCESSIBLE;
BuffDesc.BindFlags = BIND_NONE;
BuffDesc.CPUAccessFlags = CPU_ACCESS_READ;
}
Diligent::BufferData BuffData;
if(BuffDesc.Usage != USAGE_DYNAMIC && !(BuffDesc.Usage == USAGE_CPU_ACCESSIBLE && (BuffDesc.CPUAccessFlags & CPU_ACCESS_WRITE) != 0))
{
BuffData.pData = instance_offsets;
BuffData.DataSize = sizeof(instance_offsets);
}
m_pRenderDevice->CreateBuffer(BuffDesc, BuffData, &m_pInstBuff[InstBuff]);
}
ShaderCreationAttribs CreationAttrs;
BasicShaderSourceStreamFactory BasicSSSFactory;
CreationAttrs.pShaderSourceStreamFactory = &BasicSSSFactory;
CreationAttrs.Desc.TargetProfile = bUseGLSL ? SHADER_PROFILE_GL_4_2 : SHADER_PROFILE_DX_5_0;
CreationAttrs.UseCombinedTextureSamplers = true;
RefCntAutoPtr<Diligent::IShader> pVSInst, pPS;
{
CreationAttrs.FilePath = bUseGLSL ? "Shaders\\minimalInstGL.vsh" : "Shaders\\minimalInstDX.vsh";
CreationAttrs.Desc.ShaderType = SHADER_TYPE_VERTEX;
m_pRenderDevice->CreateShader( CreationAttrs, &pVSInst );
}
{
CreationAttrs.FilePath = bUseGLSL ? "Shaders\\minimalGL.psh" : "Shaders\\minimalDX.psh";
CreationAttrs.Desc.ShaderType = SHADER_TYPE_PIXEL;
m_pRenderDevice->CreateShader( CreationAttrs, &pPS );
}
PipelineStateDesc PSODesc;
PSODesc.Name = "Test buffer access PSO";
PSODesc.GraphicsPipeline.DepthStencilDesc.DepthEnable = False;
PSODesc.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE;
PSODesc.GraphicsPipeline.BlendDesc.IndependentBlendEnable = False;
PSODesc.GraphicsPipeline.BlendDesc.RenderTargets[0].BlendEnable = False;
PSODesc.GraphicsPipeline.NumRenderTargets = 1;
PSODesc.GraphicsPipeline.RTVFormats[0] = pSwapChain->GetDesc().ColorBufferFormat;
PSODesc.GraphicsPipeline.DSVFormat = pSwapChain->GetDesc().DepthBufferFormat;
PSODesc.GraphicsPipeline.pVS = pVSInst;
PSODesc.GraphicsPipeline.pPS = pPS;
LayoutElement Elems[] =
{
LayoutElement( 0, 1, 3, Diligent::VT_FLOAT32, false, 0 ),
LayoutElement( 1, 1, 3, Diligent::VT_FLOAT32, false, sizeof( float ) * 3, sizeof( float ) * 6),
LayoutElement( 2, 3, 2, Diligent::VT_FLOAT32, false, 0, 0, LayoutElement::FREQUENCY_PER_INSTANCE )
};
PSODesc.GraphicsPipeline.InputLayout.LayoutElements = Elems;
PSODesc.GraphicsPipeline.InputLayout.NumElements = _countof( Elems );
PSODesc.GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
pDevice->CreatePipelineState(PSODesc, &m_pPSO);
}
void TestBufferAccess::Draw(float fTime)
{
m_pDeviceContext->SetPipelineState(m_pPSO);
// No shader resources needed
//m_pDeviceContext->TransitionShaderResources(m_pPSO, nullptr);
//m_pDeviceContext->CommitShaderResources(nullptr);
IBuffer *pBuffs[] = {nullptr, m_pVertexBuff, nullptr, m_pInstBuff[0], nullptr};
Uint32 Offsets[_countof( pBuffs )] = {0, 0, 0, 0, 0};
m_pDeviceContext->SetVertexBuffers( 0, _countof( pBuffs ), pBuffs, Offsets, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET );
DrawAttribs DrawAttrs(3, DRAW_FLAG_VERIFY_STATES);
DrawAttrs.NumVertices = 3;
DrawAttrs.NumInstances = NumInstances;
m_pDeviceContext->Draw(DrawAttrs);
float fDX = m_fXExtent / (float)(NumRows+1);
float fDY = m_fYExtent / (float)(NumRows+1);
float instance_offsets[NumInstances*2];
for(int Inst = 0; Inst < NumInstances; ++Inst)
{
instance_offsets[Inst*2] = (1+Inst) * fDX;
instance_offsets[Inst*2+1] = 1.f * fDY + sin(fTime) * fDY * 0.3f;
}
m_pDeviceContext->UpdateBuffer(m_pInstBuff[1], sizeof( float ) * 2, sizeof( float ) * 4, &instance_offsets[2], RESOURCE_STATE_TRANSITION_MODE_TRANSITION );
pBuffs[3] = m_pInstBuff[1];
m_pDeviceContext->SetVertexBuffers( 0, _countof( pBuffs ), pBuffs, Offsets, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET );
m_pDeviceContext->Draw(DrawAttrs);
for(int Inst = 0; Inst < NumInstances; ++Inst)
{
instance_offsets[Inst*2] = (1+Inst) * fDX;
instance_offsets[Inst*2+1] = 2.f * fDY + sin(fTime*0.8f) * fDY * 0.3f;
}
m_pDeviceContext->UpdateBuffer(m_pInstBuff[2], sizeof( float ) * 2, sizeof( float ) * 4, &instance_offsets[2], RESOURCE_STATE_TRANSITION_MODE_TRANSITION );
m_pDeviceContext->CopyBuffer(m_pInstBuff[2], sizeof( float ) * 2, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, m_pInstBuff[1], sizeof( float ) * 2, sizeof( float ) * 4, RESOURCE_STATE_TRANSITION_MODE_TRANSITION );
StateTransitionDesc Barrier(m_pInstBuff[1], RESOURCE_STATE_UNKNOWN, RESOURCE_STATE_VERTEX_BUFFER, true);
m_pDeviceContext->TransitionResourceStates(1, &Barrier);
m_pDeviceContext->Draw(DrawAttrs);
for(int Inst = 0; Inst < NumInstances; ++Inst)
{
instance_offsets[Inst*2] = (1+Inst) * fDX;
instance_offsets[Inst*2+1] = 3.f * fDY + sin(fTime*1.2f) * fDY * 0.3f;
}
// Test updating dynamic buffer
{
MapHelper<float> pInstData( m_pDeviceContext, m_pInstBuff[3], MAP_WRITE, MAP_FLAG_DISCARD );
memcpy(pInstData, instance_offsets, sizeof(instance_offsets));
}
pBuffs[3] = m_pInstBuff[3];
m_pDeviceContext->SetVertexBuffers( 0, _countof( pBuffs ), pBuffs, Offsets, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET );
m_pDeviceContext->Draw(DrawAttrs);
bool TestStagingBuffers = false;
if(TestStagingBuffers)
{
MapHelper<float> pStagingData;
// Test reading data from staging resource
{
m_pDeviceContext->CopyBuffer(m_pInstBuff[3], 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, m_pInstBuff[4], 0, sizeof( instance_offsets ), RESOURCE_STATE_TRANSITION_MODE_TRANSITION );
pStagingData.Map( m_pDeviceContext, m_pInstBuff[4], MAP_READ, MAP_FLAG_NONE );
for(int i = 0; i < _countof(instance_offsets); ++i)
assert(pStagingData[i] == instance_offsets[i]);
pStagingData.Unmap();
}
// D3D12 does not allow writing to the CPU-readable buffers
if(m_pRenderDevice->GetDeviceCaps().DevType != DeviceType::D3D12)
{
// Test writing data to staging resource
{
pStagingData.Map( m_pDeviceContext, m_pInstBuff[5], MAP_WRITE, MAP_FLAG_NONE );
for(int Inst = 0; Inst < NumInstances; ++Inst)
{
pStagingData[Inst*2] = (1+Inst) * fDX;
pStagingData[Inst*2+1] = 4.f * fDY + sin(fTime*1.3f) * fDY * 0.3f;
}
pStagingData.Unmap();
}
StateTransitionDesc Barriers[2] =
{
StateTransitionDesc{m_pInstBuff[5], RESOURCE_STATE_UNKNOWN, RESOURCE_STATE_COPY_SOURCE, true},
StateTransitionDesc{m_pInstBuff[2], RESOURCE_STATE_UNKNOWN, RESOURCE_STATE_COPY_DEST, true},
};
m_pDeviceContext->TransitionResourceStates(2, Barriers);
m_pDeviceContext->CopyBuffer(m_pInstBuff[5], 0, RESOURCE_STATE_TRANSITION_MODE_VERIFY, m_pInstBuff[2], 0, sizeof( instance_offsets ), RESOURCE_STATE_TRANSITION_MODE_VERIFY );
pBuffs[3] = m_pInstBuff[2];
m_pDeviceContext->SetVertexBuffers( 0, _countof( pBuffs ), pBuffs, Offsets, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, SET_VERTEX_BUFFERS_FLAG_RESET );
m_pDeviceContext->Draw(DrawAttrs);
// Test reading & writing data to the staging resource
/*{
MapHelper<float> pInstData2( m_pDeviceContext, m_pInstBuff[6], MAP_READ_WRITE, 0 );
MapHelper<float> pInstData3( std::move(pInstData2) );
MapHelper<float> pInstData;
pInstData = std::move(pInstData3);
static float fPrevTime = fTime;
for(int Inst = 0; Inst < NumInstances; ++Inst)
{
pInstData[Inst*2] += (fTime-fPrevTime) * sin(fTime)*0.1f * m_fXExtent;
}
fPrevTime = fTime;
}*/
m_pDeviceContext->CopyBuffer(m_pInstBuff[6], 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, m_pInstBuff[2], 0, sizeof( instance_offsets ), RESOURCE_STATE_TRANSITION_MODE_TRANSITION );
m_pDeviceContext->Draw(DrawAttrs);
}
}
SetStatus(TestResult::Succeeded);
}
|
// Copyright 2013 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/media/midi_permission_context.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/content_settings/permission_queue_controller.h"
#include "chrome/browser/content_settings/permission_request_id.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
#include "chrome/browser/ui/website_settings/permission_bubble_request.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"
class MidiPermissionRequest : public PermissionBubbleRequest {
public:
MidiPermissionRequest(
MidiPermissionContext* context,
const PermissionRequestID& id,
const GURL& requesting_frame,
bool user_gesture,
const std::string& display_languages,
const base::Callback<void(bool)>& callback);
virtual ~MidiPermissionRequest();
// PermissionBubbleDelegate:
virtual int GetIconID() const OVERRIDE;
virtual base::string16 GetMessageText() const OVERRIDE;
virtual base::string16 GetMessageTextFragment() const OVERRIDE;
virtual bool HasUserGesture() const OVERRIDE;
virtual GURL GetRequestingHostname() const OVERRIDE;
virtual void PermissionGranted() OVERRIDE;
virtual void PermissionDenied() OVERRIDE;
virtual void Cancelled() OVERRIDE;
virtual void RequestFinished() OVERRIDE;
private:
MidiPermissionContext* context_;
const PermissionRequestID id_;
GURL requesting_frame_;
bool user_gesture_;
std::string display_languages_;
const base::Callback<void(bool)>& callback_;
bool is_finished_;
DISALLOW_COPY_AND_ASSIGN(MidiPermissionRequest);
};
MidiPermissionRequest::MidiPermissionRequest(
MidiPermissionContext* context,
const PermissionRequestID& id,
const GURL& requesting_frame,
bool user_gesture,
const std::string& display_languages,
const base::Callback<void(bool)>& callback)
: context_(context),
id_(id),
requesting_frame_(requesting_frame),
user_gesture_(user_gesture),
display_languages_(display_languages),
callback_(callback),
is_finished_(false) {}
MidiPermissionRequest::~MidiPermissionRequest() {
DCHECK(is_finished_);
}
int MidiPermissionRequest::GetIconID() const {
return IDR_ALLOWED_MIDI_SYSEX;
}
base::string16 MidiPermissionRequest::GetMessageText() const {
return l10n_util::GetStringFUTF16(
IDS_MIDI_SYSEX_INFOBAR_QUESTION,
net::FormatUrl(requesting_frame_.GetOrigin(), display_languages_));
}
base::string16 MidiPermissionRequest::GetMessageTextFragment() const {
return l10n_util::GetStringUTF16(IDS_MIDI_SYSEX_PERMISSION_FRAGMENT);
}
bool MidiPermissionRequest::HasUserGesture() const {
return user_gesture_;
}
GURL MidiPermissionRequest::GetRequestingHostname() const {
return requesting_frame_;
}
void MidiPermissionRequest::PermissionGranted() {
context_->NotifyPermissionSet(id_, requesting_frame_, callback_, true);
}
void MidiPermissionRequest::PermissionDenied() {
context_->NotifyPermissionSet(id_, requesting_frame_, callback_, false);
}
void MidiPermissionRequest::Cancelled() {
}
void MidiPermissionRequest::RequestFinished() {
is_finished_ = true;
// Deletes 'this'.
context_->RequestFinished(this);
}
MidiPermissionContext::MidiPermissionContext(Profile* profile)
: profile_(profile),
shutting_down_(false),
weak_factory_(this) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
}
MidiPermissionContext::~MidiPermissionContext() {
DCHECK(!permission_queue_controller_);
DCHECK(pending_requests_.empty());
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
}
void MidiPermissionContext::Shutdown() {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
permission_queue_controller_.reset();
shutting_down_ = true;
}
void MidiPermissionContext::RequestMidiSysExPermission(
content::WebContents* web_contents,
int bridge_id,
const GURL& requesting_frame,
bool user_gesture,
const base::Callback<void(bool)>& result_callback,
base::Closure* cancel_callback) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
DCHECK(!shutting_down_);
// TODO(toyoshim): Support Extension's manifest declared permission.
// See http://crbug.com/266338.
int render_process_id = web_contents->GetRenderProcessHost()->GetID();
int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID();
if (cancel_callback) {
*cancel_callback = base::Bind(
&MidiPermissionContext::CancelMidiSysExPermissionRequest,
weak_factory_.GetWeakPtr(), render_process_id, render_view_id,
bridge_id);
}
const PermissionRequestID id(
render_process_id, render_view_id, bridge_id, GURL());
GURL embedder = web_contents->GetURL();
// |requesting_frame| can be empty and invalid when the frame is a local
// file. Here local files should be granted to show an infobar.
// Any user's action will not be stored to content settings data base.
if ((!requesting_frame.is_valid() && !requesting_frame.is_empty()) ||
!embedder.is_valid()) {
LOG(WARNING) << "Attempt to use MIDI sysex from an invalid URL: "
<< requesting_frame << "," << embedder
<< " (Web MIDI is not supported in popups)";
PermissionDecided(id, requesting_frame, embedder, result_callback, false);
return;
}
DecidePermission(web_contents, id, requesting_frame, embedder, user_gesture,
result_callback);
}
void MidiPermissionContext::CancelMidiSysExPermissionRequest(
int render_process_id,
int render_view_id,
int bridge_id) {
CancelPendingInfobarRequest(
PermissionRequestID(
render_process_id, render_view_id, bridge_id, GURL()));
}
void MidiPermissionContext::DecidePermission(
content::WebContents* web_contents,
const PermissionRequestID& id,
const GURL& requesting_frame,
const GURL& embedder,
bool user_gesture,
const base::Callback<void(bool)>& callback) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
ContentSetting content_setting =
profile_->GetHostContentSettingsMap()->GetContentSetting(
requesting_frame,
embedder,
CONTENT_SETTINGS_TYPE_MIDI_SYSEX,
std::string());
switch (content_setting) {
case CONTENT_SETTING_BLOCK:
PermissionDecided(id, requesting_frame, embedder, callback, false);
break;
case CONTENT_SETTING_ALLOW:
PermissionDecided(id, requesting_frame, embedder, callback, true);
break;
default:
if (PermissionBubbleManager::Enabled()) {
PermissionBubbleManager* bubble_manager =
PermissionBubbleManager::FromWebContents(web_contents);
if (bubble_manager) {
scoped_ptr<MidiPermissionRequest> request_ptr(
new MidiPermissionRequest(
this, id, requesting_frame, user_gesture,
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages),
callback));
MidiPermissionRequest* request = request_ptr.get();
bool inserted = pending_requests_.add(
id.ToString(), request_ptr.Pass()).second;
DCHECK(inserted) << "Duplicate id " << id.ToString();
bubble_manager->AddRequest(request);
}
return;
}
// TODO(gbillock): Delete this and the infobar delegate when
// we're using only bubbles. crbug.com/337458
GetQueueController()->CreateInfoBarRequest(
id, requesting_frame, embedder, std::string(), base::Bind(
&MidiPermissionContext::NotifyPermissionSet,
base::Unretained(this), id, requesting_frame, callback));
}
}
void MidiPermissionContext::PermissionDecided(
const PermissionRequestID& id,
const GURL& requesting_frame,
const GURL& embedder,
const base::Callback<void(bool)>& callback,
bool allowed) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
NotifyPermissionSet(id, requesting_frame, callback, allowed);
}
void MidiPermissionContext::NotifyPermissionSet(
const PermissionRequestID& id,
const GURL& requesting_frame,
const base::Callback<void(bool)>& callback,
bool allowed) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
TabSpecificContentSettings* content_settings =
TabSpecificContentSettings::Get(id.render_process_id(),
id.render_view_id());
if (content_settings) {
if (allowed)
content_settings->OnMidiSysExAccessed(requesting_frame);
else
content_settings->OnMidiSysExAccessBlocked(requesting_frame);
}
callback.Run(allowed);
}
PermissionQueueController* MidiPermissionContext::GetQueueController() {
if (!permission_queue_controller_) {
permission_queue_controller_.reset(
new PermissionQueueController(profile_,
CONTENT_SETTINGS_TYPE_MIDI_SYSEX));
}
return permission_queue_controller_.get();
}
void MidiPermissionContext::RequestFinished(
MidiPermissionRequest* request) {
base::ScopedPtrHashMap<std::string, MidiPermissionRequest>::iterator it;
for (it = pending_requests_.begin(); it != pending_requests_.end(); it++) {
if (it->second == request) {
pending_requests_.take_and_erase(it);
return;
}
}
NOTREACHED() << "Missing request";
}
void MidiPermissionContext::CancelPendingInfobarRequest(
const PermissionRequestID& id) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
if (shutting_down_)
return;
if (PermissionBubbleManager::Enabled()) {
MidiPermissionRequest* cancelling = pending_requests_.get(id.ToString());
content::WebContents* web_contents = tab_util::GetWebContentsByID(
id.render_process_id(), id.render_view_id());
if (cancelling != NULL && web_contents != NULL &&
PermissionBubbleManager::FromWebContents(web_contents) != NULL) {
PermissionBubbleManager::FromWebContents(web_contents)->
CancelRequest(cancelling);
}
return;
}
GetQueueController()->CancelInfoBarRequest(id);
}
|
#ifndef HEADER_AUDIOCPP
#define HEADER_AUDIOCPP
#ifndef __ANDROID__
#include <MT2D/MT2D_Terminal_Define.h>
#include <MT2D/MT2D_Debug.h>
#else
#include "../../MT2D_Terminal_Define.h"
#endif
#ifdef _DEBUG
#include <stdio.h>
#endif
#ifdef SDL_USE_AUDIO
#if defined(linux) || defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
#include <SDL2/SDL.h>
#include <SDL2/SDL_audio.h>
#include <SDL2/SDL_mixer.h>
#elif defined(__ANDROID__)
#include <SDL.h>
#include <SDL_audio.h>
#include <SDL_mixer.h>
#elif defined _WIN32
#include <SDL.h>
#include <SDL_mixer.h>
#endif
//#include <queue>
//#include <cmath>
#include <time.h>
#include <MT2D\File\MT2D_File.h>
extern bool nosound;
/**
Private struct
**/
typedef struct MT2D_Audio_Buffer {
#ifdef SDL_USE_AUDIO
bool SDL_AUDIO_STARTED;
Mix_Music *SDL_music;
int music_loaded;
Mix_Chunk *SDL_Audio[8]; // we can play only max 8 audio files at the same time.
time_t SDL_Audio_Started[8];
int sound_loaded;
#endif
};
MT2D_Audio_Buffer SDL_ABuffer;
bool SDL_AUDIO_STARTED = false;
extern char SDL_SOUND_TYPE;
void SDL_Start_Sound_System()
{
MT2D_Ide_Printf("Start Sound System");
SDL_ABuffer.music_loaded = 0;
for (int i = 0; i < 8; i++) {
SDL_ABuffer.SDL_Audio[i] = 0;
SDL_ABuffer.SDL_Audio_Started[i] = 0;
}
SDL_ABuffer.SDL_AUDIO_STARTED = 0;
SDL_ABuffer.SDL_music = 0;
SDL_ABuffer.sound_loaded = 0;
if(SDL_SOUND_TYPE == (char)-1){
SDL_SOUND_TYPE = 1;
if(SDL_Init(SDL_INIT_AUDIO) < 0){
MT2D_Ide_Printf(SDL_GetError());
exit(1);
}else{
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 4, 4096) < 0) {
MT2D_Ide_Printf(SDL_GetError());
}
if (Mix_Init(MIX_INIT_OGG) < 0) {
MT2D_Ide_Printf(SDL_GetError());
}
//SDL_PauseAudio(0);
}
}
MT2D_Ide_Printf("Start Sound System OK");
}
void SDL_Close_Sound_System()
{
MT2D_Ide_Printf("Close Sound System");
if (SDL_SOUND_TYPE == 1) {
while (Mix_Playing(0) != 0);
for (int i = 0; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[0]) {
Mix_FreeChunk(SDL_ABuffer.SDL_Audio[0]);
}
}
Mix_FreeMusic(SDL_ABuffer.SDL_music);
Mix_CloseAudio();
SDL_Quit();
}
MT2D_Ide_Printf("Close Sound System OK");
}
void SDL_Clear_Audio_Buffer() {
MT2D_Ide_Printf("Clear Audio Buffer");
Mix_Chunk *MC;
time_t NOW = clock();
for (int i = 0; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[i] != NULL && NOW-SDL_ABuffer.SDL_Audio_Started[i] > SDL_ABuffer.SDL_Audio[i]->alen) {
//the sound has already played
Mix_FreeChunk(SDL_ABuffer.SDL_Audio[i]);
SDL_ABuffer.SDL_Audio[i] = 0;
SDL_ABuffer.SDL_Audio_Started[i] = 0;
}
}
MT2D_Ide_Printf("Clear Audio Buffer OK");
}
void SDL_Play_Music(char *Name){
MT2D_Ide_Printf(Name);
MT2D_Ide_Printf("Music Loading");
if (SDL_SOUND_TYPE == 1) {
MT2D_Ide_Printf("Starting SDL Play music");
if (Name) {
if (!SDL_ABuffer.music_loaded) {
#ifdef __ANDROID__
SDL_RWops *file = SDL_RWFromFile(Name,"rb");
SDL_ABuffer.SDL_music = Mix_LoadMUS_RW(file,1);
// SDL_RWclose(file);
#else
SDL_RWops* rw = SDL_RWFromFile(Name, "rb");
if (NULL == rw) {
MT2D_Ide_Printf(SDL_GetError());
return;
}
SDL_ABuffer.SDL_music = Mix_LoadMUS_RW(rw,1);
// SDL_ABuffer.SDL_music = Mix_LoadMUS(Name);
#endif
if (!SDL_ABuffer.SDL_music) {
MT2D_Ide_Printf("Mix_LoadMUS...");
MT2D_Ide_Printf(Name);
MT2D_Ide_Printf(Mix_GetError());
}
SDL_ABuffer.music_loaded = 1;
MT2D_Ide_Printf("Starting Music");
Mix_PlayMusic(SDL_ABuffer.SDL_music, 10);
}
else {
if (SDL_ABuffer.SDL_music) {
Mix_FreeMusic(SDL_ABuffer.SDL_music);
}
#ifdef __ANDROID__
SDL_RWops *file = SDL_RWFromFile(Name,"rb");
SDL_ABuffer.SDL_music = Mix_LoadMUS_RW(file,1);
// SDL_RWclose(file);
#else
MT2D_FILE* file = MT2D_FILE_OPEN(Name, "rb");
MT2D_FILE_SEEK(file, 0, SEEK_END);
int size = MT2D_FILE_TELL(file);
char* buff = (char*)malloc(size * sizeof(char));
MT2D_FILE_SEEK(file, 0, SEEK_SET);
MT2D_FILE_READ(file, buff, size, 1);
SDL_RWops* a = SDL_RWFromMem(buff, size);
SDL_ABuffer.SDL_music = Mix_LoadMUS_RW(a,1);
//SDL_ABuffer.SDL_music = Mix_LoadMUS(Name);
#endif
if (!SDL_ABuffer.SDL_music) {
MT2D_Ide_Printf("Mix_LoadMUS...");
MT2D_Ide_Printf(Name);
MT2D_Ide_Printf(Mix_GetError());
}
SDL_ABuffer.music_loaded = 1;
Mix_PlayMusic(SDL_ABuffer.SDL_music, 10);
}
}
else {
MT2D_Ide_Printf("No music name received");
}
}
}
void SDL_PlayMusicFromMemory(void *music, unsigned int size, bool free) {
MT2D_Ide_Printf("Music Loading");
if (SDL_SOUND_TYPE == 1) {
MT2D_Ide_Printf("Starting SDL Play music");
if (music) {
if (!SDL_ABuffer.music_loaded) {
SDL_RWops* rw = SDL_RWFromMem(music, size);
if (NULL == rw) {
MT2D_Ide_Printf(SDL_GetError());
return;
}
SDL_ABuffer.SDL_music = Mix_LoadMUS_RW(rw, 1);
if (!SDL_ABuffer.SDL_music) {
MT2D_Ide_Printf("Mix_LoadMUS Error...");
MT2D_Ide_Printf(Mix_GetError());
}
SDL_ABuffer.music_loaded = 1;
MT2D_Ide_Printf("Starting Music");
Mix_PlayMusic(SDL_ABuffer.SDL_music, 10);
}
else {
if (SDL_ABuffer.SDL_music) {
Mix_FreeMusic(SDL_ABuffer.SDL_music);
}
SDL_RWops* rw = SDL_RWFromMem(music, size);
SDL_ABuffer.SDL_music = Mix_LoadMUS_RW(rw, 1);
if (!SDL_ABuffer.SDL_music) {
MT2D_Ide_Printf("Mix_LoadMUS Error...");
MT2D_Ide_Printf(Mix_GetError());
}
SDL_ABuffer.music_loaded = 1;
Mix_PlayMusic(SDL_ABuffer.SDL_music, 10);
}
}
else {
MT2D_Ide_Printf("No music received");
}
}
}
void SDL_Play_Sound(char *Name){
MT2D_Ide_Printf("Loading sound...");
MT2D_Ide_Printf(Name);
if (SDL_SOUND_TYPE == 1) {
bool Played = 0;
int i = 0;
SDL_Clear_Audio_Buffer();
for (; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[i] == 0) {
MT2D_Ide_Printf("Found channel to load");
SDL_ABuffer.SDL_Audio[i] = Mix_LoadWAV(Name);
MT2D_Ide_Printf("Wav Loaded");
Mix_PlayChannel(i, SDL_ABuffer.SDL_Audio[i], 0);
SDL_ABuffer.SDL_Audio_Started[i] = clock();
Played = true;
i = 8;
}
}
if (Played == false) {
/*All the channels are in use so*/
/*first we check this audio is already being played*/
#ifdef __ANDROID__
SDL_RWops *file = SDL_RWFromFile(Name,"rb");
Mix_Chunk *Tmp = Mix_LoadWAV_RW(file,1);
//SDL_RWclose(file);
#else
Mix_Chunk *Tmp = Mix_LoadWAV(Name);
#endif
for (i = 0; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[i]->volume == Tmp->volume &&
SDL_ABuffer.SDL_Audio[i]->alen == Tmp->alen &&
SDL_ABuffer.SDL_Audio[i]->allocated == Tmp->allocated) {
Mix_FreeChunk(Tmp);
Mix_PlayChannel(i, SDL_ABuffer.SDL_Audio[i], 0);
SDL_ABuffer.SDL_Audio_Started[i] = clock();
i = 8;
Played = true;
}
}
if (Played == false) {
/*this file isnt being played, so lets replace the sound that were being played that is near to finish*/
int IdChannel = 0;
time_t NOW = clock();
int ShortestTime = SDL_ABuffer.SDL_Audio[0]->alen - (NOW - SDL_ABuffer.SDL_Audio_Started[0]);
for (i = 1; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[i]->alen - (NOW - SDL_ABuffer.SDL_Audio_Started[i]) < ShortestTime)
{
IdChannel = i;
ShortestTime = SDL_ABuffer.SDL_Audio[i]->alen - (NOW - SDL_ABuffer.SDL_Audio_Started[i]);
}
}
Mix_FreeChunk(SDL_ABuffer.SDL_Audio[IdChannel]);
SDL_ABuffer.SDL_Audio[IdChannel] = Tmp;
Mix_PlayChannel(IdChannel, SDL_ABuffer.SDL_Audio[IdChannel], 0);
SDL_ABuffer.SDL_Audio_Started[IdChannel] = clock();
}
}
}
MT2D_Ide_Printf("audio played");
}
void SDL_PlaySoundFromMemory(void* memoryBlock, unsigned int size, bool free) {
MT2D_Ide_Printf("Loading sound From Container...");
if (SDL_SOUND_TYPE == 1) {
bool Played = 0;
int i = 0;
SDL_Clear_Audio_Buffer();
SDL_RWops* memFile = SDL_RWFromMem(memoryBlock, size);
for (; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[i] == 0) {
MT2D_Ide_Printf("Found channel to load");
SDL_ABuffer.SDL_Audio[i] = Mix_LoadWAV_RW(memFile, 1);
MT2D_Ide_Printf("Wav Loaded");
Mix_PlayChannel(i, SDL_ABuffer.SDL_Audio[i], 0);
SDL_ABuffer.SDL_Audio_Started[i] = clock();
Played = true;
i = 8;
}
}
if (Played == false) {
/*All the channels are in use so*/
/*first we check this audio is already being played*/
Mix_Chunk* Tmp = Mix_LoadWAV_RW(memFile, 1);
for (i = 0; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[i]->volume == Tmp->volume &&
SDL_ABuffer.SDL_Audio[i]->alen == Tmp->alen &&
SDL_ABuffer.SDL_Audio[i]->allocated == Tmp->allocated) {
Mix_FreeChunk(Tmp);
Mix_PlayChannel(i, SDL_ABuffer.SDL_Audio[i], 0);
SDL_ABuffer.SDL_Audio_Started[i] = clock();
i = 8;
Played = true;
}
}
if (Played == false) {
/*this file isnt being played, so lets replace the sound that were being played that is near to finish*/
int IdChannel = 0;
time_t NOW = clock();
int ShortestTime = SDL_ABuffer.SDL_Audio[0]->alen - (NOW - SDL_ABuffer.SDL_Audio_Started[0]);
for (i = 1; i < 8; i++) {
if (SDL_ABuffer.SDL_Audio[i]->alen - (NOW - SDL_ABuffer.SDL_Audio_Started[i]) < ShortestTime)
{
IdChannel = i;
ShortestTime = SDL_ABuffer.SDL_Audio[i]->alen - (NOW - SDL_ABuffer.SDL_Audio_Started[i]);
}
}
Mix_FreeChunk(SDL_ABuffer.SDL_Audio[IdChannel]);
SDL_ABuffer.SDL_Audio[IdChannel] = Tmp;
Mix_PlayChannel(IdChannel, SDL_ABuffer.SDL_Audio[IdChannel], 0);
SDL_ABuffer.SDL_Audio_Started[IdChannel] = clock();
}
}
}
MT2D_Ide_Printf("audio played");
}
#else
//#warning define "SDL_USE_AUDIO" must be declared to use the SDL audio code
#endif
#endif
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkOpenGLGPUVolumeRayCastMapper.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkOpenGLGPUVolumeRayCastMapper.h"
#include "vtkOpenGLVolumeGradientOpacityTable.h"
#include "vtkOpenGLVolumeOpacityTable.h"
#include "vtkOpenGLVolumeRGBTable.h"
#include "vtkVolumeShaderComposer.h"
#include "vtkVolumeStateRAII.h"
// Include compiled shader code
#include <raycasterfs.h>
#include <raycastervs.h>
// VTK includes
#include <vtkBoundingBox.h>
#include <vtkCamera.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkClipConvexPolyData.h>
#include <vtkColorTransferFunction.h>
#include <vtkCommand.h>
#include <vtkContourFilter.h>
#include <vtkDataArray.h>
#include <vtkDensifyPolyData.h>
#include <vtkFloatArray.h>
#include <vtkFrameBufferObject2.h>
#include <vtkImageData.h>
#include <vtkLightCollection.h>
#include <vtkLight.h>
#include <vtkMath.h>
#include <vtkMatrix4x4.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
#include <vtkOpenGLError.h>
#include <vtkOpenGLCamera.h>
#include <vtkOpenGLRenderWindow.h>
#include "vtkOpenGLResourceFreeCallback.h"
#include <vtkOpenGLShaderCache.h>
#include <vtkPerlinNoise.h>
#include <vtkPixelBufferObject.h>
#include <vtkPixelExtent.h>
#include <vtkPixelTransfer.h>
#include <vtkPlaneCollection.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkShader.h>
#include <vtkShaderProgram.h>
#include <vtkSmartPointer.h>
#include <vtkTessellatedBoxSource.h>
#include <vtkTextureObject.h>
#include <vtkTimerLog.h>
#include <vtkTransform.h>
#include <vtkUnsignedCharArray.h>
#include <vtkUnsignedIntArray.h>
#include <vtkVolumeMask.h>
#include <vtkVolumeProperty.h>
#include <vtkWeakPointer.h>
#include <vtkHardwareSelector.h>
#include <vtk_glew.h>
// C/C++ includes
#include <cassert>
#include <limits>
#include <map>
#include <sstream>
#include <string>
vtkStandardNewMacro(vtkOpenGLGPUVolumeRayCastMapper);
//----------------------------------------------------------------------------
class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal
{
public:
// Constructor
//--------------------------------------------------------------------------
vtkInternal(vtkOpenGLGPUVolumeRayCastMapper* parent)
{
this->Parent = parent;
this->ValidTransferFunction = false;
this->LoadDepthTextureExtensionsSucceeded = false;
this->CameraWasInsideInLastUpdate = false;
this->CubeVBOId = 0;
this->CubeVAOId = 0;
this->CubeIndicesId = 0;
this->InterpolationType = vtkTextureObject::Linear;
this->VolumeTextureObject = 0;
this->NoiseTextureObject = NULL;
this->DepthTextureObject = 0;
this->TextureWidth = 1024;
this->ActualSampleDistance = 1.0;
this->RGBTables = 0;
this->OpacityTables = 0;
this->Mask1RGBTable = 0;
this->Mask2RGBTable = 0;
this->GradientOpacityTables = 0;
this->CurrentMask = 0;
this->Dimensions[0] = this->Dimensions[1] = this->Dimensions[2] = -1;
this->TextureSize[0] = this->TextureSize[1] = this->TextureSize[2] = -1;
this->WindowLowerLeft[0] = this->WindowLowerLeft[1] = 0;
this->WindowSize[0] = this->WindowSize[1] = 0;
this->LastDepthPassWindowSize[0] = this->LastDepthPassWindowSize[1] = 0;
this->LastRenderToImageWindowSize[0] = 0;
this->LastRenderToImageWindowSize[1] = 0;
this->ScalarsRange[0][0] = this->ScalarsRange[0][1] = 0.0;
this->ScalarsRange[1][0] = this->ScalarsRange[1][1] = 0.0;
this->ScalarsRange[2][0] = this->ScalarsRange[2][1] = 0.0;
this->ScalarsRange[3][0] = this->ScalarsRange[3][1] = 0.0;
this->CurrentSelectionPass = vtkHardwareSelector::MIN_KNOWN_PASS - 1;
this->CellScale[0] = this->CellScale[1] = this->CellScale[2] = 0.0;
this->NoiseTextureData = NULL;
this->NumberOfLights = 0;
this->LightComplexity = 0;
this->Extents[0] = VTK_INT_MAX;
this->Extents[1] = VTK_INT_MIN;
this->Extents[2] = VTK_INT_MAX;
this->Extents[3] = VTK_INT_MIN;
this->Extents[4] = VTK_INT_MAX;
this->Extents[5] = VTK_INT_MIN;
this->CellToPointMatrix->Identity();
this->AdjustedTexMin[0] = this->AdjustedTexMin[1] = this->AdjustedTexMin[2] = 0.0f;
this->AdjustedTexMin[3] = 1.0f;
this->AdjustedTexMax[0] = this->AdjustedTexMax[1] = this->AdjustedTexMax[2] = 1.0f;
this->AdjustedTexMax[3] = 1.0f;
this->MaskTextures = new vtkMapMaskTextureId;
this->Scale.clear();
this->Bias.clear();
this->NeedToInitializeResources = false;
this->ShaderCache = 0;
this->FBO = 0;
this->RTTDepthBufferTextureObject = 0;
this->RTTDepthTextureObject = 0;
this->RTTColorTextureObject = 0;
this->RTTDepthTextureType = -1;
this->DPFBO = 0;
this->DPDepthBufferTextureObject = 0;
this->DPColorTextureObject = 0;
}
// Destructor
//--------------------------------------------------------------------------
~vtkInternal()
{
delete [] this->NoiseTextureData;
if (this->NoiseTextureObject)
{
this->NoiseTextureObject->Delete();
this->NoiseTextureObject = NULL;
}
if (this->DepthTextureObject)
{
this->DepthTextureObject->Delete();
this->DepthTextureObject = NULL;
}
if (this->FBO)
{
this->FBO->Delete();
this->FBO = NULL;
}
if (this->RTTDepthBufferTextureObject)
{
this->RTTDepthBufferTextureObject->Delete();
this->RTTDepthBufferTextureObject = NULL;
}
if (this->RTTDepthTextureObject)
{
this->RTTDepthTextureObject->Delete();
this->RTTDepthTextureObject = NULL;
}
if (this->RTTColorTextureObject)
{
this->RTTColorTextureObject->Delete();
this->RTTColorTextureObject = NULL;
}
this->DeleteTransferFunctions();
delete this->MaskTextures;
this->Scale.clear();
this->Bias.clear();
}
// Helper methods
//--------------------------------------------------------------------------
template<typename T>
static void ToFloat(const T& in1, const T& in2, float (&out)[2]);
template<typename T>
static void ToFloat(const T& in1, const T& in2, const T& in3,
float (&out)[3]);
template<typename T>
static void ToFloat(T* in, float* out, int noOfComponents);
template<typename T>
static void ToFloat(T (&in)[3], float (&out)[3]);
template<typename T>
static void ToFloat(T (&in)[2], float (&out)[2]);
template<typename T>
static void ToFloat(T& in, float& out);
template<typename T>
static void ToFloat(T (&in)[4][2], float (&out)[4][2]);
void Initialize(vtkRenderer* ren, vtkVolume* vol,
int noOfComponents, int independentComponents);
bool LoadVolume(vtkRenderer* ren, vtkImageData* imageData,
vtkVolumeProperty* volumeProperty,
vtkDataArray* scalars, int independentComponents);
bool LoadMask(vtkRenderer* ren, vtkImageData* input,
vtkImageData* maskInput, int textureExtent[6],
vtkVolume* volume);
void DeleteTransferFunctions();
void ComputeBounds(vtkImageData* input);
// Update OpenGL volume information
int UpdateVolume(vtkVolumeProperty* volumeProperty);
// Update interpolation to be used for 3D volume
int UpdateInterpolationType(vtkVolumeProperty* volumeProperty);
// Update transfer color function based on the incoming inputs
// and number of scalar components.
int UpdateColorTransferFunction(vtkRenderer* ren,
vtkVolume* vol,
unsigned int component);
// Update opacity transfer function (not gradient opacity)
int UpdateOpacityTransferFunction(vtkRenderer* ren,
vtkVolume* vol,
unsigned int component);
// Update gradient opacity function
int UpdateGradientOpacityTransferFunction(vtkRenderer* ren,
vtkVolume* vol,
unsigned int component);
// Update noise texture (used to reduce rendering artifacts
// specifically banding effects)
void CreateNoiseTexture(vtkRenderer* ren);
// Update depth texture (used for early termination of the ray)
void CaptureDepthTexture(vtkRenderer* ren, vtkVolume* vol);
// Test if camera is inside the volume geometry
bool IsCameraInside(vtkRenderer* ren, vtkVolume* vol);
// Compute transformation from cell texture-coordinates to point texture-coords
// (CTP). Cell data maps correctly to OpenGL cells, point data does not (VTK
// defines points at the cell corners). To set the point data in the center of the
// OpenGL texels, a translation of 0.5 texels is applied, and the range is rescaled
// to the point range.
//
// delta = TextureExtentsMax - TextureExtentsMin;
// min = vec3(0.5) / delta;
// max = (delta - vec3(0.5)) / delta;
// range = max - min
//
// CTP = translation * Scale
// CTP = range.x, 0, 0, min.x
// 0, range.y, 0, min.y
// 0, 0, range.z, min.z
// 0, 0, 0, 1.0
void ComputeCellToPointMatrix();
// Update parameters for lighting that will be used in the shader.
void SetLightingParameters(vtkRenderer* ren,
vtkShaderProgram* prog,
vtkVolume* vol);
// Update the volume geometry
void RenderVolumeGeometry(vtkRenderer* ren,
vtkShaderProgram* prog,
vtkVolume* vol,
vtkImageData* input);
// Update cropping params to shader
void SetCroppingRegions(vtkRenderer* ren, vtkShaderProgram* prog,
vtkVolume* vol);
// Update clipping params to shader
void SetClippingPlanes(vtkRenderer* ren, vtkShaderProgram* prog,
vtkVolume* vol);
// Update the interval of sampling
void UpdateSamplingDistance(vtkImageData *input,
vtkRenderer* ren, vtkVolume* vol);
// Check if the mapper should enter picking mode.
void CheckPickingState(vtkRenderer* ren);
// Configure the vtkHardwareSelector to begin a picking pass.
void BeginPicking(vtkRenderer* ren);
// Update the prop Id if hardware selection is enabled.
void SetPickingId(vtkRenderer* ren);
// Configure the vtkHardwareSelector to end a picking pass.
void EndPicking(vtkRenderer* ren);
// Load OpenGL extensiosn required to grab depth sampler buffer
void LoadRequireDepthTextureExtensions(vtkRenderWindow* renWin);
// Create GL buffers
void CreateBufferObjects();
// Dispose / free GL buffers
void DeleteBufferObjects();
// Convert vtkTextureObject to vtkImageData
void ConvertTextureToImageData(vtkTextureObject* texture,
vtkImageData* output);
// Render to texture for final rendering
void SetupRenderToTexture(vtkRenderer* ren);
void ExitRenderToTexture(vtkRenderer* ren);
// Render to texture for depth pass
void SetupDepthPass(vtkRenderer* ren);
void ExitDepthPass(vtkRenderer* ren);
void ReleaseRenderToTextureGraphicsResources(vtkWindow* win);
void ReleaseDepthPassGraphicsResources(vtkWindow* win);
// Private member variables
//--------------------------------------------------------------------------
vtkOpenGLGPUVolumeRayCastMapper* Parent;
bool ValidTransferFunction;
bool LoadDepthTextureExtensionsSucceeded;
bool CameraWasInsideInLastUpdate;
bool HandleLargeDataTypes;
GLuint CubeVBOId;
GLuint CubeVAOId;
GLuint CubeIndicesId;
int InterpolationType;
vtkTextureObject* VolumeTextureObject;
vtkTextureObject* NoiseTextureObject;
vtkTextureObject* DepthTextureObject;
int TextureWidth;
std::vector<double> Scale;
std::vector<double> Bias;
float* NoiseTextureData;
float ActualSampleDistance;
int LastProjectionParallel;
int Dimensions[3];
int TextureSize[3];
int WindowLowerLeft[2];
int WindowSize[2];
int LastDepthPassWindowSize[2];
int LastRenderToImageWindowSize[2];
double ScalarsRange[4][2];
double LoadedBounds[6];
int Extents[6];
double DatasetStepSize[3];
double CellScale[3];
double CellStep[3];
double CellSpacing[3];
int NumberOfLights;
int LightComplexity;
std::ostringstream ExtensionsStringStream;
vtkOpenGLVolumeRGBTables* RGBTables;
std::map<int, std::string> RGBTablesMap;
vtkOpenGLVolumeOpacityTables* OpacityTables;
std::map<int, std::string> OpacityTablesMap;
vtkOpenGLVolumeRGBTable* Mask1RGBTable;
vtkOpenGLVolumeRGBTable* Mask2RGBTable;
vtkOpenGLVolumeGradientOpacityTables* GradientOpacityTables;
std::map<int, std::string> GradientOpacityTablesMap;
vtkTimeStamp ShaderBuildTime;
vtkNew<vtkMatrix4x4> TextureToDataSetMat;
vtkNew<vtkMatrix4x4> InverseTextureToDataSetMat;
vtkNew<vtkMatrix4x4> InverseProjectionMat;
vtkNew<vtkMatrix4x4> InverseModelViewMat;
vtkNew<vtkMatrix4x4> InverseVolumeMat;
vtkNew<vtkMatrix4x4> TextureToEyeTransposeInverse;
vtkNew<vtkMatrix4x4> TempMatrix1;
vtkNew<vtkMatrix4x4> CellToPointMatrix;
float AdjustedTexMin[4];
float AdjustedTexMax[4];
vtkSmartPointer<vtkPolyData> BBoxPolyData;
vtkMapMaskTextureId* MaskTextures;
vtkVolumeMask* CurrentMask;
vtkTimeStamp InitializationTime;
vtkTimeStamp InputUpdateTime;
vtkTimeStamp VolumeUpdateTime;
vtkTimeStamp ReleaseResourcesTime;
vtkTimeStamp DepthPassTime;
vtkTimeStamp DepthPassSetupTime;
vtkTimeStamp SelectionStateTime;
int CurrentSelectionPass;
bool IsPicking;
bool NeedToInitializeResources;
vtkShaderProgram* ShaderProgram;
vtkOpenGLShaderCache* ShaderCache;
vtkFrameBufferObject2* FBO;
vtkTextureObject* RTTDepthBufferTextureObject;
vtkTextureObject* RTTDepthTextureObject;
vtkTextureObject* RTTColorTextureObject;
int RTTDepthTextureType;
vtkFrameBufferObject2* DPFBO;
vtkTextureObject* DPDepthBufferTextureObject;
vtkTextureObject* DPColorTextureObject;
vtkNew<vtkContourFilter> ContourFilter;
vtkNew<vtkPolyDataMapper> ContourMapper;
vtkNew<vtkActor> ContourActor;
};
//----------------------------------------------------------------------------
template<typename T>
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ToFloat(
const T& in1, const T& in2, float (&out)[2])
{
out[0] = static_cast<float>(in1);
out[1] = static_cast<float>(in2);
}
template<typename T>
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ToFloat(
const T& in1, const T& in2, const T& in3, float (&out)[3])
{
out[0] = static_cast<float>(in1);
out[1] = static_cast<float>(in2);
out[2] = static_cast<float>(in3);
}
//----------------------------------------------------------------------------
template<typename T>
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ToFloat(
T* in, float* out, int noOfComponents)
{
for (int i = 0; i < noOfComponents; ++i)
{
out[i] = static_cast<float>(in[i]);
}
}
//----------------------------------------------------------------------------
template<typename T>
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ToFloat(
T (&in)[3], float (&out)[3])
{
out[0] = static_cast<float>(in[0]);
out[1] = static_cast<float>(in[1]);
out[2] = static_cast<float>(in[2]);
}
//----------------------------------------------------------------------------
template<typename T>
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ToFloat(
T (&in)[2], float (&out)[2])
{
out[0] = static_cast<float>(in[0]);
out[1] = static_cast<float>(in[1]);
}
//----------------------------------------------------------------------------
template<typename T>
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ToFloat(
T& in, float& out)
{
out = static_cast<float>(in);
}
//----------------------------------------------------------------------------
template<typename T>
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ToFloat(
T (&in)[4][2], float (&out)[4][2])
{
out[0][0] = static_cast<float>(in[0][0]);
out[0][1] = static_cast<float>(in[0][1]);
out[1][0] = static_cast<float>(in[1][0]);
out[1][1] = static_cast<float>(in[1][1]);
out[2][0] = static_cast<float>(in[2][0]);
out[2][1] = static_cast<float>(in[2][1]);
out[3][0] = static_cast<float>(in[3][0]);
out[3][1] = static_cast<float>(in[3][1]);
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::Initialize(
vtkRenderer* vtkNotUsed(ren), vtkVolume* vol, int
noOfComponents, int independentComponents)
{
this->DeleteTransferFunctions();
// Create RGB lookup table
if (noOfComponents > 1 && independentComponents)
{
this->RGBTables = new vtkOpenGLVolumeRGBTables(noOfComponents);
}
else
{
this->RGBTables = new vtkOpenGLVolumeRGBTables(1);
}
if (this->Parent->MaskInput != 0 &&
this->Parent->MaskType == LabelMapMaskType)
{
if(this->Mask1RGBTable == NULL)
{
this->Mask1RGBTable = vtkOpenGLVolumeRGBTable::New();
}
if(this->Mask2RGBTable == NULL)
{
this->Mask2RGBTable = vtkOpenGLVolumeRGBTable::New();
}
}
// We support upto four components
if (noOfComponents > 1 && independentComponents)
{
this->OpacityTables = new vtkOpenGLVolumeOpacityTables(noOfComponents);
}
else
{
this->OpacityTables = new vtkOpenGLVolumeOpacityTables(1);
}
if (noOfComponents > 1 && independentComponents)
{
// Assuming that all four components has gradient opacity for now
this->GradientOpacityTables =
new vtkOpenGLVolumeGradientOpacityTables(noOfComponents);
}
else
{
if (vol->GetProperty()->HasGradientOpacity())
{
this->GradientOpacityTables =
new vtkOpenGLVolumeGradientOpacityTables(1);
}
}
this->OpacityTablesMap.clear();
this->RGBTablesMap.clear();
this->GradientOpacityTablesMap.clear();
std::ostringstream numeric;
for (int i = 0; i < noOfComponents; ++i)
{
numeric << i;
if (i > 0)
{
this->OpacityTablesMap[i] = std::string("in_opacityTransferFunc") +
numeric.str();
this->RGBTablesMap[i] = std::string("in_colorTransferFunc") +
numeric.str();
this->GradientOpacityTablesMap[i] = std::string("in_gradientTransferFunc") +
numeric.str();
}
else
{
this->OpacityTablesMap[i] = std::string("in_opacityTransferFunc");
this->RGBTablesMap[i] = std::string("in_colorTransferFunc");
this->GradientOpacityTablesMap[i] = std::string("in_gradientTransferFunc");
}
numeric.str("");
numeric.clear();
}
this->InitializationTime.Modified();
}
//----------------------------------------------------------------------------
bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::LoadVolume(
vtkRenderer* ren,
vtkImageData* imageData,
vtkVolumeProperty* volumeProperty,
vtkDataArray* scalars,
int vtkNotUsed(independentComponents))
{
// Allocate data with internal format and foramt as (GL_RED)
GLint internalFormat = 0;
GLenum format = 0;
GLenum type = 0;
this->HandleLargeDataTypes = false;
int noOfComponents = scalars->GetNumberOfComponents();
if (!this->VolumeTextureObject)
{
this->VolumeTextureObject = vtkTextureObject::New();
}
this->VolumeTextureObject->SetContext(vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
int scalarType = scalars->GetDataType();
// Get the default choices for format from the texture
format = this->VolumeTextureObject->GetDefaultFormat(
scalarType, noOfComponents,false);
internalFormat = this->VolumeTextureObject->GetDefaultInternalFormat(
scalarType, noOfComponents,false);
type = this->VolumeTextureObject->GetDefaultDataType(scalarType);
bool supportsFloat = false;
#if GL_ES_VERSION_2_0 != 1
if (glewIsSupported("GL_ARB_texture_float") ||
vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
supportsFloat = true;
}
#elif GL_ES_VERSION_3_0 == 1
supportsFloat = true;
#endif
// scale and bias
// NP = P*scale + bias
// given two point matcvhes a,b to c,d the fomula
// is scale = (d-c)/(b-a) and
// bias = c - a*scale
// for unsigned/float types c is zero
std::vector<double> bias(noOfComponents, 0.0);
std::vector<double> scale(noOfComponents, 1.0);
double oglScale = 1.0;
double oglBias = 0.0;
switch(scalarType)
{
case VTK_FLOAT:
if (supportsFloat)
{
switch(noOfComponents)
{
case 1:
internalFormat = GL_R16F;
format = GL_RED;
break;
case 2:
internalFormat = GL_RG16F;
format = GL_RG;
break;
case 3:
internalFormat = GL_RGB16F;
format = GL_RGB;
break;
case 4:
internalFormat = GL_RGBA16F;
format = GL_RGBA;
break;
}
}
else
{
switch(noOfComponents)
{
case 1:
internalFormat = GL_RED;
format = GL_RED;
break;
case 2:
internalFormat = GL_RG;
format = GL_RG;
break;
case 3:
internalFormat = GL_RGB;
format = GL_RGB;
break;
case 4:
internalFormat = GL_RGBA;
format = GL_RGBA;
break;
}
}
break;
case VTK_UNSIGNED_CHAR:
oglScale = 1.0 / (VTK_UNSIGNED_CHAR_MAX + 1);
oglBias = 0.0;
break;
case VTK_SIGNED_CHAR:
oglScale = 2.0 / (VTK_UNSIGNED_CHAR_MAX + 1);
oglBias = -1.0 - VTK_SIGNED_CHAR_MIN * oglScale;
break;
case VTK_CHAR:
// not supported
assert("check: impossible case" && 0);
break;
case VTK_BIT:
// not supported
assert("check: impossible case" && 0);
break;
case VTK_ID_TYPE:
// not supported
assert("check: impossible case" && 0);
break;
case VTK_INT:
case VTK_DOUBLE:
case VTK___INT64:
case VTK_LONG:
case VTK_LONG_LONG:
case VTK_UNSIGNED_INT:
case VTK_UNSIGNED___INT64:
case VTK_UNSIGNED_LONG:
case VTK_UNSIGNED_LONG_LONG:
this->HandleLargeDataTypes = true;
type = GL_FLOAT;
switch(noOfComponents)
{
case 1:
if (supportsFloat)
{
internalFormat = GL_R16F;
}
else
{
internalFormat = GL_RED;
}
format = GL_RED;
break;
case 2:
internalFormat = GL_RG;
format = GL_RG;
break;
case 3:
internalFormat = GL_RGB;
format = GL_RGB;
break;
case 4:
internalFormat = GL_RGBA;
format = GL_RGBA;
break;
}
break;
case VTK_SHORT:
oglScale = 2.0 / (VTK_UNSIGNED_SHORT_MAX + 1);
oglBias = -1.0 - VTK_SHORT_MIN * oglScale;
break;
case VTK_STRING:
// not supported
assert("check: impossible case" && 0);
break;
case VTK_UNSIGNED_SHORT:
oglScale = 1.0 / (VTK_UNSIGNED_SHORT_MAX + 1);
oglBias = 0.0;
break;
default:
assert("check: impossible case" && 0);
break;
}
for (int n = 0; n < noOfComponents; ++n)
{
double oglA = this->ScalarsRange[n][0] * oglScale + oglBias;
double oglB = this->ScalarsRange[n][1] * oglScale + oglBias;
scale[n] = 1.0/ (oglB - oglA);
bias[n] = 0.0 - oglA*scale[n];
}
// Update scale and bias
this->Scale = scale;
this->Bias = bias;
// Update texture size
imageData->GetExtent(this->Extents);
if (this->Parent->CellFlag)
{
int i = 1;
while (i < 6)
{
this->Extents[i]--;
i += 2;
}
}
int i = 0;
while(i < 3)
{
this->TextureSize[i] = this->Extents[2*i+1] - this->Extents[2*i] + 1;
++i;
}
this->VolumeTextureObject->SetDataType(type);
this->VolumeTextureObject->SetFormat(format);
this->VolumeTextureObject->SetInternalFormat(internalFormat);
this->UpdateInterpolationType(volumeProperty);
if (!this->HandleLargeDataTypes)
{
void* dataPtr = scalars->GetVoidPointer(0);
this->VolumeTextureObject->Create3DFromRaw(
this->TextureSize[0],
this->TextureSize[1],
this->TextureSize[2],
noOfComponents,
scalarType,
dataPtr);
this->VolumeTextureObject->Activate();
this->VolumeTextureObject->SetWrapS(vtkTextureObject::ClampToEdge);
this->VolumeTextureObject->SetWrapT(vtkTextureObject::ClampToEdge);
this->VolumeTextureObject->SetWrapR(vtkTextureObject::ClampToEdge);
this->VolumeTextureObject->SetMagnificationFilter(this->InterpolationType);
this->VolumeTextureObject->SetMinificationFilter(this->InterpolationType);
this->VolumeTextureObject->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f);
}
else
{
// Convert and send to the GPU, z-slice by z-slice so that we won't allocate
// memory at once.Allocate memory on the GPU (NULL data pointer with the
// right dimensions). Here we are assuming that
// GL_ARB_texture_non_power_of_two is available
this->VolumeTextureObject->Create3DFromRaw(
this->TextureSize[0],
this->TextureSize[1],
this->TextureSize[2],
noOfComponents,
scalarType,
0);
this->VolumeTextureObject->Activate();
this->VolumeTextureObject->SetWrapS(vtkTextureObject::ClampToEdge);
this->VolumeTextureObject->SetWrapT(vtkTextureObject::ClampToEdge);
this->VolumeTextureObject->SetWrapR(vtkTextureObject::ClampToEdge);
this->VolumeTextureObject->SetMagnificationFilter(this->InterpolationType);
this->VolumeTextureObject->SetMinificationFilter(this->InterpolationType);
this->VolumeTextureObject->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f);
// Send the slices one by one to the GPU. We are not sending all of them
// together so as to avoid allocating big data on the GPU which may not
// work if the original dataset is big as well.
vtkFloatArray* sliceArray = vtkFloatArray::New();
sliceArray->SetNumberOfComponents(noOfComponents);
sliceArray->SetNumberOfTuples(this->TextureSize[0] * this->TextureSize[1]);
void* slicePtr = sliceArray->GetVoidPointer(0);
int k = 0;
int kInc = (this->Dimensions[0] - this->Parent->CellFlag) *
(this->Dimensions[1] - this->Parent->CellFlag);
int kOffset = (this->Extents[4] *
(this->Dimensions[1] - this->Parent->CellFlag) +
this->Extents[2]) *
(this->Dimensions[0] - this->Parent->CellFlag) +
this->Extents[0];
float *tupPtr = new float [noOfComponents];
while(k < this->TextureSize[2])
{
int j = 0;
int jOffset = 0;
int jDestOffset = 0;
while(j < this->TextureSize[1])
{
i = 0;
while(i < this->TextureSize[0])
{
double * scalarPtr = scalars->GetTuple(kOffset + jOffset + i);
for (int n = 0; n < noOfComponents; ++n)
{
tupPtr[n] = scalarPtr[n]*scale[n] + bias[n];
}
sliceArray->SetTuple(jDestOffset + i, tupPtr);
++i;
}
++j;
jOffset += this->Dimensions[0] - this->Parent->CellFlag;
jDestOffset += this->TextureSize[0];
}
// Here we are assuming that GL_ARB_texture_non_power_of_two is
// available
glTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, k,
this->TextureSize[0], this->TextureSize[1], 1,
format, type, slicePtr);
++k;
kOffset += kInc;
}
delete [] tupPtr;
sliceArray->Delete();
}
// do not tie up the texture unit unless we are activly using it
// textures can exist without being active
this->VolumeTextureObject->Deactivate();
return 1;
}
//-----------------------------------------------------------------------------
bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::LoadMask(vtkRenderer* ren,
vtkImageData* vtkNotUsed(input), vtkImageData* maskInput,
int textureExtent[6], vtkVolume* vtkNotUsed(volume))
{
bool result = true;
// Mask
if(maskInput != 0)
{
// Find the texture.
std::map<vtkImageData *,vtkVolumeMask*>::iterator it2 =
this->MaskTextures->Map.find(maskInput);
vtkVolumeMask* mask = 0;
if(it2 == this->MaskTextures->Map.end())
{
mask = new vtkVolumeMask();
this->MaskTextures->Map[maskInput] = mask;
}
else
{
mask = (*it2).second;
}
mask->Update(ren,
maskInput,
this->Parent->CellFlag,
textureExtent,
this->Parent->ScalarMode,
this->Parent->ArrayAccessMode,
this->Parent->ArrayId,
this->Parent->ArrayName,
static_cast<vtkIdType>(static_cast<float>(
this->Parent->MaxMemoryInBytes) *
this->Parent->MaxMemoryFraction));
result = result && mask->IsLoaded();
this->CurrentMask = mask;
}
return result;
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::DeleteTransferFunctions()
{
delete this->RGBTables;
this->RGBTables = NULL;
if (this->Mask1RGBTable)
{
this->Mask1RGBTable->Delete();
this->Mask1RGBTable = NULL;
}
if (this->Mask2RGBTable)
{
this->Mask2RGBTable->Delete();
this->Mask2RGBTable = NULL;
}
delete this->OpacityTables;
this->OpacityTables = NULL;
delete this->GradientOpacityTables;
this->GradientOpacityTables = NULL;
if (this->MaskTextures != NULL)
{
if (!this->MaskTextures->Map.empty())
{
std::map<vtkImageData*,vtkVolumeMask*>::iterator it =
this->MaskTextures->Map.begin();
while(it != this->MaskTextures->Map.end())
{
vtkVolumeMask* texture = (*it).second;
delete texture;
++it;
}
this->MaskTextures->Map.clear();
}
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ComputeBounds(
vtkImageData* input)
{
double origin[3];
input->GetSpacing(this->CellSpacing);
input->GetOrigin(origin);
input->GetExtent(this->Extents);
if (this->Parent->CellFlag)
{
int i = 1;
while (i < 6)
{
this->Extents[i]--;
i += 2;
}
}
int swapBounds[3];
swapBounds[0] = (this->CellSpacing[0] < 0);
swapBounds[1] = (this->CellSpacing[1] < 0);
swapBounds[2] = (this->CellSpacing[2] < 0);
// Loaded data represents points
if (!this->Parent->CellFlag)
{
// If spacing is negative, we may have to rethink the equation
// between real point and texture coordinate...
this->LoadedBounds[0] = origin[0] +
static_cast<double>(this->Extents[0 + swapBounds[0]]) *
this->CellSpacing[0];
this->LoadedBounds[2] = origin[1] +
static_cast<double>(this->Extents[2 + swapBounds[1]]) *
this->CellSpacing[1];
this->LoadedBounds[4] = origin[2] +
static_cast<double>(this->Extents[4 + swapBounds[2]]) *
this->CellSpacing[2];
this->LoadedBounds[1] = origin[0] +
static_cast<double>(this->Extents[1 - swapBounds[0]]) *
this->CellSpacing[0];
this->LoadedBounds[3] = origin[1] +
static_cast<double>(this->Extents[3 - swapBounds[1]]) *
this->CellSpacing[1];
this->LoadedBounds[5] = origin[2] +
static_cast<double>(this->Extents[5 - swapBounds[2]]) *
this->CellSpacing[2];
}
// Loaded extents represent cells
else
{
int wholeTextureExtent[6];
input->GetExtent(wholeTextureExtent);
int i = 1;
while (i < 6)
{
wholeTextureExtent[i]--;
i += 2;
}
i = 0;
while (i < 3)
{
if(this->Extents[2 * i] == wholeTextureExtent[2 * i])
{
this->LoadedBounds[2 * i + swapBounds[i]] = origin[i];
}
else
{
this->LoadedBounds[2 * i + swapBounds[i]] = origin[i] +
(static_cast<double>(this->Extents[2 * i]) + 0.5) *
this->CellSpacing[i];
}
if(this->Extents[2 * i + 1] == wholeTextureExtent[2 * i + 1])
{
this->LoadedBounds[2 * i + 1 - swapBounds[i]] = origin[i] +
(static_cast<double>(this->Extents[2 * i + 1]) + 1.0) *
this->CellSpacing[i];
}
else
{
this->LoadedBounds[2 * i + 1-swapBounds[i]] = origin[i] +
(static_cast<double>(this->Extents[2 * i + 1]) + 0.5) *
this->CellSpacing[i];
}
++i;
}
}
}
//----------------------------------------------------------------------------
int vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolume(
vtkVolumeProperty* volumeProperty)
{
if (volumeProperty->GetMTime() > this->VolumeUpdateTime.GetMTime())
{
int interpolationType = this->InterpolationType;
this->UpdateInterpolationType(volumeProperty);
if (interpolationType != this->InterpolationType)
{
this->VolumeTextureObject->Activate();
this->VolumeTextureObject->SetMagnificationFilter(this->InterpolationType);
this->VolumeTextureObject->SetMinificationFilter(this->InterpolationType);
}
}
this->VolumeUpdateTime.Modified();
return 0;
}
//----------------------------------------------------------------------------
int vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateInterpolationType(
vtkVolumeProperty* volumeProperty)
{
if (volumeProperty != NULL)
{
if (volumeProperty->GetInterpolationType() ==
VTK_LINEAR_INTERPOLATION &&
this->InterpolationType != vtkTextureObject::Linear)
{
this->InterpolationType = vtkTextureObject::Linear;
return 0;
}
else if(volumeProperty->GetInterpolationType() ==
VTK_NEAREST_INTERPOLATION &&
this->InterpolationType != vtkTextureObject::Nearest)
{
this->InterpolationType = vtkTextureObject::Nearest;
return 0;
}
else if (volumeProperty->GetInterpolationType() !=
VTK_LINEAR_INTERPOLATION &&
volumeProperty->GetInterpolationType() !=
VTK_NEAREST_INTERPOLATION)
{
std::cerr << "Invalid interpolation type for volume texture"
<< std::endl;
return 1;
}
else
{
// Do nothing
return 0;
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::
UpdateColorTransferFunction(vtkRenderer* ren, vtkVolume* vol,
unsigned int component)
{
// Volume property cannot be null.
vtkVolumeProperty* volumeProperty = vol->GetProperty();
// Build the colormap in a 1D texture.
// 1D RGB-texture=mapping from scalar values to color values
// build the table.
vtkColorTransferFunction* colorTransferFunction =
volumeProperty->GetRGBTransferFunction(component);
// Add points only if its not being added before
if (colorTransferFunction->GetSize() < 1)
{
colorTransferFunction->AddRGBPoint(this->ScalarsRange[component][0],
0.0, 0.0, 0.0);
colorTransferFunction->AddRGBPoint(this->ScalarsRange[component][1],
1.0, 1.0, 1.0);
}
int filterVal =
volumeProperty->GetInterpolationType() == VTK_LINEAR_INTERPOLATION ?
vtkTextureObject::Linear : vtkTextureObject::Nearest;
double scalarRange[2];
for (int i = 0; i < 2; ++i)
{
scalarRange[i] = this->ScalarsRange[component][i];
}
this->RGBTables->GetTable(component)->Update(
volumeProperty->GetRGBTransferFunction(component),
scalarRange,
#if GL_ES_VERSION_2_0 != 1
filterVal,
#else
vtkTextureObject::Nearest,
#endif
vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
if (this->Parent->MaskInput != 0 &&
this->Parent->MaskType == LabelMapMaskType)
{
vtkColorTransferFunction* colorTransferFunc =
volumeProperty->GetRGBTransferFunction(1);
this->Mask1RGBTable->Update(colorTransferFunc, scalarRange,
vtkTextureObject::Nearest,
vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
colorTransferFunc = volumeProperty->GetRGBTransferFunction(2);
this->Mask2RGBTable->Update(colorTransferFunc, scalarRange,
vtkTextureObject::Nearest,
vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
}
return 0;
}
//----------------------------------------------------------------------------
int vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::
UpdateOpacityTransferFunction(vtkRenderer* ren, vtkVolume* vol,
unsigned int component)
{
if (!vol)
{
return 1;
}
vtkVolumeProperty* volumeProperty = vol->GetProperty();
// Transfer function table index based on whether independent / dependent
// components. If dependent, use the first scalar opacity transfer function
unsigned int lookupTableIndex = volumeProperty->GetIndependentComponents() ?
component : 0;
vtkPiecewiseFunction* scalarOpacity =
volumeProperty->GetScalarOpacity(lookupTableIndex);
if (scalarOpacity->GetSize() < 1)
{
scalarOpacity->AddPoint(this->ScalarsRange[component][0], 0.0);
scalarOpacity->AddPoint(this->ScalarsRange[component][1], 0.5);
}
int filterVal =
volumeProperty->GetInterpolationType() == VTK_LINEAR_INTERPOLATION ?
vtkTextureObject::Linear : vtkTextureObject::Nearest;
double scalarRange[2];
for (int i = 0; i < 2; ++i)
{
scalarRange[i] = this->ScalarsRange[component][i];
}
this->OpacityTables->GetTable(lookupTableIndex)->Update(
scalarOpacity,this->Parent->BlendMode,
this->ActualSampleDistance,
scalarRange,
volumeProperty->GetScalarOpacityUnitDistance(component),
#if GL_ES_VERSION_2_0 != 1
filterVal,
#else
vtkTextureObject::Nearest,
#endif
vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
return 0;
}
//----------------------------------------------------------------------------
int vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::
UpdateGradientOpacityTransferFunction(vtkRenderer* ren, vtkVolume* vol,
unsigned int component)
{
if (!vol)
{
return 1;
}
vtkVolumeProperty* volumeProperty = vol->GetProperty();
// Transfer function table index based on whether independent / dependent
// components. If dependent, use the first gradient opacity transfer function
unsigned int lookupTableIndex = volumeProperty->GetIndependentComponents() ?
component : 0;
// TODO Currently we expect the all of the tables will
// be initialized once and if at that time, the gradient
// opacity was not enabled then it is not used later.
if (!volumeProperty->HasGradientOpacity(lookupTableIndex) ||
!this->GradientOpacityTables)
{
return 1;
}
vtkPiecewiseFunction* gradientOpacity =
volumeProperty->GetGradientOpacity(lookupTableIndex);
if (gradientOpacity->GetSize() < 1)
{
gradientOpacity->AddPoint(this->ScalarsRange[component][0], 0.0);
gradientOpacity->AddPoint(this->ScalarsRange[component][1], 0.5);
}
int filterVal =
volumeProperty->GetInterpolationType() == VTK_LINEAR_INTERPOLATION ?
vtkTextureObject::Linear : vtkTextureObject::Nearest;
double scalarRange[2];
for (int i = 0; i < 2; ++i)
{
scalarRange[i] = this->ScalarsRange[component][i];
}
this->GradientOpacityTables->GetTable(lookupTableIndex)->Update(
gradientOpacity,
this->ActualSampleDistance,
scalarRange,
volumeProperty->GetScalarOpacityUnitDistance(component),
#if GL_ES_VERSION_2_0 != 1
filterVal,
#else
vtkTextureObject::Nearest,
#endif
vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
return 0;
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::CreateNoiseTexture(
vtkRenderer* ren)
{
vtkOpenGLRenderWindow* glWindow = vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow());
if (!this->NoiseTextureObject)
{
this->NoiseTextureObject = vtkTextureObject::New();
}
this->NoiseTextureObject->SetContext(glWindow);
bool updateSize = false;
bool useUserSize = this->Parent->NoiseTextureSize[0] > 0 &&
this->Parent->NoiseTextureSize[1] > 0;
if (useUserSize)
{
int const twidth = this->NoiseTextureObject->GetWidth();
int const theight = this->NoiseTextureObject->GetHeight();
updateSize = this->Parent->NoiseTextureSize[0] != twidth ||
this->Parent->NoiseTextureSize[1] != theight;
}
if (!this->NoiseTextureObject->GetHandle() || updateSize ||
this->NoiseTextureObject->GetMTime() < this->Parent->NoiseGenerator->GetMTime())
{
int* winSize = ren->GetRenderWindow()->GetSize();
int sizeX = useUserSize ? this->Parent->NoiseTextureSize[0] : winSize[0];
int sizeY = useUserSize ? this->Parent->NoiseTextureSize[1] : winSize[1];
int const maxSize = vtkTextureObject::GetMaximumTextureSize(glWindow);
if (sizeX > maxSize || sizeY > maxSize)
{
sizeX = vtkMath::Max(sizeX, maxSize);
sizeY = vtkMath::Max(sizeY, maxSize);
}
// Allocate buffer. After controlling for the maximum supported size sizeX/Y
// might have changed, so an additional check is needed.
int const twidth = this->NoiseTextureObject->GetWidth();
int const theight = this->NoiseTextureObject->GetHeight();
bool sizeChanged = sizeX != twidth || sizeY != theight;
if (sizeChanged || !this->NoiseTextureData)
{
delete[] this->NoiseTextureData;
this->NoiseTextureData = NULL;
this->NoiseTextureData = new float[sizeX * sizeY];
}
// Generate jitter noise
if (!this->Parent->NoiseGenerator)
{
// Use default settings
vtkPerlinNoise* perlinNoise = vtkPerlinNoise::New();
perlinNoise->SetPhase(0.0, 0.0, 0.0);
perlinNoise->SetFrequency(sizeX, sizeY, 1.0);
perlinNoise->SetAmplitude(0.5); /* [-n, n] */
this->Parent->NoiseGenerator = perlinNoise;
}
int const bufferSize = sizeX * sizeY;
for (int i = 0; i < bufferSize; i++)
{
int const x = i % sizeX;
int const y = i / sizeY;
this->NoiseTextureData[i] = static_cast<float>(
this->Parent->NoiseGenerator->EvaluateFunction(x, y, 0.0) + 0.1);
}
// Prepare texture
this->NoiseTextureObject->Create2DFromRaw(sizeX, sizeY, 1, VTK_FLOAT,
this->NoiseTextureData);
this->NoiseTextureObject->SetWrapS(vtkTextureObject::Repeat);
this->NoiseTextureObject->SetWrapT(vtkTextureObject::Repeat);
this->NoiseTextureObject->SetMagnificationFilter(vtkTextureObject::Nearest);
this->NoiseTextureObject->SetMinificationFilter(vtkTextureObject::Nearest);
this->NoiseTextureObject->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f);
this->NoiseTextureObject->Modified();
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::CaptureDepthTexture(
vtkRenderer* ren, vtkVolume* vtkNotUsed(vol))
{
// Make sure our render window is the current OpenGL context
ren->GetRenderWindow()->MakeCurrent();
// Load required extensions for grabbing depth sampler buffer
if (!this->LoadDepthTextureExtensionsSucceeded)
{
this->LoadRequireDepthTextureExtensions(ren->GetRenderWindow());
}
// If we can't load the necessary extensions, provide
// feedback on why it failed.
if(!this->LoadDepthTextureExtensionsSucceeded)
{
std::cerr << this->ExtensionsStringStream.str() << std::endl;
return;
}
if (!this->DepthTextureObject)
{
this->DepthTextureObject = vtkTextureObject::New();
}
this->DepthTextureObject->SetContext(vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
if (!this->DepthTextureObject->GetHandle())
{
// First set the parameters
this->DepthTextureObject->SetWrapS(vtkTextureObject::ClampToEdge);
this->DepthTextureObject->SetWrapT(vtkTextureObject::ClampToEdge);
this->DepthTextureObject->SetMagnificationFilter(vtkTextureObject::Linear);
this->DepthTextureObject->SetMinificationFilter(vtkTextureObject::Linear);
this->DepthTextureObject->AllocateDepth(this->WindowSize[0],
this->WindowSize[1],
4);
}
#if GL_ES_VERSION_2_0 != 1
// currently broken on ES
this->DepthTextureObject->CopyFromFrameBuffer(this->WindowLowerLeft[0],
this->WindowLowerLeft[1],
0, 0,
this->WindowSize[0],
this->WindowSize[1]);
#endif
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetLightingParameters(
vtkRenderer* ren, vtkShaderProgram* prog, vtkVolume* vol)
{
if (!ren || !prog || !vol)
{
return;
}
if (vol && !vol->GetProperty()->GetShade())
{
return;
}
prog->SetUniformi("in_twoSidedLighting", ren->GetTwoSidedLighting());
// for lightkit case there are some parameters to set
vtkCamera* cam = ren->GetActiveCamera();
vtkTransform* viewTF = cam->GetModelViewTransformObject();
// Bind some light settings
int numberOfLights = 0;
vtkLightCollection *lc = ren->GetLights();
vtkLight *light;
vtkCollectionSimpleIterator sit;
float lightAmbientColor[6][3];
float lightDiffuseColor[6][3];
float lightSpecularColor[6][3];
float lightDirection[6][3];
for(lc->InitTraversal(sit);
(light = lc->GetNextLight(sit)); )
{
float status = light->GetSwitch();
if (status > 0.0)
{
double* aColor = light->GetAmbientColor();
double* dColor = light->GetDiffuseColor();
double* sColor = light->GetDiffuseColor();
double intensity = light->GetIntensity();
lightAmbientColor[numberOfLights][0] = aColor[0] * intensity;
lightAmbientColor[numberOfLights][1] = aColor[1] * intensity;
lightAmbientColor[numberOfLights][2] = aColor[2] * intensity;
lightDiffuseColor[numberOfLights][0] = dColor[0] * intensity;
lightDiffuseColor[numberOfLights][1] = dColor[1] * intensity;
lightDiffuseColor[numberOfLights][2] = dColor[2] * intensity;
lightSpecularColor[numberOfLights][0] = sColor[0] * intensity;
lightSpecularColor[numberOfLights][1] = sColor[1] * intensity;
lightSpecularColor[numberOfLights][2] = sColor[2] * intensity;
// Get required info from light
double* lfp = light->GetTransformedFocalPoint();
double* lp = light->GetTransformedPosition();
double lightDir[3];
vtkMath::Subtract(lfp, lp, lightDir);
vtkMath::Normalize(lightDir);
double *tDir = viewTF->TransformNormal(lightDir);
lightDirection[numberOfLights][0] = tDir[0];
lightDirection[numberOfLights][1] = tDir[1];
lightDirection[numberOfLights][2] = tDir[2];
numberOfLights++;
}
}
prog->SetUniform3fv("in_lightAmbientColor",
numberOfLights, lightAmbientColor);
prog->SetUniform3fv("in_lightDiffuseColor",
numberOfLights, lightDiffuseColor);
prog->SetUniform3fv("in_lightSpecularColor",
numberOfLights, lightSpecularColor);
prog->SetUniform3fv("in_lightDirection",
numberOfLights, lightDirection);
prog->SetUniformi("in_numberOfLights",
numberOfLights);
// we are done unless we have positional lights
if (this->LightComplexity < 3)
{
return;
}
// if positional lights pass down more parameters
float lightAttenuation[6][3];
float lightPosition[6][3];
float lightConeAngle[6];
float lightExponent[6];
int lightPositional[6];
numberOfLights = 0;
for(lc->InitTraversal(sit);
(light = lc->GetNextLight(sit)); )
{
float status = light->GetSwitch();
if (status > 0.0)
{
double* attn = light->GetAttenuationValues();
lightAttenuation[numberOfLights][0] = attn[0];
lightAttenuation[numberOfLights][1] = attn[1];
lightAttenuation[numberOfLights][2] = attn[2];
lightExponent[numberOfLights] = light->GetExponent();
lightConeAngle[numberOfLights] = light->GetConeAngle();
double* lp = light->GetTransformedPosition();
double* tlp = viewTF->TransformPoint(lp);
lightPosition[numberOfLights][0] = tlp[0];
lightPosition[numberOfLights][1] = tlp[1];
lightPosition[numberOfLights][2] = tlp[2];
lightPositional[numberOfLights] = light->GetPositional();
numberOfLights++;
}
}
prog->SetUniform3fv("in_lightAttenuation", numberOfLights, lightAttenuation);
prog->SetUniform1iv("in_lightPositional", numberOfLights, lightPositional);
prog->SetUniform3fv("in_lightPosition", numberOfLights, lightPosition);
prog->SetUniform1fv("in_lightExponent", numberOfLights, lightExponent);
prog->SetUniform1fv("in_lightConeAngle", numberOfLights, lightConeAngle);
}
//-----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ComputeCellToPointMatrix()
{
this->CellToPointMatrix->Identity();
this->AdjustedTexMin[0] = this->AdjustedTexMin[1] = this->AdjustedTexMin[2] = 0.0f;
this->AdjustedTexMin[3] = 1.0f;
this->AdjustedTexMax[0] = this->AdjustedTexMax[1] = this->AdjustedTexMax[2] = 1.0f;
this->AdjustedTexMax[3] = 1.0f;
if (!this->Parent->CellFlag) // point data
{
float delta[3];
delta[0] = this->Extents[1] - this->Extents[0];
delta[1] = this->Extents[3] - this->Extents[2];
delta[2] = this->Extents[5] - this->Extents[4];
float min[3];
min[0] = 0.5f / delta[0];
min[1] = 0.5f / delta[1];
min[2] = 0.5f / delta[2];
float range[3]; // max - min
range[0] = (delta[0] - 0.5f) / delta[0] - min[0];
range[1] = (delta[1] - 0.5f) / delta[1] - min[1];
range[2] = (delta[2] - 0.5f) / delta[2] - min[2];
this->CellToPointMatrix->SetElement(0, 0, range[0]); // Scale diag
this->CellToPointMatrix->SetElement(1, 1, range[1]);
this->CellToPointMatrix->SetElement(2, 2, range[2]);
this->CellToPointMatrix->SetElement(0, 3, min[0]); // t vector
this->CellToPointMatrix->SetElement(1, 3, min[1]);
this->CellToPointMatrix->SetElement(2, 3, min[2]);
// Adjust limit coordinates for texture access.
float const zeros[4] = {0.0f, 0.0f, 0.0f, 1.0f}; // GL tex min
float const ones[4] = {1.0f, 1.0f, 1.0f, 1.0f}; // GL tex max
this->CellToPointMatrix->MultiplyPoint(zeros, this->AdjustedTexMin);
this->CellToPointMatrix->MultiplyPoint(ones, this->AdjustedTexMax);
}
}
//----------------------------------------------------------------------------
bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::IsCameraInside(
vtkRenderer* ren, vtkVolume* vol)
{
this->TempMatrix1->DeepCopy(vol->GetMatrix());
this->TempMatrix1->Invert();
vtkCamera* cam = ren->GetActiveCamera();
double camWorldRange[2];
double camWorldPos[4];
double camFocalWorldPoint[4];
double camWorldDirection[4];
double camPos[4];
double camPlaneNormal[4];
cam->GetPosition(camWorldPos);
camWorldPos[3] = 1.0;
this->TempMatrix1->MultiplyPoint( camWorldPos, camPos );
cam->GetFocalPoint(camFocalWorldPoint);
camFocalWorldPoint[3]=1.0;
// The range (near/far) must also be transformed
// into the local coordinate system.
camWorldDirection[0] = camFocalWorldPoint[0] - camWorldPos[0];
camWorldDirection[1] = camFocalWorldPoint[1] - camWorldPos[1];
camWorldDirection[2] = camFocalWorldPoint[2] - camWorldPos[2];
camWorldDirection[3] = 0.0;
// Compute the normalized near plane normal
this->TempMatrix1->MultiplyPoint(camWorldDirection, camPlaneNormal);
vtkMath::Normalize(camWorldDirection);
vtkMath::Normalize(camPlaneNormal);
double camNearWorldPoint[4];
double camNearPoint[4];
cam->GetClippingRange(camWorldRange);
camNearWorldPoint[0] = camWorldPos[0] + camWorldRange[0]*camWorldDirection[0];
camNearWorldPoint[1] = camWorldPos[1] + camWorldRange[0]*camWorldDirection[1];
camNearWorldPoint[2] = camWorldPos[2] + camWorldRange[0]*camWorldDirection[2];
camNearWorldPoint[3] = 1.;
this->TempMatrix1->MultiplyPoint( camNearWorldPoint, camNearPoint );
double tolerance[3] = { 1e-12, 1e-12, 1e-12 };
if (vtkMath::PointIsWithinBounds(camNearPoint, this->LoadedBounds, tolerance))
{
return true;
}
return false;
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::RenderVolumeGeometry(
vtkRenderer* ren, vtkShaderProgram* prog,
vtkVolume* vol, vtkImageData* input)
{
if (this->NeedToInitializeResources ||
input->GetMTime() > this->InputUpdateTime.GetMTime() ||
this->IsCameraInside(ren, vol) ||
this->CameraWasInsideInLastUpdate)
{
vtkNew<vtkTessellatedBoxSource> boxSource;
boxSource->SetBounds(this->LoadedBounds);
boxSource->QuadsOn();
boxSource->SetLevel(0);
vtkNew<vtkDensifyPolyData> densityPolyData;
if (input->GetMTime() <= this->InputUpdateTime.GetMTime() &&
this->IsCameraInside(ren, vol))
{
// Normals should be transformed using the transpose of inverse
// InverseVolumeMat
this->TempMatrix1->DeepCopy(vol->GetMatrix());
this->TempMatrix1->Invert();
vtkCamera* cam = ren->GetActiveCamera();
double camWorldRange[2];
double camWorldPos[4];
double camFocalWorldPoint[4];
double camWorldDirection[4];
double camPos[4];
double camPlaneNormal[4];
cam->GetPosition(camWorldPos);
camWorldPos[3] = 1.0;
this->TempMatrix1->MultiplyPoint(camWorldPos, camPos);
cam->GetFocalPoint(camFocalWorldPoint);
camFocalWorldPoint[3]=1.0;
// The range (near/far) must also be transformed
// into the local coordinate system.
camWorldDirection[0] = camFocalWorldPoint[0] - camWorldPos[0];
camWorldDirection[1] = camFocalWorldPoint[1] - camWorldPos[1];
camWorldDirection[2] = camFocalWorldPoint[2] - camWorldPos[2];
camWorldDirection[3] = 0.0;
// Compute the normalized near plane normal
this->TempMatrix1->MultiplyPoint(camWorldDirection, camPlaneNormal);
vtkMath::Normalize(camWorldDirection);
vtkMath::Normalize(camPlaneNormal);
double camNearWorldPoint[4];
double camFarWorldPoint[4];
double camNearPoint[4];
double camFarPoint[4];
cam->GetClippingRange(camWorldRange);
camNearWorldPoint[0] = camWorldPos[0] + camWorldRange[0]*camWorldDirection[0];
camNearWorldPoint[1] = camWorldPos[1] + camWorldRange[0]*camWorldDirection[1];
camNearWorldPoint[2] = camWorldPos[2] + camWorldRange[0]*camWorldDirection[2];
camNearWorldPoint[3] = 1.;
camFarWorldPoint[0] = camWorldPos[0] + camWorldRange[1]*camWorldDirection[0];
camFarWorldPoint[1] = camWorldPos[1] + camWorldRange[1]*camWorldDirection[1];
camFarWorldPoint[2] = camWorldPos[2] + camWorldRange[1]*camWorldDirection[2];
camFarWorldPoint[3] = 1.;
this->TempMatrix1->MultiplyPoint(camNearWorldPoint, camNearPoint);
this->TempMatrix1->MultiplyPoint(camFarWorldPoint, camFarPoint);
vtkNew<vtkPlane> nearPlane;
// We add an offset to the near plane to avoid hardware clipping of the
// near plane due to floating-point precision.
// camPlaneNormal is a unit vector, if the offset is larger than the
// distance between near and far point, it will not work. Hence, we choose
// a fraction of the near-far distance. However, care should be taken
// to avoid hardware clipping in volumes with very small spacing where the
// distance between near and far plane is also very small. In that case,
// a minimum offset is chosen. This is chosen based on the typical
// epsilon values on x86 systems.
double offset = sqrt(vtkMath::Distance2BetweenPoints(
camNearPoint, camFarPoint)) / 1000.0;
// Minimum offset to avoid floating point precision issues for volumes
// with very small spacing
double minOffset = static_cast<double>(
std::numeric_limits<float>::epsilon()) * 1000.0;
offset = offset < minOffset ? minOffset : offset;
camNearPoint[0] += camPlaneNormal[0]*offset;
camNearPoint[1] += camPlaneNormal[1]*offset;
camNearPoint[2] += camPlaneNormal[2]*offset;
nearPlane->SetOrigin( camNearPoint );
nearPlane->SetNormal( camPlaneNormal );
vtkNew<vtkPlaneCollection> planes;
planes->RemoveAllItems();
planes->AddItem(nearPlane.GetPointer());
vtkNew<vtkClipConvexPolyData> clip;
clip->SetInputConnection(boxSource->GetOutputPort());
clip->SetPlanes(planes.GetPointer());
densityPolyData->SetInputConnection(clip->GetOutputPort());
this->CameraWasInsideInLastUpdate = true;
}
else
{
densityPolyData->SetInputConnection(boxSource->GetOutputPort());
this->CameraWasInsideInLastUpdate = false;
}
densityPolyData->SetNumberOfSubdivisions(2);
densityPolyData->Update();
this->BBoxPolyData = vtkSmartPointer<vtkPolyData>::New();
this->BBoxPolyData->ShallowCopy(densityPolyData->GetOutput());
vtkPoints* points = this->BBoxPolyData->GetPoints();
vtkCellArray* cells = this->BBoxPolyData->GetPolys();
vtkNew<vtkUnsignedIntArray> polys;
polys->SetNumberOfComponents(3);
vtkIdType npts;
vtkIdType *pts;
// See if the volume transform is orientation-preserving
// and orient polygons accordingly
vtkMatrix4x4* volMat = vol->GetMatrix();
double det = vtkMath::Determinant3x3(
volMat->GetElement(0, 0), volMat->GetElement(0, 1), volMat->GetElement(0, 2),
volMat->GetElement(1, 0), volMat->GetElement(1, 1), volMat->GetElement(1, 2),
volMat->GetElement(2, 0), volMat->GetElement(2, 1), volMat->GetElement(2, 2));
bool preservesOrientation = det > 0.0;
const vtkIdType indexMap[3] = {
preservesOrientation ? 0 : 2,
1,
preservesOrientation ? 2 : 0
};
while(cells->GetNextCell(npts, pts))
{
polys->InsertNextTuple3(pts[indexMap[0]], pts[indexMap[1]], pts[indexMap[2]]);
}
// Dispose any previously created buffers
this->DeleteBufferObjects();
// Now create new ones
this->CreateBufferObjects();
// TODO: should realy use the built in VAO class
// which handles these apple issues internally
#ifdef __APPLE__
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
#endif
{
glBindVertexArray(this->CubeVAOId);
}
// Pass cube vertices to buffer object memory
glBindBuffer (GL_ARRAY_BUFFER, this->CubeVBOId);
glBufferData (GL_ARRAY_BUFFER, points->GetData()->GetDataSize() *
points->GetData()->GetDataTypeSize(),
points->GetData()->GetVoidPointer(0), GL_STATIC_DRAW);
prog->EnableAttributeArray("in_vertexPos");
prog->UseAttributeArray("in_vertexPos", 0, 0, VTK_FLOAT,
3, vtkShaderProgram::NoNormalize);
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->CubeIndicesId);
glBufferData (GL_ELEMENT_ARRAY_BUFFER, polys->GetDataSize() *
polys->GetDataTypeSize(), polys->GetVoidPointer(0),
GL_STATIC_DRAW);
}
else
{
#ifdef __APPLE__
if (!vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
glBindBuffer (GL_ARRAY_BUFFER, this->CubeVBOId);
prog->EnableAttributeArray("in_vertexPos");
prog->UseAttributeArray("in_vertexPos", 0, 0, VTK_FLOAT,
3, vtkShaderProgram::NoNormalize);
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->CubeIndicesId);
}
else
#endif
{
glBindVertexArray(this->CubeVAOId);
}
}
glDrawElements(GL_TRIANGLES,
this->BBoxPolyData->GetNumberOfCells() * 3,
GL_UNSIGNED_INT, 0);
#ifdef __APPLE__
if (!vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
glBindBuffer (GL_ARRAY_BUFFER, 0);
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0);
}
else
#endif
{
glBindVertexArray(0);
glBindBuffer (GL_ARRAY_BUFFER, 0);
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetCroppingRegions(
vtkRenderer* vtkNotUsed(ren), vtkShaderProgram* prog,
vtkVolume* vtkNotUsed(vol))
{
if (this->Parent->GetCropping())
{
int cropFlags = this->Parent->GetCroppingRegionFlags();
double croppingRegionPlanes[6];
this->Parent->GetCroppingRegionPlanes(croppingRegionPlanes);
// Clamp it
croppingRegionPlanes[0] = croppingRegionPlanes[0] < this->LoadedBounds[0] ?
this->LoadedBounds[0] : croppingRegionPlanes[0];
croppingRegionPlanes[0] = croppingRegionPlanes[0] > this->LoadedBounds[1] ?
this->LoadedBounds[1] : croppingRegionPlanes[0];
croppingRegionPlanes[1] = croppingRegionPlanes[1] < this->LoadedBounds[0] ?
this->LoadedBounds[0] : croppingRegionPlanes[1];
croppingRegionPlanes[1] = croppingRegionPlanes[1] > this->LoadedBounds[1] ?
this->LoadedBounds[1] : croppingRegionPlanes[1];
croppingRegionPlanes[2] = croppingRegionPlanes[2] < this->LoadedBounds[2] ?
this->LoadedBounds[2] : croppingRegionPlanes[2];
croppingRegionPlanes[2] = croppingRegionPlanes[2] > this->LoadedBounds[3] ?
this->LoadedBounds[3] : croppingRegionPlanes[2];
croppingRegionPlanes[3] = croppingRegionPlanes[3] < this->LoadedBounds[2] ?
this->LoadedBounds[2] : croppingRegionPlanes[3];
croppingRegionPlanes[3] = croppingRegionPlanes[3] > this->LoadedBounds[3] ?
this->LoadedBounds[3] : croppingRegionPlanes[3];
croppingRegionPlanes[4] = croppingRegionPlanes[4] < this->LoadedBounds[4] ?
this->LoadedBounds[4] : croppingRegionPlanes[4];
croppingRegionPlanes[4] = croppingRegionPlanes[4] > this->LoadedBounds[5] ?
this->LoadedBounds[5] : croppingRegionPlanes[4];
croppingRegionPlanes[5] = croppingRegionPlanes[5] < this->LoadedBounds[4] ?
this->LoadedBounds[4] : croppingRegionPlanes[5];
croppingRegionPlanes[5] = croppingRegionPlanes[5] > this->LoadedBounds[5] ?
this->LoadedBounds[5] : croppingRegionPlanes[5];
float cropPlanes[6] = { static_cast<float>(croppingRegionPlanes[0]),
static_cast<float>(croppingRegionPlanes[1]),
static_cast<float>(croppingRegionPlanes[2]),
static_cast<float>(croppingRegionPlanes[3]),
static_cast<float>(croppingRegionPlanes[4]),
static_cast<float>(croppingRegionPlanes[5]) };
prog->SetUniform1fv("in_croppingPlanes", 6, cropPlanes);
const int numberOfRegions = 32;
int cropFlagsArray[numberOfRegions];
cropFlagsArray[0] = 0;
int i = 1;
while(cropFlags && i < 32)
{
cropFlagsArray[i] = cropFlags & 1;
cropFlags = cropFlags >> 1;
++i;
}
for (; i < 32; ++i)
{
cropFlagsArray[i] = 0;
}
prog->SetUniform1iv("in_croppingFlags", numberOfRegions, cropFlagsArray);
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetClippingPlanes(
vtkRenderer* vtkNotUsed(ren), vtkShaderProgram* prog,
vtkVolume* vtkNotUsed(vol))
{
if (this->Parent->GetClippingPlanes())
{
std::vector<float> clippingPlanes;
// Currently we don't have any clipping plane
clippingPlanes.push_back(0);
this->Parent->ClippingPlanes->InitTraversal();
vtkPlane* plane;
while ((plane = this->Parent->ClippingPlanes->GetNextItem()))
{
// Planes are in world coordinates
double planeOrigin[3], planeNormal[3];
plane->GetOrigin(planeOrigin);
plane->GetNormal(planeNormal);
clippingPlanes.push_back(planeOrigin[0]);
clippingPlanes.push_back(planeOrigin[1]);
clippingPlanes.push_back(planeOrigin[2]);
clippingPlanes.push_back(planeNormal[0]);
clippingPlanes.push_back(planeNormal[1]);
clippingPlanes.push_back(planeNormal[2]);
}
clippingPlanes[0] = clippingPlanes.size() > 1 ?
static_cast<int>(clippingPlanes.size() - 1): 0;
prog->SetUniform1fv("in_clippingPlanes",
static_cast<int>(clippingPlanes.size()),
&clippingPlanes[0]);
}
}
// -----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::CheckPickingState(vtkRenderer* ren)
{
vtkHardwareSelector* selector = ren->GetSelector();
bool selectorPicking = selector != NULL;
if (selector)
{
// this mapper currently only supports cell picking
selectorPicking &= selector->GetFieldAssociation() == vtkDataObject::FIELD_ASSOCIATION_CELLS;
}
this->IsPicking = selectorPicking || ren->GetRenderWindow()->GetIsPicking();
if (this->IsPicking)
{
// rebuild the shader on every pass
this->SelectionStateTime.Modified();
this->CurrentSelectionPass = selector ? selector->GetCurrentPass() : vtkHardwareSelector::ACTOR_PASS;
}
else if (this->CurrentSelectionPass != vtkHardwareSelector::MIN_KNOWN_PASS - 1)
{
// return to the regular rendering state
this->SelectionStateTime.Modified();
this->CurrentSelectionPass = vtkHardwareSelector::MIN_KNOWN_PASS - 1;
}
}
// -----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::BeginPicking(vtkRenderer* ren)
{
vtkHardwareSelector* selector = ren->GetSelector();
if (selector && this->IsPicking)
{
selector->BeginRenderProp();
if (this->CurrentSelectionPass >= vtkHardwareSelector::ID_LOW24)
{
selector->RenderAttributeId(0);
}
}
}
//------------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetPickingId
(vtkRenderer* ren)
{
float propIdColor[3] = {0.0, 0.0, 0.0};
vtkHardwareSelector* selector = ren->GetSelector();
if (selector && this->IsPicking)
{
// query the selector for the appropriate id
selector->GetPropColorValue(propIdColor);
}
else // RenderWindow is picking
{
unsigned int const idx = ren->GetCurrentPickId();
vtkHardwareSelector::Convert(idx, propIdColor);
}
this->ShaderProgram->SetUniform3f("in_propId", propIdColor);
}
// ---------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::EndPicking(vtkRenderer* ren)
{
vtkHardwareSelector* selector = ren->GetSelector();
if(selector && this->IsPicking)
{
if (this->CurrentSelectionPass >= vtkHardwareSelector::ID_LOW24)
{
// tell the selector the maximum number of cells that the mapper could render
unsigned int const numVoxels = (this->Extents[1] - this->Extents[0]) *
(this->Extents[3] - this->Extents[2]) * (this->Extents[5] - this->Extents[4]);
selector->RenderAttributeId(numVoxels);
}
selector->EndRenderProp();
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateSamplingDistance(
vtkImageData* input, vtkRenderer* vtkNotUsed(ren), vtkVolume* vol)
{
if (!this->Parent->AutoAdjustSampleDistances)
{
if (this->Parent->LockSampleDistanceToInputSpacing)
{
float const d = static_cast<float>(this->Parent->SpacingAdjustedSampleDistance(
this->CellSpacing, this->Extents));
float const sample = this->Parent->SampleDistance;
// ActualSampleDistance will grow proportionally to numVoxels^(1/3) (see
// vtkVolumeMapper.cxx). Until it reaches 1/2 average voxel size when number of
// voxels is 1E6.
this->ActualSampleDistance = (sample / d < 0.999f || sample / d > 1.001f) ?
d : this->Parent->SampleDistance;
return;
}
this->ActualSampleDistance = this->Parent->SampleDistance;
}
else
{
input->GetSpacing(this->CellSpacing);
vtkMatrix4x4* worldToDataset = vol->GetMatrix();
double minWorldSpacing = VTK_DOUBLE_MAX;
int i = 0;
while (i < 3)
{
double tmp = worldToDataset->GetElement(0,i);
double tmp2 = tmp * tmp;
tmp = worldToDataset->GetElement(1,i);
tmp2 += tmp * tmp;
tmp = worldToDataset->GetElement(2,i);
tmp2 += tmp * tmp;
// We use fabs() in case the spacing is negative.
double worldSpacing = fabs(this->CellSpacing[i] * sqrt(tmp2));
if(worldSpacing < minWorldSpacing)
{
minWorldSpacing = worldSpacing;
}
++i;
}
// minWorldSpacing is the optimal sample distance in world space.
// To go faster (reduceFactor<1.0), we multiply this distance
// by 1/reduceFactor.
this->ActualSampleDistance = static_cast<float>(minWorldSpacing);
if (this->Parent->ReductionFactor < 1.0 &&
this->Parent->ReductionFactor != 0.0)
{
this->ActualSampleDistance /=
static_cast<GLfloat>(this->Parent->ReductionFactor);
}
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::
LoadRequireDepthTextureExtensions(vtkRenderWindow* vtkNotUsed(renWin))
{
// Reset the message stream for extensions
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
this->LoadDepthTextureExtensionsSucceeded = true;
return;
}
this->ExtensionsStringStream.str("");
this->ExtensionsStringStream.clear();
#if GL_ES_VERSION_2_0 != 1
// Check for float texture support. This extension became core
// in 3.0
if (!glewIsSupported("GL_ARB_texture_float"))
{
this->ExtensionsStringStream << "Required extension "
<< " GL_ARB_texture_float is not supported";
return;
}
#else
#if GL_ES_VERSION_3_0 != 1
this->ExtensionsStringStream << "Requires ES version 3.0 or later";
return;
#endif
#endif
// NOTE: Support for depth sampler texture made into the core since version
// 1.4 and therefore we are no longer checking for it.
this->LoadDepthTextureExtensionsSucceeded = true;
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::CreateBufferObjects()
{
#ifdef __APPLE__
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
#endif
{
glGenVertexArrays(1, &this->CubeVAOId);
}
glGenBuffers(1, &this->CubeVBOId);
glGenBuffers(1, &this->CubeIndicesId);
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::DeleteBufferObjects()
{
if (this->CubeVBOId)
{
glBindBuffer (GL_ARRAY_BUFFER, this->CubeVBOId);
glDeleteBuffers(1, &this->CubeVBOId);
this->CubeVBOId = 0;
}
if (this->CubeIndicesId)
{
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->CubeIndicesId);
glDeleteBuffers(1, &this->CubeIndicesId);
this->CubeIndicesId = 0;
}
if (this->CubeVAOId)
{
#ifdef __APPLE__
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
#endif
{
glDeleteVertexArrays(1, &this->CubeVAOId);
}
this->CubeVAOId = 0;
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::
ConvertTextureToImageData(vtkTextureObject* texture, vtkImageData* output)
{
if (!texture)
{
return;
}
unsigned int tw = texture->GetWidth();
unsigned int th = texture->GetHeight();
unsigned int tnc = texture->GetComponents();
int tt = texture->GetVTKDataType();
vtkPixelExtent texExt(0U, tw-1U, 0U, th-1U);
int dataExt[6]={0,0, 0,0, 0,0};
texExt.GetData(dataExt);
double dataOrigin[6] = {0, 0, 0, 0, 0, 0};
vtkImageData *id = vtkImageData::New();
id->SetOrigin(dataOrigin);
id->SetDimensions(tw, th, 1);
id->SetExtent(dataExt);
id->AllocateScalars(tt, tnc);
vtkPixelBufferObject *pbo = texture->Download();
vtkPixelTransfer::Blit(texExt,
texExt,
texExt,
texExt,
tnc,
tt,
pbo->MapPackedBuffer(),
tnc,
tt,
id->GetScalarPointer(0, 0, 0));
pbo->UnmapPackedBuffer();
pbo->Delete();
if (!output)
{
output = vtkImageData::New();
}
output->DeepCopy(id);
id->Delete();
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetupRenderToTexture(
vtkRenderer* ren)
{
if (this->Parent->RenderToImage && this->Parent->CurrentPass == RenderPass)
{
if ( (this->LastRenderToImageWindowSize[0] != this->WindowSize[0]) ||
(this->LastRenderToImageWindowSize[1] != this->WindowSize[1]) )
{
this->LastRenderToImageWindowSize[0] = this->WindowSize[0];
this->LastRenderToImageWindowSize[1] = this->WindowSize[1];
this->ReleaseRenderToTextureGraphicsResources(ren->GetRenderWindow());
}
if (!this->FBO)
{
this->FBO = vtkFrameBufferObject2::New();
}
this->FBO->SetContext(vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
this->FBO->Bind(GL_FRAMEBUFFER);
this->FBO->InitializeViewport(this->WindowSize[0], this->WindowSize[1]);
int depthImageScalarType = this->Parent->GetDepthImageScalarType();
bool initDepthTexture = true;
// Re-instantiate the depth texture object if the scalar type requested has
// changed from the last frame
if (this->RTTDepthTextureObject &&
this->RTTDepthTextureType == depthImageScalarType)
{
initDepthTexture = false;
}
if (initDepthTexture)
{
if (this->RTTDepthTextureObject)
{
this->RTTDepthTextureObject->Delete();
this->RTTDepthTextureObject = 0;
}
this->RTTDepthTextureObject = vtkTextureObject::New();
this->RTTDepthTextureObject->SetContext(
vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
this->RTTDepthTextureObject->Create2D(this->WindowSize[0],
this->WindowSize[1], 1,
depthImageScalarType, false);
this->RTTDepthTextureObject->Activate();
this->RTTDepthTextureObject->SetMinificationFilter(
vtkTextureObject::Nearest);
this->RTTDepthTextureObject->SetMagnificationFilter(
vtkTextureObject::Nearest);
this->RTTDepthTextureObject->SetAutoParameters(0);
// Cache the value of the scalar type
this->RTTDepthTextureType = depthImageScalarType;
}
if (!this->RTTColorTextureObject)
{
this->RTTColorTextureObject = vtkTextureObject::New();
this->RTTColorTextureObject->SetContext(
vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
this->RTTColorTextureObject->Create2D(this->WindowSize[0],
this->WindowSize[1], 4,
VTK_UNSIGNED_CHAR, false);
this->RTTColorTextureObject->Activate();
this->RTTColorTextureObject->SetMinificationFilter(
vtkTextureObject::Nearest);
this->RTTColorTextureObject->SetMagnificationFilter(
vtkTextureObject::Nearest);
this->RTTColorTextureObject->SetAutoParameters(0);
}
if (!this->RTTDepthBufferTextureObject)
{
this->RTTDepthBufferTextureObject = vtkTextureObject::New();
this->RTTDepthBufferTextureObject->SetContext(
vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
this->RTTDepthBufferTextureObject->AllocateDepth(
this->WindowSize[0], this->WindowSize[1], vtkTextureObject::Float32);
this->RTTDepthBufferTextureObject->Activate();
this->RTTDepthBufferTextureObject->SetMinificationFilter(
vtkTextureObject::Nearest);
this->RTTDepthBufferTextureObject->SetMagnificationFilter(
vtkTextureObject::Nearest);
this->RTTDepthBufferTextureObject->SetAutoParameters(0);
}
this->FBO->Bind(GL_FRAMEBUFFER);
this->FBO->AddTexDepthAttachment(
GL_DRAW_FRAMEBUFFER,
this->RTTDepthBufferTextureObject->GetHandle());
this->FBO->AddTexColorAttachment(
GL_DRAW_FRAMEBUFFER, 0U,
this->RTTColorTextureObject->GetHandle());
this->FBO->AddTexColorAttachment(
GL_DRAW_FRAMEBUFFER, 1U,
this->RTTDepthTextureObject->GetHandle());
this->FBO->ActivateDrawBuffers(2);
this->FBO->CheckFrameBufferStatus(GL_FRAMEBUFFER);
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ExitRenderToTexture(
vtkRenderer* vtkNotUsed(ren))
{
if (this->Parent->RenderToImage && this->Parent->CurrentPass == RenderPass)
{
this->FBO->RemoveTexDepthAttachment(GL_DRAW_FRAMEBUFFER);
this->FBO->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U);
this->FBO->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U);
this->FBO->DeactivateDrawBuffers();
this->FBO->UnBind(GL_FRAMEBUFFER);
this->RTTDepthBufferTextureObject->Deactivate();
this->RTTColorTextureObject->Deactivate();
this->RTTDepthTextureObject->Deactivate();
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetupDepthPass(
vtkRenderer* ren)
{
if ( (this->LastDepthPassWindowSize[0] != this->WindowSize[0]) ||
(this->LastDepthPassWindowSize[1] != this->WindowSize[1]) )
{
this->LastDepthPassWindowSize[0] = this->WindowSize[0];
this->LastDepthPassWindowSize[1] = this->WindowSize[1];
this->ReleaseDepthPassGraphicsResources(ren->GetRenderWindow());
}
if (!this->DPFBO)
{
this->DPFBO = vtkFrameBufferObject2::New();
}
this->DPFBO->SetContext(vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
this->DPFBO->Bind(GL_FRAMEBUFFER);
this->DPFBO->InitializeViewport(this->WindowSize[0], this->WindowSize[1]);
if (!this->DPDepthBufferTextureObject ||
!this->DPColorTextureObject)
{
this->DPDepthBufferTextureObject = vtkTextureObject::New();
this->DPDepthBufferTextureObject->SetContext(
vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()));
this->DPDepthBufferTextureObject->AllocateDepth(
this->WindowSize[0], this->WindowSize[1], vtkTextureObject::Native);
this->DPDepthBufferTextureObject->Activate();
this->DPDepthBufferTextureObject->SetMinificationFilter(
vtkTextureObject::Nearest);
this->DPDepthBufferTextureObject->SetMagnificationFilter(
vtkTextureObject::Nearest);
this->DPDepthBufferTextureObject->SetAutoParameters(0);
this->DPDepthBufferTextureObject->Bind();
this->DPColorTextureObject = vtkTextureObject::New();
this->DPColorTextureObject->SetContext(
vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow()));
this->DPColorTextureObject->Create2D(this->WindowSize[0],
this->WindowSize[1], 4,
VTK_UNSIGNED_CHAR, false);
this->DPColorTextureObject->Activate();
this->DPColorTextureObject->SetMinificationFilter(
vtkTextureObject::Nearest);
this->DPColorTextureObject->SetMagnificationFilter(
vtkTextureObject::Nearest);
this->DPColorTextureObject->SetAutoParameters(0);
this->DPFBO->AddTexDepthAttachment(
GL_DRAW_FRAMEBUFFER,
this->DPDepthBufferTextureObject->GetHandle());
this->DPFBO->AddTexColorAttachment(
GL_DRAW_FRAMEBUFFER, 0U,
this->DPColorTextureObject->GetHandle());
}
this->DPFBO->ActivateDrawBuffers(1);
this->DPFBO->CheckFrameBufferStatus(GL_FRAMEBUFFER);
// Setup the contour polydata mapper to render to DPFBO
this->ContourMapper->SetInputConnection(
this->ContourFilter->GetOutputPort());
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ExitDepthPass(
vtkRenderer* vtkNotUsed(ren))
{
this->DPFBO->DeactivateDrawBuffers();
this->DPFBO->UnBind(GL_FRAMEBUFFER);
this->DPDepthBufferTextureObject->Deactivate();
this->DPColorTextureObject->Deactivate();
glDisable(GL_DEPTH_TEST);
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal
::ReleaseRenderToTextureGraphicsResources(vtkWindow* win)
{
vtkOpenGLRenderWindow *rwin =
vtkOpenGLRenderWindow::SafeDownCast(win);
if (rwin)
{
if (this->FBO)
{
this->FBO->Delete();
this->FBO = 0;
}
if (this->RTTDepthBufferTextureObject)
{
this->RTTDepthBufferTextureObject->ReleaseGraphicsResources(win);
this->RTTDepthBufferTextureObject->Delete();
this->RTTDepthBufferTextureObject = 0;
}
if (this->RTTDepthTextureObject)
{
this->RTTDepthTextureObject->ReleaseGraphicsResources(win);
this->RTTDepthTextureObject->Delete();
this->RTTDepthTextureObject = 0;
}
if (this->RTTColorTextureObject)
{
this->RTTColorTextureObject->ReleaseGraphicsResources(win);
this->RTTColorTextureObject->Delete();
this->RTTColorTextureObject = 0;
}
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal
::ReleaseDepthPassGraphicsResources(vtkWindow* win)
{
vtkOpenGLRenderWindow *rwin =
vtkOpenGLRenderWindow::SafeDownCast(win);
if (rwin)
{
if (this->DPFBO)
{
this->DPFBO->Delete();
this->DPFBO = 0;
}
if (this->DPDepthBufferTextureObject)
{
this->DPDepthBufferTextureObject->ReleaseGraphicsResources(win);
this->DPDepthBufferTextureObject->Delete();
this->DPDepthBufferTextureObject = 0;
}
if (this->DPColorTextureObject)
{
this->DPColorTextureObject->ReleaseGraphicsResources(win);
this->DPColorTextureObject->Delete();
this->DPColorTextureObject = 0;
}
this->ContourMapper->ReleaseGraphicsResources(win);
}
}
//----------------------------------------------------------------------------
vtkOpenGLGPUVolumeRayCastMapper::vtkOpenGLGPUVolumeRayCastMapper() :
vtkGPUVolumeRayCastMapper()
{
this->Impl = new vtkInternal(this);
this->ReductionFactor = 1.0;
this->CurrentPass = RenderPass;
this->NoiseTextureSize[0] = this->NoiseTextureSize[1] = -1;
this->NoiseGenerator = NULL;
this->ResourceCallback = new vtkOpenGLResourceFreeCallback<vtkOpenGLGPUVolumeRayCastMapper>(this,
&vtkOpenGLGPUVolumeRayCastMapper::ReleaseGraphicsResources);
}
//----------------------------------------------------------------------------
vtkOpenGLGPUVolumeRayCastMapper::~vtkOpenGLGPUVolumeRayCastMapper()
{
if (this->ResourceCallback)
{
this->ResourceCallback->Release();
delete this->ResourceCallback;
this->ResourceCallback = NULL;
}
if (this->NoiseGenerator)
{
this->NoiseGenerator->Delete();
this->NoiseGenerator = NULL;
}
delete this->Impl;
this->Impl = 0;
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ReductionFactor: " << this->ReductionFactor << "\n";
os << indent << "CurrentPass: " << this->CurrentPass << "\n";
}
//----------------------------------------------------------------------------
vtkTextureObject* vtkOpenGLGPUVolumeRayCastMapper::GetDepthTexture()
{
return this->Impl->RTTDepthTextureObject;
}
//----------------------------------------------------------------------------
vtkTextureObject* vtkOpenGLGPUVolumeRayCastMapper::GetColorTexture()
{
return this->Impl->RTTColorTextureObject;
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::GetDepthImage(vtkImageData* output)
{
return this->Impl->ConvertTextureToImageData(
this->Impl->RTTDepthTextureObject, output);
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::GetColorImage(vtkImageData* output)
{
return this->Impl->ConvertTextureToImageData(
this->Impl->RTTColorTextureObject, output);
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::ReleaseGraphicsResources(
vtkWindow *window)
{
if (!this->ResourceCallback->IsReleasing())
{
this->ResourceCallback->Release();
return;
}
this->Impl->DeleteBufferObjects();
if (this->Impl->VolumeTextureObject)
{
this->Impl->VolumeTextureObject->ReleaseGraphicsResources(window);
this->Impl->VolumeTextureObject->Delete();
this->Impl->VolumeTextureObject = 0;
}
if (this->Impl->NoiseTextureObject)
{
this->Impl->NoiseTextureObject->ReleaseGraphicsResources(window);
this->Impl->NoiseTextureObject->Delete();
this->Impl->NoiseTextureObject = 0;
}
if (this->Impl->DepthTextureObject)
{
this->Impl->DepthTextureObject->ReleaseGraphicsResources(window);
this->Impl->DepthTextureObject->Delete();
this->Impl->DepthTextureObject = 0;
}
this->Impl->ReleaseRenderToTextureGraphicsResources(window);
this->Impl->ReleaseDepthPassGraphicsResources(window);
if(this->Impl->MaskTextures != 0)
{
if(!this->Impl->MaskTextures->Map.empty())
{
std::map<vtkImageData*, vtkVolumeMask*>::iterator it =
this->Impl->MaskTextures->Map.begin();
while(it != this->Impl->MaskTextures->Map.end())
{
vtkVolumeMask* texture = (*it).second;
texture->ReleaseGraphicsResources(window);
delete texture;
++it;
}
this->Impl->MaskTextures->Map.clear();
}
}
if(this->Impl->RGBTables)
{
this->Impl->RGBTables->ReleaseGraphicsResources(window);
delete this->Impl->RGBTables;
this->Impl->RGBTables = 0;
}
if(this->Impl->Mask1RGBTable)
{
this->Impl->Mask1RGBTable->ReleaseGraphicsResources(window);
this->Impl->Mask1RGBTable->Delete();
this->Impl->Mask1RGBTable = NULL;
}
if(this->Impl->Mask2RGBTable)
{
this->Impl->Mask2RGBTable->ReleaseGraphicsResources(window);
this->Impl->Mask2RGBTable->Delete();
this->Impl->Mask2RGBTable = NULL;
}
if(this->Impl->OpacityTables)
{
this->Impl->OpacityTables->ReleaseGraphicsResources(window);
delete this->Impl->OpacityTables;
this->Impl->OpacityTables = 0;
}
if (this->Impl->GradientOpacityTables)
{
this->Impl->GradientOpacityTables->ReleaseGraphicsResources(window);
delete this->Impl->GradientOpacityTables;
this->Impl->GradientOpacityTables = 0;
}
this->Impl->ReleaseResourcesTime.Modified();
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::BuildShader(vtkRenderer* ren,
vtkVolume* vol,
int noOfComponents)
{
std::string vertexShader (raycastervs);
std::string fragmentShader (raycasterfs);
// Every volume should have a property (cannot be NULL);
vtkVolumeProperty* volumeProperty = vol->GetProperty();
int independentComponents = volumeProperty->GetIndependentComponents();
if (volumeProperty->GetShade())
{
vtkLightCollection* lc = ren->GetLights();
vtkLight* light;
this->Impl->NumberOfLights = 0;
// Compute light complexity.
vtkCollectionSimpleIterator sit;
for (lc->InitTraversal(sit); (light = lc->GetNextLight(sit)); )
{
float status = light->GetSwitch();
if (status > 0.0)
{
this->Impl->NumberOfLights++;
if (this->Impl->LightComplexity == 0)
{
this->Impl->LightComplexity = 1;
}
}
if (this->Impl->LightComplexity == 1
&& (this->Impl->NumberOfLights > 1
|| light->GetIntensity() != 1.0
|| light->GetLightType() != VTK_LIGHT_TYPE_HEADLIGHT))
{
this->Impl->LightComplexity = 2;
}
if (this->Impl->LightComplexity < 3
&& (light->GetPositional()))
{
this->Impl->LightComplexity = 3;
break;
}
}
}
// Base methods replacements
//--------------------------------------------------------------------------
vertexShader = vtkvolume::replace(
vertexShader,
"//VTK::ComputeClipPos::Impl",
vtkvolume::ComputeClipPositionImplementation(ren, this, vol),
true);
vertexShader = vtkvolume::replace(
vertexShader,
"//VTK::ComputeTextureCoords::Impl",
vtkvolume::ComputeTextureCoordinates(ren, this, vol),
true);
vertexShader = vtkvolume::replace(
vertexShader,
"//VTK::Base::Dec",
vtkvolume::BaseDeclarationVertex(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Base::Dec",
vtkvolume::BaseDeclarationFragment(ren, this, vol, this->Impl->NumberOfLights,
this->Impl->LightComplexity,
vol->GetProperty()->HasGradientOpacity(),
noOfComponents, independentComponents),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Base::Init",
vtkvolume::BaseInit(ren, this, vol, this->Impl->LightComplexity),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Base::Impl",
vtkvolume::BaseImplementation(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Base::Exit",
vtkvolume::BaseExit(ren, this, vol),
true);
// Termination methods replacements
//--------------------------------------------------------------------------
vertexShader = vtkvolume::replace(
vertexShader,
"//VTK::Termination::Dec",
vtkvolume::TerminationDeclarationVertex(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Termination::Dec",
vtkvolume::TerminationDeclarationFragment(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Terminate::Init",
vtkvolume::TerminationInit(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Terminate::Impl",
vtkvolume::TerminationImplementation(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Terminate::Exit",
vtkvolume::TerminationExit(ren, this, vol),
true);
// Shading methods replacements
//--------------------------------------------------------------------------
vertexShader = vtkvolume::replace(
vertexShader,
"//VTK::Shading::Dec",
vtkvolume::ShadingDeclarationVertex(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Shading::Dec",
vtkvolume::ShadingDeclarationFragment(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Shading::Init",
vtkvolume::ShadingInit(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Shading::Impl",
vtkvolume::ShadingImplementation(ren, this, vol, this->MaskInput,
this->Impl->CurrentMask,
this->MaskType, noOfComponents,
independentComponents),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Shading::Exit",
vtkvolume::ShadingExit(ren, this, vol, noOfComponents,
independentComponents),
true);
// Compute methods replacements
//--------------------------------------------------------------------------
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::ComputeOpacity::Dec",
vtkvolume::ComputeOpacityDeclaration(ren, this, vol, noOfComponents,
independentComponents,
this->Impl->OpacityTablesMap),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::ComputeGradient::Dec",
vtkvolume::ComputeGradientDeclaration(ren, this, vol, noOfComponents,
independentComponents,
this->Impl->GradientOpacityTablesMap),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::ComputeColor::Dec",
vtkvolume::ComputeColorDeclaration(ren, this, vol, noOfComponents,
independentComponents,
this->Impl->RGBTablesMap),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::ComputeLighting::Dec",
vtkvolume::ComputeLightingDeclaration(ren, this, vol, noOfComponents,
independentComponents,
this->Impl->NumberOfLights,
this->Impl->LightComplexity),
true);
fragmentShader = vtkvolume::replace(fragmentShader,
"//VTK::ComputeRayDirection::Dec",
vtkvolume::ComputeRayDirectionDeclaration(ren, this, vol,noOfComponents),
true);
// Cropping methods replacements
//--------------------------------------------------------------------------
vertexShader = vtkvolume::replace(
vertexShader,
"//VTK::Cropping::Dec",
vtkvolume::CroppingDeclarationVertex(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Cropping::Dec",
vtkvolume::CroppingDeclarationFragment(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Cropping::Init",
vtkvolume::CroppingInit(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Cropping::Impl",
vtkvolume::CroppingImplementation(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Cropping::Exit",
vtkvolume::CroppingExit(ren, this, vol),
true);
// Clipping methods replacements
//--------------------------------------------------------------------------
vertexShader = vtkvolume::replace(
vertexShader,
"//VTK::Clipping::Dec",
vtkvolume::ClippingDeclarationVertex(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Clipping::Dec",
vtkvolume::ClippingDeclarationFragment(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Clipping::Init",
vtkvolume::ClippingInit(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Clipping::Impl",
vtkvolume::ClippingImplementation(ren, this, vol),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::Clipping::Exit",
vtkvolume::ClippingExit(ren, this, vol),
true);
// Masking methods replacements
//--------------------------------------------------------------------------
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::BinaryMask::Dec",
vtkvolume::BinaryMaskDeclaration(ren, this, vol, this->MaskInput,
this->Impl->CurrentMask,
this->MaskType),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::BinaryMask::Impl",
vtkvolume::BinaryMaskImplementation(ren, this, vol, this->MaskInput,
this->Impl->CurrentMask,
this->MaskType),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::CompositeMask::Dec",
vtkvolume::CompositeMaskDeclarationFragment(
ren, this, vol, this->MaskInput,
this->Impl->CurrentMask,
this->MaskType),
true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::CompositeMask::Impl",
vtkvolume::CompositeMaskImplementation(
ren, this, vol, this->MaskInput,
this->Impl->CurrentMask,
this->MaskType,
noOfComponents),
true);
// Picking replacements
//--------------------------------------------------------------------------
if (this->Impl->CurrentSelectionPass != (vtkHardwareSelector::MIN_KNOWN_PASS - 1))
{
switch(this->Impl->CurrentSelectionPass)
{
case vtkHardwareSelector::ID_LOW24:
fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Exit",
vtkvolume::PickingIdLow24PassExit(ren, this, vol), true);
break;
case vtkHardwareSelector::ID_MID24:
fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Exit",
vtkvolume::PickingIdMid24PassExit(ren, this, vol), true);
break;
default: // ACTOR_PASS, PROCESS_PASS
fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Dec",
vtkvolume::PickingActorPassDeclaration(ren, this, vol), true);
fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Exit",
vtkvolume::PickingActorPassExit(ren, this, vol), true);
break;
}
}
// Render to texture
//--------------------------------------------------------------------------
if (this->RenderToImage)
{
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::RenderToImage::Init",
vtkvolume::RenderToImageInit(
ren, this, vol), true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::RenderToImage::Impl",
vtkvolume::RenderToImageImplementation(
ren, this, vol), true);
fragmentShader = vtkvolume::replace(
fragmentShader,
"//VTK::RenderToImage::Exit",
vtkvolume::RenderToImageExit(
ren, this, vol), true);
}
// Now compile the shader
//--------------------------------------------------------------------------
this->Impl->ShaderProgram = this->Impl->ShaderCache->ReadyShaderProgram(
vertexShader.c_str(), fragmentShader.c_str(), "");
if (!this->Impl->ShaderProgram || !this->Impl->ShaderProgram->GetCompiled())
{
vtkErrorMacro("Shader failed to compile");
}
this->Impl->ShaderBuildTime.Modified();
}
//-----------------------------------------------------------------------------
// Update the reduction factor of the render viewport (this->ReductionFactor)
// according to the time spent in seconds to render the previous frame
// (this->TimeToDraw) and a time in seconds allocated to render the next
// frame (allocatedTime).
// \pre valid_current_reduction_range: this->ReductionFactor>0.0 && this->ReductionFactor<=1.0
// \pre positive_TimeToDraw: this->TimeToDraw>=0.0
// \pre positive_time: allocatedTime>0.0
// \post valid_new_reduction_range: this->ReductionFactor>0.0 && this->ReductionFactor<=1.0
//-----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::ComputeReductionFactor(
double allocatedTime)
{
if ( !this->AutoAdjustSampleDistances )
{
this->ReductionFactor = 1.0 / this->ImageSampleDistance;
return;
}
if ( this->TimeToDraw )
{
double oldFactor = this->ReductionFactor;
double timeToDraw;
if (allocatedTime < 1.0)
{
timeToDraw = this->SmallTimeToDraw;
if ( timeToDraw == 0.0 )
{
timeToDraw = this->BigTimeToDraw/3.0;
}
}
else
{
timeToDraw = this->BigTimeToDraw;
}
// This should be the case when rendering the volume very first time
// 10.0 is an arbitrary value chosen which happen to a large number
// in this context
if ( timeToDraw == 0.0 )
{
timeToDraw = 10.0;
}
double fullTime = timeToDraw / this->ReductionFactor;
double newFactor = allocatedTime / fullTime;
// Compute average factor
this->ReductionFactor = (newFactor + oldFactor)/2.0;
// Discretize reduction factor so that it doesn't cause
// visual artifacts when used to reduce the sample distance
this->ReductionFactor = (this->ReductionFactor > 1.0) ? 1.0 :
(this->ReductionFactor);
if (this->ReductionFactor < 0.20)
{
this->ReductionFactor = 0.10;
}
else if (this->ReductionFactor < 0.50)
{
this->ReductionFactor = 0.20;
}
else if (this->ReductionFactor < 1.0)
{
this->ReductionFactor = 0.50;
}
// Clamp it
if ( 1.0/this->ReductionFactor > this->MaximumImageSampleDistance )
{
this->ReductionFactor = 1.0 / this->MaximumImageSampleDistance;
}
if ( 1.0/this->ReductionFactor < this->MinimumImageSampleDistance )
{
this->ReductionFactor = 1.0 / this->MinimumImageSampleDistance;
}
}
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren,
vtkVolume* vol)
{
vtkOpenGLClearErrorMacro();
this->ResourceCallback->RegisterGraphicsResources(
static_cast<vtkOpenGLRenderWindow *>(ren->GetRenderWindow()));
this->Impl->TempMatrix1->Identity();
this->Impl->NeedToInitializeResources =
(this->Impl->ReleaseResourcesTime.GetMTime() >
this->Impl->InitializationTime.GetMTime());
// Make sure the context is current
vtkOpenGLRenderWindow* renWin =
vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow());
renWin->MakeCurrent();
// Update in_volume first to make sure states are current
vol->Update();
// Get the input
vtkImageData* input = this->GetTransformedInput();
// Get the volume property (must have one)
vtkVolumeProperty* volumeProperty = vol->GetProperty();
// Get the camera
vtkOpenGLCamera* cam = vtkOpenGLCamera::SafeDownCast(ren->GetActiveCamera());
// Check whether we have independent components or not
int independentComponents = volumeProperty->GetIndependentComponents();
// Get window size and corners
ren->GetTiledSizeAndOrigin(
this->Impl->WindowSize, this->Impl->WindowSize + 1,
this->Impl->WindowLowerLeft, this->Impl->WindowLowerLeft + 1);
vtkDataArray* scalars = this->GetScalars(input,
this->ScalarMode,
this->ArrayAccessMode,
this->ArrayId,
this->ArrayName,
this->CellFlag);
// How many components are there?
int noOfComponents = scalars->GetNumberOfComponents();
// Allocate important variables
this->Impl->Bias.resize(noOfComponents, 0.0);
if (this->Impl->NeedToInitializeResources ||
(volumeProperty->GetMTime() >
this->Impl->InitializationTime.GetMTime()))
{
this->Impl->Initialize(ren, vol, noOfComponents,
independentComponents);
}
// Three dependent components are not supported
if ((noOfComponents == 3) && !independentComponents)
{
vtkErrorMacro("Three dependent components are not supported");
}
for (int n = 0; n < noOfComponents; ++n)
{
double* range = scalars->GetRange(n);
for (int i = 0; i < 2; ++i)
{
this->Impl->ScalarsRange[n][i] = range[i];
}
}
// Update the volume if needed
bool volumeModified = false;
if (this->Impl->NeedToInitializeResources ||
(input->GetMTime() > this->Impl->InputUpdateTime.GetMTime()))
{
volumeModified = true;
input->GetDimensions(this->Impl->Dimensions);
// Update bounds, data, and geometry
this->Impl->ComputeBounds(input);
this->Impl->LoadVolume(ren, input, volumeProperty,
scalars, independentComponents);
this->Impl->ComputeCellToPointMatrix();
this->Impl->LoadMask(ren, input, this->MaskInput,
this->Impl->Extents, vol);
}
else
{
this->Impl->UpdateVolume(volumeProperty);
}
// Mask
vtkVolumeMask* mask = 0;
if(this->MaskInput != 0)
{
std::map<vtkImageData *,vtkVolumeMask*>::iterator it2 =
this->Impl->MaskTextures->Map.find(this->MaskInput);
if(it2 == this->Impl->MaskTextures->Map.end())
{
mask=0;
}
else
{
mask=(*it2).second;
}
}
this->Impl->CurrentMask = mask;
this->ComputeReductionFactor(vol->GetAllocatedRenderTime());
this->Impl->UpdateSamplingDistance(input, ren, vol);
// Update the transfer functions
if (independentComponents)
{
for (int i = 0; i < noOfComponents; ++i)
{
this->Impl->UpdateOpacityTransferFunction(ren, vol, i);
this->Impl->UpdateGradientOpacityTransferFunction(ren, vol, i);
this->Impl->UpdateColorTransferFunction(ren, vol, i);
}
}
else
{
if (noOfComponents == 2 || noOfComponents == 4)
{
this->Impl->UpdateOpacityTransferFunction(ren, vol, noOfComponents - 1);
this->Impl->UpdateGradientOpacityTransferFunction(ren, vol,
noOfComponents - 1);
this->Impl->UpdateColorTransferFunction(ren, vol, 0);
}
}
// Update noise sampler texture
if (this->UseJittering)
{
this->Impl->CreateNoiseTexture(ren);
}
// Grab depth sampler buffer (to handle cases when we are rendering geometry
// and in_volume together
this->Impl->CaptureDepthTexture(ren, vol);
// Update sampling distance
int* loadedExtent = input->GetExtent();
this->Impl->CellStep[0] =
(1.0/static_cast<double>(loadedExtent[1] - loadedExtent[0]));
this->Impl->CellStep[1] =
(1.0/static_cast<double>(loadedExtent[3] - loadedExtent[2]));
this->Impl->CellStep[2] =
(1.0/static_cast<double>(loadedExtent[5] -loadedExtent[4]));
this->Impl->CellScale[0] = (this->Impl->LoadedBounds[1] -
this->Impl->LoadedBounds[0]) * 0.5;
this->Impl->CellScale[1] = (this->Impl->LoadedBounds[3] -
this->Impl->LoadedBounds[2]) * 0.5;
this->Impl->CellScale[2] = (this->Impl->LoadedBounds[5] -
this->Impl->LoadedBounds[4]) * 0.5;
this->Impl->DatasetStepSize[0] = 1.0 / (this->Impl->LoadedBounds[1] -
this->Impl->LoadedBounds[0]);
this->Impl->DatasetStepSize[1] = 1.0 / (this->Impl->LoadedBounds[3] -
this->Impl->LoadedBounds[2]);
this->Impl->DatasetStepSize[2] = 1.0 / (this->Impl->LoadedBounds[5] -
this->Impl->LoadedBounds[4]);
// Compute texture to dataset matrix
this->Impl->TextureToDataSetMat->Identity();
this->Impl->TextureToDataSetMat->SetElement(0, 0,
(1.0 / this->Impl->DatasetStepSize[0]));
this->Impl->TextureToDataSetMat->SetElement(1, 1,
(1.0 / this->Impl->DatasetStepSize[1]));
this->Impl->TextureToDataSetMat->SetElement(2, 2,
(1.0 / this->Impl->DatasetStepSize[2]));
this->Impl->TextureToDataSetMat->SetElement(3, 3,
1.0);
this->Impl->TextureToDataSetMat->SetElement(0, 3,
this->Impl->LoadedBounds[0]);
this->Impl->TextureToDataSetMat->SetElement(1, 3,
this->Impl->LoadedBounds[2]);
this->Impl->TextureToDataSetMat->SetElement(2, 3,
this->Impl->LoadedBounds[4]);
this->Impl->ShaderCache = vtkOpenGLRenderWindow::SafeDownCast(
ren->GetRenderWindow())->GetShaderCache();
this->Impl->CheckPickingState(ren);
if (this->UseDepthPass && this->GetBlendMode() ==
vtkVolumeMapper::COMPOSITE_BLEND)
{
this->CurrentPass = DepthPass;
if (this->Impl->NeedToInitializeResources ||
volumeProperty->GetMTime() > this->Impl->DepthPassSetupTime.GetMTime() ||
this->GetMTime() > this->Impl->DepthPassSetupTime.GetMTime() ||
cam->GetParallelProjection() != this->Impl->LastProjectionParallel ||
this->Impl->SelectionStateTime.GetMTime() > this->Impl->ShaderBuildTime.GetMTime())
{
this->Impl->LastProjectionParallel =
cam->GetParallelProjection();
this->Impl->ContourFilter->SetInputData(input);
for (int i = 0; i < this->GetDepthPassContourValues()->GetNumberOfContours(); ++i)
{
this->Impl->ContourFilter->SetValue(i,
this->DepthPassContourValues->GetValue(i));
}
vtkNew<vtkMatrix4x4> newMatrix;
newMatrix->DeepCopy(vol->GetMatrix());
this->Impl->SetupDepthPass(ren);
this->Impl->ContourActor->Render(ren,
this->Impl->ContourMapper.GetPointer());
this->Impl->ExitDepthPass(ren);
this->Impl->DepthPassSetupTime.Modified();
this->Impl->DepthPassTime.Modified();
this->CurrentPass = RenderPass;
this->BuildShader(ren, vol, noOfComponents);
}
else if (cam->GetMTime() > this->Impl->DepthPassTime.GetMTime())
{
this->Impl->SetupDepthPass(ren);
this->Impl->ContourActor->Render(ren,
this->Impl->ContourMapper.GetPointer());
this->Impl->ExitDepthPass(ren);
this->Impl->DepthPassTime.Modified();
this->CurrentPass = RenderPass;
}
// Configure picking begin (changes blending, so needs to be called before
// vtkVolumeStateRAII)
if (this->Impl->IsPicking)
{
this->Impl->BeginPicking(ren);
}
// Set OpenGL states
vtkVolumeStateRAII glState;
if (this->RenderToImage)
{
this->Impl->SetupRenderToTexture(ren);
}
// NOTE: This is a must call or else, multiple viewport
// rendering would not work. We need this primarily because
// FBO set it otherwise.
glViewport(this->Impl->WindowLowerLeft[0],
this->Impl->WindowLowerLeft[1],
this->Impl->WindowSize[0],
this->Impl->WindowSize[1]);
renWin->GetShaderCache()->ReadyShaderProgram(this->Impl->ShaderProgram);
this->Impl->DPDepthBufferTextureObject->Activate();
this->Impl->ShaderProgram->SetUniformi("in_depthPassSampler",
this->Impl->DPDepthBufferTextureObject->GetTextureUnit());
this->DoGPURender(ren, vol, input,
cam, this->Impl->ShaderProgram,
noOfComponents, independentComponents);
this->Impl->DPDepthBufferTextureObject->Deactivate();
}
else
{
// Configure picking begin (changes blending, so needs to be called before
// vtkVolumeStateRAII)
if (this->Impl->IsPicking)
{
this->Impl->BeginPicking(ren);
}
// Set OpenGL states
vtkVolumeStateRAII glState;
// Build shader now
// First get the shader cache from the render window. This is important
// to make sure that shader cache knows the state of various shader programs
// in use.
if (this->Impl->NeedToInitializeResources ||
volumeProperty->GetMTime() >
this->Impl->ShaderBuildTime.GetMTime() ||
this->GetMTime() > this->Impl->ShaderBuildTime.GetMTime() ||
cam->GetParallelProjection() != this->Impl->LastProjectionParallel ||
this->Impl->SelectionStateTime.GetMTime() > this->Impl->ShaderBuildTime.GetMTime())
{
this->Impl->LastProjectionParallel =
cam->GetParallelProjection();
this->BuildShader(ren, vol, noOfComponents);
}
else
{
// Bind the shader
this->Impl->ShaderCache->ReadyShaderProgram(
this->Impl->ShaderProgram);
}
if (this->RenderToImage)
{
this->Impl->SetupRenderToTexture(ren);
this->DoGPURender(ren, vol, input,
cam, this->Impl->ShaderProgram,
noOfComponents, independentComponents);
this->Impl->ExitRenderToTexture(ren);
}
else
{
this->DoGPURender(ren, vol, input,
cam, this->Impl->ShaderProgram,
noOfComponents, independentComponents);
}
}
// Configure picking end
if (this->Impl->IsPicking)
{
this->Impl->EndPicking(ren);
}
if (volumeModified)
{
this->Impl->InputUpdateTime.Modified();
}
glFinish();
}
//----------------------------------------------------------------------------
void vtkOpenGLGPUVolumeRayCastMapper::DoGPURender(vtkRenderer* ren,
vtkVolume* vol,
vtkImageData* input,
vtkOpenGLCamera* cam,
vtkShaderProgram* prog,
int noOfComponents,
int independentComponents)
{
// Temporary variables
float fvalue2[2];
float fvalue3[3];
float fvalue4[4];
vtkVolumeProperty* volumeProperty = vol->GetProperty();
// Bind textures
//--------------------------------------------------------------------------
this->Impl->VolumeTextureObject->Activate();
prog->SetUniformi("in_volume",
this->Impl->VolumeTextureObject->GetTextureUnit());
// Opacity, color, and gradient opacity samplers / textures
int numberOfSamplers = (independentComponents ? noOfComponents : 1);
for (int i = 0; i < numberOfSamplers; ++i)
{
this->Impl->OpacityTables->GetTable(i)->Activate();
prog->SetUniformi(
this->Impl->OpacityTablesMap[i].c_str(),
this->Impl->OpacityTables->GetTable(i)->GetTextureUnit());
if (this->BlendMode != vtkGPUVolumeRayCastMapper::ADDITIVE_BLEND)
{
this->Impl->RGBTables->GetTable(i)->Activate();
prog->SetUniformi(
this->Impl->RGBTablesMap[i].c_str(),
this->Impl->RGBTables->GetTable(i)->GetTextureUnit());
}
if (this->Impl->GradientOpacityTables)
{
this->Impl->GradientOpacityTables->GetTable(i)->Activate();
prog->SetUniformi(
this->Impl->GradientOpacityTablesMap[i].c_str(),
this->Impl->GradientOpacityTables->GetTable(i)->GetTextureUnit());
}
}
if (this->Impl->NoiseTextureObject)
{
this->Impl->NoiseTextureObject->Activate();
prog->SetUniformi("in_noiseSampler",
this->Impl->NoiseTextureObject->GetTextureUnit());
}
// currently broken on ES
#if GL_ES_VERSION_2_0 != 1
this->Impl->DepthTextureObject->Activate();
prog->SetUniformi("in_depthSampler",
this->Impl->DepthTextureObject->GetTextureUnit());
#endif
if (this->Impl->CurrentMask)
{
this->Impl->CurrentMask->Activate();
prog->SetUniformi(
"in_mask", this->Impl->CurrentMask->GetTextureUnit());
}
if(noOfComponents == 1 &&
this->BlendMode != vtkGPUVolumeRayCastMapper::ADDITIVE_BLEND)
{
if (this->MaskInput != 0 && this->MaskType == LabelMapMaskType)
{
this->Impl->Mask1RGBTable->Activate();
prog->SetUniformi("in_mask1",
this->Impl->Mask1RGBTable->GetTextureUnit());
this->Impl->Mask2RGBTable->Activate();
prog->SetUniformi("in_mask2", this->Impl->Mask2RGBTable->GetTextureUnit());
prog->SetUniformf("in_maskBlendFactor", this->MaskBlendFactor);
}
}
// Bind light and material properties
//--------------------------------------------------------------------------
this->Impl->SetLightingParameters(ren, prog, vol);
float ambient[4][3];
float diffuse[4][3];
float specular[4][3];
float specularPower[4];
for (int i = 0; i < numberOfSamplers; ++i)
{
ambient[i][0] = ambient[i][1] = ambient[i][2] =
volumeProperty->GetAmbient(i);
diffuse[i][0] = diffuse[i][1] = diffuse[i][2] =
volumeProperty->GetDiffuse(i);
specular[i][0] = specular[i][1] = specular[i][2] =
volumeProperty->GetSpecular(i);
specularPower[i] = volumeProperty->GetSpecularPower(i);
}
prog->SetUniform3fv("in_ambient", numberOfSamplers, ambient);
prog->SetUniform3fv("in_diffuse", numberOfSamplers, diffuse);
prog->SetUniform3fv("in_specular", numberOfSamplers, specular);
prog->SetUniform1fv("in_shininess", numberOfSamplers, specularPower);
double clippingRange[2];
cam->GetClippingRange(clippingRange);
// Bind matrices
//--------------------------------------------------------------------------
vtkMatrix4x4* glTransformMatrix;
vtkMatrix4x4* modelviewMatrix;
vtkMatrix3x3* normalMatrix;
vtkMatrix4x4* projectionMatrix;
cam->GetKeyMatrices(ren, modelviewMatrix, normalMatrix,
projectionMatrix, glTransformMatrix);
this->Impl->InverseProjectionMat->DeepCopy(projectionMatrix);
this->Impl->InverseProjectionMat->Invert();
prog->SetUniformMatrix("in_projectionMatrix", projectionMatrix);
prog->SetUniformMatrix("in_inverseProjectionMatrix",
this->Impl->InverseProjectionMat.GetPointer());
this->Impl->InverseModelViewMat->DeepCopy(modelviewMatrix);
this->Impl->InverseModelViewMat->Invert();
prog->SetUniformMatrix("in_modelViewMatrix", modelviewMatrix);
prog->SetUniformMatrix("in_inverseModelViewMatrix",
this->Impl->InverseModelViewMat.GetPointer());
this->Impl->TempMatrix1->DeepCopy(vol->GetMatrix());
this->Impl->TempMatrix1->Transpose();
this->Impl->InverseVolumeMat->DeepCopy(this->Impl->TempMatrix1.GetPointer());
this->Impl->InverseVolumeMat->Invert();
prog->SetUniformMatrix("in_volumeMatrix",
this->Impl->TempMatrix1.GetPointer());
prog->SetUniformMatrix("in_inverseVolumeMatrix",
this->Impl->InverseVolumeMat.GetPointer());
this->Impl->TempMatrix1->DeepCopy(this->Impl->TextureToDataSetMat.GetPointer());
this->Impl->TempMatrix1->Transpose();
this->Impl->InverseTextureToDataSetMat->DeepCopy(
this->Impl->TempMatrix1.GetPointer());
this->Impl->InverseTextureToDataSetMat->Invert();
prog->SetUniformMatrix("in_textureDatasetMatrix",
this->Impl->TempMatrix1.GetPointer());
prog->SetUniformMatrix("in_inverseTextureDatasetMatrix",
this->Impl->InverseTextureToDataSetMat.GetPointer());
vtkMatrix4x4::Multiply4x4(this->Impl->TempMatrix1.GetPointer(),
modelviewMatrix,
this->Impl->TextureToEyeTransposeInverse.GetPointer());
vtkMatrix4x4::Multiply4x4(this->Impl->TextureToDataSetMat.GetPointer(),
this->Impl->TextureToEyeTransposeInverse.GetPointer(),
this->Impl->TextureToEyeTransposeInverse.GetPointer());
this->Impl->TextureToEyeTransposeInverse->Invert();
prog->SetUniformMatrix(
"in_texureToEyeIt", this->Impl->TextureToEyeTransposeInverse.GetPointer());
// Bind other misc parameters
//--------------------------------------------------------------------------
if (cam->GetParallelProjection())
{
double dir[4];
cam->GetDirectionOfProjection(dir);
vtkInternal::ToFloat(dir[0], dir[1], dir[2], fvalue3);
prog->SetUniform3fv(
"in_projectionDirection", 1, &fvalue3);
}
// Pass constant uniforms at initialization
prog->SetUniformi("in_noOfComponents", noOfComponents);
prog->SetUniformi("in_independentComponents", independentComponents);
float tscale[4] = {1.0, 1.0, 1.0, 1.0};
float tbias[4] = {0.0, 0.0, 0.0, 0.0};
if (!this->Impl->HandleLargeDataTypes && (noOfComponents == 1 ||
noOfComponents == 2 || independentComponents))
{
for (int i = 0; i < noOfComponents; i++)
{
tscale[i] = this->Impl->Scale[i];
tbias[i] = this->Impl->Bias[i];
}
}
prog->SetUniform4f("in_volume_scale", tscale);
prog->SetUniform4f("in_volume_bias", tbias);
// Step should be dependant on the bounds and not on the texture size
// since we can have non uniform voxel size / spacing / aspect ratio
vtkInternal::ToFloat(this->Impl->CellStep, fvalue3);
prog->SetUniform3fv("in_cellStep", 1, &fvalue3);
vtkInternal::ToFloat(this->Impl->CellScale, fvalue3);
prog->SetUniform3fv("in_cellScale", 1, &fvalue3);
vtkInternal::ToFloat(this->Impl->CellSpacing, fvalue3);
prog->SetUniform3fv("in_cellSpacing", 1, &fvalue3);
prog->SetUniformf("in_sampleDistance", this->Impl->ActualSampleDistance);
float scalarsRange[4][2];
vtkInternal::ToFloat(this->Impl->ScalarsRange, scalarsRange);
prog->SetUniform2fv("in_scalarsRange", 4, scalarsRange);
vtkInternal::ToFloat(cam->GetPosition(), fvalue3, 3);
prog->SetUniform3fv("in_cameraPos", 1, &fvalue3);
vtkInternal::ToFloat(this->Impl->LoadedBounds[0],
this->Impl->LoadedBounds[2],
this->Impl->LoadedBounds[4], fvalue3);
prog->SetUniform3fv("in_volumeExtentsMin", 1, &fvalue3);
vtkInternal::ToFloat(this->Impl->LoadedBounds[1],
this->Impl->LoadedBounds[3],
this->Impl->LoadedBounds[5], fvalue3);
prog->SetUniform3fv("in_volumeExtentsMax", 1, &fvalue3);
vtkInternal::ToFloat(this->Impl->Extents[0],
this->Impl->Extents[2],
this->Impl->Extents[4], fvalue3);
prog->SetUniform3fv("in_textureExtentsMin", 1, &fvalue3);
vtkInternal::ToFloat(this->Impl->Extents[1],
this->Impl->Extents[3],
this->Impl->Extents[5], fvalue3);
prog->SetUniform3fv("in_textureExtentsMax", 1, &fvalue3);
// TODO Take consideration of reduction factor
vtkInternal::ToFloat(this->Impl->WindowLowerLeft, fvalue2);
prog->SetUniform2fv("in_windowLowerLeftCorner", 1, &fvalue2);
vtkInternal::ToFloat(1.0 / this->Impl->WindowSize[0],
1.0 / this->Impl->WindowSize[1], fvalue2);
prog->SetUniform2fv("in_inverseOriginalWindowSize", 1, &fvalue2);
vtkInternal::ToFloat(1.0 / this->Impl->WindowSize[0],
1.0 / this->Impl->WindowSize[1], fvalue2);
prog->SetUniform2fv("in_inverseWindowSize", 1, &fvalue2);
prog->SetUniformi("in_useJittering", this->GetUseJittering());
prog->SetUniformi("in_cellFlag", this->CellFlag);
vtkInternal::ToFloat(this->Impl->AdjustedTexMin[0],
this->Impl->AdjustedTexMin[1],
this->Impl->AdjustedTexMin[2], fvalue3);
prog->SetUniform3fv("in_texMin", 1, &fvalue3);
vtkInternal::ToFloat(this->Impl->AdjustedTexMax[0],
this->Impl->AdjustedTexMax[1],
this->Impl->AdjustedTexMax[2], fvalue3);
prog->SetUniform3fv("in_texMax", 1, &fvalue3);
this->Impl->TempMatrix1->DeepCopy(this->Impl->CellToPointMatrix.GetPointer());
this->Impl->TempMatrix1->Transpose();
prog->SetUniformMatrix("in_cellToPoint", this->Impl->TempMatrix1.GetPointer());
prog->SetUniformi("in_clampDepthToBackface", this->GetClampDepthToBackface());
// Bind cropping
//--------------------------------------------------------------------------
this->Impl->SetCroppingRegions(ren, prog, vol);
// Bind clipping
//--------------------------------------------------------------------------
this->Impl->SetClippingPlanes(ren, prog, vol);
// Bind the prop Id
//--------------------------------------------------------------------------
if (this->Impl->CurrentSelectionPass < vtkHardwareSelector::ID_LOW24)
{
this->Impl->SetPickingId(ren);
}
// Set the scalar range to be considered for average ip blend
//--------------------------------------------------------------------------
double avgRange[2];
this->GetAverageIPScalarRange(avgRange);
if (avgRange[1] < avgRange[0])
{
double tmp = avgRange[1];
avgRange[1] = avgRange[0];
avgRange[0] = tmp;
}
vtkInternal::ToFloat(avgRange[0], avgRange[1], fvalue2);
prog->SetUniform2fv("in_averageIPRange", 1, &fvalue2);
// Finally set the scale and bias for color correction
//--------------------------------------------------------------------------
prog->SetUniformf("in_scale", 1.0 / this->FinalColorWindow);
prog->SetUniformf("in_bias",
(0.5 - (this->FinalColorLevel/this->FinalColorWindow)));
if (noOfComponents > 1 && independentComponents)
{
for (int i = 0; i < noOfComponents; ++i)
{
fvalue4[i] = static_cast<float>(volumeProperty->GetComponentWeight(i));
}
prog->SetUniform4fv("in_componentWeight", 1, &fvalue4);
}
// Render volume geometry to trigger render
//--------------------------------------------------------------------------
this->Impl->RenderVolumeGeometry(ren, prog, vol, input);
// Undo binds and de-activate buffers
//--------------------------------------------------------------------------
this->Impl->VolumeTextureObject->Deactivate();
if (this->Impl->NoiseTextureObject)
{
this->Impl->NoiseTextureObject->Deactivate();
}
this->Impl->DepthTextureObject->Deactivate();
for (int i = 0; i < numberOfSamplers; ++i)
{
this->Impl->OpacityTables->GetTable(i)->Deactivate();
if (this->BlendMode != vtkGPUVolumeRayCastMapper::ADDITIVE_BLEND)
{
this->Impl->RGBTables->GetTable(i)->Deactivate();
}
if (this->Impl->GradientOpacityTables)
{
this->Impl->GradientOpacityTables->GetTable(i)->Deactivate();
}
}
if (this->Impl->CurrentMask)
{
this->Impl->CurrentMask->Deactivate();
}
if(noOfComponents == 1 &&
this->BlendMode != vtkGPUVolumeRayCastMapper::ADDITIVE_BLEND)
{
if (this->MaskInput != 0 && this->MaskType == LabelMapMaskType)
{
this->Impl->Mask1RGBTable->Deactivate();
this->Impl->Mask2RGBTable->Deactivate();
}
}
vtkOpenGLCheckErrorMacro("failed after Render");
}
//----------------------------------------------------------------------------
vtkCxxSetObjectMacro(vtkOpenGLGPUVolumeRayCastMapper, NoiseGenerator,
vtkImplicitFunction);
|
// 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 "net/base/net_errors.h"
#include <errno.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include "base/logging.h"
#include "base/posix/safe_strerror.h"
#include "build/build_config.h"
namespace net {
Error MapSystemError(logging::SystemErrorCode os_error) {
if (os_error != 0)
DVLOG(2) << "Error " << os_error;
// There are numerous posix error codes, but these are the ones we thus far
// find interesting.
switch (os_error) {
case EAGAIN:
#if EWOULDBLOCK != EAGAIN
case EWOULDBLOCK:
#endif
return ERR_IO_PENDING;
case EACCES:
return ERR_ACCESS_DENIED;
case ENETDOWN:
return ERR_INTERNET_DISCONNECTED;
case ETIMEDOUT:
return ERR_TIMED_OUT;
case ECONNRESET:
case ENETRESET: // Related to keep-alive.
case EPIPE:
return ERR_CONNECTION_RESET;
case ECONNABORTED:
return ERR_CONNECTION_ABORTED;
case ECONNREFUSED:
return ERR_CONNECTION_REFUSED;
case EHOSTUNREACH:
case EHOSTDOWN:
case ENETUNREACH:
case EAFNOSUPPORT:
return ERR_ADDRESS_UNREACHABLE;
case EADDRNOTAVAIL:
return ERR_ADDRESS_INVALID;
case EMSGSIZE:
return ERR_MSG_TOO_BIG;
case ENOTCONN:
return ERR_SOCKET_NOT_CONNECTED;
case EISCONN:
return ERR_SOCKET_IS_CONNECTED;
case EINVAL:
return ERR_INVALID_ARGUMENT;
case EADDRINUSE:
return ERR_ADDRESS_IN_USE;
case E2BIG: // Argument list too long.
return ERR_INVALID_ARGUMENT;
case EBADF: // Bad file descriptor.
return ERR_INVALID_HANDLE;
case EBUSY: // Device or resource busy.
return ERR_INSUFFICIENT_RESOURCES;
case ECANCELED: // Operation canceled.
return ERR_ABORTED;
case EDEADLK: // Resource deadlock avoided.
return ERR_INSUFFICIENT_RESOURCES;
case EDQUOT: // Disk quota exceeded.
return ERR_FILE_NO_SPACE;
case EEXIST: // File exists.
return ERR_FILE_EXISTS;
case EFAULT: // Bad address.
return ERR_INVALID_ARGUMENT;
case EFBIG: // File too large.
return ERR_FILE_TOO_BIG;
case EISDIR: // Operation not allowed for a directory.
return ERR_ACCESS_DENIED;
case ENAMETOOLONG: // Filename too long.
return ERR_FILE_PATH_TOO_LONG;
case ENFILE: // Too many open files in system.
return ERR_INSUFFICIENT_RESOURCES;
case ENOBUFS: // No buffer space available.
return ERR_OUT_OF_MEMORY;
case ENODEV: // No such device.
return ERR_INVALID_ARGUMENT;
case ENOENT: // No such file or directory.
return ERR_FILE_NOT_FOUND;
case ENOLCK: // No locks available.
return ERR_INSUFFICIENT_RESOURCES;
case ENOMEM: // Not enough space.
return ERR_OUT_OF_MEMORY;
case ENOSPC: // No space left on device.
return ERR_FILE_NO_SPACE;
case ENOSYS: // Function not implemented.
return ERR_NOT_IMPLEMENTED;
case ENOTDIR: // Not a directory.
return ERR_FILE_NOT_FOUND;
case ENOTSUP: // Operation not supported.
return ERR_NOT_IMPLEMENTED;
case EPERM: // Operation not permitted.
return ERR_ACCESS_DENIED;
case EROFS: // Read-only file system.
return ERR_ACCESS_DENIED;
case ETXTBSY: // Text file busy.
return ERR_ACCESS_DENIED;
case EUSERS: // Too many users.
return ERR_INSUFFICIENT_RESOURCES;
case EMFILE: // Too many open files.
return ERR_INSUFFICIENT_RESOURCES;
#if defined(OS_FUCHSIA)
case EIO:
// MXIO maps all unrecognized errors to EIO. If you see this message then
// consider adding custom error in MXIO for the corresponding error.
DLOG(FATAL) << "EIO was returned by MXIO.";
return ERR_FAILED;
#endif // OS_FUCHSIA
case 0:
return OK;
default:
LOG(WARNING) << "Unknown error " << base::safe_strerror(os_error) << " ("
<< os_error << ") mapped to net::ERR_FAILED";
return ERR_FAILED;
}
}
} // namespace net
|
/* /////////////////////////////////////////////////////////////////////////
* File: stlsoft/smartptr/scoped_handle_borland_.hpp (evolved from MLResPtr.h, ::SynesisStd)
*
* Purpose: scoped_handle - parameterisable RAII class for arbitrary
* resource types; special implementation for Borland.
*
* Created: 1st November 1994
* Updated: 10th August 2009
*
* Thanks to: Maciej Kaniewski, for requesting Borland compatibility (in
* order to use FastFormat and Pantheios)
*
* Home: http://stlsoft.org/
*
* Copyright (c) 1994-2009, Matthew Wilson and Synesis Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name(s) of Matthew Wilson and Synesis Software nor the names of
* any contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* ////////////////////////////////////////////////////////////////////// */
/** \file stlsoft/smartptr/scoped_handle_borland_.hpp
*
* \brief [C++ only] Definition of the stlsoft::scoped_handle smart
* pointer class template
* (\ref group__library__smart_pointers "Smart Pointers" Library).
*/
#ifndef STLSOFT_INCL_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE_BORLAND_
#define STLSOFT_INCL_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE_BORLAND_
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define STLSOFT_VER_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE_BORLAND__MAJOR 6
# define STLSOFT_VER_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE_BORLAND__MINOR 1
# define STLSOFT_VER_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE_BORLAND__REVISION 2
# define STLSOFT_VER_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE_BORLAND__EDIT 670
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* Includes
*/
#ifndef STLSOFT_INCL_STLSOFT_H_STLSOFT
# include <stlsoft/stlsoft.h>
#endif /* !STLSOFT_INCL_STLSOFT_H_STLSOFT */
/* /////////////////////////////////////////////////////////////////////////
* Compatibility
*/
//#if !defined(STLSOFT_COMPILER_IS_MSVC)
#if !defined(STLSOFT_COMPILER_IS_BORLAND)
# error This file is only defined for Borland C/C++ compiler versions
#endif /* compiler */
/* /////////////////////////////////////////////////////////////////////////
* Namespace
*/
#ifndef _STLSOFT_NO_NAMESPACE
namespace stlsoft
{
#endif /* _STLSOFT_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* Helper classes
*/
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define USE_INTERNAL_MEMORY
struct scoped_handle_borland_impl_
{
template <ss_typename_param_k H>
struct function_type
{
public:
typedef H resource_type;
public:
virtual void destroy(resource_type h) = 0;
virtual void release() = 0;
};
struct void_function_type
{
public:
virtual void destroy() = 0;
virtual void release() = 0;
};
/* Template for function of the form
*
* R (cdecl*)(H)
*/
template< ss_typename_param_k H
, ss_typename_param_k R
>
struct cdecl_function_type
: function_type<H>
{
public:
typedef H resource_type;
typedef cdecl_function_type<H, R> class_type;
typedef R (STLSOFT_CDECL* function_type)(H);
private:
cdecl_function_type(function_type fn)
: m_fn(fn)
{}
cdecl_function_type(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy(resource_type h)
{
m_fn(h);
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* R (fastcall*)(H)
*/
template< ss_typename_param_k H
, ss_typename_param_k R
>
struct fastcall_function_type
: function_type<H>
{
public:
typedef H resource_type;
typedef fastcall_function_type<H, R> class_type;
typedef R (STLSOFT_FASTCALL* function_type)(H);
private:
fastcall_function_type(function_type fn)
: m_fn(fn)
{}
fastcall_function_type(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy(resource_type h)
{
m_fn(h);
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* R (stdcall*)(H)
*/
template< ss_typename_param_k H
, ss_typename_param_k R
>
struct stdcall_function_type
: function_type<H>
{
public:
typedef H resource_type;
typedef stdcall_function_type<H, R> class_type;
typedef R (STLSOFT_STDCALL* function_type)(H);
private:
stdcall_function_type(function_type fn)
: m_fn(fn)
{}
stdcall_function_type(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy(resource_type h)
{
m_fn(h);
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* void (cdecl*)(H)
*/
template <ss_typename_param_k H>
struct cdecl_function_type_v
: function_type<H>
{
public:
typedef H resource_type;
typedef cdecl_function_type_v<H> class_type;
typedef void (STLSOFT_CDECL* function_type)(H);
public:
cdecl_function_type_v(function_type fn)
: m_fn(fn)
{}
cdecl_function_type_v(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy(resource_type h)
{
m_fn(h);
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* void (fastcall*)(H)
*/
template <ss_typename_param_k H>
struct fastcall_function_type_v
: function_type<H>
{
public:
typedef H resource_type;
typedef fastcall_function_type_v<H> class_type;
typedef void (STLSOFT_FASTCALL* function_type)(H);
public:
fastcall_function_type_v(function_type fn)
: m_fn(fn)
{}
fastcall_function_type_v(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy(resource_type h)
{
m_fn(h);
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* void (stdcall*)(H)
*/
template <ss_typename_param_k H>
struct stdcall_function_type_v
: function_type<H>
{
public:
typedef H resource_type;
typedef stdcall_function_type_v<H> class_type;
typedef void (STLSOFT_STDCALL* function_type)(H);
public:
stdcall_function_type_v(function_type fn)
: m_fn(fn)
{}
stdcall_function_type_v(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy(resource_type h)
{
m_fn(h);
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* R (cdecl*)(void)
*/
template <ss_typename_param_k R>
struct cdecl_void_function_type
: void_function_type
{
public:
typedef cdecl_void_function_type<R> class_type;
typedef R (STLSOFT_CDECL* function_type)();
private:
cdecl_void_function_type(function_type fn)
: m_fn(fn)
{}
cdecl_void_function_type(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy()
{
m_fn();
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* R (fastcall*)(void)
*/
template <ss_typename_param_k R>
struct fastcall_void_function_type
: void_function_type
{
public:
typedef fastcall_void_function_type<R> class_type;
typedef R (STLSOFT_FASTCALL* function_type)();
private:
fastcall_void_function_type(function_type fn)
: m_fn(fn)
{}
fastcall_void_function_type(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy()
{
m_fn();
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* R (stdcall*)(void)
*/
template <ss_typename_param_k R>
struct stdcall_void_function_type
: void_function_type
{
public:
typedef stdcall_void_function_type<R> class_type;
typedef R (STLSOFT_STDCALL* function_type)();
private:
stdcall_void_function_type(function_type fn)
: m_fn(fn)
{}
stdcall_void_function_type(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy()
{
m_fn();
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* void (cdecl*)(void)
*/
struct cdecl_void_function_type_v
: void_function_type
{
public:
typedef cdecl_void_function_type_v class_type;
typedef void (STLSOFT_CDECL* function_type)();
public:
cdecl_void_function_type_v(function_type fn)
: m_fn(fn)
{}
cdecl_void_function_type_v(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy()
{
m_fn();
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* void (fastcall*)(void)
*/
struct fastcall_void_function_type_v
: void_function_type
{
public:
typedef fastcall_void_function_type_v class_type;
typedef void (STLSOFT_FASTCALL* function_type)();
public:
fastcall_void_function_type_v(function_type fn)
: m_fn(fn)
{}
fastcall_void_function_type_v(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy()
{
m_fn();
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
/* Template for function of the form
*
* void (stdcall*)(void)
*/
struct stdcall_void_function_type_v
: void_function_type
{
public:
typedef stdcall_void_function_type_v class_type;
typedef void (STLSOFT_STDCALL* function_type)();
public:
stdcall_void_function_type_v(function_type fn)
: m_fn(fn)
{}
stdcall_void_function_type_v(class_type const&);
class_type& operator =(class_type const&);
private:
void* operator new(size_t cb, void* p, size_t n)
{
STLSOFT_ASSERT(cb <= n);
#ifdef USE_INTERNAL_MEMORY
return p;
#else /* ? USE_INTERNAL_MEMORY */
return ::operator new(cb);
#endif /* USE_INTERNAL_MEMORY */
}
void operator delete(void* pv)
{
#ifndef USE_INTERNAL_MEMORY
::operator delete(pv);
#else /* ? USE_INTERNAL_MEMORY */
STLSOFT_SUPPRESS_UNUSED(pv);
#endif /* USE_INTERNAL_MEMORY */
}
#ifndef __BORLANDC__
void operator delete(void* pv, void* p, size_t n)
{
operator delete(pv);
}
#endif /* compiler */
public:
static class_type* create(void* p, size_t n, function_type fn)
{
return new(p, n) class_type(fn);
}
public:
virtual void destroy()
{
m_fn();
}
virtual void release()
{
delete this;
}
private:
function_type m_fn;
};
};
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* Classes
*/
template <ss_typename_param_k H>
class scoped_handle
{
public:
typedef H resource_type;
typedef H handle_type;
typedef scoped_handle<H> class_type;
private:
typedef scoped_handle_borland_impl_::function_type<H> function_type;
public: // NOTE: These constants have to be public for the Borland compiler
enum
{
cdecl_function_type_v_size = sizeof(scoped_handle_borland_impl_::cdecl_function_type_v<H>)
, cdecl_function_type_size = sizeof(scoped_handle_borland_impl_::cdecl_function_type<H, int>)
};
public:
#ifdef STLSOFT_CF_CDECL_SUPPORTED
# if !defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT) || \
defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED)
scoped_handle(
resource_type h
, void (STLSOFT_CDECL *fn)(resource_type)
, resource_type hNull = 0
)
: m_handle(h)
, m_hNull(hNull)
, m_fn(scoped_handle_borland_impl_::cdecl_function_type_v<H>::create(&m_bytes, sizeof(m_bytes), fn))
{}
scoped_handle( resource_type* ph
, void (STLSOFT_CDECL *fn)(resource_type*)
, resource_type hNull = 0);
# endif /* !STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT || STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED */
# if defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT)
template <ss_typename_param_k R>
scoped_handle(
resource_type h
, R (STLSOFT_CDECL *fn)(resource_type)
, resource_type hNull = 0
)
: m_handle(h)
, m_hNull(hNull)
, m_fn(scoped_handle_borland_impl_::cdecl_function_type<H, R>::create(&m_bytes, sizeof(m_bytes), fn))
{}
template <ss_typename_param_k R>
scoped_handle( resource_type* ph
, R (STLSOFT_CDECL *fn)(resource_type*)
, resource_type hNull = 0);
# endif /* STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT */
#endif /* STLSOFT_CF_CDECL_SUPPORTED */
#ifdef STLSOFT_CF_FASTCALL_SUPPORTED
# if !defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT) || \
defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED)
scoped_handle( resource_type h
, void (STLSOFT_FASTCALL *fn)(resource_type)
, resource_type hNull = 0)
: m_handle(h)
, m_hNull(hNull)
, m_fn(scoped_handle_borland_impl_::fastcall_function_type_v<H>::create(&m_bytes, sizeof(m_bytes), fn))
{}
scoped_handle( resource_type h
, void (STLSOFT_FASTCALL *fn)(resource_type *)
, resource_type hNull = 0);
# endif /* !STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT || STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED */
# if defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT)
template <ss_typename_param_k R>
scoped_handle( resource_type h
, R (STLSOFT_FASTCALL *fn)(resource_type)
, resource_type hNull = 0)
: m_handle(h)
, m_hNull(hNull)
, m_fn(scoped_handle_borland_impl_::fastcall_function_type<H, R>::create(&m_bytes, sizeof(m_bytes), fn))
{}
template <ss_typename_param_k R>
scoped_handle( resource_type* ph
, R (STLSOFT_FASTCALL *fn)(resource_type*)
, resource_type hNull = 0);
# endif /* STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT */
#endif /* STLSOFT_CF_FASTCALL_SUPPORTED */
#ifdef STLSOFT_CF_STDCALL_SUPPORTED
# if !defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT) || \
defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED)
scoped_handle( resource_type h
, void (STLSOFT_STDCALL *fn)(resource_type)
, resource_type hNull = 0)
: m_handle(h)
, m_hNull(hNull)
, m_fn(scoped_handle_borland_impl_::stdcall_function_type_v<H>::create(&m_bytes, sizeof(m_bytes), fn))
{}
scoped_handle( resource_type *ph
, void (STLSOFT_STDCALL *fn)(resource_type*)
, resource_type hNull = 0);
# endif /* !STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT || STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED */
# if defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT)
template <ss_typename_param_k R>
scoped_handle( resource_type h
, R (STLSOFT_STDCALL *fn)(resource_type)
, resource_type hNull = 0)
: m_handle(h)
, m_hNull(hNull)
, m_fn(scoped_handle_borland_impl_::stdcall_function_type<H, R>::create(&m_bytes, sizeof(m_bytes), fn))
{}
template <ss_typename_param_k R>
scoped_handle( resource_type* ph
, R (STLSOFT_STDCALL *fn)(resource_type*)
, resource_type hNull = 0);
# endif /* STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT */
#endif /* STLSOFT_CF_STDCALL_SUPPORTED */
~scoped_handle()
{
STLSOFT_MESSAGE_ASSERT("Invariant violation: function pointer must not be NULL", NULL != m_fn);
if(!empty())
{
m_fn->destroy(m_handle);
}
m_fn->release();
}
public:
bool empty() const
{
STLSOFT_MESSAGE_ASSERT("Invariant violation: function pointer must not be NULL", NULL != m_fn);
return get_null_value_() == m_handle;
}
public:
void close()
{
STLSOFT_MESSAGE_ASSERT("Invariant violation: function pointer must not be NULL", NULL != m_fn);
if(!empty())
{
m_fn->destroy(m_handle);
m_handle = get_null_value_();
}
}
resource_type detach()
{
STLSOFT_MESSAGE_ASSERT("Invariant violation: function pointer must not be NULL", NULL != m_fn);
resource_type h = m_handle;
m_handle = get_null_value_();
return h;
}
public:
resource_type handle() const
{
return m_handle;
}
resource_type get() const
{
return m_handle;
}
private:
resource_type get_null_value_() const
{
return m_hNull;
}
private:
handle_type m_handle;
const resource_type m_hNull;
function_type* const m_fn;
union
{
long double ld;
#if !defined(STLSOFT_COMPILER_IS_BORLAND) || \
__BORLANDC__ > 0x0560
ss_byte_t cdecl_R[cdecl_function_type_size];
#endif /* compiler */
} m_bytes;
private:
scoped_handle(class_type const&);
class_type& operator =(class_type const&);
};
STLSOFT_TEMPLATE_SPECIALISATION
class scoped_handle<void>
{
public:
typedef void resource_type;
typedef void handle_type;
typedef scoped_handle<void> class_type;
private:
typedef scoped_handle_borland_impl_::void_function_type function_type;
public:
enum
{
cdecl_function_type_size = sizeof(function_type)
};
public:
#ifdef STLSOFT_CF_CDECL_SUPPORTED
# if !defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT) || \
defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED)
scoped_handle( void (STLSOFT_CDECL *fn)())
: m_bInvoked(false)
, m_fn(scoped_handle_borland_impl_::cdecl_void_function_type_v::create(&m_bytes, sizeof(m_bytes), fn))
{}
# endif /* !STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT || STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED */
# if defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT)
template <ss_typename_param_k R>
scoped_handle( R (STLSOFT_CDECL *fn)())
: m_bInvoked(false)
, m_fn(scoped_handle_borland_impl_::cdecl_void_function_type<R>::create(&m_bytes, sizeof(m_bytes), fn))
{}
# endif /* STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT */
#endif /* STLSOFT_CF_CDECL_SUPPORTED */
#ifdef STLSOFT_CF_FASTCALL_SUPPORTED
# if !defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT) || \
defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED)
scoped_handle( void (STLSOFT_FASTCALL *fn)())
: m_bInvoked(false)
, m_fn(scoped_handle_borland_impl_::fastcall_void_function_type_v::create(&m_bytes, sizeof(m_bytes), fn))
{}
# endif /* !STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT || STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED */
# if defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT)
template <ss_typename_param_k R>
scoped_handle( R (STLSOFT_FASTCALL *fn)())
: m_bInvoked(false)
, m_fn(scoped_handle_borland_impl_::fastcall_void_function_type<R>::create(&m_bytes, sizeof(m_bytes), fn))
{}
# endif /* STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT */
#endif /* STLSOFT_CF_FASTCALL_SUPPORTED */
#ifdef STLSOFT_CF_STDCALL_SUPPORTED
# if !defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT) || \
defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED)
scoped_handle( void (STLSOFT_STDCALL *fn)())
: m_bInvoked(false)
, m_fn(scoped_handle_borland_impl_::stdcall_void_function_type_v::create(&m_bytes, sizeof(m_bytes), fn))
{}
# endif /* !STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT || STLSOFT_CF_MEMBER_TEMPLATE_CTOR_OVERLOAD_DISCRIMINATED */
# if defined(STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT)
template <ss_typename_param_k R>
scoped_handle( R (STLSOFT_STDCALL *fn)())
: m_bInvoked(false)
, m_fn(scoped_handle_borland_impl_::stdcall_void_function_type<R>::create(&m_bytes, sizeof(m_bytes), fn))
{}
# endif /* STLSOFT_CF_MEMBER_TEMPLATE_CTOR_SUPPORT */
#endif /* STLSOFT_CF_STDCALL_SUPPORTED */
~scoped_handle()
{
close();
}
public:
bool empty() const
{
return m_bInvoked;
}
public:
void close()
{
if(!empty())
{
m_fn->destroy();
m_bInvoked = true;
}
}
resource_type detach()
{
m_bInvoked = true;
}
public:
resource_type handle() const
{
}
resource_type get() const
{
}
private:
ss_bool_t m_bInvoked;
function_type* const m_fn;
union
{
long double ld;
ss_byte_t cdecl_R[cdecl_function_type_size];
} m_bytes;
private:
scoped_handle(class_type const&);
class_type& operator =(class_type const&);
};
/* /////////////////////////////////////////////////////////////////////////
* swapping
*/
template< ss_typename_param_k H
>
inline void swap(scoped_handle<H>& lhs, scoped_handle<H>& rhs)
{
lhs.swap(rhs);
}
////////////////////////////////////////////////////////////////////////////
// Shims
template<ss_typename_param_k H>
#if defined(STLSOFT_COMPILER_IS_WATCOM)
inline H get_handle(scoped_handle<H> const& h)
#else /* ? compiler */
inline ss_typename_type_ret_k scoped_handle<H>::handle_type get_handle(scoped_handle<H> const& h)
#endif /* compiler */
{
return h.get();
}
/* /////////////////////////////////////////////////////////////////////////
* Unit-testing
*/
#ifdef STLSOFT_UNITTEST
# include "./unittest/scoped_handle_unittest_.h"
#endif /* STLSOFT_UNITTEST */
/* ////////////////////////////////////////////////////////////////////// */
#ifndef _STLSOFT_NO_NAMESPACE
} // namespace stlsoft
#endif /* _STLSOFT_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* Compiler warnings
*/
/* ////////////////////////////////////////////////////////////////////// */
#endif /* !STLSOFT_INCL_STLSOFT_SMARTPTR_HPP_SCOPED_HANDLE_BORLAND_ */
/* ///////////////////////////// end of file //////////////////////////// */
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoingui.h"
#include "bitcoinunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "miner.h"
#include "networkstyle.h"
#include "notificator.h"
#include "openuridialog.h"
#include "optionsdialog.h"
#include "optionsmodel.h"
#include "rpcconsole.h"
#include "utilitydialog.h"
#ifdef ENABLE_WALLET
#include "blockexplorer.h"
#include "walletframe.h"
#include "walletmodel.h"
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include "init.h"
#include "masternodelist.h"
#include "ui_interface.h"
#include "util.h"
#include <iostream>
#include <QAction>
#include <QApplication>
#include <QDateTime>
#include <QDesktopWidget>
#include <QDragEnterEvent>
#include <QIcon>
#include <QListWidget>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressBar>
#include <QProgressDialog>
#include <QSettings>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QTimer>
#include <QToolBar>
#include <QVBoxLayout>
#if QT_VERSION < 0x050000
#include <QTextDocument>
#include <QUrl>
#else
#include <QUrlQuery>
#endif
const QString BitcoinGUI::DEFAULT_WALLET = "~Default";
BitcoinGUI::BitcoinGUI(const NetworkStyle* networkStyle, QWidget* parent) : QMainWindow(parent),
clientModel(0),
walletFrame(0),
unitDisplayControl(0),
labelStakingIcon(0),
labelEncryptionIcon(0),
labelTorIcon(0),
labelConnectionsIcon(0),
labelBlocksIcon(0),
progressBarLabel(0),
progressBar(0),
progressDialog(0),
appMenuBar(0),
overviewAction(0),
historyAction(0),
masternodeAction(0),
quitAction(0),
sendCoinsAction(0),
usedSendingAddressesAction(0),
usedReceivingAddressesAction(0),
signMessageAction(0),
verifyMessageAction(0),
bip38ToolAction(0),
multisigCreateAction(0),
multisigSpendAction(0),
multisigSignAction(0),
aboutAction(0),
receiveCoinsAction(0),
privacyAction(0),
optionsAction(0),
toggleHideAction(0),
encryptWalletAction(0),
backupWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
openRPCConsoleAction(0),
openAction(0),
showHelpMessageAction(0),
multiSendAction(0),
trayIcon(0),
trayIconMenu(0),
notificator(0),
rpcConsole(0),
explorerWindow(0),
prevBlocks(0),
spinnerFrame(0)
{
/* Open CSS when configured */
this->setStyleSheet(GUIUtil::loadStyleSheet());
GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this);
QString windowTitle = tr("Icolcoin Core") + " - ";
#ifdef ENABLE_WALLET
/* if compiled with wallet support, -disablewallet can still disable the wallet */
enableWallet = !GetBoolArg("-disablewallet", false);
#else
enableWallet = false;
#endif // ENABLE_WALLET
if (enableWallet) {
windowTitle += tr("Wallet");
} else {
windowTitle += tr("Node");
}
QString userWindowTitle = QString::fromStdString(GetArg("-windowtitle", ""));
if (!userWindowTitle.isEmpty()) windowTitle += " - " + userWindowTitle;
windowTitle += " " + networkStyle->getTitleAddText();
#ifndef Q_OS_MAC
QApplication::setWindowIcon(networkStyle->getAppIcon());
setWindowIcon(networkStyle->getAppIcon());
#else
MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon());
#endif
setWindowTitle(windowTitle);
#if defined(Q_OS_MAC) && QT_VERSION < 0x050000
// This property is not implemented in Qt 5. Setting it has no effect.
// A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras.
setUnifiedTitleAndToolBarOnMac(true);
#endif
rpcConsole = new RPCConsole(enableWallet ? this : 0);
#ifdef ENABLE_WALLET
if (enableWallet) {
/** Create wallet frame*/
walletFrame = new WalletFrame(this);
explorerWindow = new BlockExplorer(this);
} else
#endif // ENABLE_WALLET
{
/* When compiled without wallet or -disablewallet is provided,
* the central widget is the rpc console.
*/
setCentralWidget(rpcConsole);
}
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions(networkStyle);
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
createTrayIcon(networkStyle);
// Create status bar
statusBar();
// Status bar notification icons
QFrame* frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0, 0, 0, 0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout* frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3, 0, 3, 0);
frameBlocksLayout->setSpacing(3);
unitDisplayControl = new UnitDisplayStatusBarControl();
labelStakingIcon = new QLabel();
labelAutoMintIcon = new QPushButton();
labelAutoMintIcon->setObjectName("labelAutoMintIcon");
labelAutoMintIcon->setFlat(true); // Make the button look like a label, but clickable
labelAutoMintIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}");
labelAutoMintIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelEncryptionIcon = new QPushButton();
labelEncryptionIcon->setObjectName("labelEncryptionIcon");
labelEncryptionIcon->setFlat(true); // Make the button look like a label, but clickable
labelEncryptionIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}");
labelEncryptionIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelTorIcon = new QLabel();
labelConnectionsIcon = new QPushButton();
labelConnectionsIcon->setObjectName("labelConnectionsIcon");
labelConnectionsIcon->setFlat(true); // Make the button look like a label, but clickable
labelConnectionsIcon->setStyleSheet(".QPushButton { background-color: rgba(255, 255, 255, 0);}");
labelConnectionsIcon->setMaximumSize(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelBlocksIcon = new QLabel();
#ifdef ENABLE_WALLET
if (enableWallet) {
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelStakingIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelAutoMintIcon);
}
#endif // ENABLE_WALLET
frameBlocksLayout->addWidget(labelTorIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(true);
progressBarLabel->setObjectName("progressBarLabel");
progressBar = new GUIUtil::ProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(true);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if (curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") {
progressBar->setStyleSheet("QProgressBar { background-color: #F8F8F8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00CCFF, stop: 1 #33CCFF); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
// Jump directly to tabs in RPC-console
connect(openInfoAction, SIGNAL(triggered()), rpcConsole, SLOT(showInfo()));
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(showConsole()));
connect(openNetworkAction, SIGNAL(triggered()), rpcConsole, SLOT(showNetwork()));
connect(openPeersAction, SIGNAL(triggered()), rpcConsole, SLOT(showPeers()));
connect(openRepairAction, SIGNAL(triggered()), rpcConsole, SLOT(showRepair()));
connect(openConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showConfEditor()));
connect(openMNConfEditorAction, SIGNAL(triggered()), rpcConsole, SLOT(showMNConfEditor()));
connect(showBackupsAction, SIGNAL(triggered()), rpcConsole, SLOT(showBackups()));
connect(labelConnectionsIcon, SIGNAL(clicked()), rpcConsole, SLOT(showPeers()));
connect(labelEncryptionIcon, SIGNAL(clicked()), walletFrame, SLOT(toggleLockWallet()));
connect(labelAutoMintIcon, SIGNAL(clicked()), this, SLOT(optionsClicked()));
// Get restart command-line parameters and handle restart
connect(rpcConsole, SIGNAL(handleRestart(QStringList)), this, SLOT(handleRestart(QStringList)));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide()));
connect(openBlockExplorerAction, SIGNAL(triggered()), explorerWindow, SLOT(show()));
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, SIGNAL(triggered()), explorerWindow, SLOT(hide()));
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
// Subscribe to notifications from core
subscribeToCoreSignals();
QTimer* timerStakingIcon = new QTimer(labelStakingIcon);
connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(setStakingStatus()));
timerStakingIcon->start(10000);
setStakingStatus();
QTimer* timerAutoMintIcon = new QTimer(labelAutoMintIcon);
connect(timerAutoMintIcon, SIGNAL(timeout()), this, SLOT(setAutoMintStatus()));
timerAutoMintIcon->start(10000);
setAutoMintStatus();
}
BitcoinGUI::~BitcoinGUI()
{
// Unsubscribe from notifications from core
unsubscribeFromCoreSignals();
GUIUtil::saveWindowGeometry("nWindow", this);
if (trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
MacDockIconHandler::cleanup();
#endif
}
void BitcoinGUI::createActions(const NetworkStyle* networkStyle)
{
QActionGroup* tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
#ifdef Q_OS_MAC
overviewAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1));
#else
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
#endif
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Icolcoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
sendCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2));
#else
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
#endif
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and icolcoin: URIs)"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
#ifdef Q_OS_MAC
receiveCoinsAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3));
#else
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
#endif
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
#ifdef Q_OS_MAC
historyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4));
#else
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
#endif
tabGroup->addAction(historyAction);
privacyAction = new QAction(QIcon(":/icons/privacy"), tr("&Privacy"), this);
privacyAction->setStatusTip(tr("Privacy Actions for zICOL"));
privacyAction->setToolTip(privacyAction->statusTip());
privacyAction->setCheckable(true);
#ifdef Q_OS_MAC
privacyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5));
#else
privacyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
#endif
tabGroup->addAction(privacyAction);
#ifdef ENABLE_WALLET
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction = new QAction(QIcon(":/icons/masternodes"), tr("&Masternodes"), this);
masternodeAction->setStatusTip(tr("Browse masternodes"));
masternodeAction->setToolTip(masternodeAction->statusTip());
masternodeAction->setCheckable(true);
#ifdef Q_OS_MAC
masternodeAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_6));
#else
masternodeAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_6));
#endif
tabGroup->addAction(masternodeAction);
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(masternodeAction, SIGNAL(triggered()), this, SLOT(gotoMasternodePage()));
}
// These showNormalIfMinimized are needed because Send Coins and Receive Coins
// can be triggered from the tray menu, and need to show the GUI to be useful.
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(privacyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(privacyAction, SIGNAL(triggered()), this, SLOT(gotoPrivacyPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
#endif // ENABLE_WALLET
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(networkStyle->getAppIcon(), tr("&About Icolcoin Core"), this);
aboutAction->setStatusTip(tr("Show information about Icolcoin Core"));
aboutAction->setMenuRole(QAction::AboutRole);
#if QT_VERSION < 0x050000
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
#else
aboutQtAction = new QAction(QIcon(":/qt-project.org/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
#endif
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setStatusTip(tr("Modify configuration options for Icolcoin"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(networkStyle->getAppIcon(), tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
unlockWalletAction = new QAction(tr("&Unlock Wallet..."), this);
unlockWalletAction->setToolTip(tr("Unlock wallet"));
lockWalletAction = new QAction(tr("&Lock Wallet"), this);
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
signMessageAction->setStatusTip(tr("Sign messages with your Icolcoin addresses to prove you own them"));
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Icolcoin addresses"));
bip38ToolAction = new QAction(QIcon(":/icons/key"), tr("&BIP38 tool"), this);
bip38ToolAction->setToolTip(tr("Encrypt and decrypt private keys using a passphrase"));
multiSendAction = new QAction(QIcon(":/icons/edit"), tr("&MultiSend"), this);
multiSendAction->setToolTip(tr("MultiSend Settings"));
multiSendAction->setCheckable(true);
openInfoAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Information"), this);
openInfoAction->setStatusTip(tr("Show diagnostic information"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug console"), this);
openRPCConsoleAction->setStatusTip(tr("Open debugging console"));
openNetworkAction = new QAction(QIcon(":/icons/connect_4"), tr("&Network Monitor"), this);
openNetworkAction->setStatusTip(tr("Show network monitor"));
openPeersAction = new QAction(QIcon(":/icons/connect_4"), tr("&Peers list"), this);
openPeersAction->setStatusTip(tr("Show peers info"));
openRepairAction = new QAction(QIcon(":/icons/options"), tr("Wallet &Repair"), this);
openRepairAction->setStatusTip(tr("Show wallet repair options"));
openConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open Wallet &Configuration File"), this);
openConfEditorAction->setStatusTip(tr("Open configuration file"));
openMNConfEditorAction = new QAction(QIcon(":/icons/edit"), tr("Open &Masternode Configuration File"), this);
openMNConfEditorAction->setStatusTip(tr("Open Masternode configuration file"));
showBackupsAction = new QAction(QIcon(":/icons/browse"), tr("Show Automatic &Backups"), this);
showBackupsAction->setStatusTip(tr("Show automatically created wallet backups"));
usedSendingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Sending addresses..."), this);
usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
usedReceivingAddressesAction = new QAction(QIcon(":/icons/address-book"), tr("&Receiving addresses..."), this);
usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
multisigCreateAction = new QAction(QIcon(":/icons/address-book"), tr("&Multisignature creation..."), this);
multisigCreateAction->setStatusTip(tr("Create a new multisignature address and add it to this wallet"));
multisigSpendAction = new QAction(QIcon(":/icons/send"), tr("&Multisignature spending..."), this);
multisigSpendAction->setStatusTip(tr("Spend from a multisignature address"));
multisigSignAction = new QAction(QIcon(":/icons/editpaste"), tr("&Multisignature signing..."), this);
multisigSignAction->setStatusTip(tr("Sign with a multisignature address"));
openAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_FileIcon), tr("Open &URI..."), this);
openAction->setStatusTip(tr("Open a Icolcoin: URI or payment request"));
openBlockExplorerAction = new QAction(QIcon(":/icons/explorer"), tr("&Blockchain explorer"), this);
openBlockExplorerAction->setStatusTip(tr("Block explorer window"));
showHelpMessageAction = new QAction(QApplication::style()->standardIcon(QStyle::SP_MessageBoxInformation), tr("&Command-line options"), this);
showHelpMessageAction->setMenuRole(QAction::NoRole);
showHelpMessageAction->setStatusTip(tr("Show the Icolcoin Core help message to get a list with possible Icolcoin command-line options"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked()));
#ifdef ENABLE_WALLET
if (walletFrame) {
connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase()));
connect(unlockWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(unlockWallet(bool)));
connect(lockWalletAction, SIGNAL(triggered()), walletFrame, SLOT(lockWallet()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
connect(bip38ToolAction, SIGNAL(triggered()), this, SLOT(gotoBip38Tool()));
connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses()));
connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses()));
connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked()));
connect(multiSendAction, SIGNAL(triggered()), this, SLOT(gotoMultiSendDialog()));
connect(multisigCreateAction, SIGNAL(triggered()), this, SLOT(gotoMultisigCreate()));
connect(multisigSpendAction, SIGNAL(triggered()), this, SLOT(gotoMultisigSpend()));
connect(multisigSignAction, SIGNAL(triggered()), this, SLOT(gotoMultisigSign()));
}
#endif // ENABLE_WALLET
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu* file = appMenuBar->addMenu(tr("&File"));
if (walletFrame) {
file->addAction(openAction);
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(usedSendingAddressesAction);
file->addAction(usedReceivingAddressesAction);
file->addSeparator();
file->addAction(multisigCreateAction);
file->addAction(multisigSpendAction);
file->addAction(multisigSignAction);
file->addSeparator();
}
file->addAction(quitAction);
QMenu* settings = appMenuBar->addMenu(tr("&Settings"));
if (walletFrame) {
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addAction(unlockWalletAction);
settings->addAction(lockWalletAction);
settings->addAction(bip38ToolAction);
settings->addAction(multiSendAction);
settings->addSeparator();
}
settings->addAction(optionsAction);
if (walletFrame) {
QMenu* tools = appMenuBar->addMenu(tr("&Tools"));
tools->addAction(openInfoAction);
tools->addAction(openRPCConsoleAction);
tools->addAction(openNetworkAction);
tools->addAction(openPeersAction);
tools->addAction(openRepairAction);
tools->addSeparator();
tools->addAction(openConfEditorAction);
tools->addAction(openMNConfEditorAction);
tools->addAction(showBackupsAction);
tools->addAction(openBlockExplorerAction);
}
QMenu* help = appMenuBar->addMenu(tr("&Help"));
help->addAction(showHelpMessageAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void BitcoinGUI::createToolBars()
{
if (walletFrame) {
QToolBar* toolbar = new QToolBar(tr("Tabs toolbar"));
toolbar->setObjectName("Main-Toolbar"); // Name for CSS addressing
toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
// // Add some empty space at the top of the toolbars
// QAction* spacer = new QAction(this);
// toolbar->addAction(spacer);
// toolbar->widgetForAction(spacer)->setObjectName("ToolbarSpacer");
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(privacyAction);
toolbar->addAction(historyAction);
toolbar->addAction(privacyAction);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
toolbar->addAction(masternodeAction);
}
toolbar->setMovable(false); // remove unused icon in upper left corner
toolbar->setOrientation(Qt::Vertical);
toolbar->setIconSize(QSize(40,40));
overviewAction->setChecked(true);
/** Create additional container for toolbar and walletFrame and make it the central widget.
This is a workaround mostly for toolbar styling on Mac OS but should work fine for every other OSes too.
*/
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(toolbar);
layout->addWidget(walletFrame);
layout->setSpacing(0);
layout->setContentsMargins(QMargins());
layout->setDirection(QBoxLayout::LeftToRight);
QWidget* containerWidget = new QWidget();
containerWidget->setLayout(layout);
setCentralWidget(containerWidget);
}
}
void BitcoinGUI::setClientModel(ClientModel* clientModel)
{
this->clientModel = clientModel;
if (clientModel) {
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks());
connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
// Receive and report messages from client model
connect(clientModel, SIGNAL(message(QString, QString, unsigned int)), this, SLOT(message(QString, QString, unsigned int)));
// Show progress dialog
connect(clientModel, SIGNAL(showProgress(QString, int)), this, SLOT(showProgress(QString, int)));
rpcConsole->setClientModel(clientModel);
updateTorIcon();
#ifdef ENABLE_WALLET
if (walletFrame) {
walletFrame->setClientModel(clientModel);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(clientModel->getOptionsModel());
connect(clientModel->getOptionsModel(), SIGNAL(zeromintEnableChanged(bool)), this, SLOT(setAutoMintStatus()));
//Show trayIcon
if (trayIcon)
{
trayIcon->show();
}
} else {
// Disable possibility to show main window via action
toggleHideAction->setEnabled(false);
if (trayIconMenu) {
// Disable context menu on tray icon
trayIconMenu->clear();
}
}
}
#ifdef ENABLE_WALLET
bool BitcoinGUI::addWallet(const QString& name, WalletModel* walletModel)
{
if (!walletFrame)
return false;
setWalletActionsEnabled(true);
return walletFrame->addWallet(name, walletModel);
}
bool BitcoinGUI::setCurrentWallet(const QString& name)
{
if (!walletFrame)
return false;
return walletFrame->setCurrentWallet(name);
}
void BitcoinGUI::removeAllWallets()
{
if (!walletFrame)
return;
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
#endif // ENABLE_WALLET
void BitcoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
privacyAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction->setEnabled(enabled);
}
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
multisigCreateAction->setEnabled(enabled);
multisigSpendAction->setEnabled(enabled);
multisigSignAction->setEnabled(enabled);
bip38ToolAction->setEnabled(enabled);
usedSendingAddressesAction->setEnabled(enabled);
usedReceivingAddressesAction->setEnabled(enabled);
openAction->setEnabled(enabled);
}
void BitcoinGUI::createTrayIcon(const NetworkStyle* networkStyle)
{
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
QString toolTip = tr("Icolcoin Core client") + " " + networkStyle->getTitleAddText();
trayIcon->setToolTip(toolTip);
trayIcon->setIcon(networkStyle->getAppIcon());
trayIcon->hide();
#endif
notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
}
void BitcoinGUI::createTrayIconMenu()
{
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-Mac OSes)
if (!trayIcon)
return;
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler* dockIconHandler = MacDockIconHandler::instance();
dockIconHandler->setMainWindow((QMainWindow*)this);
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addAction(privacyAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addAction(bip38ToolAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openInfoAction);
trayIconMenu->addAction(openRPCConsoleAction);
trayIconMenu->addAction(openNetworkAction);
trayIconMenu->addAction(openPeersAction);
trayIconMenu->addAction(openRepairAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openConfEditorAction);
trayIconMenu->addAction(openMNConfEditorAction);
trayIconMenu->addAction(showBackupsAction);
trayIconMenu->addAction(openBlockExplorerAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if (reason == QSystemTrayIcon::Trigger) {
// Click on system tray icon triggers show/hide of the main window
toggleHidden();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if (!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, enableWallet);
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
if (!clientModel)
return;
HelpMessageDialog dlg(this, true);
dlg.exec();
}
void BitcoinGUI::showHelpMessageClicked()
{
HelpMessageDialog* help = new HelpMessageDialog(this, false);
help->setAttribute(Qt::WA_DeleteOnClose);
help->show();
}
#ifdef ENABLE_WALLET
void BitcoinGUI::openClicked()
{
OpenURIDialog dlg(this);
if (dlg.exec()) {
emit receivedURI(dlg.getURI());
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
if (walletFrame) walletFrame->gotoOverviewPage();
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
if (walletFrame) walletFrame->gotoHistoryPage();
}
void BitcoinGUI::gotoMasternodePage()
{
QSettings settings;
if (settings.value("fShowMasternodesTab").toBool()) {
masternodeAction->setChecked(true);
if (walletFrame) walletFrame->gotoMasternodePage();
}
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void BitcoinGUI::gotoPrivacyPage()
{
privacyAction->setChecked(true);
if (walletFrame) walletFrame->gotoPrivacyPage();
}
void BitcoinGUI::gotoSendCoinsPage(QString addr)
{
sendCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void BitcoinGUI::gotoMultisigCreate()
{
if(walletFrame) walletFrame->gotoMultisigDialog(0);
}
void BitcoinGUI::gotoMultisigSpend()
{
if(walletFrame) walletFrame->gotoMultisigDialog(1);
}
void BitcoinGUI::gotoMultisigSign()
{
if(walletFrame) walletFrame->gotoMultisigDialog(2);
}
void BitcoinGUI::gotoBip38Tool()
{
if (walletFrame) walletFrame->gotoBip38Tool();
}
void BitcoinGUI::gotoMultiSendDialog()
{
multiSendAction->setChecked(true);
if (walletFrame)
walletFrame->gotoMultiSendDialog();
}
void BitcoinGUI::gotoBlockExplorerPage()
{
if (walletFrame) walletFrame->gotoBlockExplorerPage();
}
#endif // ENABLE_WALLET
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch (count) {
case 0:
icon = ":/icons/connect_0";
break;
case 1:
case 2:
case 3:
icon = ":/icons/connect_1";
break;
case 4:
case 5:
case 6:
icon = ":/icons/connect_2";
break;
case 7:
case 8:
case 9:
icon = ":/icons/connect_3";
break;
default:
icon = ":/icons/connect_4";
break;
}
QIcon connectionItem = QIcon(icon).pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelConnectionsIcon->setIcon(connectionItem);
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Icolcoin network", "", count));
}
void BitcoinGUI::setNumBlocks(int count)
{
if (!clientModel)
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BLOCK_SOURCE_NETWORK:
progressBarLabel->setText(tr("Synchronizing with network..."));
break;
case BLOCK_SOURCE_DISK:
progressBarLabel->setText(tr("Importing blocks from disk..."));
break;
case BLOCK_SOURCE_REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk..."));
break;
case BLOCK_SOURCE_NONE:
// Case: not Importing, not Reindexing and no network connection
progressBarLabel->setText(tr("No block source available..."));
break;
}
QString tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
QDateTime currentDate = QDateTime::currentDateTime();
int secs = lastBlockDate.secsTo(currentDate);
tooltip = tr("Processed %n blocks of transaction history.", "", count);
// Set icon state: spinning if catching up, tick otherwise
// if(secs < 25*60) // 90*60 for bitcoin but we are 4x times faster
if (masternodeSync.IsBlockchainSynced()) {
QString strSyncStatus;
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
if (masternodeSync.IsSynced()) {
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
} else {
int nAttempt;
int progress = 0;
labelBlocksIcon->setPixmap(QIcon(QString(
":/movies/spinner-%1")
.arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
#ifdef ENABLE_WALLET
if (walletFrame)
walletFrame->showOutOfSyncWarning(false);
#endif // ENABLE_WALLET
nAttempt = masternodeSync.RequestedMasternodeAttempt < MASTERNODE_SYNC_THRESHOLD ?
masternodeSync.RequestedMasternodeAttempt + 1 :
MASTERNODE_SYNC_THRESHOLD;
progress = nAttempt + (masternodeSync.RequestedMasternodeAssets - 1) * MASTERNODE_SYNC_THRESHOLD;
progressBar->setMaximum(4 * MASTERNODE_SYNC_THRESHOLD);
progressBar->setFormat(tr("Synchronizing additional data: %p%"));
progressBar->setValue(progress);
}
strSyncStatus = QString(masternodeSync.GetSyncStatus().c_str());
progressBarLabel->setText(strSyncStatus);
tooltip = strSyncStatus + QString("<br>") + tooltip;
} else {
// Represent time from last generated block in human readable text
QString timeBehindText;
const int HOUR_IN_SECONDS = 60 * 60;
const int DAY_IN_SECONDS = 24 * 60 * 60;
const int WEEK_IN_SECONDS = 7 * 24 * 60 * 60;
const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar
if (secs < 2 * DAY_IN_SECONDS) {
timeBehindText = tr("%n hour(s)", "", secs / HOUR_IN_SECONDS);
} else if (secs < 2 * WEEK_IN_SECONDS) {
timeBehindText = tr("%n day(s)", "", secs / DAY_IN_SECONDS);
} else if (secs < YEAR_IN_SECONDS) {
timeBehindText = tr("%n week(s)", "", secs / WEEK_IN_SECONDS);
} else {
int years = secs / YEAR_IN_SECONDS;
int remainder = secs % YEAR_IN_SECONDS;
timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)", "", remainder / WEEK_IN_SECONDS));
}
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind. Scanning block %2").arg(timeBehindText).arg(count));
progressBar->setMaximum(1000000000);
progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
if (count != prevBlocks) {
labelBlocksIcon->setPixmap(QIcon(QString(
":/movies/spinner-%1")
.arg(spinnerFrame, 3, 10, QChar('0')))
.pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
}
prevBlocks = count;
#ifdef ENABLE_WALLET
if (walletFrame)
walletFrame->showOutOfSyncWarning(true);
#endif // ENABLE_WALLET
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::message(const QString& title, const QString& message, unsigned int style, bool* ret)
{
QString strTitle = tr("Icolcoin Core"); // default title
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
// Prefer supplied title over style based title
if (!title.isEmpty()) {
msgType = title;
} else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
break;
default:
break;
}
}
// Append title to "Icolcoin - "
if (!msgType.isEmpty())
strTitle += " - " + msgType;
// Check for error/warning icon
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
} else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
// Display message
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this);
int r = mBox.exec();
if (ret != NULL)
*ret = r == QMessageBox::Ok;
} else
notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message);
}
void BitcoinGUI::changeEvent(QEvent* e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if (e->type() == QEvent::WindowStateChange) {
if (clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) {
QWindowStateChangeEvent* wsevt = static_cast<QWindowStateChangeEvent*>(e);
if (!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) {
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent* event)
{
#ifndef Q_OS_MAC // Ignored on Mac
if (clientModel && clientModel->getOptionsModel()) {
if (!clientModel->getOptionsModel()->getMinimizeOnClose()) {
QApplication::quit();
}
}
#endif
QMainWindow::closeEvent(event);
}
#ifdef ENABLE_WALLET
void BitcoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address)
{
// Only send notifications when not disabled
if(!bdisableSystemnotifications){
// On new transaction, make an info balloon
message((amount) < 0 ? (pwalletMain->fMultiSendNotify == true ? tr("Sent MultiSend transaction") : tr("Sent transaction")) : tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(unit, amount, true))
.arg(type)
.arg(address),
CClientUIInterface::MSG_INFORMATION);
pwalletMain->fMultiSendNotify = false;
}
}
#endif // ENABLE_WALLET
void BitcoinGUI::dragEnterEvent(QDragEnterEvent* event)
{
// Accept only URIs
if (event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent* event)
{
if (event->mimeData()->hasUrls()) {
foreach (const QUrl& uri, event->mimeData()->urls()) {
emit receivedURI(uri.toString());
}
}
event->acceptProposedAction();
}
bool BitcoinGUI::eventFilter(QObject* object, QEvent* event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip) {
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
#ifdef ENABLE_WALLET
void BitcoinGUI::setStakingStatus()
{
if (pwalletMain)
fMultiSend = pwalletMain->isMultiSendEnabled();
if (nLastCoinStakeSearchInterval) {
labelStakingIcon->show();
labelStakingIcon->setPixmap(QIcon(":/icons/staking_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(tr("Staking is active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active")));
} else {
labelStakingIcon->show();
labelStakingIcon->setPixmap(QIcon(":/icons/staking_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelStakingIcon->setToolTip(tr("Staking is not active\n MultiSend: %1").arg(fMultiSend ? tr("Active") : tr("Not Active")));
}
}
void BitcoinGUI::setAutoMintStatus()
{
if (fEnableZeromint) {
labelAutoMintIcon->show();
labelAutoMintIcon->setIcon(QIcon(":/icons/automint_active").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelAutoMintIcon->setToolTip(tr("AutoMint is currently enabled and set to ") + QString::number(nZeromintPercentage) + "%.\n");
} else {
labelAutoMintIcon->show();
labelAutoMintIcon->setIcon(QIcon(":/icons/automint_inactive").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelAutoMintIcon->setToolTip(tr("AutoMint is disabled"));
}
}
bool BitcoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
// URI has to be valid
if (walletFrame && walletFrame->handlePaymentRequest(recipient)) {
showNormalIfMinimized();
gotoSendCoinsPage();
return true;
}
return false;
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch (status) {
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setIcon(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(false);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::UnlockedForAnonymizationOnly:
labelEncryptionIcon->show();
labelEncryptionIcon->setIcon(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b> for anonymization and staking only"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setIcon(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
unlockWalletAction->setVisible(true);
lockWalletAction->setVisible(false);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
#endif // ENABLE_WALLET
void BitcoinGUI::updateTorIcon()
{
std::string ip_port;
bool tor_enabled = clientModel->getTorInfo(ip_port);
if (tor_enabled) {
if (labelTorIcon->pixmap() == 0) {
QString ip_port_q = QString::fromStdString(ip_port);
labelTorIcon->setPixmap(QIcon(":/icons/onion").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
labelTorIcon->setToolTip(tr("Tor is <b>enabled</b>: %1").arg(ip_port_q));
} else {
labelTorIcon->show();
}
} else {
labelTorIcon->hide();
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
if (!clientModel)
return;
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden()) {
show();
activateWindow();
} else if (isMinimized()) {
showNormal();
activateWindow();
} else if (GUIUtil::isObscured(this)) {
raise();
activateWindow();
} else if (fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void BitcoinGUI::detectShutdown()
{
if (ShutdownRequested()) {
if (rpcConsole)
rpcConsole->hide();
qApp->quit();
}
}
void BitcoinGUI::showProgress(const QString& title, int nProgress)
{
if (nProgress == 0) {
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
} else if (nProgress == 100) {
if (progressDialog) {
progressDialog->close();
progressDialog->deleteLater();
}
} else if (progressDialog)
progressDialog->setValue(nProgress);
}
static bool ThreadSafeMessageBox(BitcoinGUI* gui, const std::string& message, const std::string& caption, unsigned int style)
{
bool modal = (style & CClientUIInterface::MODAL);
// The SECURE flag has no effect in the Qt GUI.
// bool secure = (style & CClientUIInterface::SECURE);
style &= ~CClientUIInterface::SECURE;
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(gui, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
void BitcoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
void BitcoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3));
}
/** Get restart command-line parameters and request restart */
void BitcoinGUI::handleRestart(QStringList args)
{
if (!ShutdownRequested())
emit requestedRestart(args);
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl() : optionsModel(0),
menu(0)
{
createContextMenu();
setToolTip(tr("Unit to show amounts in. Click to select another unit."));
}
/** So that it responds to button clicks */
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent* event)
{
onDisplayUnitsClicked(event->pos());
}
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu();
foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) {
QAction* menuAction = new QAction(QString(BitcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
menu->addAction(menuAction);
}
connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onMenuSelection(QAction*)));
}
/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel* optionsModel)
{
if (optionsModel) {
this->optionsModel = optionsModel;
// be aware of a display unit change reported by the OptionsModel object.
connect(optionsModel, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int)));
// initialize the display units label with the current value in the model.
updateDisplayUnit(optionsModel->getDisplayUnit());
}
}
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
if (Params().NetworkID() == CBaseChainParams::MAIN) {
setPixmap(QIcon(":/icons/unit_" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE));
} else {
setPixmap(QIcon(":/icons/unit_t" + BitcoinUnits::id(newUnits)).pixmap(39, STATUSBAR_ICONSIZE));
}
}
/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
QPoint globalPos = mapToGlobal(point);
menu->exec(globalPos);
}
/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
if (action) {
optionsModel->setDisplayUnit(action->data());
}
}
|
#pragma once
//----------------------------------------------------------------------------//
// Settings
//----------------------------------------------------------------------------//
// Use standard templates library
#define _USE_STL
#define USE_STL // stl always enabled
// Compile with OpenGL driver (see RenderDriver.hpp)
#define _USE_GL
// Compile with OpenGLES driver (see RenderDriver.hpp)
//#define _USE_GLES
// Compile with Direct3D11 driver (see RenderDriver.hpp)
//#define _USE_D3D11
// Enable debug context of rendering (see RenderDriver.hpp)
//#define _DEBUG_RC
#if defined(_DEBUG) && !defined(_DEBUG_RC)
# define DEBUG_RC
#endif
// Enable fast half-float conversion (see Math.hpp)
#define _FAST_HALF_FLOAT
// Use engine as static library
//#define _ENGINE_STATIC_LIB
#ifdef _ENGINE_STATIC_LIB
# define ENGINE_STATIC_LIB
#endif
//----------------------------------------------------------------------------//
// Import/Export
//----------------------------------------------------------------------------//
#ifdef _ENGINE_BUILDING_DLL
# define ENGINE_API __declspec(dllexport)
#elif defined(ENGINE_STATIC_LIB)
# define ENGINE_API
#else
# define ENGINE_API __declspec(dllimport)
#endif
//----------------------------------------------------------------------------//
// Compiler/Preprocessor
//----------------------------------------------------------------------------//
#define _QUOTE( x ) #x
#define _QUOTE_IN_PLACE( x ) _QUOTE( x )
#define __FILELINE__ __FILE__"(" _QUOTE_IN_PLACE( __LINE__ ) ")"
#ifdef _MSC_VER
# define COMPILER_MESSAGE(_prefix, _message) __pragma( message( __FILELINE__ " : "_prefix ": " _message ) )
# define DEPRECATED __declspec( deprecated( "It will be removed or changed in closest time" ) )
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
# define PACK __pragma( pack( push, 1 ) )
# define PACKED
# define UNPACK ;__pragma( pack( pop ) )
# define THREAD_LOCAL __declspec(thread)
# define NOINLINE __declspec(noinline)
# pragma warning( disable : 4251 ) // dll interface
# pragma warning( disable : 4275 ) // dll interface
# pragma warning( disable : 4201 ) // unnamed union
# pragma warning( disable : 4100 ) // unused arg
# pragma warning(disable : 4996) // The POSIX name
#elif defined(__GNUC__)
# define COMPILER_MESSAGE(_prefix, _message) __pragma( message( __FILELINE__ " : "_prefix ": " _message ) )
# define DEPRECATED __declspec( deprecated( "It will be removed or changed in closest time" ) )
# define PACK
# define PACKED __attribute__((packed))
# define UNPACK
# define THREAD_LOCAL __thread
# define NOINLINE __attribute__((noinline))
# define abstract =0
#else
# define COMPILER_MESSAGE(_prefix, _message)
# define DEPRECATED
# define PACK
# define PACKED
# define UNPACK
# define THREAD_LOCAL
# define NOINLINE
#endif
#define COMPILER_MESSAGE_EX(_prefix, _source, _message) COMPILER_MESSAGE(_prefix, _source " : " _message)
#define WARNING_EX(_source, _message) COMPILER_MESSAGE_EX("Warning", _source, _message)
#define WARNING(_message) WARNING_EX(__FUNCTION__, _message)
#define FIXME_EX(_source, _message) COMPILER_MESSAGE_EX("FixMe", _source, _message)
#define FIXME(_message) FIXME_EX(__FUNCTION__, _message)
#define TODO_EX(_source, _message) COMPILER_MESSAGE_EX("ToDo", _source, _message)
#define TODO(_message) TODO_EX(__FUNCTION__, _message)
#define NOT_IMPLEMENTED_YET() FIXME("Not implemented yet")
#define NOT_IMPLEMENTED_YET_EX(_source) FIXME_EX(_source, "Not implemented yet")
//----------------------------------------------------------------------------//
// Debug
//----------------------------------------------------------------------------//
#if defined(_DEBUG) && !defined(DEBUG)
# define DEBUG
#endif
#if !defined(DEBUG) && !defined(NDEBUG)
# define NDEBUG
#endif
#ifdef _DEBUG
# include <assert.h>
# define ASSERT(x, ...) assert(x && ##__VA_ARGS__ "")
#else
# define ASSERT(x, ...)
#endif
#define STATIC_ASSERT(cond, desc) static_assert(conde, desc)
//----------------------------------------------------------------------------//
// Includes
//----------------------------------------------------------------------------//
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <time.h>
#include <algorithm>
namespace ge
{
//----------------------------------------------------------------------------//
// Basic types
//----------------------------------------------------------------------------//
typedef int8_t int8;
typedef uint8_t uint8;
typedef int16_t int16;
typedef uint16_t uint16;
typedef int32_t int32;
typedef uint32_t uint32;
typedef int64_t int64;
typedef uint64_t uint64;
typedef unsigned int uint;
//----------------------------------------------------------------------------//
// Common enumerations
//----------------------------------------------------------------------------//
enum AccessMode : uint8
{
AM_None = 0,
AM_Read = 0x1,
AM_Write = 0x2,
AM_ReadWrite = AM_Read | AM_Write,
};
//----------------------------------------------------------------------------//
// Utils
//----------------------------------------------------------------------------//
template <typename T> inline T&& Move(T& _ref) { return static_cast<T&&>(_ref); }
template <typename T> inline T&& Move(T&& _ref) { return static_cast<T&&>(_ref); }
template <typename T> void Swap(T& _a, T& _b)
{
T&& _c = Move(_a);
_a = Move(_b);
_b = _c;
}
//----------------------------------------------------------------------------//
// NonCopyable
//----------------------------------------------------------------------------//
class NonCopyable
{
public:
NonCopyable(void) { }
~NonCopyable(void) { }
private:
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator = (const NonCopyable&) = delete;
};
//----------------------------------------------------------------------------//
// Singleton
//----------------------------------------------------------------------------//
template <class T> class Singleton : public NonCopyable
{
public:
Singleton(void)
{
ASSERT(s_instance == nullptr, "Instance of this class already exists");
s_instance = static_cast<T*>(this);
}
~Singleton(void)
{
s_instance = nullptr;
}
/// Get instance.
static T* Get(void) { return s_instance; }
/// Get instance.
template <class X> static X* Get(void) { return static_cast<X*>(s_instance); }
protected:
static T* s_instance;
};
template <class T> T* Singleton<T>::s_instance = 0;
//----------------------------------------------------------------------------//
// Function
//----------------------------------------------------------------------------//
template <class F> void* FuncPtr(F _func) { union { F f; void* p; }_fp = { _func }; return _fp.p; }
template <class F> F FuncCast(void* _func) { union { void* p; F f; }_fp = { _func }; return _fp.f; }
template <class R, class... A> struct Function
{
typedef R(*Invoke)(void*, void*, A...);
Invoke invoke;
void* func;
void* self;
Function(R(*_func)(A...)) : invoke(InvokeFunc), func(FuncPtr(_func)), self(nullptr) { }
template <class C> Function(C* _self, R(C::*_func)(A...)) : invoke(InvokeMethod<C>), func(FuncPtr(_func)), self(_self) { }
template <class C> Function(const C* _self, R(C::*_func)(A...) const) : invoke(InvokeConstMethod<C>), func(FuncPtr(_func)), self(const_cast<C*>(_self)) { }
operator bool(void) const { return func != nullptr; }
R operator () (A... _args)
{
ASSERT(func != nullptr);
return invoke(self, func, _args...);
}
static R InvokeFunc(void* _self, void* _func, A... _args)
{
typedef R(*Func)(A...);
return FuncCast<Func>(_func)(_args...);
}
template <class C> static R InvokeMethod(void* _self, void* _func, A... _args)
{
ASSERT(_self != nullptr);
typedef R(C::*Func)(A...);
return (*((C*)_self).*FuncCast<Func>(_func))(_args...);
}
template <class C> static R InvokeConstMethod(void* _self, void* _func, A... _args)
{
ASSERT(_self != nullptr);
typedef R(C::*Func)(A...) const;
return (*((const C*)_self).*FuncCast<Func>(_func))(_args...);
}
};
template <class R, class... A> Function<R, A...> MakeFunction(R(*_func)(A...))
{
return Function<R, A...>(_func);
}
template <class C, class R, class... A> Function<R, A...> MakeFunction(C* _self, R(C::*_func)(A...))
{
return Function<R, A...>(_self, _func);
}
template <class C, class R, class... A> Function<R, A...> MakeFunction(const C* _self, R(C::*_func)(A...) const)
{
return Function<R, A...>(_self, _func);
}
//----------------------------------------------------------------------------//
// Closure
//----------------------------------------------------------------------------//
template <int I, typename T> struct TArgHolder
{
T arg;
TArgHolder(T _arg) : arg(_arg) { }
TArgHolder(TArgHolder&& _temp) : arg(Move(_temp.arg)) { }
TArgHolder& operator = (TArgHolder&& _temp) { arg = Move(_temp.arg); return *this; }
};
template <int... I> struct TIndicesTuple
{
};
template <int N, typename I = TIndicesTuple<>> struct TArgIndexer;
template <int N, int... I> struct TArgIndexer<N, TIndicesTuple<I...>> : TArgIndexer <N - 1, TIndicesTuple<I..., sizeof...(I)>>
{
};
template <int... I> struct TArgIndexer<0, TIndicesTuple<I...>>
{
typedef TIndicesTuple<I...> Indices;
};
template <typename I, typename... A> struct TClosureBase;
template <int... I, typename... A> struct TClosureBase <TIndicesTuple<I...>, A...> : TArgHolder<I, A>...
{
TClosureBase(A... _args) : TArgHolder<I, A>(_args)... {}
};
template <class R, class... A> struct Closure : TClosureBase<typename TArgIndexer<sizeof...(A)>::Indices, A...>
{
typedef Function<R, A...> Func;
Func func;
Closure(Func _func, A... _args) : TClosureBase(_args...), func(_func) { }
R operator ()(void) { return _Invoke(TArgIndexer<sizeof...(A)>::Indices()); }
operator Func(void) const { return Func; }
protected:
template <int... I> R _Invoke(const TIndicesTuple<I...>&) { return func(TArgHolder<I, A>::arg...); }
};
template <class R, class... A, class... P> Closure<R, A...> MakeClosure(R(*_func)(A...), P... _params)
{
return Closure<R, A...>(Function<R, A...>(_func), _params...);
}
template <class C, class R, class... A, class... P> Closure<R, A...> MakeClosure(C* _self, R(C::*_func)(A...), P... _params)
{
return Closure<R, A...>(Function<R, A...>(_self, _func), _params...);
}
template <class C, class R, class... A, class... P> Closure<R, A...> MakeClosure(const C* _self, R(C::*_func)(A...) const, P... _params)
{
return Closure<R, A...>(Function<R, A...>(_self, _func), _params...);
}
//----------------------------------------------------------------------------//
//
//----------------------------------------------------------------------------//
}
|
#pragma once
#include <QMBTPCH.hpp>
#include "Core/Memory/MemoryManager.hpp"
#include "Core/Types/BasicVector.hpp"
namespace QMBT
{
/**
* @brief A templated allocator that can only be used to allocate memory for a
* collection of the same type.
*
* @tparam Object
*/
template <typename Object, ResizePolicy Policy = ResizePolicy::Fixed>
class PoolAllocator
{
public:
//Prohibit default construction, moving and assignment
PoolAllocator(const PoolAllocator&) = delete;
PoolAllocator(PoolAllocator&&) = delete;
PoolAllocator& operator=(const PoolAllocator&) = delete;
PoolAllocator& operator=(PoolAllocator&&) = delete;
/**
* @brief Construct a new Pool Allocator object.
*
* @param debugName The name that will appear in logs and any editor.
* @param chunksPerBlock After this many items have been allocated, the allocator allocates
* a new block of size equal to chunksPerBlock * sizeof(Object).
*/
PoolAllocator(const char* debugName = "Allocator", Size blockSize = 1);
/**
* @brief Destroy the Pool Allocator object and frees all the allocated memory
*
*/
~PoolAllocator();
/**
* @brief Gets an address in the pool, constructs the object at the address and returns the address
*
* @return Object* The pointer to the newly allocated memory
*/
void* Allocate();
/**
* @brief Allocates a new block of memory and calls the constructor
* @details Allocation complexity is O(1)
*
* @tparam Object The type to be created
* @tparam Args Variadic arguments
* @param argList The arguments to the constructor of the type Object
* @return Object* The pointer to the newly allocated and created object
*/
template <typename... Args>
Object* New(Args... argList)
{
void* address = Allocate(); // Allocate the raw memory and get a pointer to it
return new (address) Object(argList...); //Call the placement new operator, which constructs the Object
}
/**
* @brief Deallocates raw memory without calling any destructor
* @details Deallocation complexity is O(1)
*
* @param ptr The pointer to the memory to be deallocated
*/
void Deallocate(Object* ptr);
/**
* @brief Deallocates a pointer and calls the destructor
* @details Deallocation complexity is O(1)
*
* @tparam Object The type of the passed pointer
* @param ptr The pointer to the memory to be deallocated
*/
void Delete(Object* ptr);
inline Size GetUsedSize() const { return m_Data->UsedSize; }
private:
PoolAllocator(PoolAllocator&);
Chunk* AllocateBlock(Size chunkSize);
private:
// Declaration order is important
std::shared_ptr<AllocatorData> m_Data;
Size m_BlockSize;
Size m_ObjectSize;
Chunk* m_CurrentPtr = nullptr;
std::vector<Chunk*> m_AllocatedBlocks;
};
template <typename Object, ResizePolicy Policy>
PoolAllocator<Object, Policy>::PoolAllocator(const char* debugName, Size blockSize)
: m_Data(std::make_shared<AllocatorData>(debugName, 0)), m_BlockSize(blockSize), m_ObjectSize(sizeof(Object)),
m_CurrentPtr(AllocateBlock(m_ObjectSize))
{
QMBT_CORE_ASSERT(blockSize > 0, "Block size has to be more than 0!");
MemoryManager::GetInstance()
.Register(m_Data);
m_AllocatedBlocks.push_back(m_CurrentPtr);
}
template <typename Object, ResizePolicy Policy>
PoolAllocator<Object, Policy>::~PoolAllocator()
{
MemoryManager::GetInstance().UnRegister(m_Data);
for (auto& ptr : m_AllocatedBlocks)
{
free(ptr);
}
}
template <typename Object, ResizePolicy Policy>
void* PoolAllocator<Object, Policy>::Allocate()
{
// No chunks left in the current block, or no block
// exists yet, Allocate a new one. If resize policy is fixed,
// then log an error.
if (m_CurrentPtr == nullptr)
{
if constexpr (Policy == ResizePolicy::Fixed)
{
LOG_CORE_ERROR("{0} out of memory!", m_Data->DebugName);
}
else
{
m_CurrentPtr = AllocateBlock(m_ObjectSize);
m_AllocatedBlocks.push_back(m_CurrentPtr);
}
}
// The return value is the current position of
// the allocation pointer:
Chunk* freeChunk = m_CurrentPtr;
// Advance (bump) the allocation pointer to the next chunk.
// When no chunks left, the `m_CurrentPtr` will be set to `nullptr`, and
// this will cause allocation of a new block on the next request:
m_CurrentPtr = m_CurrentPtr->next;
m_Data->UsedSize += m_ObjectSize;
LOG_CORE_INFO("{0} Allocated {1} bytes", m_Data->DebugName, m_ObjectSize);
return freeChunk;
}
template <typename Object, ResizePolicy Policy>
void PoolAllocator<Object, Policy>::Deallocate(Object* ptr)
{
// The freed chunk's next pointer points to the
// current allocation pointer:
reinterpret_cast<Chunk*>(ptr)->next = m_CurrentPtr;
// And the allocation pointer is now set
// to the returned (free) chunk:
m_CurrentPtr = reinterpret_cast<Chunk*>(ptr);
m_Data->UsedSize -= m_ObjectSize;
LOG_CORE_INFO("{0} Deallocated {1} bytes", m_Data->DebugName, m_ObjectSize);
}
template <typename Object, ResizePolicy Policy>
void PoolAllocator<Object, Policy>::Delete(Object* ptr)
{
ptr->~Object(); // Call the destructor on the object
Deallocate(ptr); // Deallocate the pointer
}
template <typename Object, ResizePolicy Policy>
Chunk* PoolAllocator<Object, Policy>::AllocateBlock(Size chunkSize)
{
QMBT_CORE_ASSERT(chunkSize > sizeof(Chunk), "Object size must be larger than pointer size");
// The total memory (in Bytes), to be allocated
Size blockSize = m_BlockSize * chunkSize;
// The first chunk of the new block
Chunk* blockBegin = reinterpret_cast<Chunk*>(malloc(blockSize));
m_Data->TotalSize += blockSize;
MemoryManager::GetInstance().UpdateTotalSize(blockSize);
// Once the block is allocated, we need to chain all
// the chunks in this block:
Chunk* chunk = blockBegin;
for (int i = 0; i < m_BlockSize - 1; ++i)
{
chunk->next =
reinterpret_cast<Chunk*>(reinterpret_cast<char*>(chunk) + chunkSize);
chunk = chunk->next;
}
chunk->next = nullptr;
LOG_CORE_INFO("{0} Allocated block ({1} chunks)", m_Data->DebugName, m_BlockSize);
return blockBegin;
}
} // namespace QMBT
|
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include "shmdata.h"
#include "color.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv; // this might break something
int main(int argc, char *argv[]) {
key_t key;
int shmflg;
int shmid;
int size;
key = 9000;
size = sizeof(shmdata);
shmflg = 0666;
// get an shm
if ((shmid = shmget(key, size, shmflg)) == -1) {
print_error("[SINK] shmget failed");
return 1;
} else {
print_debug("[SINK] Got an shm!");
}
// attach the shm to this process
shmdata *data = (shmdata *)shmat(shmid, data, shmflg);
if (data == (shmdata *)-1) {
print_error("[SINK] failed to attach");
return 1;
} else {
print_debug("[SINK] found character stream");
}
/** DO STUFF HERE **/
Mat img(data->width, data->height, CV_8UC4);
namedWindow("sink_test", CV_WINDOW_AUTOSIZE);
while (true) {
img.rows = data->height;
img.cols = data->width;
img.data = data->data;
memcpy(data->data, img.data, SHMDATASIZE);
imshow("sink_test", img);
waitKey(30);
}
/** END DO STUFF **/
// detach the shm from this process
if (shmdt(data) == -1) {
print_error("[SINK] failed to detach");
return 1;
} else {
print_debug("[SINK] finished");
}
return 0;
}
|
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cout;
using std::ifstream;
using std::istringstream;
using std::string;
using std::vector;
using std::abs;
enum class State {kEmpty, kObstacle};
vector<State> ParseLine(string line) {
istringstream sline(line);
int n;
char c;
vector<State> row;
while (sline >> n >> c && c == ',') {
if (n == 0) {
row.push_back(State::kEmpty);
} else {
row.push_back(State::kObstacle);
}
}
return row;
}
vector<vector<State>> ReadBoardFile(string path) {
ifstream myfile (path);
vector<vector<State>> board{};
if (myfile) {
string line;
while (getline(myfile, line)) {
vector<State> row = ParseLine(line);
board.push_back(row);
}
}
return board;
}
// TODO: Write the Search function stub here.
vector<vector<State>> Search(vector<vector<State>> grid, int init[2], int goal[2]) {
cout << "No path found!" << "\n";
return std::vector<vector<State>> {};
}
string CellString(State cell) {
switch(cell) {
case State::kObstacle: return "⛰️ ";
default: return "0 ";
}
}
void PrintBoard(const vector<vector<State>> board) {
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
cout << CellString(board[i][j]);
}
cout << "\n";
}
}
int main() {
// TODO: Declare "init" and "goal" arrays with values {0, 0} and {4, 5} respectively.
auto board = ReadBoardFile("1.board");
// TODO: Call Search with "board", "init", and "goal". Store the results in the variable "solution".
int init[2]{0, 0};
int goal[2]{4, 5};
// TODO: Change the following line to pass "solution" to PrintBoard.
auto solution = Search(board, init, goal);
PrintBoard(solution);
}
|
#include "hedgelib/hl_blob.h"
#include "hedgelib/io/hl_file.h"
#include <cstring>
namespace hl
{
blob& blob::operator=(const blob& other)
{
if (&other != this)
{
u8* newData = new u8[other.m_size];
std::memcpy(newData, other.m_data, other.m_size);
delete[] m_data;
m_data = newData;
m_size = other.m_size;
}
return *this;
}
blob& blob::operator=(blob&& other) noexcept
{
if (&other != this)
{
delete[] m_data;
m_data = other.m_data;
other.m_data = nullptr;
m_size = other.m_size;
other.m_size = 0;
}
return *this;
}
blob::blob(std::size_t size, const void* initialData) :
m_data(new u8[size]), m_size(size)
{
// Copy initial data into blob, if any.
if (initialData)
{
std::memcpy(m_data, initialData, size);
}
}
blob::blob(const nchar* filePath) :
m_data(file::load(filePath, m_size).release()) {}
blob::blob(const blob& other) :
m_data(new u8[other.m_size]),
m_size(other.m_size)
{
// Copy data from other blob into this blob.
std::memcpy(m_data, other.m_data, other.m_size);
}
blob::blob(blob&& other) noexcept :
m_data(other.m_data), m_size(other.m_size)
{
other.m_data = nullptr;
other.m_size = 0;
}
blob::~blob()
{
delete[] m_data;
}
} // hl
|
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <boost/uuid/uuid_io.hpp>
#include <cmn/agent_cmn.h>
#include <oper/route_common.h>
#include <oper/agent_route_walker.h>
#include <oper/vrf.h>
#include <oper/mirror_table.h>
#include <controller/controller_export.h>
#include <controller/controller_vrf_export.h>
#include <controller/controller_route_walker.h>
#include <controller/controller_peer.h>
#include <controller/controller_init.h>
#include <controller/controller_types.h>
VrfExport::State::State() : DBState(), exported_(false),
force_chg_(false), rt_export_(), last_sequence_number_(0) {
};
VrfExport::State::~State() {
};
bool VrfExport::State::IsExportable(uint64_t sequence_number) {
// Sequence number passed in argument is of channel to which this state
// belongs. Once channel sends the vrf subscription after flap/fresh
// connection, state's sequence number will be updated to that of channel.
// After this all routes in this VRF become eligible for export.
// This is needed as control-node mandates that VRF is subscribed before any
// route is seen in same else it will again flap the
// connection(intentionally).
// Note: In case of flaps etc CN removes VRF subscription.
// This sequence number macthing helps in making sure that VRF sub is
// sent before any route is published.
return (last_sequence_number_ != sequence_number);
}
void VrfExport::Notify(const Agent *agent, AgentXmppChannel *bgp_xmpp_peer,
DBTablePartBase *partition, DBEntryBase *e) {
BgpPeer *bgp_peer = static_cast<BgpPeer *>(bgp_xmpp_peer->bgp_peer_id());
VrfEntry *vrf = static_cast<VrfEntry *>(e);
//PBB VRF is implictly created, agent is not supposed to send RI
//subscription message since control-node will not be aware of this RI
//We still want to set a state and subscribe for bridge table for
//building ingress replication tree
bool send_subscribe = vrf->ShouldExportRoute();
uint32_t instance_id = vrf->rd();
//Instance ID being zero is possible because of VN unavailability and VRF
//ending up with NULL VRF. Reason being config sequence.
//So seeing 0 instance_id delete the state so that resubscribe can be done
//with new id and then re-export all route.
//Note: Assumption is that instance id will never change from non zero to
//some other non zero value.
//Also Instance ID check is for TSN and TA only.
bool deleted = (vrf->IsDeleted()) || (instance_id == VrfEntry::kInvalidIndex);
if (deleted) {
bgp_peer->DeleteVrfState(partition, e);
if (!AgentXmppChannel::IsXmppChannelActive(agent, bgp_xmpp_peer)) {
return;
}
if (bgp_peer) {
CONTROLLER_TRACE(Trace, bgp_peer->GetName(), vrf->GetName(),
"VRF deleted, remove state");
bgp_peer->DeleteVrfState(partition, e);
}
return;
}
if (!AgentXmppChannel::IsBgpPeerActive(agent, bgp_xmpp_peer))
return;
DBTableBase::ListenerId id = bgp_peer->GetVrfExportListenerId();
State *state = static_cast<State *>(vrf->GetState(partition->parent(), id));
uint8_t table_type;
if (state == NULL) {
state = new State();
state->exported_ = false;
state->mcast_exported_ = false;
state->force_chg_ = true;
vrf->SetState(partition->parent(), id, state);
// Dont export routes belonging to Fabric VRF table
for (table_type = (Agent::INVALID + 1);
table_type < Agent::ROUTE_TABLE_MAX; table_type++) {
state->rt_export_[table_type] =
RouteExport::Init(
static_cast<AgentRouteTable *>
(vrf->GetRouteTable(table_type)),
bgp_xmpp_peer);
}
}
if (state->last_sequence_number_ == bgp_xmpp_peer->sequence_number()) {
state->force_chg_ = false;
} else {
state->last_sequence_number_ = bgp_xmpp_peer->sequence_number();
}
if (send_subscribe == false) {
state->force_chg_ = false;
}
if (send_subscribe && ((state->exported_ == false) ||
(state->force_chg_ == true))) {
if (AgentXmppChannel::ControllerSendSubscribe(bgp_xmpp_peer, vrf,
true)) {
CONTROLLER_TRACE(Trace, bgp_peer->GetName(), vrf->GetName(),
"Subscribe");
state->exported_ = true;
if (state->force_chg_ == true) {
bgp_peer->route_walker()->StartRouteWalk(vrf, true,
ControllerRouteWalker::NOTIFYALL);
state->force_chg_ = false;
if (Agent::GetInstance()->mulitcast_builder() == bgp_xmpp_peer) {
state->mcast_exported_ = true;
} else {
state->mcast_exported_ = false;
}
}
return;
}
} else {
if (send_subscribe &&
(Agent::GetInstance()->mulitcast_builder() == bgp_xmpp_peer) &&
!state->mcast_exported_) {
// When Agent switches to a new multicast builder, we have to
// send multicast subscribe to the new multicast builder. Otherwise,
// Agent can get stuck with old multicast tree affecting BUM
// traffic.
bgp_peer->route_walker()->StartRouteWalk(vrf, true,
ControllerRouteWalker::NOTIFYMULTICAST);
state->mcast_exported_ = true;
} else if (send_subscribe &&
Agent::GetInstance()->mulitcast_builder() != bgp_xmpp_peer) {
// If it is not the multicast builder, mark the flag false so that
// if it becomes multicast builder we notify mutlcast routes
state->mcast_exported_ = false;
} else {
CONTROLLER_TRACE(Trace, bgp_peer->GetName(), vrf->GetName(),
"Already subscribed");
}
}
}
|
/*
* Copyright 2009 The WebRTC 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 "p2p/base/p2p_transport_channel.h"
#include <list>
#include <memory>
#include <utility>
#include "p2p/base/basic_ice_controller.h"
#include "p2p/base/connection.h"
#include "p2p/base/fake_port_allocator.h"
#include "p2p/base/ice_transport_internal.h"
#include "p2p/base/mock_async_resolver.h"
#include "p2p/base/packet_transport_internal.h"
#include "p2p/base/test_stun_server.h"
#include "p2p/base/test_turn_server.h"
#include "p2p/client/basic_port_allocator.h"
#include "rtc_base/checks.h"
#include "rtc_base/dscp.h"
#include "rtc_base/fake_clock.h"
#include "rtc_base/fake_mdns_responder.h"
#include "rtc_base/fake_network.h"
#include "rtc_base/firewall_socket_server.h"
#include "rtc_base/gunit.h"
#include "rtc_base/helpers.h"
#include "rtc_base/logging.h"
#include "rtc_base/mdns_responder_interface.h"
#include "rtc_base/nat_server.h"
#include "rtc_base/nat_socket_factory.h"
#include "rtc_base/proxy_server.h"
#include "rtc_base/socket_address.h"
#include "rtc_base/ssl_adapter.h"
#include "rtc_base/thread.h"
#include "rtc_base/virtual_socket_server.h"
#include "system_wrappers/include/metrics.h"
#include "test/field_trial.h"
namespace {
using rtc::SocketAddress;
using ::testing::_;
using ::testing::Assign;
using ::testing::Contains;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::InvokeWithoutArgs;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::SetArgPointee;
using ::testing::SizeIs;
// Default timeout for tests in this file.
// Should be large enough for slow buildbots to run the tests reliably.
static const int kDefaultTimeout = 10000;
static const int kMediumTimeout = 3000;
static const int kShortTimeout = 1000;
static const int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
cricket::PORTALLOCATOR_DISABLE_RELAY |
cricket::PORTALLOCATOR_DISABLE_TCP;
static const int LOW_RTT = 20;
// Addresses on the public internet.
static const SocketAddress kPublicAddrs[2] = {SocketAddress("11.11.11.11", 0),
SocketAddress("22.22.22.22", 0)};
// IPv6 Addresses on the public internet.
static const SocketAddress kIPv6PublicAddrs[2] = {
SocketAddress("2400:4030:1:2c00:be30:abcd:efab:cdef", 0),
SocketAddress("2600:0:1000:1b03:2e41:38ff:fea6:f2a4", 0)};
// For configuring multihomed clients.
static const SocketAddress kAlternateAddrs[2] = {
SocketAddress("101.101.101.101", 0), SocketAddress("202.202.202.202", 0)};
static const SocketAddress kIPv6AlternateAddrs[2] = {
SocketAddress("2401:4030:1:2c00:be30:abcd:efab:cdef", 0),
SocketAddress("2601:0:1000:1b03:2e41:38ff:fea6:f2a4", 0)};
// Addresses for HTTP proxy servers.
static const SocketAddress kHttpsProxyAddrs[2] = {
SocketAddress("11.11.11.1", 443), SocketAddress("22.22.22.1", 443)};
// Addresses for SOCKS proxy servers.
static const SocketAddress kSocksProxyAddrs[2] = {
SocketAddress("11.11.11.1", 1080), SocketAddress("22.22.22.1", 1080)};
// Internal addresses for NAT boxes.
static const SocketAddress kNatAddrs[2] = {SocketAddress("192.168.1.1", 0),
SocketAddress("192.168.2.1", 0)};
// Private addresses inside the NAT private networks.
static const SocketAddress kPrivateAddrs[2] = {
SocketAddress("192.168.1.11", 0), SocketAddress("192.168.2.22", 0)};
// For cascaded NATs, the internal addresses of the inner NAT boxes.
static const SocketAddress kCascadedNatAddrs[2] = {
SocketAddress("192.168.10.1", 0), SocketAddress("192.168.20.1", 0)};
// For cascaded NATs, private addresses inside the inner private networks.
static const SocketAddress kCascadedPrivateAddrs[2] = {
SocketAddress("192.168.10.11", 0), SocketAddress("192.168.20.22", 0)};
// The address of the public STUN server.
static const SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
// The addresses for the public turn server.
static const SocketAddress kTurnUdpIntAddr("99.99.99.3",
cricket::STUN_SERVER_PORT);
static const SocketAddress kTurnTcpIntAddr("99.99.99.4",
cricket::STUN_SERVER_PORT + 1);
static const SocketAddress kTurnUdpExtAddr("99.99.99.5", 0);
static const cricket::RelayCredentials kRelayCredentials("test", "test");
// Based on ICE_UFRAG_LENGTH
const char* kIceUfrag[4] = {"UF00", "UF01", "UF02", "UF03"};
// Based on ICE_PWD_LENGTH
const char* kIcePwd[4] = {
"TESTICEPWD00000000000000", "TESTICEPWD00000000000001",
"TESTICEPWD00000000000002", "TESTICEPWD00000000000003"};
const cricket::IceParameters kIceParams[4] = {
{kIceUfrag[0], kIcePwd[0], false},
{kIceUfrag[1], kIcePwd[1], false},
{kIceUfrag[2], kIcePwd[2], false},
{kIceUfrag[3], kIcePwd[3], false}};
const uint64_t kLowTiebreaker = 11111;
const uint64_t kHighTiebreaker = 22222;
enum { MSG_ADD_CANDIDATES, MSG_REMOVE_CANDIDATES };
cricket::IceConfig CreateIceConfig(
int receiving_timeout,
cricket::ContinualGatheringPolicy continual_gathering_policy,
absl::optional<int> backup_ping_interval = absl::nullopt) {
cricket::IceConfig config;
config.receiving_timeout = receiving_timeout;
config.continual_gathering_policy = continual_gathering_policy;
config.backup_connection_ping_interval = backup_ping_interval;
return config;
}
cricket::Candidate CreateUdpCandidate(const std::string& type,
const std::string& ip,
int port,
int priority,
const std::string& ufrag = "") {
cricket::Candidate c;
c.set_address(rtc::SocketAddress(ip, port));
c.set_component(cricket::ICE_CANDIDATE_COMPONENT_DEFAULT);
c.set_protocol(cricket::UDP_PROTOCOL_NAME);
c.set_priority(priority);
c.set_username(ufrag);
c.set_type(type);
return c;
}
cricket::BasicPortAllocator* CreateBasicPortAllocator(
rtc::NetworkManager* network_manager,
const cricket::ServerAddresses& stun_servers,
const rtc::SocketAddress& turn_server_udp,
const rtc::SocketAddress& turn_server_tcp) {
cricket::RelayServerConfig turn_server;
turn_server.credentials = kRelayCredentials;
if (!turn_server_udp.IsNil()) {
turn_server.ports.push_back(
cricket::ProtocolAddress(turn_server_udp, cricket::PROTO_UDP));
}
if (!turn_server_tcp.IsNil()) {
turn_server.ports.push_back(
cricket::ProtocolAddress(turn_server_tcp, cricket::PROTO_TCP));
}
std::vector<cricket::RelayServerConfig> turn_servers(1, turn_server);
cricket::BasicPortAllocator* allocator =
new cricket::BasicPortAllocator(network_manager);
allocator->Initialize();
allocator->SetConfiguration(stun_servers, turn_servers, 0, webrtc::NO_PRUNE);
return allocator;
}
class MockIceControllerFactory : public cricket::IceControllerFactoryInterface {
public:
~MockIceControllerFactory() = default;
std::unique_ptr<cricket::IceControllerInterface> Create(
const cricket::IceControllerFactoryArgs& args) {
RecordIceControllerCreated();
return std::make_unique<cricket::BasicIceController>(args);
}
MOCK_METHOD0(RecordIceControllerCreated, void());
};
} // namespace
namespace cricket {
// This test simulates 2 P2P endpoints that want to establish connectivity
// with each other over various network topologies and conditions, which can be
// specified in each individial test.
// A virtual network (via VirtualSocketServer) along with virtual firewalls and
// NATs (via Firewall/NATSocketServer) are used to simulate the various network
// conditions. We can configure the IP addresses of the endpoints,
// block various types of connectivity, or add arbitrary levels of NAT.
// We also run a STUN server and a relay server on the virtual network to allow
// our typical P2P mechanisms to do their thing.
// For each case, we expect the P2P stack to eventually settle on a specific
// form of connectivity to the other side. The test checks that the P2P
// negotiation successfully establishes connectivity within a certain time,
// and that the result is what we expect.
// Note that this class is a base class for use by other tests, who will provide
// specialized test behavior.
class P2PTransportChannelTestBase : public ::testing::Test,
public rtc::MessageHandler,
public sigslot::has_slots<> {
public:
P2PTransportChannelTestBase()
: vss_(new rtc::VirtualSocketServer()),
nss_(new rtc::NATSocketServer(vss_.get())),
ss_(new rtc::FirewallSocketServer(nss_.get())),
main_(ss_.get()),
stun_server_(TestStunServer::Create(&main_, kStunAddr)),
turn_server_(&main_, kTurnUdpIntAddr, kTurnUdpExtAddr),
socks_server1_(ss_.get(),
kSocksProxyAddrs[0],
ss_.get(),
kSocksProxyAddrs[0]),
socks_server2_(ss_.get(),
kSocksProxyAddrs[1],
ss_.get(),
kSocksProxyAddrs[1]),
force_relay_(false) {
ep1_.role_ = ICEROLE_CONTROLLING;
ep2_.role_ = ICEROLE_CONTROLLED;
ServerAddresses stun_servers;
stun_servers.insert(kStunAddr);
ep1_.allocator_.reset(
CreateBasicPortAllocator(&ep1_.network_manager_, stun_servers,
kTurnUdpIntAddr, rtc::SocketAddress()));
ep2_.allocator_.reset(
CreateBasicPortAllocator(&ep2_.network_manager_, stun_servers,
kTurnUdpIntAddr, rtc::SocketAddress()));
webrtc::metrics::Reset();
}
protected:
enum Config {
OPEN, // Open to the Internet
NAT_FULL_CONE, // NAT, no filtering
NAT_ADDR_RESTRICTED, // NAT, must send to an addr to recv
NAT_PORT_RESTRICTED, // NAT, must send to an addr+port to recv
NAT_SYMMETRIC, // NAT, endpoint-dependent bindings
NAT_DOUBLE_CONE, // Double NAT, both cone
NAT_SYMMETRIC_THEN_CONE, // Double NAT, symmetric outer, cone inner
BLOCK_UDP, // Firewall, UDP in/out blocked
BLOCK_UDP_AND_INCOMING_TCP, // Firewall, UDP in/out and TCP in blocked
BLOCK_ALL_BUT_OUTGOING_HTTP, // Firewall, only TCP out on 80/443
PROXY_HTTPS, // All traffic through HTTPS proxy
PROXY_SOCKS, // All traffic through SOCKS proxy
NUM_CONFIGS
};
struct Result {
Result(const std::string& controlling_type,
const std::string& controlling_protocol,
const std::string& controlled_type,
const std::string& controlled_protocol,
int wait)
: controlling_type(controlling_type),
controlling_protocol(controlling_protocol),
controlled_type(controlled_type),
controlled_protocol(controlled_protocol),
connect_wait(wait) {}
// The expected candidate type and protocol of the controlling ICE agent.
std::string controlling_type;
std::string controlling_protocol;
// The expected candidate type and protocol of the controlled ICE agent.
std::string controlled_type;
std::string controlled_protocol;
// How long to wait before the correct candidate pair is selected.
int connect_wait;
};
struct ChannelData {
bool CheckData(const char* data, int len) {
bool ret = false;
if (!ch_packets_.empty()) {
std::string packet = ch_packets_.front();
ret = (packet == std::string(data, len));
ch_packets_.pop_front();
}
return ret;
}
std::string name_; // TODO(?) - Currently not used.
std::list<std::string> ch_packets_;
std::unique_ptr<P2PTransportChannel> ch_;
};
struct CandidatesData : public rtc::MessageData {
CandidatesData(IceTransportInternal* ch, const Candidate& c)
: channel(ch), candidates(1, c) {}
CandidatesData(IceTransportInternal* ch, const std::vector<Candidate>& cc)
: channel(ch), candidates(cc) {}
IceTransportInternal* channel;
Candidates candidates;
};
struct Endpoint : public sigslot::has_slots<> {
Endpoint()
: role_(ICEROLE_UNKNOWN),
tiebreaker_(0),
role_conflict_(false),
save_candidates_(false) {}
bool HasTransport(const rtc::PacketTransportInternal* transport) {
return (transport == cd1_.ch_.get() || transport == cd2_.ch_.get());
}
ChannelData* GetChannelData(rtc::PacketTransportInternal* transport) {
if (!HasTransport(transport))
return NULL;
if (cd1_.ch_.get() == transport)
return &cd1_;
else
return &cd2_;
}
void SetIceRole(IceRole role) { role_ = role; }
IceRole ice_role() { return role_; }
void SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; }
uint64_t GetIceTiebreaker() { return tiebreaker_; }
void OnRoleConflict(bool role_conflict) { role_conflict_ = role_conflict; }
bool role_conflict() { return role_conflict_; }
void SetAllocationStepDelay(uint32_t delay) {
allocator_->set_step_delay(delay);
}
void SetAllowTcpListen(bool allow_tcp_listen) {
allocator_->set_allow_tcp_listen(allow_tcp_listen);
}
void OnIceRegathering(PortAllocatorSession*, IceRegatheringReason reason) {
++ice_regathering_counter_[reason];
}
int GetIceRegatheringCountForReason(IceRegatheringReason reason) {
return ice_regathering_counter_[reason];
}
rtc::FakeNetworkManager network_manager_;
std::unique_ptr<BasicPortAllocator> allocator_;
webrtc::AsyncResolverFactory* async_resolver_factory_;
ChannelData cd1_;
ChannelData cd2_;
IceRole role_;
uint64_t tiebreaker_;
bool role_conflict_;
bool save_candidates_;
std::vector<std::unique_ptr<CandidatesData>> saved_candidates_;
bool ready_to_send_ = false;
std::map<IceRegatheringReason, int> ice_regathering_counter_;
};
ChannelData* GetChannelData(rtc::PacketTransportInternal* transport) {
if (ep1_.HasTransport(transport))
return ep1_.GetChannelData(transport);
else
return ep2_.GetChannelData(transport);
}
IceParameters IceParamsWithRenomination(const IceParameters& ice,
bool renomination) {
IceParameters new_ice = ice;
new_ice.renomination = renomination;
return new_ice;
}
void CreateChannels(const IceConfig& ep1_config,
const IceConfig& ep2_config,
bool renomination = false) {
IceParameters ice_ep1_cd1_ch =
IceParamsWithRenomination(kIceParams[0], renomination);
IceParameters ice_ep2_cd1_ch =
IceParamsWithRenomination(kIceParams[1], renomination);
ep1_.cd1_.ch_.reset(CreateChannel(0, ICE_CANDIDATE_COMPONENT_DEFAULT,
ice_ep1_cd1_ch, ice_ep2_cd1_ch));
ep2_.cd1_.ch_.reset(CreateChannel(1, ICE_CANDIDATE_COMPONENT_DEFAULT,
ice_ep2_cd1_ch, ice_ep1_cd1_ch));
ep1_.cd1_.ch_->SetIceConfig(ep1_config);
ep2_.cd1_.ch_->SetIceConfig(ep2_config);
ep1_.cd1_.ch_->MaybeStartGathering();
ep2_.cd1_.ch_->MaybeStartGathering();
ep1_.cd1_.ch_->allocator_session()->SignalIceRegathering.connect(
&ep1_, &Endpoint::OnIceRegathering);
ep2_.cd1_.ch_->allocator_session()->SignalIceRegathering.connect(
&ep2_, &Endpoint::OnIceRegathering);
}
void CreateChannels() {
IceConfig default_config;
CreateChannels(default_config, default_config, false);
}
P2PTransportChannel* CreateChannel(int endpoint,
int component,
const IceParameters& local_ice,
const IceParameters& remote_ice) {
P2PTransportChannel* channel = new P2PTransportChannel(
"test content name", component, GetAllocator(endpoint),
GetEndpoint(endpoint)->async_resolver_factory_);
channel->SignalReadyToSend.connect(
this, &P2PTransportChannelTestBase::OnReadyToSend);
channel->SignalCandidateGathered.connect(
this, &P2PTransportChannelTestBase::OnCandidateGathered);
channel->SignalCandidatesRemoved.connect(
this, &P2PTransportChannelTestBase::OnCandidatesRemoved);
channel->SignalReadPacket.connect(
this, &P2PTransportChannelTestBase::OnReadPacket);
channel->SignalRoleConflict.connect(
this, &P2PTransportChannelTestBase::OnRoleConflict);
channel->SignalNetworkRouteChanged.connect(
this, &P2PTransportChannelTestBase::OnNetworkRouteChanged);
channel->SignalSentPacket.connect(
this, &P2PTransportChannelTestBase::OnSentPacket);
channel->SetIceParameters(local_ice);
if (remote_ice_parameter_source_ == FROM_SETICEPARAMETERS) {
channel->SetRemoteIceParameters(remote_ice);
}
channel->SetIceRole(GetEndpoint(endpoint)->ice_role());
channel->SetIceTiebreaker(GetEndpoint(endpoint)->GetIceTiebreaker());
return channel;
}
void DestroyChannels() {
main_.Clear(this);
ep1_.cd1_.ch_.reset();
ep2_.cd1_.ch_.reset();
ep1_.cd2_.ch_.reset();
ep2_.cd2_.ch_.reset();
}
P2PTransportChannel* ep1_ch1() { return ep1_.cd1_.ch_.get(); }
P2PTransportChannel* ep1_ch2() { return ep1_.cd2_.ch_.get(); }
P2PTransportChannel* ep2_ch1() { return ep2_.cd1_.ch_.get(); }
P2PTransportChannel* ep2_ch2() { return ep2_.cd2_.ch_.get(); }
TestTurnServer* test_turn_server() { return &turn_server_; }
rtc::VirtualSocketServer* virtual_socket_server() { return vss_.get(); }
// Common results.
static const Result kLocalUdpToLocalUdp;
static const Result kLocalUdpToStunUdp;
static const Result kLocalUdpToPrflxUdp;
static const Result kPrflxUdpToLocalUdp;
static const Result kStunUdpToLocalUdp;
static const Result kStunUdpToStunUdp;
static const Result kStunUdpToPrflxUdp;
static const Result kPrflxUdpToStunUdp;
static const Result kLocalUdpToRelayUdp;
static const Result kPrflxUdpToRelayUdp;
static const Result kRelayUdpToPrflxUdp;
static const Result kLocalTcpToLocalTcp;
static const Result kLocalTcpToPrflxTcp;
static const Result kPrflxTcpToLocalTcp;
rtc::NATSocketServer* nat() { return nss_.get(); }
rtc::FirewallSocketServer* fw() { return ss_.get(); }
Endpoint* GetEndpoint(int endpoint) {
if (endpoint == 0) {
return &ep1_;
} else if (endpoint == 1) {
return &ep2_;
} else {
return NULL;
}
}
BasicPortAllocator* GetAllocator(int endpoint) {
return GetEndpoint(endpoint)->allocator_.get();
}
void AddAddress(int endpoint, const SocketAddress& addr) {
GetEndpoint(endpoint)->network_manager_.AddInterface(addr);
}
void AddAddress(int endpoint,
const SocketAddress& addr,
const std::string& ifname,
rtc::AdapterType adapter_type) {
GetEndpoint(endpoint)->network_manager_.AddInterface(addr, ifname,
adapter_type);
}
void RemoveAddress(int endpoint, const SocketAddress& addr) {
GetEndpoint(endpoint)->network_manager_.RemoveInterface(addr);
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, addr);
}
void SetProxy(int endpoint, rtc::ProxyType type) {
rtc::ProxyInfo info;
info.type = type;
info.address = (type == rtc::PROXY_HTTPS) ? kHttpsProxyAddrs[endpoint]
: kSocksProxyAddrs[endpoint];
GetAllocator(endpoint)->set_proxy("unittest/1.0", info);
}
void SetAllocatorFlags(int endpoint, int flags) {
GetAllocator(endpoint)->set_flags(flags);
}
void SetIceRole(int endpoint, IceRole role) {
GetEndpoint(endpoint)->SetIceRole(role);
}
void SetIceTiebreaker(int endpoint, uint64_t tiebreaker) {
GetEndpoint(endpoint)->SetIceTiebreaker(tiebreaker);
}
bool GetRoleConflict(int endpoint) {
return GetEndpoint(endpoint)->role_conflict();
}
void SetAllocationStepDelay(int endpoint, uint32_t delay) {
return GetEndpoint(endpoint)->SetAllocationStepDelay(delay);
}
void SetAllowTcpListen(int endpoint, bool allow_tcp_listen) {
return GetEndpoint(endpoint)->SetAllowTcpListen(allow_tcp_listen);
}
// Return true if the approprite parts of the expected Result, based
// on the local and remote candidate of ep1_ch1, match. This can be
// used in an EXPECT_TRUE_WAIT.
bool CheckCandidate1(const Result& expected) {
const std::string& local_type = LocalCandidate(ep1_ch1())->type();
const std::string& local_protocol = LocalCandidate(ep1_ch1())->protocol();
const std::string& remote_type = RemoteCandidate(ep1_ch1())->type();
const std::string& remote_protocol = RemoteCandidate(ep1_ch1())->protocol();
return (local_protocol == expected.controlling_protocol &&
remote_protocol == expected.controlled_protocol &&
local_type == expected.controlling_type &&
remote_type == expected.controlled_type);
}
// EXPECT_EQ on the approprite parts of the expected Result, based
// on the local and remote candidate of ep1_ch1. This is like
// CheckCandidate1, except that it will provide more detail about
// what didn't match.
void ExpectCandidate1(const Result& expected) {
if (CheckCandidate1(expected)) {
return;
}
const std::string& local_type = LocalCandidate(ep1_ch1())->type();
const std::string& local_protocol = LocalCandidate(ep1_ch1())->protocol();
const std::string& remote_type = RemoteCandidate(ep1_ch1())->type();
const std::string& remote_protocol = RemoteCandidate(ep1_ch1())->protocol();
EXPECT_EQ(expected.controlling_type, local_type);
EXPECT_EQ(expected.controlled_type, remote_type);
EXPECT_EQ(expected.controlling_protocol, local_protocol);
EXPECT_EQ(expected.controlled_protocol, remote_protocol);
}
// Return true if the approprite parts of the expected Result, based
// on the local and remote candidate of ep2_ch1, match. This can be
// used in an EXPECT_TRUE_WAIT.
bool CheckCandidate2(const Result& expected) {
const std::string& local_type = LocalCandidate(ep2_ch1())->type();
const std::string& local_protocol = LocalCandidate(ep2_ch1())->protocol();
const std::string& remote_type = RemoteCandidate(ep2_ch1())->type();
const std::string& remote_protocol = RemoteCandidate(ep2_ch1())->protocol();
return (local_protocol == expected.controlled_protocol &&
remote_protocol == expected.controlling_protocol &&
local_type == expected.controlled_type &&
remote_type == expected.controlling_type);
}
// EXPECT_EQ on the approprite parts of the expected Result, based
// on the local and remote candidate of ep2_ch1. This is like
// CheckCandidate2, except that it will provide more detail about
// what didn't match.
void ExpectCandidate2(const Result& expected) {
if (CheckCandidate2(expected)) {
return;
}
const std::string& local_type = LocalCandidate(ep2_ch1())->type();
const std::string& local_protocol = LocalCandidate(ep2_ch1())->protocol();
const std::string& remote_type = RemoteCandidate(ep2_ch1())->type();
const std::string& remote_protocol = RemoteCandidate(ep2_ch1())->protocol();
EXPECT_EQ(expected.controlled_type, local_type);
EXPECT_EQ(expected.controlling_type, remote_type);
EXPECT_EQ(expected.controlled_protocol, local_protocol);
EXPECT_EQ(expected.controlling_protocol, remote_protocol);
}
static bool CheckCandidate(P2PTransportChannel* channel,
SocketAddress from,
SocketAddress to) {
auto local_candidate = LocalCandidate(channel);
auto remote_candidate = RemoteCandidate(channel);
return local_candidate != nullptr &&
local_candidate->address().EqualIPs(from) &&
remote_candidate != nullptr &&
remote_candidate->address().EqualIPs(to);
}
static bool CheckCandidatePair(P2PTransportChannel* ch1,
P2PTransportChannel* ch2,
SocketAddress from,
SocketAddress to) {
return CheckCandidate(ch1, from, to) && CheckCandidate(ch2, to, from);
}
static bool CheckConnected(P2PTransportChannel* ch1,
P2PTransportChannel* ch2) {
return ch1 != nullptr && ch1->receiving() && ch1->writable() &&
ch2 != nullptr && ch2->receiving() && ch2->writable();
}
static bool CheckCandidatePairAndConnected(P2PTransportChannel* ch1,
P2PTransportChannel* ch2,
SocketAddress from,
SocketAddress to) {
return CheckConnected(ch1, ch2) && CheckCandidatePair(ch1, ch2, from, to);
}
virtual void Test(const Result& expected) {
rtc::ScopedFakeClock clock;
int64_t connect_start = rtc::TimeMillis();
int64_t connect_time;
// Create the channels and wait for them to connect.
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
expected.connect_wait + kShortTimeout, clock);
connect_time = rtc::TimeMillis() - connect_start;
if (connect_time < expected.connect_wait) {
RTC_LOG(LS_INFO) << "Connect time: " << connect_time << " ms";
} else {
RTC_LOG(LS_INFO) << "Connect time: TIMEOUT (" << expected.connect_wait
<< " ms)";
}
// Allow a few turns of the crank for the selected connections to emerge.
// This may take up to 2 seconds.
if (ep1_ch1()->selected_connection() && ep2_ch1()->selected_connection()) {
int64_t converge_start = rtc::TimeMillis();
int64_t converge_time;
// Verifying local and remote channel selected connection information.
// This is done only for the RFC 5245 as controlled agent will use
// USE-CANDIDATE from controlling (ep1) agent. We can easily predict from
// EP1 result matrix.
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidate1(expected) && CheckCandidate2(expected),
kDefaultTimeout, clock);
// Also do EXPECT_EQ on each part so that failures are more verbose.
ExpectCandidate1(expected);
ExpectCandidate2(expected);
converge_time = rtc::TimeMillis() - converge_start;
int64_t converge_wait = 2000;
if (converge_time < converge_wait) {
RTC_LOG(LS_INFO) << "Converge time: " << converge_time << " ms";
} else {
RTC_LOG(LS_INFO) << "Converge time: TIMEOUT (" << converge_time
<< " ms)";
}
}
// Try sending some data to other end.
TestSendRecv(&clock);
// Destroy the channels, and wait for them to be fully cleaned up.
DestroyChannels();
}
void TestSendRecv(rtc::ThreadProcessingFakeClock* clock) {
for (int i = 0; i < 10; ++i) {
const char* data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int len = static_cast<int>(strlen(data));
// local_channel1 <==> remote_channel1
EXPECT_EQ_SIMULATED_WAIT(len, SendData(ep1_ch1(), data, len),
kMediumTimeout, *clock);
EXPECT_TRUE_SIMULATED_WAIT(CheckDataOnChannel(ep2_ch1(), data, len),
kMediumTimeout, *clock);
EXPECT_EQ_SIMULATED_WAIT(len, SendData(ep2_ch1(), data, len),
kMediumTimeout, *clock);
EXPECT_TRUE_SIMULATED_WAIT(CheckDataOnChannel(ep1_ch1(), data, len),
kMediumTimeout, *clock);
}
}
// This test waits for the transport to become receiving and writable on both
// end points. Once they are, the end points set new local ice parameters and
// restart the ice gathering. Finally it waits for the transport to select a
// new connection using the newly generated ice candidates.
// Before calling this function the end points must be configured.
void TestHandleIceUfragPasswordChanged() {
rtc::ScopedFakeClock clock;
ep1_ch1()->SetRemoteIceParameters(kIceParams[1]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[0]);
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kMediumTimeout, clock);
const Candidate* old_local_candidate1 = LocalCandidate(ep1_ch1());
const Candidate* old_local_candidate2 = LocalCandidate(ep2_ch1());
const Candidate* old_remote_candidate1 = RemoteCandidate(ep1_ch1());
const Candidate* old_remote_candidate2 = RemoteCandidate(ep2_ch1());
ep1_ch1()->SetIceParameters(kIceParams[2]);
ep1_ch1()->SetRemoteIceParameters(kIceParams[3]);
ep1_ch1()->MaybeStartGathering();
ep2_ch1()->SetIceParameters(kIceParams[3]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[2]);
ep2_ch1()->MaybeStartGathering();
EXPECT_TRUE_SIMULATED_WAIT(LocalCandidate(ep1_ch1())->generation() !=
old_local_candidate1->generation(),
kMediumTimeout, clock);
EXPECT_TRUE_SIMULATED_WAIT(LocalCandidate(ep2_ch1())->generation() !=
old_local_candidate2->generation(),
kMediumTimeout, clock);
EXPECT_TRUE_SIMULATED_WAIT(RemoteCandidate(ep1_ch1())->generation() !=
old_remote_candidate1->generation(),
kMediumTimeout, clock);
EXPECT_TRUE_SIMULATED_WAIT(RemoteCandidate(ep2_ch1())->generation() !=
old_remote_candidate2->generation(),
kMediumTimeout, clock);
EXPECT_EQ(1u, RemoteCandidate(ep2_ch1())->generation());
EXPECT_EQ(1u, RemoteCandidate(ep1_ch1())->generation());
}
void TestSignalRoleConflict() {
rtc::ScopedFakeClock clock;
// Default EP1 is in controlling state.
SetIceTiebreaker(0, kLowTiebreaker);
SetIceRole(1, ICEROLE_CONTROLLING);
SetIceTiebreaker(1, kHighTiebreaker);
// Creating channels with both channels role set to CONTROLLING.
CreateChannels();
// Since both the channels initiated with controlling state and channel2
// has higher tiebreaker value, channel1 should receive SignalRoleConflict.
EXPECT_TRUE_SIMULATED_WAIT(GetRoleConflict(0), kShortTimeout, clock);
EXPECT_FALSE(GetRoleConflict(1));
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kShortTimeout, clock);
EXPECT_TRUE(ep1_ch1()->selected_connection() &&
ep2_ch1()->selected_connection());
TestSendRecv(&clock);
DestroyChannels();
}
void TestPacketInfoIsSet(rtc::PacketInfo info) {
EXPECT_NE(info.packet_type, rtc::PacketType::kUnknown);
EXPECT_NE(info.protocol, rtc::PacketInfoProtocolType::kUnknown);
EXPECT_TRUE(info.network_id.has_value());
}
void OnReadyToSend(rtc::PacketTransportInternal* transport) {
GetEndpoint(transport)->ready_to_send_ = true;
}
// We pass the candidates directly to the other side.
void OnCandidateGathered(IceTransportInternal* ch, const Candidate& c) {
if (force_relay_ && c.type() != RELAY_PORT_TYPE)
return;
if (GetEndpoint(ch)->save_candidates_) {
GetEndpoint(ch)->saved_candidates_.push_back(
std::unique_ptr<CandidatesData>(new CandidatesData(ch, c)));
} else {
main_.Post(RTC_FROM_HERE, this, MSG_ADD_CANDIDATES,
new CandidatesData(ch, c));
}
}
void OnNetworkRouteChanged(absl::optional<rtc::NetworkRoute> network_route) {
// If the |network_route| is unset, don't count. This is used in the case
// when the network on remote side is down, the signal will be fired with an
// unset network route and it shouldn't trigger a connection switch.
if (network_route) {
++selected_candidate_pair_switches_;
}
}
int reset_selected_candidate_pair_switches() {
int switches = selected_candidate_pair_switches_;
selected_candidate_pair_switches_ = 0;
return switches;
}
void PauseCandidates(int endpoint) {
GetEndpoint(endpoint)->save_candidates_ = true;
}
void OnCandidatesRemoved(IceTransportInternal* ch,
const std::vector<Candidate>& candidates) {
// Candidate removals are not paused.
CandidatesData* candidates_data = new CandidatesData(ch, candidates);
main_.Post(RTC_FROM_HERE, this, MSG_REMOVE_CANDIDATES, candidates_data);
}
// Tcp candidate verification has to be done when they are generated.
void VerifySavedTcpCandidates(int endpoint, const std::string& tcptype) {
for (auto& data : GetEndpoint(endpoint)->saved_candidates_) {
for (auto& candidate : data->candidates) {
EXPECT_EQ(candidate.protocol(), TCP_PROTOCOL_NAME);
EXPECT_EQ(candidate.tcptype(), tcptype);
if (candidate.tcptype() == TCPTYPE_ACTIVE_STR) {
EXPECT_EQ(candidate.address().port(), DISCARD_PORT);
} else if (candidate.tcptype() == TCPTYPE_PASSIVE_STR) {
EXPECT_NE(candidate.address().port(), DISCARD_PORT);
} else {
FAIL() << "Unknown tcptype: " << candidate.tcptype();
}
}
}
}
void ResumeCandidates(int endpoint) {
Endpoint* ed = GetEndpoint(endpoint);
for (auto& candidate : ed->saved_candidates_) {
main_.Post(RTC_FROM_HERE, this, MSG_ADD_CANDIDATES, candidate.release());
}
ed->saved_candidates_.clear();
ed->save_candidates_ = false;
}
void OnMessage(rtc::Message* msg) {
switch (msg->message_id) {
case MSG_ADD_CANDIDATES: {
std::unique_ptr<CandidatesData> data(
static_cast<CandidatesData*>(msg->pdata));
P2PTransportChannel* rch = GetRemoteChannel(data->channel);
if (!rch) {
return;
}
for (auto& c : data->candidates) {
if (remote_ice_parameter_source_ != FROM_CANDIDATE) {
c.set_username("");
c.set_password("");
}
RTC_LOG(LS_INFO) << "Candidate(" << data->channel->component() << "->"
<< rch->component() << "): " << c.ToString();
rch->AddRemoteCandidate(c);
}
break;
}
case MSG_REMOVE_CANDIDATES: {
std::unique_ptr<CandidatesData> data(
static_cast<CandidatesData*>(msg->pdata));
P2PTransportChannel* rch = GetRemoteChannel(data->channel);
if (!rch) {
return;
}
for (Candidate& c : data->candidates) {
RTC_LOG(LS_INFO) << "Removed remote candidate " << c.ToString();
rch->RemoveRemoteCandidate(c);
}
break;
}
}
}
void OnReadPacket(rtc::PacketTransportInternal* transport,
const char* data,
size_t len,
const int64_t& /* packet_time_us */,
int flags) {
std::list<std::string>& packets = GetPacketList(transport);
packets.push_front(std::string(data, len));
}
void OnRoleConflict(IceTransportInternal* channel) {
GetEndpoint(channel)->OnRoleConflict(true);
IceRole new_role = GetEndpoint(channel)->ice_role() == ICEROLE_CONTROLLING
? ICEROLE_CONTROLLED
: ICEROLE_CONTROLLING;
channel->SetIceRole(new_role);
}
void OnSentPacket(rtc::PacketTransportInternal* transport,
const rtc::SentPacket& packet) {
TestPacketInfoIsSet(packet.info);
}
int SendData(IceTransportInternal* channel, const char* data, size_t len) {
rtc::PacketOptions options;
return channel->SendPacket(data, len, options, 0);
}
bool CheckDataOnChannel(IceTransportInternal* channel,
const char* data,
int len) {
return GetChannelData(channel)->CheckData(data, len);
}
static const Candidate* LocalCandidate(P2PTransportChannel* ch) {
return (ch && ch->selected_connection())
? &ch->selected_connection()->local_candidate()
: NULL;
}
static const Candidate* RemoteCandidate(P2PTransportChannel* ch) {
return (ch && ch->selected_connection())
? &ch->selected_connection()->remote_candidate()
: NULL;
}
Endpoint* GetEndpoint(rtc::PacketTransportInternal* transport) {
if (ep1_.HasTransport(transport)) {
return &ep1_;
} else if (ep2_.HasTransport(transport)) {
return &ep2_;
} else {
return NULL;
}
}
P2PTransportChannel* GetRemoteChannel(IceTransportInternal* ch) {
if (ch == ep1_ch1())
return ep2_ch1();
else if (ch == ep1_ch2())
return ep2_ch2();
else if (ch == ep2_ch1())
return ep1_ch1();
else if (ch == ep2_ch2())
return ep1_ch2();
else
return NULL;
}
std::list<std::string>& GetPacketList(
rtc::PacketTransportInternal* transport) {
return GetChannelData(transport)->ch_packets_;
}
enum RemoteIceParameterSource { FROM_CANDIDATE, FROM_SETICEPARAMETERS };
// How does the test pass ICE parameters to the P2PTransportChannel?
// On the candidate itself, or through SetRemoteIceParameters?
// Goes through the candidate itself by default.
void set_remote_ice_parameter_source(RemoteIceParameterSource source) {
remote_ice_parameter_source_ = source;
}
void set_force_relay(bool relay) { force_relay_ = relay; }
void ConnectSignalNominated(Connection* conn) {
conn->SignalNominated.connect(this,
&P2PTransportChannelTestBase::OnNominated);
}
void OnNominated(Connection* conn) { nominated_ = true; }
bool nominated() { return nominated_; }
private:
std::unique_ptr<rtc::VirtualSocketServer> vss_;
std::unique_ptr<rtc::NATSocketServer> nss_;
std::unique_ptr<rtc::FirewallSocketServer> ss_;
rtc::AutoSocketServerThread main_;
std::unique_ptr<TestStunServer> stun_server_;
TestTurnServer turn_server_;
rtc::SocksProxyServer socks_server1_;
rtc::SocksProxyServer socks_server2_;
Endpoint ep1_;
Endpoint ep2_;
RemoteIceParameterSource remote_ice_parameter_source_ = FROM_CANDIDATE;
bool force_relay_;
int selected_candidate_pair_switches_ = 0;
bool nominated_ = false;
};
// The tests have only a few outcomes, which we predefine.
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kLocalUdpToLocalUdp("local",
"udp",
"local",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kLocalUdpToStunUdp("local",
"udp",
"stun",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kLocalUdpToPrflxUdp("local",
"udp",
"prflx",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kPrflxUdpToLocalUdp("prflx",
"udp",
"local",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kStunUdpToLocalUdp("stun",
"udp",
"local",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kStunUdpToStunUdp("stun",
"udp",
"stun",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kStunUdpToPrflxUdp("stun",
"udp",
"prflx",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kPrflxUdpToStunUdp("prflx",
"udp",
"stun",
"udp",
1000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kLocalUdpToRelayUdp("local",
"udp",
"relay",
"udp",
2000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kPrflxUdpToRelayUdp("prflx",
"udp",
"relay",
"udp",
2000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kRelayUdpToPrflxUdp("relay",
"udp",
"prflx",
"udp",
2000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kLocalTcpToLocalTcp("local",
"tcp",
"local",
"tcp",
3000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kLocalTcpToPrflxTcp("local",
"tcp",
"prflx",
"tcp",
3000);
const P2PTransportChannelTestBase::Result
P2PTransportChannelTestBase::kPrflxTcpToLocalTcp("prflx",
"tcp",
"local",
"tcp",
3000);
// Test the matrix of all the connectivity types we expect to see in the wild.
// Just test every combination of the configs in the Config enum.
class P2PTransportChannelTest : public P2PTransportChannelTestBase {
protected:
static const Result* kMatrix[NUM_CONFIGS][NUM_CONFIGS];
void ConfigureEndpoints(Config config1,
Config config2,
int allocator_flags1,
int allocator_flags2) {
ConfigureEndpoint(0, config1);
SetAllocatorFlags(0, allocator_flags1);
SetAllocationStepDelay(0, kMinimumStepDelay);
ConfigureEndpoint(1, config2);
SetAllocatorFlags(1, allocator_flags2);
SetAllocationStepDelay(1, kMinimumStepDelay);
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
}
void ConfigureEndpoint(int endpoint, Config config) {
switch (config) {
case OPEN:
AddAddress(endpoint, kPublicAddrs[endpoint]);
break;
case NAT_FULL_CONE:
case NAT_ADDR_RESTRICTED:
case NAT_PORT_RESTRICTED:
case NAT_SYMMETRIC:
AddAddress(endpoint, kPrivateAddrs[endpoint]);
// Add a single NAT of the desired type
nat()
->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
static_cast<rtc::NATType>(config - NAT_FULL_CONE))
->AddClient(kPrivateAddrs[endpoint]);
break;
case NAT_DOUBLE_CONE:
case NAT_SYMMETRIC_THEN_CONE:
AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]);
// Add a two cascaded NATs of the desired types
nat()
->AddTranslator(kPublicAddrs[endpoint], kNatAddrs[endpoint],
(config == NAT_DOUBLE_CONE) ? rtc::NAT_OPEN_CONE
: rtc::NAT_SYMMETRIC)
->AddTranslator(kPrivateAddrs[endpoint],
kCascadedNatAddrs[endpoint], rtc::NAT_OPEN_CONE)
->AddClient(kCascadedPrivateAddrs[endpoint]);
break;
case BLOCK_UDP:
case BLOCK_UDP_AND_INCOMING_TCP:
case BLOCK_ALL_BUT_OUTGOING_HTTP:
case PROXY_HTTPS:
case PROXY_SOCKS:
AddAddress(endpoint, kPublicAddrs[endpoint]);
// Block all UDP
fw()->AddRule(false, rtc::FP_UDP, rtc::FD_ANY, kPublicAddrs[endpoint]);
if (config == BLOCK_UDP_AND_INCOMING_TCP) {
// Block TCP inbound to the endpoint
fw()->AddRule(false, rtc::FP_TCP, SocketAddress(),
kPublicAddrs[endpoint]);
} else if (config == BLOCK_ALL_BUT_OUTGOING_HTTP) {
// Block all TCP to/from the endpoint except 80/443 out
fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
SocketAddress(rtc::IPAddress(INADDR_ANY), 80));
fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
SocketAddress(rtc::IPAddress(INADDR_ANY), 443));
fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY,
kPublicAddrs[endpoint]);
} else if (config == PROXY_HTTPS) {
// Block all TCP to/from the endpoint except to the proxy server
fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
kHttpsProxyAddrs[endpoint]);
fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY,
kPublicAddrs[endpoint]);
SetProxy(endpoint, rtc::PROXY_HTTPS);
} else if (config == PROXY_SOCKS) {
// Block all TCP to/from the endpoint except to the proxy server
fw()->AddRule(true, rtc::FP_TCP, kPublicAddrs[endpoint],
kSocksProxyAddrs[endpoint]);
fw()->AddRule(false, rtc::FP_TCP, rtc::FD_ANY,
kPublicAddrs[endpoint]);
SetProxy(endpoint, rtc::PROXY_SOCKS5);
}
break;
default:
RTC_NOTREACHED();
break;
}
}
};
// Shorthands for use in the test matrix.
#define LULU &kLocalUdpToLocalUdp
#define LUSU &kLocalUdpToStunUdp
#define LUPU &kLocalUdpToPrflxUdp
#define PULU &kPrflxUdpToLocalUdp
#define SULU &kStunUdpToLocalUdp
#define SUSU &kStunUdpToStunUdp
#define SUPU &kStunUdpToPrflxUdp
#define PUSU &kPrflxUdpToStunUdp
#define LURU &kLocalUdpToRelayUdp
#define PURU &kPrflxUdpToRelayUdp
#define RUPU &kRelayUdpToPrflxUdp
#define LTLT &kLocalTcpToLocalTcp
#define LTPT &kLocalTcpToPrflxTcp
#define PTLT &kPrflxTcpToLocalTcp
// TODO(?): Enable these once TestRelayServer can accept external TCP.
#define LTRT NULL
#define LSRS NULL
// Test matrix. Originator behavior defined by rows, receiever by columns.
// TODO(?): Fix NULLs caused by lack of TCP support in NATSocket.
// TODO(?): Fix NULLs caused by no HTTP proxy support.
// TODO(?): Rearrange rows/columns from best to worst.
const P2PTransportChannelTest::Result*
P2PTransportChannelTest::kMatrix[NUM_CONFIGS][NUM_CONFIGS] = {
// OPEN CONE ADDR PORT SYMM 2CON SCON !UDP !TCP HTTP PRXH
// PRXS
/*OP*/ {LULU, LUSU, LUSU, LUSU, LUPU, LUSU, LUPU, LTPT, LTPT, LSRS,
NULL, LTPT},
/*CO*/
{SULU, SUSU, SUSU, SUSU, SUPU, SUSU, SUPU, NULL, NULL, LSRS, NULL,
LTRT},
/*AD*/
{SULU, SUSU, SUSU, SUSU, SUPU, SUSU, SUPU, NULL, NULL, LSRS, NULL,
LTRT},
/*PO*/
{SULU, SUSU, SUSU, SUSU, RUPU, SUSU, RUPU, NULL, NULL, LSRS, NULL,
LTRT},
/*SY*/
{PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL,
LTRT},
/*2C*/
{SULU, SUSU, SUSU, SUSU, SUPU, SUSU, SUPU, NULL, NULL, LSRS, NULL,
LTRT},
/*SC*/
{PULU, PUSU, PUSU, PURU, PURU, PUSU, PURU, NULL, NULL, LSRS, NULL,
LTRT},
/*!U*/
{LTPT, NULL, NULL, NULL, NULL, NULL, NULL, LTPT, LTPT, LSRS, NULL,
LTRT},
/*!T*/
{PTLT, NULL, NULL, NULL, NULL, NULL, NULL, PTLT, LTRT, LSRS, NULL,
LTRT},
/*HT*/
{LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, LSRS, NULL,
LSRS},
/*PR*/
{NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL},
/*PR*/
{LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LTRT, LSRS, NULL,
LTRT},
};
class P2PTransportChannelTestWithFieldTrials
: public P2PTransportChannelTest,
public ::testing::WithParamInterface<std::string> {
public:
void Test(const Result& expected) override {
webrtc::test::ScopedFieldTrials field_trials(GetParam());
P2PTransportChannelTest::Test(expected);
}
};
// The actual tests that exercise all the various configurations.
// Test names are of the form P2PTransportChannelTest_TestOPENToNAT_FULL_CONE
#define P2P_TEST_DECLARATION(x, y, z) \
TEST_P(P2PTransportChannelTestWithFieldTrials, z##Test##x##To##y) { \
ConfigureEndpoints(x, y, PORTALLOCATOR_ENABLE_SHARED_SOCKET, \
PORTALLOCATOR_ENABLE_SHARED_SOCKET); \
if (kMatrix[x][y] != NULL) \
Test(*kMatrix[x][y]); \
else \
RTC_LOG(LS_WARNING) << "Not yet implemented"; \
}
#define P2P_TEST(x, y) P2P_TEST_DECLARATION(x, y, /* empty argument */)
#define P2P_TEST_SET(x) \
P2P_TEST(x, OPEN) \
P2P_TEST(x, NAT_FULL_CONE) \
P2P_TEST(x, NAT_ADDR_RESTRICTED) \
P2P_TEST(x, NAT_PORT_RESTRICTED) \
P2P_TEST(x, NAT_SYMMETRIC) \
P2P_TEST(x, NAT_DOUBLE_CONE) \
P2P_TEST(x, NAT_SYMMETRIC_THEN_CONE) \
P2P_TEST(x, BLOCK_UDP) \
P2P_TEST(x, BLOCK_UDP_AND_INCOMING_TCP) \
P2P_TEST(x, BLOCK_ALL_BUT_OUTGOING_HTTP) \
P2P_TEST(x, PROXY_HTTPS) \
P2P_TEST(x, PROXY_SOCKS)
P2P_TEST_SET(OPEN)
P2P_TEST_SET(NAT_FULL_CONE)
P2P_TEST_SET(NAT_ADDR_RESTRICTED)
P2P_TEST_SET(NAT_PORT_RESTRICTED)
P2P_TEST_SET(NAT_SYMMETRIC)
P2P_TEST_SET(NAT_DOUBLE_CONE)
P2P_TEST_SET(NAT_SYMMETRIC_THEN_CONE)
P2P_TEST_SET(BLOCK_UDP)
P2P_TEST_SET(BLOCK_UDP_AND_INCOMING_TCP)
P2P_TEST_SET(BLOCK_ALL_BUT_OUTGOING_HTTP)
P2P_TEST_SET(PROXY_HTTPS)
P2P_TEST_SET(PROXY_SOCKS)
INSTANTIATE_TEST_SUITE_P(
P2PTransportChannelTestWithFieldTrials,
P2PTransportChannelTestWithFieldTrials,
// Each field-trial is ~144 tests (some return not-yet-implemented).
testing::Values("", "WebRTC-IceFieldTrials/enable_goog_ping:true/"));
// Test that we restart candidate allocation when local ufrag&pwd changed.
// Standard Ice protocol is used.
TEST_F(P2PTransportChannelTest, HandleUfragPwdChange) {
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
CreateChannels();
TestHandleIceUfragPasswordChanged();
DestroyChannels();
}
// Same as above test, but with a symmetric NAT.
// We should end up with relay<->prflx candidate pairs, with generation "1".
TEST_F(P2PTransportChannelTest, HandleUfragPwdChangeSymmetricNat) {
ConfigureEndpoints(NAT_SYMMETRIC, NAT_SYMMETRIC, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
CreateChannels();
TestHandleIceUfragPasswordChanged();
DestroyChannels();
}
// Test the operation of GetStats.
TEST_F(P2PTransportChannelTest, GetStats) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->receiving() && ep1_ch1()->writable() &&
ep2_ch1()->receiving() &&
ep2_ch1()->writable(),
kMediumTimeout, clock);
TestSendRecv(&clock);
IceTransportStats ice_transport_stats;
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
ASSERT_GE(ice_transport_stats.connection_infos.size(), 1u);
ASSERT_GE(ice_transport_stats.candidate_stats_list.size(), 1u);
EXPECT_EQ(ice_transport_stats.selected_candidate_pair_changes, 1u);
ConnectionInfo* best_conn_info = nullptr;
for (ConnectionInfo& info : ice_transport_stats.connection_infos) {
if (info.best_connection) {
best_conn_info = &info;
break;
}
}
ASSERT_TRUE(best_conn_info != nullptr);
EXPECT_TRUE(best_conn_info->new_connection);
EXPECT_TRUE(best_conn_info->receiving);
EXPECT_TRUE(best_conn_info->writable);
EXPECT_FALSE(best_conn_info->timeout);
EXPECT_EQ(10U, best_conn_info->sent_total_packets);
EXPECT_EQ(0U, best_conn_info->sent_discarded_packets);
EXPECT_EQ(10 * 36U, best_conn_info->sent_total_bytes);
EXPECT_EQ(10 * 36U, best_conn_info->recv_total_bytes);
DestroyChannels();
}
// Tests that UMAs are recorded when ICE restarts while the channel
// is disconnected.
TEST_F(P2PTransportChannelTest, TestUMAIceRestartWhileDisconnected) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kDefaultTimeout, clock);
// Drop all packets so that both channels become not writable.
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[0]);
const int kWriteTimeoutDelay = 8000;
EXPECT_TRUE_SIMULATED_WAIT(!ep1_ch1()->writable() && !ep2_ch1()->writable(),
kWriteTimeoutDelay, clock);
ep1_ch1()->SetIceParameters(kIceParams[2]);
ep1_ch1()->SetRemoteIceParameters(kIceParams[3]);
ep1_ch1()->MaybeStartGathering();
EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
"WebRTC.PeerConnection.IceRestartState",
static_cast<int>(IceRestartState::DISCONNECTED)));
ep2_ch1()->SetIceParameters(kIceParams[3]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[2]);
ep2_ch1()->MaybeStartGathering();
EXPECT_METRIC_EQ(2, webrtc::metrics::NumEvents(
"WebRTC.PeerConnection.IceRestartState",
static_cast<int>(IceRestartState::DISCONNECTED)));
DestroyChannels();
}
// Tests that UMAs are recorded when ICE restarts while the channel
// is connected.
TEST_F(P2PTransportChannelTest, TestUMAIceRestartWhileConnected) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kDefaultTimeout, clock);
ep1_ch1()->SetIceParameters(kIceParams[2]);
ep1_ch1()->SetRemoteIceParameters(kIceParams[3]);
ep1_ch1()->MaybeStartGathering();
EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
"WebRTC.PeerConnection.IceRestartState",
static_cast<int>(IceRestartState::CONNECTED)));
ep2_ch1()->SetIceParameters(kIceParams[3]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[2]);
ep2_ch1()->MaybeStartGathering();
EXPECT_METRIC_EQ(2, webrtc::metrics::NumEvents(
"WebRTC.PeerConnection.IceRestartState",
static_cast<int>(IceRestartState::CONNECTED)));
DestroyChannels();
}
// Tests that UMAs are recorded when ICE restarts while the channel
// is connecting.
TEST_F(P2PTransportChannelTest, TestUMAIceRestartWhileConnecting) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// Create the channels without waiting for them to become connected.
CreateChannels();
ep1_ch1()->SetIceParameters(kIceParams[2]);
ep1_ch1()->SetRemoteIceParameters(kIceParams[3]);
ep1_ch1()->MaybeStartGathering();
EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
"WebRTC.PeerConnection.IceRestartState",
static_cast<int>(IceRestartState::CONNECTING)));
ep2_ch1()->SetIceParameters(kIceParams[3]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[2]);
ep2_ch1()->MaybeStartGathering();
EXPECT_METRIC_EQ(2, webrtc::metrics::NumEvents(
"WebRTC.PeerConnection.IceRestartState",
static_cast<int>(IceRestartState::CONNECTING)));
DestroyChannels();
}
// Tests that a UMA on ICE regathering is recorded when there is a network
// change if and only if continual gathering is enabled.
TEST_F(P2PTransportChannelTest,
TestIceRegatheringReasonContinualGatheringByNetworkChange) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// ep1 gathers continually but ep2 does not.
IceConfig continual_gathering_config =
CreateIceConfig(1000, GATHER_CONTINUALLY);
IceConfig default_config;
CreateChannels(continual_gathering_config, default_config);
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kDefaultTimeout, clock);
// Adding address in ep1 will trigger continual gathering.
AddAddress(0, kAlternateAddrs[0]);
EXPECT_EQ_SIMULATED_WAIT(1,
GetEndpoint(0)->GetIceRegatheringCountForReason(
IceRegatheringReason::NETWORK_CHANGE),
kDefaultTimeout, clock);
ep2_ch1()->SetIceParameters(kIceParams[3]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[2]);
ep2_ch1()->MaybeStartGathering();
AddAddress(1, kAlternateAddrs[1]);
SIMULATED_WAIT(false, kDefaultTimeout, clock);
// ep2 has not enabled continual gathering.
EXPECT_EQ(0, GetEndpoint(1)->GetIceRegatheringCountForReason(
IceRegatheringReason::NETWORK_CHANGE));
DestroyChannels();
}
// Tests that a UMA on ICE regathering is recorded when there is a network
// failure if and only if continual gathering is enabled.
TEST_F(P2PTransportChannelTest,
TestIceRegatheringReasonContinualGatheringByNetworkFailure) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// ep1 gathers continually but ep2 does not.
IceConfig config1 = CreateIceConfig(1000, GATHER_CONTINUALLY);
config1.regather_on_failed_networks_interval = 2000;
IceConfig config2;
config2.regather_on_failed_networks_interval = 2000;
CreateChannels(config1, config2);
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kDefaultTimeout, clock);
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[0]);
// Timeout value such that all connections are deleted.
const int kNetworkFailureTimeout = 35000;
SIMULATED_WAIT(false, kNetworkFailureTimeout, clock);
EXPECT_LE(1, GetEndpoint(0)->GetIceRegatheringCountForReason(
IceRegatheringReason::NETWORK_FAILURE));
EXPECT_METRIC_LE(
1, webrtc::metrics::NumEvents(
"WebRTC.PeerConnection.IceRegatheringReason",
static_cast<int>(IceRegatheringReason::NETWORK_FAILURE)));
EXPECT_EQ(0, GetEndpoint(1)->GetIceRegatheringCountForReason(
IceRegatheringReason::NETWORK_FAILURE));
DestroyChannels();
}
// Test that we properly create a connection on a STUN ping from unknown address
// when the signaling is slow.
TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignaling) {
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// Emulate no remote parameters coming in.
set_remote_ice_parameter_source(FROM_CANDIDATE);
CreateChannels();
// Only have remote parameters come in for ep2, not ep1.
ep2_ch1()->SetRemoteIceParameters(kIceParams[0]);
// Pause sending ep2's candidates to ep1 until ep1 receives the peer reflexive
// candidate.
PauseCandidates(1);
// Wait until the callee becomes writable to make sure that a ping request is
// received by the caller before his remote ICE credentials are set.
ASSERT_TRUE_WAIT(ep2_ch1()->selected_connection() != nullptr, kMediumTimeout);
// Add two sets of remote ICE credentials, so that the ones used by the
// candidate will be generation 1 instead of 0.
ep1_ch1()->SetRemoteIceParameters(kIceParams[3]);
ep1_ch1()->SetRemoteIceParameters(kIceParams[1]);
// The caller should have the selected connection connected to the peer
// reflexive candidate.
const Connection* selected_connection = nullptr;
ASSERT_TRUE_WAIT(
(selected_connection = ep1_ch1()->selected_connection()) != nullptr,
kMediumTimeout);
EXPECT_EQ(PRFLX_PORT_TYPE, selected_connection->remote_candidate().type());
EXPECT_EQ(kIceUfrag[1], selected_connection->remote_candidate().username());
EXPECT_EQ(kIcePwd[1], selected_connection->remote_candidate().password());
EXPECT_EQ(1u, selected_connection->remote_candidate().generation());
ResumeCandidates(1);
// Verify ep1's selected connection is updated to use the 'local' candidate.
EXPECT_EQ_WAIT(LOCAL_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type(),
kMediumTimeout);
EXPECT_EQ(selected_connection, ep1_ch1()->selected_connection());
DestroyChannels();
}
// Test that if we learn a prflx remote candidate, its address is concealed in
// 1. the selected candidate pair accessed via the public API, and
// 2. the candidate pair stats
// until we learn the same address from signaling.
TEST_F(P2PTransportChannelTest, PeerReflexiveRemoteCandidateIsSanitized) {
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// Emulate no remote parameters coming in.
set_remote_ice_parameter_source(FROM_CANDIDATE);
CreateChannels();
// Only have remote parameters come in for ep2, not ep1.
ep2_ch1()->SetRemoteIceParameters(kIceParams[0]);
// Pause sending ep2's candidates to ep1 until ep1 receives the peer reflexive
// candidate.
PauseCandidates(1);
ASSERT_TRUE_WAIT(ep2_ch1()->selected_connection() != nullptr, kMediumTimeout);
ep1_ch1()->SetRemoteIceParameters(kIceParams[1]);
ASSERT_TRUE_WAIT(ep1_ch1()->selected_connection() != nullptr, kMediumTimeout);
// Check the selected candidate pair.
auto pair_ep1 = ep1_ch1()->GetSelectedCandidatePair();
ASSERT_TRUE(pair_ep1.has_value());
EXPECT_EQ(PRFLX_PORT_TYPE, pair_ep1->remote_candidate().type());
EXPECT_TRUE(pair_ep1->remote_candidate().address().ipaddr().IsNil());
IceTransportStats ice_transport_stats;
ep1_ch1()->GetStats(&ice_transport_stats);
// Check the candidate pair stats.
ASSERT_EQ(1u, ice_transport_stats.connection_infos.size());
EXPECT_EQ(PRFLX_PORT_TYPE,
ice_transport_stats.connection_infos[0].remote_candidate.type());
EXPECT_TRUE(ice_transport_stats.connection_infos[0]
.remote_candidate.address()
.ipaddr()
.IsNil());
// Let ep1 receive the remote candidate to update its type from prflx to host.
ResumeCandidates(1);
ASSERT_TRUE_WAIT(
ep1_ch1()->selected_connection() != nullptr &&
ep1_ch1()->selected_connection()->remote_candidate().type() ==
LOCAL_PORT_TYPE,
kMediumTimeout);
// We should be able to reveal the address after it is learnt via
// AddIceCandidate.
//
// Check the selected candidate pair.
auto updated_pair_ep1 = ep1_ch1()->GetSelectedCandidatePair();
ASSERT_TRUE(updated_pair_ep1.has_value());
EXPECT_EQ(LOCAL_PORT_TYPE, updated_pair_ep1->remote_candidate().type());
EXPECT_TRUE(
updated_pair_ep1->remote_candidate().address().EqualIPs(kPublicAddrs[1]));
ep1_ch1()->GetStats(&ice_transport_stats);
// Check the candidate pair stats.
ASSERT_EQ(1u, ice_transport_stats.connection_infos.size());
EXPECT_EQ(LOCAL_PORT_TYPE,
ice_transport_stats.connection_infos[0].remote_candidate.type());
EXPECT_TRUE(ice_transport_stats.connection_infos[0]
.remote_candidate.address()
.EqualIPs(kPublicAddrs[1]));
DestroyChannels();
}
// Test that we properly create a connection on a STUN ping from unknown address
// when the signaling is slow and the end points are behind NAT.
TEST_F(P2PTransportChannelTest, PeerReflexiveCandidateBeforeSignalingWithNAT) {
ConfigureEndpoints(OPEN, NAT_SYMMETRIC, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// Emulate no remote parameters coming in.
set_remote_ice_parameter_source(FROM_CANDIDATE);
CreateChannels();
// Only have remote parameters come in for ep2, not ep1.
ep2_ch1()->SetRemoteIceParameters(kIceParams[0]);
// Pause sending ep2's candidates to ep1 until ep1 receives the peer reflexive
// candidate.
PauseCandidates(1);
// Wait until the callee becomes writable to make sure that a ping request is
// received by the caller before his remote ICE credentials are set.
ASSERT_TRUE_WAIT(ep2_ch1()->selected_connection() != nullptr, kMediumTimeout);
// Add two sets of remote ICE credentials, so that the ones used by the
// candidate will be generation 1 instead of 0.
ep1_ch1()->SetRemoteIceParameters(kIceParams[3]);
ep1_ch1()->SetRemoteIceParameters(kIceParams[1]);
// The caller's selected connection should be connected to the peer reflexive
// candidate.
const Connection* selected_connection = nullptr;
ASSERT_TRUE_WAIT(
(selected_connection = ep1_ch1()->selected_connection()) != nullptr,
kMediumTimeout);
EXPECT_EQ(PRFLX_PORT_TYPE, selected_connection->remote_candidate().type());
EXPECT_EQ(kIceUfrag[1], selected_connection->remote_candidate().username());
EXPECT_EQ(kIcePwd[1], selected_connection->remote_candidate().password());
EXPECT_EQ(1u, selected_connection->remote_candidate().generation());
ResumeCandidates(1);
EXPECT_EQ_WAIT(PRFLX_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type(),
kMediumTimeout);
EXPECT_EQ(selected_connection, ep1_ch1()->selected_connection());
DestroyChannels();
}
// Test that we properly create a connection on a STUN ping from unknown address
// when the signaling is slow, even if the new candidate is created due to the
// remote peer doing an ICE restart, pairing this candidate across generations.
//
// Previously this wasn't working due to a bug where the peer reflexive
// candidate was only updated for the newest generation candidate pairs, and
// not older-generation candidate pairs created by pairing candidates across
// generations. This resulted in the old-generation prflx candidate being
// prioritized above new-generation candidate pairs.
TEST_F(P2PTransportChannelTest,
PeerReflexiveCandidateBeforeSignalingWithIceRestart) {
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// Only gather relay candidates, so that when the prflx candidate arrives
// it's prioritized above the current candidate pair.
GetEndpoint(0)->allocator_->SetCandidateFilter(CF_RELAY);
GetEndpoint(1)->allocator_->SetCandidateFilter(CF_RELAY);
// Setting this allows us to control when SetRemoteIceParameters is called.
set_remote_ice_parameter_source(FROM_CANDIDATE);
CreateChannels();
// Wait for the initial connection to be made.
ep1_ch1()->SetRemoteIceParameters(kIceParams[1]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[0]);
EXPECT_TRUE_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()), kDefaultTimeout);
// Simulate an ICE restart on ep2, but don't signal the candidate or new
// ICE parameters until after a prflx connection has been made.
PauseCandidates(1);
ep2_ch1()->SetIceParameters(kIceParams[3]);
ep1_ch1()->SetRemoteIceParameters(kIceParams[3]);
ep2_ch1()->MaybeStartGathering();
// The caller should have the selected connection connected to the peer
// reflexive candidate.
EXPECT_EQ_WAIT(PRFLX_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type(),
kDefaultTimeout);
const Connection* prflx_selected_connection =
ep1_ch1()->selected_connection();
// Now simulate the ICE restart on ep1.
ep1_ch1()->SetIceParameters(kIceParams[2]);
ep2_ch1()->SetRemoteIceParameters(kIceParams[2]);
ep1_ch1()->MaybeStartGathering();
// Finally send the candidates from ep2's ICE restart and verify that ep1 uses
// their information to update the peer reflexive candidate.
ResumeCandidates(1);
EXPECT_EQ_WAIT(RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type(),
kDefaultTimeout);
EXPECT_EQ(prflx_selected_connection, ep1_ch1()->selected_connection());
DestroyChannels();
}
// Test that if remote candidates don't have ufrag and pwd, we still work.
TEST_F(P2PTransportChannelTest, RemoteCandidatesWithoutUfragPwd) {
rtc::ScopedFakeClock clock;
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
CreateChannels();
const Connection* selected_connection = NULL;
// Wait until the callee's connections are created.
EXPECT_TRUE_SIMULATED_WAIT(
(selected_connection = ep2_ch1()->selected_connection()) != NULL,
kMediumTimeout, clock);
// Wait to make sure the selected connection is not changed.
SIMULATED_WAIT(ep2_ch1()->selected_connection() != selected_connection,
kShortTimeout, clock);
EXPECT_TRUE(ep2_ch1()->selected_connection() == selected_connection);
DestroyChannels();
}
// Test that a host behind NAT cannot be reached when incoming_only
// is set to true.
TEST_F(P2PTransportChannelTest, IncomingOnlyBlocked) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(NAT_FULL_CONE, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
SetAllocatorFlags(0, kOnlyLocalPorts);
CreateChannels();
ep1_ch1()->set_incoming_only(true);
// Pump for 1 second and verify that the channels are not connected.
SIMULATED_WAIT(false, kShortTimeout, clock);
EXPECT_FALSE(ep1_ch1()->receiving());
EXPECT_FALSE(ep1_ch1()->writable());
EXPECT_FALSE(ep2_ch1()->receiving());
EXPECT_FALSE(ep2_ch1()->writable());
DestroyChannels();
}
// Test that a peer behind NAT can connect to a peer that has
// incoming_only flag set.
TEST_F(P2PTransportChannelTest, IncomingOnlyOpen) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, NAT_FULL_CONE, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
SetAllocatorFlags(0, kOnlyLocalPorts);
CreateChannels();
ep1_ch1()->set_incoming_only(true);
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kMediumTimeout, clock);
DestroyChannels();
}
// Test that two peers can connect when one can only make outgoing TCP
// connections. This has been observed in some scenarios involving
// VPNs/firewalls.
TEST_F(P2PTransportChannelTest, CanOnlyMakeOutgoingTcpConnections) {
// The PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS flag is required if the
// application needs this use case to work, since the application must accept
// the tradeoff that more candidates need to be allocated.
//
// TODO(deadbeef): Later, make this flag the default, and do more elegant
// things to ensure extra candidates don't waste resources?
ConfigureEndpoints(
OPEN, OPEN,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_ANY_ADDRESS_PORTS,
kDefaultPortAllocatorFlags);
// In order to simulate nothing working but outgoing TCP connections, prevent
// the endpoint from binding to its interface's address as well as the
// "any" addresses. It can then only make a connection by using "Connect()".
fw()->SetUnbindableIps({rtc::GetAnyIP(AF_INET), rtc::GetAnyIP(AF_INET6),
kPublicAddrs[0].ipaddr()});
CreateChannels();
// Expect a "prflx" candidate on the side that can only make outgoing
// connections, endpoint 0.
Test(kPrflxTcpToLocalTcp);
DestroyChannels();
}
TEST_F(P2PTransportChannelTest, TestTcpConnectionsFromActiveToPassive) {
rtc::ScopedFakeClock clock;
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
SetAllocationStepDelay(0, kMinimumStepDelay);
SetAllocationStepDelay(1, kMinimumStepDelay);
int kOnlyLocalTcpPorts = PORTALLOCATOR_DISABLE_UDP |
PORTALLOCATOR_DISABLE_STUN |
PORTALLOCATOR_DISABLE_RELAY;
// Disable all protocols except TCP.
SetAllocatorFlags(0, kOnlyLocalTcpPorts);
SetAllocatorFlags(1, kOnlyLocalTcpPorts);
SetAllowTcpListen(0, true); // actpass.
SetAllowTcpListen(1, false); // active.
// We want SetRemoteIceParameters to be called as it normally would.
// Otherwise we won't know what parameters to use for the expected
// prflx TCP candidates.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
// Pause candidate so we could verify the candidate properties.
PauseCandidates(0);
PauseCandidates(1);
CreateChannels();
// Verify tcp candidates.
VerifySavedTcpCandidates(0, TCPTYPE_PASSIVE_STR);
VerifySavedTcpCandidates(1, TCPTYPE_ACTIVE_STR);
// Resume candidates.
ResumeCandidates(0);
ResumeCandidates(1);
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kPublicAddrs[1]),
kShortTimeout, clock);
TestSendRecv(&clock);
DestroyChannels();
}
TEST_F(P2PTransportChannelTest, TestIceRoleConflict) {
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
TestSignalRoleConflict();
}
// Tests that the ice configs (protocol, tiebreaker and role) can be passed
// down to ports.
TEST_F(P2PTransportChannelTest, TestIceConfigWillPassDownToPort) {
rtc::ScopedFakeClock clock;
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
// Give the first connection the higher tiebreaker so its role won't
// change unless we tell it to.
SetIceRole(0, ICEROLE_CONTROLLING);
SetIceTiebreaker(0, kHighTiebreaker);
SetIceRole(1, ICEROLE_CONTROLLING);
SetIceTiebreaker(1, kLowTiebreaker);
CreateChannels();
EXPECT_EQ_SIMULATED_WAIT(2u, ep1_ch1()->ports().size(), kShortTimeout, clock);
const std::vector<PortInterface*> ports_before = ep1_ch1()->ports();
for (size_t i = 0; i < ports_before.size(); ++i) {
EXPECT_EQ(ICEROLE_CONTROLLING, ports_before[i]->GetIceRole());
EXPECT_EQ(kHighTiebreaker, ports_before[i]->IceTiebreaker());
}
ep1_ch1()->SetIceRole(ICEROLE_CONTROLLED);
ep1_ch1()->SetIceTiebreaker(kLowTiebreaker);
const std::vector<PortInterface*> ports_after = ep1_ch1()->ports();
for (size_t i = 0; i < ports_after.size(); ++i) {
EXPECT_EQ(ICEROLE_CONTROLLED, ports_before[i]->GetIceRole());
// SetIceTiebreaker after ports have been created will fail. So expect the
// original value.
EXPECT_EQ(kHighTiebreaker, ports_before[i]->IceTiebreaker());
}
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kShortTimeout, clock);
EXPECT_TRUE(ep1_ch1()->selected_connection() &&
ep2_ch1()->selected_connection());
TestSendRecv(&clock);
DestroyChannels();
}
// Verify that we can set DSCP value and retrieve properly from P2PTC.
TEST_F(P2PTransportChannelTest, TestDefaultDscpValue) {
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
CreateChannels();
EXPECT_EQ(rtc::DSCP_NO_CHANGE, GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
EXPECT_EQ(rtc::DSCP_NO_CHANGE, GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
GetEndpoint(0)->cd1_.ch_->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_CS6);
GetEndpoint(1)->cd1_.ch_->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_CS6);
EXPECT_EQ(rtc::DSCP_CS6, GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
EXPECT_EQ(rtc::DSCP_CS6, GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
GetEndpoint(0)->cd1_.ch_->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_AF41);
GetEndpoint(1)->cd1_.ch_->SetOption(rtc::Socket::OPT_DSCP, rtc::DSCP_AF41);
EXPECT_EQ(rtc::DSCP_AF41, GetEndpoint(0)->cd1_.ch_->DefaultDscpValue());
EXPECT_EQ(rtc::DSCP_AF41, GetEndpoint(1)->cd1_.ch_->DefaultDscpValue());
DestroyChannels();
}
// Verify IPv6 connection is preferred over IPv4.
TEST_F(P2PTransportChannelTest, TestIPv6Connections) {
rtc::ScopedFakeClock clock;
AddAddress(0, kIPv6PublicAddrs[0]);
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kIPv6PublicAddrs[1]);
AddAddress(1, kPublicAddrs[1]);
SetAllocationStepDelay(0, kMinimumStepDelay);
SetAllocationStepDelay(1, kMinimumStepDelay);
// Enable IPv6
SetAllocatorFlags(
0, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
SetAllocatorFlags(
1, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kIPv6PublicAddrs[0],
kIPv6PublicAddrs[1]),
kShortTimeout, clock);
TestSendRecv(&clock);
DestroyChannels();
}
// Testing forceful TURN connections.
TEST_F(P2PTransportChannelTest, TestForceTurn) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(
NAT_PORT_RESTRICTED, NAT_SYMMETRIC,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET);
set_force_relay(true);
SetAllocationStepDelay(0, kMinimumStepDelay);
SetAllocationStepDelay(1, kMinimumStepDelay);
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kMediumTimeout, clock);
EXPECT_TRUE(ep1_ch1()->selected_connection() &&
ep2_ch1()->selected_connection());
EXPECT_EQ(RELAY_PORT_TYPE, RemoteCandidate(ep1_ch1())->type());
EXPECT_EQ(RELAY_PORT_TYPE, LocalCandidate(ep1_ch1())->type());
EXPECT_EQ(RELAY_PORT_TYPE, RemoteCandidate(ep2_ch1())->type());
EXPECT_EQ(RELAY_PORT_TYPE, LocalCandidate(ep2_ch1())->type());
TestSendRecv(&clock);
DestroyChannels();
}
// Test that if continual gathering is set to true, ICE gathering state will
// not change to "Complete", and vice versa.
TEST_F(P2PTransportChannelTest, TestContinualGathering) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
SetAllocationStepDelay(0, kDefaultStepDelay);
SetAllocationStepDelay(1, kDefaultStepDelay);
IceConfig continual_gathering_config =
CreateIceConfig(1000, GATHER_CONTINUALLY);
// By default, ep2 does not gather continually.
IceConfig default_config;
CreateChannels(continual_gathering_config, default_config);
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kMediumTimeout, clock);
SIMULATED_WAIT(
IceGatheringState::kIceGatheringComplete == ep1_ch1()->gathering_state(),
kShortTimeout, clock);
EXPECT_EQ(IceGatheringState::kIceGatheringGathering,
ep1_ch1()->gathering_state());
// By now, ep2 should have completed gathering.
EXPECT_EQ(IceGatheringState::kIceGatheringComplete,
ep2_ch1()->gathering_state());
DestroyChannels();
}
// Test that a connection succeeds when the P2PTransportChannel uses a pooled
// PortAllocatorSession that has not yet finished gathering candidates.
TEST_F(P2PTransportChannelTest, TestUsingPooledSessionBeforeDoneGathering) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// First create a pooled session for each endpoint.
auto& allocator_1 = GetEndpoint(0)->allocator_;
auto& allocator_2 = GetEndpoint(1)->allocator_;
int pool_size = 1;
allocator_1->SetConfiguration(allocator_1->stun_servers(),
allocator_1->turn_servers(), pool_size,
webrtc::NO_PRUNE);
allocator_2->SetConfiguration(allocator_2->stun_servers(),
allocator_2->turn_servers(), pool_size,
webrtc::NO_PRUNE);
const PortAllocatorSession* pooled_session_1 =
allocator_1->GetPooledSession();
const PortAllocatorSession* pooled_session_2 =
allocator_2->GetPooledSession();
ASSERT_NE(nullptr, pooled_session_1);
ASSERT_NE(nullptr, pooled_session_2);
// Sanity check that pooled sessions haven't gathered anything yet.
EXPECT_TRUE(pooled_session_1->ReadyPorts().empty());
EXPECT_TRUE(pooled_session_1->ReadyCandidates().empty());
EXPECT_TRUE(pooled_session_2->ReadyPorts().empty());
EXPECT_TRUE(pooled_session_2->ReadyCandidates().empty());
// Now let the endpoints connect and try exchanging some data.
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kMediumTimeout, clock);
TestSendRecv(&clock);
// Make sure the P2PTransportChannels are actually using ports from the
// pooled sessions.
auto pooled_ports_1 = pooled_session_1->ReadyPorts();
auto pooled_ports_2 = pooled_session_2->ReadyPorts();
EXPECT_THAT(pooled_ports_1,
Contains(ep1_ch1()->selected_connection()->PortForTest()));
EXPECT_THAT(pooled_ports_2,
Contains(ep2_ch1()->selected_connection()->PortForTest()));
DestroyChannels();
}
// Test that a connection succeeds when the P2PTransportChannel uses a pooled
// PortAllocatorSession that already finished gathering candidates.
TEST_F(P2PTransportChannelTest, TestUsingPooledSessionAfterDoneGathering) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// First create a pooled session for each endpoint.
auto& allocator_1 = GetEndpoint(0)->allocator_;
auto& allocator_2 = GetEndpoint(1)->allocator_;
int pool_size = 1;
allocator_1->SetConfiguration(allocator_1->stun_servers(),
allocator_1->turn_servers(), pool_size,
webrtc::NO_PRUNE);
allocator_2->SetConfiguration(allocator_2->stun_servers(),
allocator_2->turn_servers(), pool_size,
webrtc::NO_PRUNE);
const PortAllocatorSession* pooled_session_1 =
allocator_1->GetPooledSession();
const PortAllocatorSession* pooled_session_2 =
allocator_2->GetPooledSession();
ASSERT_NE(nullptr, pooled_session_1);
ASSERT_NE(nullptr, pooled_session_2);
// Wait for the pooled sessions to finish gathering before the
// P2PTransportChannels try to use them.
EXPECT_TRUE_SIMULATED_WAIT(pooled_session_1->CandidatesAllocationDone() &&
pooled_session_2->CandidatesAllocationDone(),
kDefaultTimeout, clock);
// Now let the endpoints connect and try exchanging some data.
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kMediumTimeout, clock);
TestSendRecv(&clock);
// Make sure the P2PTransportChannels are actually using ports from the
// pooled sessions.
auto pooled_ports_1 = pooled_session_1->ReadyPorts();
auto pooled_ports_2 = pooled_session_2->ReadyPorts();
EXPECT_THAT(pooled_ports_1,
Contains(ep1_ch1()->selected_connection()->PortForTest()));
EXPECT_THAT(pooled_ports_2,
Contains(ep2_ch1()->selected_connection()->PortForTest()));
DestroyChannels();
}
// Test that when the "presume_writable_when_fully_relayed" flag is set to
// true and there's a TURN-TURN candidate pair, it's presumed to be writable
// as soon as it's created.
// TODO(deadbeef): Move this and other "presumed writable" tests into a test
// class that operates on a single P2PTransportChannel, once an appropriate one
// (which supports TURN servers and TURN candidate gathering) is available.
TEST_F(P2PTransportChannelTest, TurnToTurnPresumedWritable) {
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// Only configure one channel so we can control when the remote candidate
// is added.
GetEndpoint(0)->cd1_.ch_.reset(CreateChannel(
0, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[0], kIceParams[1]));
IceConfig config;
config.presume_writable_when_fully_relayed = true;
ep1_ch1()->SetIceConfig(config);
ep1_ch1()->MaybeStartGathering();
EXPECT_EQ_WAIT(IceGatheringState::kIceGatheringComplete,
ep1_ch1()->gathering_state(), kDefaultTimeout);
// Add two remote candidates; a host candidate (with higher priority)
// and TURN candidate.
ep1_ch1()->AddRemoteCandidate(
CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
ep1_ch1()->AddRemoteCandidate(
CreateUdpCandidate(RELAY_PORT_TYPE, "2.2.2.2", 2, 0));
// Expect that the TURN-TURN candidate pair will be prioritized since it's
// "probably writable".
EXPECT_TRUE_WAIT(ep1_ch1()->selected_connection() != nullptr, kShortTimeout);
EXPECT_EQ(RELAY_PORT_TYPE, LocalCandidate(ep1_ch1())->type());
EXPECT_EQ(RELAY_PORT_TYPE, RemoteCandidate(ep1_ch1())->type());
// Also expect that the channel instantly indicates that it's writable since
// it has a TURN-TURN pair.
EXPECT_TRUE(ep1_ch1()->writable());
EXPECT_TRUE(GetEndpoint(0)->ready_to_send_);
// Also make sure we can immediately send packets.
const char* data = "test";
int len = static_cast<int>(strlen(data));
EXPECT_EQ(len, SendData(ep1_ch1(), data, len));
// Prevent pending messages to access endpoints after their destruction.
DestroyChannels();
}
// Test that a TURN/peer reflexive candidate pair is also presumed writable.
TEST_F(P2PTransportChannelTest, TurnToPrflxPresumedWritable) {
rtc::ScopedFakeClock fake_clock;
// We need to add artificial network delay to verify that the connection
// is presumed writable before it's actually writable. Without this delay
// it would become writable instantly.
virtual_socket_server()->set_delay_mean(50);
virtual_socket_server()->UpdateDelayDistribution();
ConfigureEndpoints(NAT_SYMMETRIC, NAT_SYMMETRIC, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// We want the remote TURN candidate to show up as prflx. To do this we need
// to configure the server to accept packets from an address we haven't
// explicitly installed permission for.
test_turn_server()->set_enable_permission_checks(false);
IceConfig config;
config.presume_writable_when_fully_relayed = true;
GetEndpoint(0)->cd1_.ch_.reset(CreateChannel(
0, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[0], kIceParams[1]));
GetEndpoint(1)->cd1_.ch_.reset(CreateChannel(
1, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[1], kIceParams[0]));
ep1_ch1()->SetIceConfig(config);
ep2_ch1()->SetIceConfig(config);
// Don't signal candidates from channel 2, so that channel 1 sees the TURN
// candidate as peer reflexive.
PauseCandidates(1);
ep1_ch1()->MaybeStartGathering();
ep2_ch1()->MaybeStartGathering();
// Wait for the TURN<->prflx connection.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->receiving() && ep1_ch1()->writable(),
kShortTimeout, fake_clock);
ASSERT_NE(nullptr, ep1_ch1()->selected_connection());
EXPECT_EQ(RELAY_PORT_TYPE, LocalCandidate(ep1_ch1())->type());
EXPECT_EQ(PRFLX_PORT_TYPE, RemoteCandidate(ep1_ch1())->type());
// Make sure that at this point the connection is only presumed writable,
// not fully writable.
EXPECT_FALSE(ep1_ch1()->selected_connection()->writable());
// Now wait for it to actually become writable.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection()->writable(),
kShortTimeout, fake_clock);
// Explitly destroy channels, before fake clock is destroyed.
DestroyChannels();
}
// Test that a presumed-writable TURN<->TURN connection is preferred above an
// unreliable connection (one that has failed to be pinged for some time).
TEST_F(P2PTransportChannelTest, PresumedWritablePreferredOverUnreliable) {
rtc::ScopedFakeClock fake_clock;
ConfigureEndpoints(NAT_SYMMETRIC, NAT_SYMMETRIC, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
IceConfig config;
config.presume_writable_when_fully_relayed = true;
GetEndpoint(0)->cd1_.ch_.reset(CreateChannel(
0, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[0], kIceParams[1]));
GetEndpoint(1)->cd1_.ch_.reset(CreateChannel(
1, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[1], kIceParams[0]));
ep1_ch1()->SetIceConfig(config);
ep2_ch1()->SetIceConfig(config);
ep1_ch1()->MaybeStartGathering();
ep2_ch1()->MaybeStartGathering();
// Wait for initial connection as usual.
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kShortTimeout, fake_clock);
const Connection* old_selected_connection = ep1_ch1()->selected_connection();
// Destroy the second channel and wait for the current connection on the
// first channel to become "unreliable", making it no longer writable.
GetEndpoint(1)->cd1_.ch_.reset();
EXPECT_TRUE_SIMULATED_WAIT(!ep1_ch1()->writable(), kDefaultTimeout,
fake_clock);
EXPECT_NE(nullptr, ep1_ch1()->selected_connection());
// Add a remote TURN candidate. The first channel should still have a TURN
// port available to make a TURN<->TURN pair that's presumed writable.
ep1_ch1()->AddRemoteCandidate(
CreateUdpCandidate(RELAY_PORT_TYPE, "2.2.2.2", 2, 0));
EXPECT_EQ(RELAY_PORT_TYPE, LocalCandidate(ep1_ch1())->type());
EXPECT_EQ(RELAY_PORT_TYPE, RemoteCandidate(ep1_ch1())->type());
EXPECT_TRUE(ep1_ch1()->writable());
EXPECT_TRUE(GetEndpoint(0)->ready_to_send_);
EXPECT_NE(old_selected_connection, ep1_ch1()->selected_connection());
// Explitly destroy channels, before fake clock is destroyed.
DestroyChannels();
}
// Ensure that "SignalReadyToSend" is fired as expected with a "presumed
// writable" connection. Previously this did not work.
TEST_F(P2PTransportChannelTest, SignalReadyToSendWithPresumedWritable) {
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
// Only test one endpoint, so we can ensure the connection doesn't receive a
// binding response and advance beyond being "presumed" writable.
GetEndpoint(0)->cd1_.ch_.reset(CreateChannel(
0, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[0], kIceParams[1]));
IceConfig config;
config.presume_writable_when_fully_relayed = true;
ep1_ch1()->SetIceConfig(config);
ep1_ch1()->MaybeStartGathering();
EXPECT_EQ_WAIT(IceGatheringState::kIceGatheringComplete,
ep1_ch1()->gathering_state(), kDefaultTimeout);
ep1_ch1()->AddRemoteCandidate(
CreateUdpCandidate(RELAY_PORT_TYPE, "1.1.1.1", 1, 0));
// Sanity checking the type of the connection.
EXPECT_TRUE_WAIT(ep1_ch1()->selected_connection() != nullptr, kShortTimeout);
EXPECT_EQ(RELAY_PORT_TYPE, LocalCandidate(ep1_ch1())->type());
EXPECT_EQ(RELAY_PORT_TYPE, RemoteCandidate(ep1_ch1())->type());
// Tell the socket server to block packets (returning EWOULDBLOCK).
virtual_socket_server()->SetSendingBlocked(true);
const char* data = "test";
int len = static_cast<int>(strlen(data));
EXPECT_EQ(-1, SendData(ep1_ch1(), data, len));
// Reset |ready_to_send_| flag, which is set to true if the event fires as it
// should.
GetEndpoint(0)->ready_to_send_ = false;
virtual_socket_server()->SetSendingBlocked(false);
EXPECT_TRUE(GetEndpoint(0)->ready_to_send_);
EXPECT_EQ(len, SendData(ep1_ch1(), data, len));
DestroyChannels();
}
// Test that role conflict error responses are sent as expected when receiving a
// ping from an unknown address over a TURN connection. Regression test for
// crbug.com/webrtc/9034.
TEST_F(P2PTransportChannelTest,
TurnToPrflxSelectedAfterResolvingIceControllingRoleConflict) {
rtc::ScopedFakeClock clock;
// Gather only relay candidates.
ConfigureEndpoints(NAT_SYMMETRIC, NAT_SYMMETRIC,
kDefaultPortAllocatorFlags | PORTALLOCATOR_DISABLE_UDP |
PORTALLOCATOR_DISABLE_STUN | PORTALLOCATOR_DISABLE_TCP,
kDefaultPortAllocatorFlags | PORTALLOCATOR_DISABLE_UDP |
PORTALLOCATOR_DISABLE_STUN |
PORTALLOCATOR_DISABLE_TCP);
// With conflicting ICE roles, endpoint 1 has the higher tie breaker and will
// send a binding error response.
SetIceRole(0, ICEROLE_CONTROLLING);
SetIceTiebreaker(0, kHighTiebreaker);
SetIceRole(1, ICEROLE_CONTROLLING);
SetIceTiebreaker(1, kLowTiebreaker);
// We want the remote TURN candidate to show up as prflx. To do this we need
// to configure the server to accept packets from an address we haven't
// explicitly installed permission for.
test_turn_server()->set_enable_permission_checks(false);
GetEndpoint(0)->cd1_.ch_.reset(CreateChannel(
0, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[0], kIceParams[1]));
GetEndpoint(1)->cd1_.ch_.reset(CreateChannel(
1, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[1], kIceParams[0]));
// Don't signal candidates from channel 2, so that channel 1 sees the TURN
// candidate as peer reflexive.
PauseCandidates(1);
ep1_ch1()->MaybeStartGathering();
ep2_ch1()->MaybeStartGathering();
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->receiving() && ep1_ch1()->writable(),
kMediumTimeout, clock);
ASSERT_NE(nullptr, ep1_ch1()->selected_connection());
EXPECT_EQ(RELAY_PORT_TYPE, LocalCandidate(ep1_ch1())->type());
EXPECT_EQ(PRFLX_PORT_TYPE, RemoteCandidate(ep1_ch1())->type());
DestroyChannels();
}
// Test that the writability can be established with the piggyback
// acknowledgement in the connectivity check from the remote peer.
TEST_F(P2PTransportChannelTest,
CanConnectWithPiggybackCheckAcknowledgementWhenCheckResponseBlocked) {
webrtc::test::ScopedFieldTrials field_trials(
"WebRTC-PiggybackIceCheckAcknowledgement/Enabled/");
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
IceConfig ep1_config;
IceConfig ep2_config = CreateIceConfig(1000, GATHER_CONTINUALLY);
// Let ep2 be tolerable of the loss of connectivity checks, so that it keeps
// sending pings even after ep1 becomes unwritable as we configure the
// firewall below.
ep2_config.receiving_timeout = 30 * 1000;
ep2_config.ice_unwritable_timeout = 30 * 1000;
ep2_config.ice_unwritable_min_checks = 30;
ep2_config.ice_inactive_timeout = 60 * 1000;
CreateChannels(ep1_config, ep2_config);
// Wait until both sides become writable for the first time.
EXPECT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kDefaultTimeout, clock);
// Block the ingress traffic to ep1 so that there is no check response from
// ep2.
ASSERT_NE(nullptr, LocalCandidate(ep1_ch1()));
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_IN,
LocalCandidate(ep1_ch1())->address());
// Wait until ep1 becomes unwritable. At the same time ep2 should be still
// fine so that it will keep sending pings.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1() != nullptr && !ep1_ch1()->writable(),
kDefaultTimeout, clock);
EXPECT_TRUE(ep2_ch1() != nullptr && ep2_ch1()->writable());
// Now let the pings from ep2 to flow but block any pings from ep1, so that
// ep1 can only become writable again after receiving an incoming ping from
// ep2 with piggyback acknowledgement of its previously sent pings. Note
// though that ep1 should have stopped sending pings after becoming unwritable
// in the current design.
fw()->ClearRules();
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_OUT,
LocalCandidate(ep1_ch1())->address());
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1() != nullptr && ep1_ch1()->writable(),
kDefaultTimeout, clock);
DestroyChannels();
}
// Test what happens when we have 2 users behind the same NAT. This can lead
// to interesting behavior because the STUN server will only give out the
// address of the outermost NAT.
class P2PTransportChannelSameNatTest : public P2PTransportChannelTestBase {
protected:
void ConfigureEndpoints(Config nat_type, Config config1, Config config2) {
RTC_CHECK_GE(nat_type, NAT_FULL_CONE);
RTC_CHECK_LE(nat_type, NAT_SYMMETRIC);
rtc::NATSocketServer::Translator* outer_nat = nat()->AddTranslator(
kPublicAddrs[0], kNatAddrs[0],
static_cast<rtc::NATType>(nat_type - NAT_FULL_CONE));
ConfigureEndpoint(outer_nat, 0, config1);
ConfigureEndpoint(outer_nat, 1, config2);
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
}
void ConfigureEndpoint(rtc::NATSocketServer::Translator* nat,
int endpoint,
Config config) {
RTC_CHECK(config <= NAT_SYMMETRIC);
if (config == OPEN) {
AddAddress(endpoint, kPrivateAddrs[endpoint]);
nat->AddClient(kPrivateAddrs[endpoint]);
} else {
AddAddress(endpoint, kCascadedPrivateAddrs[endpoint]);
nat->AddTranslator(kPrivateAddrs[endpoint], kCascadedNatAddrs[endpoint],
static_cast<rtc::NATType>(config - NAT_FULL_CONE))
->AddClient(kCascadedPrivateAddrs[endpoint]);
}
}
};
TEST_F(P2PTransportChannelSameNatTest, TestConesBehindSameCone) {
ConfigureEndpoints(NAT_FULL_CONE, NAT_FULL_CONE, NAT_FULL_CONE);
Test(
P2PTransportChannelTestBase::Result("prflx", "udp", "stun", "udp", 1000));
}
// Test what happens when we have multiple available pathways.
// In the future we will try different RTTs and configs for the different
// interfaces, so that we can simulate a user with Ethernet and VPN networks.
class P2PTransportChannelMultihomedTest : public P2PTransportChannelTestBase {
public:
const Connection* GetConnectionWithRemoteAddress(
P2PTransportChannel* channel,
const SocketAddress& address) {
for (Connection* conn : channel->connections()) {
if (conn->remote_candidate().address().EqualIPs(address)) {
return conn;
}
}
return nullptr;
}
Connection* GetConnectionWithLocalAddress(P2PTransportChannel* channel,
const SocketAddress& address) {
for (Connection* conn : channel->connections()) {
if (conn->local_candidate().address().EqualIPs(address)) {
return conn;
}
}
return nullptr;
}
Connection* GetConnection(P2PTransportChannel* channel,
const SocketAddress& local,
const SocketAddress& remote) {
for (Connection* conn : channel->connections()) {
if (conn->local_candidate().address().EqualIPs(local) &&
conn->remote_candidate().address().EqualIPs(remote)) {
return conn;
}
}
return nullptr;
}
void DestroyAllButBestConnection(P2PTransportChannel* channel) {
const Connection* selected_connection = channel->selected_connection();
for (Connection* conn : channel->connections()) {
if (conn != selected_connection) {
conn->Destroy();
}
}
}
};
// Test that we can establish connectivity when both peers are multihomed.
TEST_F(P2PTransportChannelMultihomedTest, TestBasic) {
AddAddress(0, kPublicAddrs[0]);
AddAddress(0, kAlternateAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
AddAddress(1, kAlternateAddrs[1]);
Test(kLocalUdpToLocalUdp);
}
// Test that we can quickly switch links if an interface goes down.
// The controlled side has two interfaces and one will die.
TEST_F(P2PTransportChannelMultihomedTest, TestFailoverControlledSide) {
rtc::ScopedFakeClock clock;
AddAddress(0, kPublicAddrs[0]);
// Simulate failing over from Wi-Fi to cell interface.
AddAddress(1, kPublicAddrs[1], "eth0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, kAlternateAddrs[1], "wlan0", rtc::ADAPTER_TYPE_CELLULAR);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Make the receiving timeout shorter for testing.
IceConfig config = CreateIceConfig(1000, GATHER_ONCE);
// Create channels and let them go writable, as usual.
CreateChannels(config, config);
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kPublicAddrs[1]),
kMediumTimeout, clock);
// Blackhole any traffic to or from the public addrs.
RTC_LOG(LS_INFO) << "Failing over...";
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[1]);
// The selected connections may switch, so keep references to them.
const Connection* selected_connection1 = ep1_ch1()->selected_connection();
// We should detect loss of receiving within 1 second or so.
EXPECT_TRUE_SIMULATED_WAIT(!selected_connection1->receiving(), kMediumTimeout,
clock);
// We should switch over to use the alternate addr on both sides
// when we are not receiving.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection()->receiving() &&
ep2_ch1()->selected_connection()->receiving(),
kMediumTimeout, clock);
EXPECT_TRUE(LocalCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[0]));
EXPECT_TRUE(
RemoteCandidate(ep1_ch1())->address().EqualIPs(kAlternateAddrs[1]));
EXPECT_TRUE(
LocalCandidate(ep2_ch1())->address().EqualIPs(kAlternateAddrs[1]));
DestroyChannels();
}
// Test that we can quickly switch links if an interface goes down.
// The controlling side has two interfaces and one will die.
TEST_F(P2PTransportChannelMultihomedTest, TestFailoverControllingSide) {
rtc::ScopedFakeClock clock;
// Simulate failing over from Wi-Fi to cell interface.
AddAddress(0, kPublicAddrs[0], "eth0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, kAlternateAddrs[0], "wlan0", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, kPublicAddrs[1]);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Make the receiving timeout shorter for testing.
IceConfig config = CreateIceConfig(1000, GATHER_ONCE);
// Create channels and let them go writable, as usual.
CreateChannels(config, config);
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kPublicAddrs[1]),
kMediumTimeout, clock);
// Blackhole any traffic to or from the public addrs.
RTC_LOG(LS_INFO) << "Failing over...";
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[0]);
// We should detect loss of receiving within 1 second or so.
// We should switch over to use the alternate addr on both sides
// when we are not receiving.
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kAlternateAddrs[0],
kPublicAddrs[1]),
kMediumTimeout, clock);
DestroyChannels();
}
// Tests that we can quickly switch links if an interface goes down when
// there are many connections.
TEST_F(P2PTransportChannelMultihomedTest, TestFailoverWithManyConnections) {
rtc::ScopedFakeClock clock;
test_turn_server()->AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
RelayServerConfig turn_server;
turn_server.credentials = kRelayCredentials;
turn_server.ports.push_back(ProtocolAddress(kTurnTcpIntAddr, PROTO_TCP));
GetAllocator(0)->AddTurnServer(turn_server);
GetAllocator(1)->AddTurnServer(turn_server);
// Enable IPv6
SetAllocatorFlags(
0, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
SetAllocatorFlags(
1, PORTALLOCATOR_ENABLE_IPV6 | PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
SetAllocationStepDelay(0, kMinimumStepDelay);
SetAllocationStepDelay(1, kMinimumStepDelay);
auto& wifi = kPublicAddrs;
auto& cellular = kAlternateAddrs;
auto& wifiIpv6 = kIPv6PublicAddrs;
auto& cellularIpv6 = kIPv6AlternateAddrs;
AddAddress(0, wifi[0], "wifi0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, wifiIpv6[0], "wifi0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, cellular[0], "cellular0", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(0, cellularIpv6[0], "cellular0", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, wifi[1], "wifi1", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, wifiIpv6[1], "wifi1", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, cellular[1], "cellular1", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, cellularIpv6[1], "cellular1", rtc::ADAPTER_TYPE_CELLULAR);
// Set smaller delay on the TCP TURN server so that TCP TURN candidates
// will be created in time.
virtual_socket_server()->SetDelayOnAddress(kTurnTcpIntAddr, 1);
virtual_socket_server()->SetDelayOnAddress(kTurnUdpExtAddr, 1);
virtual_socket_server()->set_delay_mean(500);
virtual_socket_server()->UpdateDelayDistribution();
// Make the receiving timeout shorter for testing.
IceConfig config = CreateIceConfig(1000, GATHER_CONTINUALLY);
// Create channels and let them go writable, as usual.
CreateChannels(config, config, true /* ice_renomination */);
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifiIpv6[0],
wifiIpv6[1]),
kMediumTimeout, clock);
// Blackhole any traffic to or from the wifi on endpoint 1.
RTC_LOG(LS_INFO) << "Failing over...";
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, wifi[0]);
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, wifiIpv6[0]);
// The selected connections may switch, so keep references to them.
const Connection* selected_connection1 = ep1_ch1()->selected_connection();
const Connection* selected_connection2 = ep2_ch1()->selected_connection();
EXPECT_TRUE_SIMULATED_WAIT(
!selected_connection1->receiving() && !selected_connection2->receiving(),
kMediumTimeout, clock);
// Per-network best connections will be pinged at relatively higher rate when
// the selected connection becomes not receiving.
Connection* per_network_best_connection1 =
GetConnection(ep1_ch1(), cellularIpv6[0], wifiIpv6[1]);
ASSERT_NE(nullptr, per_network_best_connection1);
int64_t last_ping_sent1 = per_network_best_connection1->last_ping_sent();
int num_pings_sent1 = per_network_best_connection1->num_pings_sent();
EXPECT_TRUE_SIMULATED_WAIT(
num_pings_sent1 < per_network_best_connection1->num_pings_sent(),
kMediumTimeout, clock);
ASSERT_GT(per_network_best_connection1->num_pings_sent() - num_pings_sent1,
0);
int64_t ping_interval1 =
(per_network_best_connection1->last_ping_sent() - last_ping_sent1) /
(per_network_best_connection1->num_pings_sent() - num_pings_sent1);
constexpr int SCHEDULING_DELAY = 200;
EXPECT_LT(
ping_interval1,
WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL + SCHEDULING_DELAY);
// It should switch over to use the cellular IPv6 addr on endpoint 1 before
// it timed out on writing.
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), cellularIpv6[0],
wifiIpv6[1]),
kMediumTimeout, clock);
DestroyChannels();
}
// Test that when the controlling side switches the selected connection,
// the nomination of the selected connection on the controlled side will
// increase.
TEST_F(P2PTransportChannelMultihomedTest, TestIceRenomination) {
rtc::ScopedFakeClock clock;
// Simulate failing over from Wi-Fi to cell interface.
AddAddress(0, kPublicAddrs[0], "eth0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, kAlternateAddrs[0], "wlan0", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, kPublicAddrs[1]);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// We want it to set the remote ICE parameters when creating channels.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
// Make the receiving timeout shorter for testing.
IceConfig config = CreateIceConfig(1000, GATHER_ONCE);
// Create channels with ICE renomination and let them go writable as usual.
CreateChannels(config, config, true);
ASSERT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kMediumTimeout, clock);
EXPECT_TRUE_SIMULATED_WAIT(
ep2_ch1()->selected_connection()->remote_nomination() > 0 &&
ep1_ch1()->selected_connection()->acked_nomination() > 0,
kDefaultTimeout, clock);
const Connection* selected_connection1 = ep1_ch1()->selected_connection();
Connection* selected_connection2 =
const_cast<Connection*>(ep2_ch1()->selected_connection());
uint32_t remote_nomination2 = selected_connection2->remote_nomination();
// |selected_connection2| should not be nominated any more since the previous
// nomination has been acknowledged.
ConnectSignalNominated(selected_connection2);
SIMULATED_WAIT(nominated(), kMediumTimeout, clock);
EXPECT_FALSE(nominated());
// Blackhole any traffic to or from the public addrs.
RTC_LOG(LS_INFO) << "Failing over...";
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[0]);
// The selected connection on the controlling side should switch.
EXPECT_TRUE_SIMULATED_WAIT(
ep1_ch1()->selected_connection() != selected_connection1, kMediumTimeout,
clock);
// The connection on the controlled side should be nominated again
// and have an increased nomination.
EXPECT_TRUE_SIMULATED_WAIT(
ep2_ch1()->selected_connection()->remote_nomination() >
remote_nomination2,
kDefaultTimeout, clock);
DestroyChannels();
}
// Test that if an interface fails temporarily and then recovers quickly,
// the selected connection will not switch.
// The case that it will switch over to the backup connection if the selected
// connection does not recover after enough time is covered in
// TestFailoverControlledSide and TestFailoverControllingSide.
TEST_F(P2PTransportChannelMultihomedTest,
TestConnectionSwitchDampeningControlledSide) {
rtc::ScopedFakeClock clock;
AddAddress(0, kPublicAddrs[0]);
// Simulate failing over from Wi-Fi to cell interface.
AddAddress(1, kPublicAddrs[1], "eth0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, kAlternateAddrs[1], "wlan0", rtc::ADAPTER_TYPE_CELLULAR);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Create channels and let them go writable, as usual.
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kPublicAddrs[1]),
kMediumTimeout, clock);
// Make the receiving timeout shorter for testing.
IceConfig config = CreateIceConfig(1000, GATHER_ONCE);
ep1_ch1()->SetIceConfig(config);
ep2_ch1()->SetIceConfig(config);
reset_selected_candidate_pair_switches();
// Blackhole any traffic to or from the public addrs.
RTC_LOG(LS_INFO) << "Failing over...";
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[1]);
// The selected connections may switch, so keep references to them.
const Connection* selected_connection1 = ep1_ch1()->selected_connection();
// We should detect loss of receiving within 1 second or so.
EXPECT_TRUE_SIMULATED_WAIT(!selected_connection1->receiving(), kMediumTimeout,
clock);
// After a short while, the link recovers itself.
SIMULATED_WAIT(false, 10, clock);
fw()->ClearRules();
// We should remain on the public address on both sides and no connection
// switches should have happened.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection()->receiving() &&
ep2_ch1()->selected_connection()->receiving(),
kMediumTimeout, clock);
EXPECT_TRUE(RemoteCandidate(ep1_ch1())->address().EqualIPs(kPublicAddrs[1]));
EXPECT_TRUE(LocalCandidate(ep2_ch1())->address().EqualIPs(kPublicAddrs[1]));
EXPECT_EQ(0, reset_selected_candidate_pair_switches());
DestroyChannels();
}
// Test that if an interface fails temporarily and then recovers quickly,
// the selected connection will not switch.
TEST_F(P2PTransportChannelMultihomedTest,
TestConnectionSwitchDampeningControllingSide) {
rtc::ScopedFakeClock clock;
// Simulate failing over from Wi-Fi to cell interface.
AddAddress(0, kPublicAddrs[0], "eth0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, kAlternateAddrs[0], "wlan0", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, kPublicAddrs[1]);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Create channels and let them go writable, as usual.
CreateChannels();
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kPublicAddrs[1]),
kMediumTimeout, clock);
// Make the receiving timeout shorter for testing.
IceConfig config = CreateIceConfig(1000, GATHER_ONCE);
ep1_ch1()->SetIceConfig(config);
ep2_ch1()->SetIceConfig(config);
reset_selected_candidate_pair_switches();
// Blackhole any traffic to or from the public addrs.
RTC_LOG(LS_INFO) << "Failing over...";
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, kPublicAddrs[0]);
// The selected connections may switch, so keep references to them.
const Connection* selected_connection1 = ep1_ch1()->selected_connection();
// We should detect loss of receiving within 1 second or so.
EXPECT_TRUE_SIMULATED_WAIT(!selected_connection1->receiving(), kMediumTimeout,
clock);
// The link recovers after a short while.
SIMULATED_WAIT(false, 10, clock);
fw()->ClearRules();
// We should not switch to the alternate addr on both sides because of the
// dampening.
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kPublicAddrs[1]),
kMediumTimeout, clock);
EXPECT_EQ(0, reset_selected_candidate_pair_switches());
DestroyChannels();
}
// Tests that if the remote side's network failed, it won't cause the local
// side to switch connections and networks.
TEST_F(P2PTransportChannelMultihomedTest, TestRemoteFailover) {
rtc::ScopedFakeClock clock;
// The interface names are chosen so that |cellular| would have higher
// candidate priority and higher cost.
auto& wifi = kPublicAddrs;
auto& cellular = kAlternateAddrs;
AddAddress(0, wifi[0], "wifi0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, cellular[0], "cellular0", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, wifi[1], "wifi0", rtc::ADAPTER_TYPE_WIFI);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Create channels and let them go writable, as usual.
CreateChannels();
// Make the receiving timeout shorter for testing.
// Set the backup connection ping interval to 25s.
IceConfig config = CreateIceConfig(1000, GATHER_ONCE, 25000);
// Ping the best connection more frequently since we don't have traffic.
config.stable_writable_connection_ping_interval = 900;
ep1_ch1()->SetIceConfig(config);
ep2_ch1()->SetIceConfig(config);
// Need to wait to make sure the connections on both networks are writable.
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifi[0], wifi[1]),
kDefaultTimeout, clock);
Connection* backup_conn =
GetConnectionWithLocalAddress(ep1_ch1(), cellular[0]);
ASSERT_NE(nullptr, backup_conn);
// After a short while, the backup connection will be writable but not
// receiving because backup connection is pinged at a slower rate.
EXPECT_TRUE_SIMULATED_WAIT(
backup_conn->writable() && !backup_conn->receiving(), kDefaultTimeout,
clock);
reset_selected_candidate_pair_switches();
// Blackhole any traffic to or from the remote WiFi networks.
RTC_LOG(LS_INFO) << "Failing over...";
fw()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, wifi[1]);
int num_switches = 0;
SIMULATED_WAIT((num_switches = reset_selected_candidate_pair_switches()) > 0,
20000, clock);
EXPECT_EQ(0, num_switches);
DestroyChannels();
}
// Tests that a Wifi-Wifi connection has the highest precedence.
TEST_F(P2PTransportChannelMultihomedTest, TestPreferWifiToWifiConnection) {
// The interface names are chosen so that |cellular| would have higher
// candidate priority if it is not for the network type.
auto& wifi = kAlternateAddrs;
auto& cellular = kPublicAddrs;
AddAddress(0, wifi[0], "test0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, cellular[0], "test1", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, wifi[1], "test0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, cellular[1], "test1", rtc::ADAPTER_TYPE_CELLULAR);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Create channels and let them go writable, as usual.
CreateChannels();
EXPECT_TRUE_WAIT_MARGIN(CheckConnected(ep1_ch1(), ep2_ch1()), 1000, 1000);
// Need to wait to make sure the connections on both networks are writable.
EXPECT_TRUE_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifi[0], wifi[1]),
1000);
DestroyChannels();
}
// Tests that a Wifi-Cellular connection has higher precedence than
// a Cellular-Cellular connection.
TEST_F(P2PTransportChannelMultihomedTest, TestPreferWifiOverCellularNetwork) {
// The interface names are chosen so that |cellular| would have higher
// candidate priority if it is not for the network type.
auto& wifi = kAlternateAddrs;
auto& cellular = kPublicAddrs;
AddAddress(0, cellular[0], "test1", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, wifi[1], "test0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, cellular[1], "test1", rtc::ADAPTER_TYPE_CELLULAR);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Create channels and let them go writable, as usual.
CreateChannels();
EXPECT_TRUE_WAIT_MARGIN(CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(),
cellular[0], wifi[1]),
1000, 1000);
DestroyChannels();
}
// Test that the backup connection is pinged at a rate no faster than
// what was configured.
TEST_F(P2PTransportChannelMultihomedTest, TestPingBackupConnectionRate) {
AddAddress(0, kPublicAddrs[0]);
// Adding alternate address will make sure |kPublicAddrs| has the higher
// priority than others. This is due to FakeNetwork::AddInterface method.
AddAddress(1, kAlternateAddrs[1]);
AddAddress(1, kPublicAddrs[1]);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Create channels and let them go writable, as usual.
CreateChannels();
EXPECT_TRUE_WAIT_MARGIN(CheckConnected(ep1_ch1(), ep2_ch1()), 1000, 1000);
int backup_ping_interval = 2000;
ep2_ch1()->SetIceConfig(
CreateIceConfig(2000, GATHER_ONCE, backup_ping_interval));
// After the state becomes COMPLETED, the backup connection will be pinged
// once every |backup_ping_interval| milliseconds.
ASSERT_TRUE_WAIT(ep2_ch1()->GetState() == IceTransportState::STATE_COMPLETED,
1000);
auto connections = ep2_ch1()->connections();
ASSERT_EQ(2U, connections.size());
Connection* backup_conn = connections[1];
EXPECT_TRUE_WAIT(backup_conn->writable(), kMediumTimeout);
int64_t last_ping_response_ms = backup_conn->last_ping_response_received();
EXPECT_TRUE_WAIT(
last_ping_response_ms < backup_conn->last_ping_response_received(),
kDefaultTimeout);
int time_elapsed =
backup_conn->last_ping_response_received() - last_ping_response_ms;
RTC_LOG(LS_INFO) << "Time elapsed: " << time_elapsed;
EXPECT_GE(time_elapsed, backup_ping_interval);
DestroyChannels();
}
TEST_F(P2PTransportChannelMultihomedTest, TestGetState) {
rtc::ScopedFakeClock clock;
AddAddress(0, kAlternateAddrs[0]);
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
// Create channels and let them go writable, as usual.
CreateChannels();
// Both transport channels will reach STATE_COMPLETED quickly.
EXPECT_EQ_SIMULATED_WAIT(IceTransportState::STATE_COMPLETED,
ep1_ch1()->GetState(), kShortTimeout, clock);
EXPECT_EQ_SIMULATED_WAIT(IceTransportState::STATE_COMPLETED,
ep2_ch1()->GetState(), kShortTimeout, clock);
DestroyChannels();
}
// Tests that when a network interface becomes inactive, if Continual Gathering
// policy is GATHER_CONTINUALLY, the ports associated with that network
// will be removed from the port list of the channel, and the respective
// remote candidates on the other participant will be removed eventually.
TEST_F(P2PTransportChannelMultihomedTest, TestNetworkBecomesInactive) {
rtc::ScopedFakeClock clock;
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
// Create channels and let them go writable, as usual.
IceConfig ep1_config = CreateIceConfig(2000, GATHER_CONTINUALLY);
IceConfig ep2_config = CreateIceConfig(2000, GATHER_ONCE);
CreateChannels(ep1_config, ep2_config);
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
ASSERT_TRUE_SIMULATED_WAIT(CheckConnected(ep1_ch1(), ep2_ch1()),
kDefaultTimeout, clock);
// More than one port has been created.
EXPECT_LE(1U, ep1_ch1()->ports().size());
// Endpoint 1 enabled continual gathering; the port will be removed
// when the interface is removed.
RemoveAddress(0, kPublicAddrs[0]);
EXPECT_TRUE(ep1_ch1()->ports().empty());
// The remote candidates will be removed eventually.
EXPECT_TRUE_SIMULATED_WAIT(ep2_ch1()->remote_candidates().empty(), 1000,
clock);
size_t num_ports = ep2_ch1()->ports().size();
EXPECT_LE(1U, num_ports);
size_t num_remote_candidates = ep1_ch1()->remote_candidates().size();
// Endpoint 2 did not enable continual gathering; the local port will still be
// removed when the interface is removed but the remote candidates on the
// other participant will not be removed.
RemoveAddress(1, kPublicAddrs[1]);
EXPECT_EQ_SIMULATED_WAIT(0U, ep2_ch1()->ports().size(), kDefaultTimeout,
clock);
SIMULATED_WAIT(0U == ep1_ch1()->remote_candidates().size(), 500, clock);
EXPECT_EQ(num_remote_candidates, ep1_ch1()->remote_candidates().size());
DestroyChannels();
}
// Tests that continual gathering will create new connections when a new
// interface is added.
TEST_F(P2PTransportChannelMultihomedTest,
TestContinualGatheringOnNewInterface) {
auto& wifi = kAlternateAddrs;
auto& cellular = kPublicAddrs;
AddAddress(0, wifi[0], "test_wifi0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, cellular[1], "test_cell1", rtc::ADAPTER_TYPE_CELLULAR);
// Set continual gathering policy.
IceConfig continual_gathering_config =
CreateIceConfig(1000, GATHER_CONTINUALLY);
CreateChannels(continual_gathering_config, continual_gathering_config);
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
EXPECT_TRUE_WAIT_MARGIN(CheckConnected(ep1_ch1(), ep2_ch1()), kDefaultTimeout,
kDefaultTimeout);
// Add a new wifi interface on end point 2. We should expect a new connection
// to be created and the new one will be the best connection.
AddAddress(1, wifi[1], "test_wifi1", rtc::ADAPTER_TYPE_WIFI);
const Connection* conn;
EXPECT_TRUE_WAIT((conn = ep1_ch1()->selected_connection()) != nullptr &&
conn->remote_candidate().address().EqualIPs(wifi[1]),
kDefaultTimeout);
EXPECT_TRUE_WAIT((conn = ep2_ch1()->selected_connection()) != nullptr &&
conn->local_candidate().address().EqualIPs(wifi[1]),
kDefaultTimeout);
// Add a new cellular interface on end point 1, we should expect a new
// backup connection created using this new interface.
AddAddress(0, cellular[0], "test_cellular0", rtc::ADAPTER_TYPE_CELLULAR);
EXPECT_TRUE_WAIT(
ep1_ch1()->GetState() == IceTransportState::STATE_COMPLETED &&
(conn = GetConnectionWithLocalAddress(ep1_ch1(), cellular[0])) !=
nullptr &&
conn != ep1_ch1()->selected_connection() && conn->writable(),
kDefaultTimeout);
EXPECT_TRUE_WAIT(
ep2_ch1()->GetState() == IceTransportState::STATE_COMPLETED &&
(conn = GetConnectionWithRemoteAddress(ep2_ch1(), cellular[0])) !=
nullptr &&
conn != ep2_ch1()->selected_connection() && conn->receiving(),
kDefaultTimeout);
DestroyChannels();
}
// Tests that we can switch links via continual gathering.
TEST_F(P2PTransportChannelMultihomedTest,
TestSwitchLinksViaContinualGathering) {
rtc::ScopedFakeClock clock;
AddAddress(0, kPublicAddrs[0]);
AddAddress(1, kPublicAddrs[1]);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Set continual gathering policy.
IceConfig continual_gathering_config =
CreateIceConfig(1000, GATHER_CONTINUALLY);
// Create channels and let them go writable, as usual.
CreateChannels(continual_gathering_config, continual_gathering_config);
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kPublicAddrs[1]),
kMediumTimeout, clock);
// Add the new address first and then remove the other one.
RTC_LOG(LS_INFO) << "Draining...";
AddAddress(1, kAlternateAddrs[1]);
RemoveAddress(1, kPublicAddrs[1]);
// We should switch to use the alternate address after an exchange of pings.
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kAlternateAddrs[1]),
kMediumTimeout, clock);
// Remove one address first and then add another address.
RTC_LOG(LS_INFO) << "Draining again...";
RemoveAddress(1, kAlternateAddrs[1]);
AddAddress(1, kAlternateAddrs[0]);
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), kPublicAddrs[0],
kAlternateAddrs[0]),
kMediumTimeout, clock);
DestroyChannels();
}
// Tests that the backup connection will be restored after it is destroyed.
TEST_F(P2PTransportChannelMultihomedTest, TestRestoreBackupConnection) {
rtc::ScopedFakeClock clock;
auto& wifi = kAlternateAddrs;
auto& cellular = kPublicAddrs;
AddAddress(0, wifi[0], "test_wifi0", rtc::ADAPTER_TYPE_WIFI);
AddAddress(0, cellular[0], "test_cell0", rtc::ADAPTER_TYPE_CELLULAR);
AddAddress(1, wifi[1], "test_wifi1", rtc::ADAPTER_TYPE_WIFI);
AddAddress(1, cellular[1], "test_cell1", rtc::ADAPTER_TYPE_CELLULAR);
// Use only local ports for simplicity.
SetAllocatorFlags(0, kOnlyLocalPorts);
SetAllocatorFlags(1, kOnlyLocalPorts);
// Create channels and let them go writable, as usual.
IceConfig config = CreateIceConfig(1000, GATHER_CONTINUALLY);
config.regather_on_failed_networks_interval = 2000;
CreateChannels(config, config);
EXPECT_TRUE_SIMULATED_WAIT(
CheckCandidatePairAndConnected(ep1_ch1(), ep2_ch1(), wifi[0], wifi[1]),
kMediumTimeout, clock);
// Destroy all backup connections.
DestroyAllButBestConnection(ep1_ch1());
// Ensure the backup connection is removed first.
EXPECT_TRUE_SIMULATED_WAIT(
GetConnectionWithLocalAddress(ep1_ch1(), cellular[0]) == nullptr,
kDefaultTimeout, clock);
const Connection* conn;
EXPECT_TRUE_SIMULATED_WAIT(
(conn = GetConnectionWithLocalAddress(ep1_ch1(), cellular[0])) !=
nullptr &&
conn != ep1_ch1()->selected_connection() && conn->writable(),
kDefaultTimeout, clock);
DestroyChannels();
}
// A collection of tests which tests a single P2PTransportChannel by sending
// pings.
class P2PTransportChannelPingTest : public ::testing::Test,
public sigslot::has_slots<> {
public:
P2PTransportChannelPingTest()
: vss_(new rtc::VirtualSocketServer()), thread_(vss_.get()) {}
protected:
void PrepareChannel(P2PTransportChannel* ch) {
ch->SetIceRole(ICEROLE_CONTROLLING);
ch->SetIceParameters(kIceParams[0]);
ch->SetRemoteIceParameters(kIceParams[1]);
ch->SignalNetworkRouteChanged.connect(
this, &P2PTransportChannelPingTest::OnNetworkRouteChanged);
ch->SignalReadyToSend.connect(this,
&P2PTransportChannelPingTest::OnReadyToSend);
ch->SignalStateChanged.connect(
this, &P2PTransportChannelPingTest::OnChannelStateChanged);
ch->SignalCandidatePairChanged.connect(
this, &P2PTransportChannelPingTest::OnCandidatePairChanged);
}
Connection* WaitForConnectionTo(
P2PTransportChannel* ch,
const std::string& ip,
int port_num,
rtc::ThreadProcessingFakeClock* clock = nullptr) {
if (clock == nullptr) {
EXPECT_TRUE_WAIT(GetConnectionTo(ch, ip, port_num) != nullptr,
kMediumTimeout);
} else {
EXPECT_TRUE_SIMULATED_WAIT(GetConnectionTo(ch, ip, port_num) != nullptr,
kMediumTimeout, *clock);
}
return GetConnectionTo(ch, ip, port_num);
}
Port* GetPort(P2PTransportChannel* ch) {
if (ch->ports().empty()) {
return nullptr;
}
return static_cast<Port*>(ch->ports()[0]);
}
Port* GetPrunedPort(P2PTransportChannel* ch) {
if (ch->pruned_ports().empty()) {
return nullptr;
}
return static_cast<Port*>(ch->pruned_ports()[0]);
}
Connection* GetConnectionTo(P2PTransportChannel* ch,
const std::string& ip,
int port_num) {
Port* port = GetPort(ch);
if (!port) {
return nullptr;
}
return port->GetConnection(rtc::SocketAddress(ip, port_num));
}
Connection* FindNextPingableConnectionAndPingIt(P2PTransportChannel* ch) {
Connection* conn = ch->FindNextPingableConnection();
if (conn) {
ch->MarkConnectionPinged(conn);
}
return conn;
}
int SendData(IceTransportInternal* channel,
const char* data,
size_t len,
int packet_id) {
rtc::PacketOptions options;
options.packet_id = packet_id;
return channel->SendPacket(data, len, options, 0);
}
Connection* CreateConnectionWithCandidate(P2PTransportChannel* channel,
rtc::ScopedFakeClock* clock,
const std::string& ip_addr,
int port,
int priority,
bool writable) {
channel->AddRemoteCandidate(
CreateUdpCandidate(LOCAL_PORT_TYPE, ip_addr, port, priority));
EXPECT_TRUE_SIMULATED_WAIT(
GetConnectionTo(channel, ip_addr, port) != nullptr, kMediumTimeout,
*clock);
Connection* conn = GetConnectionTo(channel, ip_addr, port);
if (conn && writable) {
conn->ReceivedPingResponse(LOW_RTT, "id"); // make it writable
}
return conn;
}
void NominateConnection(Connection* conn, uint32_t remote_nomination = 1U) {
conn->set_remote_nomination(remote_nomination);
conn->SignalNominated(conn);
}
void OnNetworkRouteChanged(absl::optional<rtc::NetworkRoute> network_route) {
last_network_route_ = network_route;
if (last_network_route_) {
last_sent_packet_id_ = last_network_route_->last_sent_packet_id;
}
++selected_candidate_pair_switches_;
}
void ReceivePingOnConnection(
Connection* conn,
const std::string& remote_ufrag,
int priority,
uint32_t nomination,
const absl::optional<std::string>& piggyback_ping_id) {
IceMessage msg;
msg.SetType(STUN_BINDING_REQUEST);
msg.AddAttribute(std::make_unique<StunByteStringAttribute>(
STUN_ATTR_USERNAME,
conn->local_candidate().username() + ":" + remote_ufrag));
msg.AddAttribute(
std::make_unique<StunUInt32Attribute>(STUN_ATTR_PRIORITY, priority));
if (nomination != 0) {
msg.AddAttribute(std::make_unique<StunUInt32Attribute>(
STUN_ATTR_NOMINATION, nomination));
}
if (piggyback_ping_id) {
msg.AddAttribute(std::make_unique<StunByteStringAttribute>(
STUN_ATTR_LAST_ICE_CHECK_RECEIVED, piggyback_ping_id.value()));
}
msg.SetTransactionID(rtc::CreateRandomString(kStunTransactionIdLength));
msg.AddMessageIntegrity(conn->local_candidate().password());
msg.AddFingerprint();
rtc::ByteBufferWriter buf;
msg.Write(&buf);
conn->OnReadPacket(buf.Data(), buf.Length(), rtc::TimeMicros());
}
void ReceivePingOnConnection(Connection* conn,
const std::string& remote_ufrag,
int priority,
uint32_t nomination = 0) {
ReceivePingOnConnection(conn, remote_ufrag, priority, nomination,
absl::nullopt);
}
void OnReadyToSend(rtc::PacketTransportInternal* transport) {
channel_ready_to_send_ = true;
}
void OnChannelStateChanged(IceTransportInternal* channel) {
channel_state_ = channel->GetState();
}
void OnCandidatePairChanged(const CandidatePairChangeEvent& event) {
last_candidate_change_event_ = event;
}
int last_sent_packet_id() { return last_sent_packet_id_; }
bool channel_ready_to_send() { return channel_ready_to_send_; }
void reset_channel_ready_to_send() { channel_ready_to_send_ = false; }
IceTransportState channel_state() { return channel_state_; }
int reset_selected_candidate_pair_switches() {
int switches = selected_candidate_pair_switches_;
selected_candidate_pair_switches_ = 0;
return switches;
}
// Return true if the |pair| matches the last network route.
bool CandidatePairMatchesNetworkRoute(CandidatePairInterface* pair) {
if (!pair) {
return !last_network_route_.has_value();
} else {
return pair->local_candidate().network_id() ==
last_network_route_->local_network_id &&
pair->remote_candidate().network_id() ==
last_network_route_->remote_network_id;
}
}
bool ConnectionMatchesChangeEvent(Connection* conn, std::string reason) {
if (!conn) {
return !last_candidate_change_event_.has_value();
} else {
const auto& last_selected_pair =
last_candidate_change_event_->selected_candidate_pair;
return last_selected_pair.local_candidate().IsEquivalent(
conn->local_candidate()) &&
last_selected_pair.remote_candidate().IsEquivalent(
conn->remote_candidate()) &&
last_candidate_change_event_->last_data_received_ms ==
conn->last_data_received() &&
last_candidate_change_event_->reason == reason;
}
}
private:
std::unique_ptr<rtc::VirtualSocketServer> vss_;
rtc::AutoSocketServerThread thread_;
int selected_candidate_pair_switches_ = 0;
int last_sent_packet_id_ = -1;
bool channel_ready_to_send_ = false;
absl::optional<CandidatePairChangeEvent> last_candidate_change_event_;
IceTransportState channel_state_ = IceTransportState::STATE_INIT;
absl::optional<rtc::NetworkRoute> last_network_route_;
};
TEST_F(P2PTransportChannelPingTest, TestTriggeredChecks) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("trigger checks", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn1 != nullptr);
ASSERT_TRUE(conn2 != nullptr);
// Before a triggered check, the first connection to ping is the
// highest priority one.
EXPECT_EQ(conn2, FindNextPingableConnectionAndPingIt(&ch));
// Receiving a ping causes a triggered check which should make conn1
// be pinged first instead of conn2, even though conn2 has a higher
// priority.
conn1->ReceivedPing();
EXPECT_EQ(conn1, FindNextPingableConnectionAndPingIt(&ch));
}
TEST_F(P2PTransportChannelPingTest, TestAllConnectionsPingedSufficiently) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("ping sufficiently", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn1 != nullptr);
ASSERT_TRUE(conn2 != nullptr);
// Low-priority connection becomes writable so that the other connection
// is not pruned.
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_TRUE_WAIT(
conn1->num_pings_sent() >= MIN_PINGS_AT_WEAK_PING_INTERVAL &&
conn2->num_pings_sent() >= MIN_PINGS_AT_WEAK_PING_INTERVAL,
kDefaultTimeout);
}
// Verify that the connections are pinged at the right time.
TEST_F(P2PTransportChannelPingTest, TestStunPingIntervals) {
rtc::ScopedFakeClock clock;
int RTT_RATIO = 4;
int SCHEDULING_RANGE = 200;
int RTT_RANGE = 10;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("TestChannel", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn != nullptr);
SIMULATED_WAIT(conn->num_pings_sent() == 1, kDefaultTimeout, clock);
// Initializing.
int64_t start = clock.TimeNanos();
SIMULATED_WAIT(conn->num_pings_sent() >= MIN_PINGS_AT_WEAK_PING_INTERVAL,
kDefaultTimeout, clock);
int64_t ping_interval_ms = (clock.TimeNanos() - start) /
rtc::kNumNanosecsPerMillisec /
(MIN_PINGS_AT_WEAK_PING_INTERVAL - 1);
EXPECT_EQ(ping_interval_ms, WEAK_PING_INTERVAL);
// Stabilizing.
conn->ReceivedPingResponse(LOW_RTT, "id");
int ping_sent_before = conn->num_pings_sent();
start = clock.TimeNanos();
// The connection becomes strong but not stable because we haven't been able
// to converge the RTT.
SIMULATED_WAIT(conn->num_pings_sent() == ping_sent_before + 1, kMediumTimeout,
clock);
ping_interval_ms = (clock.TimeNanos() - start) / rtc::kNumNanosecsPerMillisec;
EXPECT_GE(ping_interval_ms,
WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL);
EXPECT_LE(
ping_interval_ms,
WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL + SCHEDULING_RANGE);
// Stabilized.
// The connection becomes stable after receiving more than RTT_RATIO rtt
// samples.
for (int i = 0; i < RTT_RATIO; i++) {
conn->ReceivedPingResponse(LOW_RTT, "id");
}
ping_sent_before = conn->num_pings_sent();
start = clock.TimeNanos();
SIMULATED_WAIT(conn->num_pings_sent() == ping_sent_before + 1, kMediumTimeout,
clock);
ping_interval_ms = (clock.TimeNanos() - start) / rtc::kNumNanosecsPerMillisec;
EXPECT_GE(ping_interval_ms,
STRONG_AND_STABLE_WRITABLE_CONNECTION_PING_INTERVAL);
EXPECT_LE(
ping_interval_ms,
STRONG_AND_STABLE_WRITABLE_CONNECTION_PING_INTERVAL + SCHEDULING_RANGE);
// Destabilized.
conn->ReceivedPingResponse(LOW_RTT, "id");
// Create a in-flight ping.
conn->Ping(clock.TimeNanos() / rtc::kNumNanosecsPerMillisec);
start = clock.TimeNanos();
// In-flight ping timeout and the connection will be unstable.
SIMULATED_WAIT(
!conn->stable(clock.TimeNanos() / rtc::kNumNanosecsPerMillisec),
kMediumTimeout, clock);
int64_t duration_ms =
(clock.TimeNanos() - start) / rtc::kNumNanosecsPerMillisec;
EXPECT_GE(duration_ms, 2 * conn->rtt() - RTT_RANGE);
EXPECT_LE(duration_ms, 2 * conn->rtt() + RTT_RANGE);
// The connection become unstable due to not receiving ping responses.
ping_sent_before = conn->num_pings_sent();
SIMULATED_WAIT(conn->num_pings_sent() == ping_sent_before + 1, kMediumTimeout,
clock);
// The interval is expected to be
// WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL.
start = clock.TimeNanos();
ping_sent_before = conn->num_pings_sent();
SIMULATED_WAIT(conn->num_pings_sent() == ping_sent_before + 1, kMediumTimeout,
clock);
ping_interval_ms = (clock.TimeNanos() - start) / rtc::kNumNanosecsPerMillisec;
EXPECT_GE(ping_interval_ms,
WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL);
EXPECT_LE(
ping_interval_ms,
WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL + SCHEDULING_RANGE);
}
// Test that we start pinging as soon as we have a connection and remote ICE
// parameters.
TEST_F(P2PTransportChannelPingTest, PingingStartedAsSoonAsPossible) {
rtc::ScopedFakeClock clock;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("TestChannel", 1, &pa);
ch.SetIceRole(ICEROLE_CONTROLLING);
ch.SetIceParameters(kIceParams[0]);
ch.MaybeStartGathering();
EXPECT_EQ_WAIT(IceGatheringState::kIceGatheringComplete, ch.gathering_state(),
kDefaultTimeout);
// Simulate a binding request being received, creating a peer reflexive
// candidate pair while we still don't have remote ICE parameters.
IceMessage request;
request.SetType(STUN_BINDING_REQUEST);
request.AddAttribute(std::make_unique<StunByteStringAttribute>(
STUN_ATTR_USERNAME, kIceUfrag[1]));
uint32_t prflx_priority = ICE_TYPE_PREFERENCE_PRFLX << 24;
request.AddAttribute(std::make_unique<StunUInt32Attribute>(STUN_ATTR_PRIORITY,
prflx_priority));
Port* port = GetPort(&ch);
ASSERT_NE(nullptr, port);
port->SignalUnknownAddress(port, rtc::SocketAddress("1.1.1.1", 1), PROTO_UDP,
&request, kIceUfrag[1], false);
Connection* conn = GetConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_NE(nullptr, conn);
// Simulate waiting for a second (and change) and verify that no pings were
// sent, since we don't yet have remote ICE parameters.
SIMULATED_WAIT(conn->num_pings_sent() > 0, 1025, clock);
EXPECT_EQ(0, conn->num_pings_sent());
// Set remote ICE parameters. Now we should be able to ping. Ensure that
// the first ping is sent as soon as possible, within one simulated clock
// tick.
ch.SetRemoteIceParameters(kIceParams[1]);
EXPECT_TRUE_SIMULATED_WAIT(conn->num_pings_sent() > 0, 1, clock);
}
TEST_F(P2PTransportChannelPingTest, TestNoTriggeredChecksWhenWritable) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("trigger checks", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn1 != nullptr);
ASSERT_TRUE(conn2 != nullptr);
EXPECT_EQ(conn2, FindNextPingableConnectionAndPingIt(&ch));
EXPECT_EQ(conn1, FindNextPingableConnectionAndPingIt(&ch));
conn1->ReceivedPingResponse(LOW_RTT, "id");
ASSERT_TRUE(conn1->writable());
conn1->ReceivedPing();
// Ping received, but the connection is already writable, so no
// "triggered check" and conn2 is pinged before conn1 because it has
// a higher priority.
EXPECT_EQ(conn2, FindNextPingableConnectionAndPingIt(&ch));
}
TEST_F(P2PTransportChannelPingTest, TestFailedConnectionNotPingable) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("Do not ping failed connections", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(conn1, ch.FindNextPingableConnection());
conn1->Prune(); // A pruned connection may still be pingable.
EXPECT_EQ(conn1, ch.FindNextPingableConnection());
conn1->FailAndPrune();
EXPECT_TRUE(nullptr == ch.FindNextPingableConnection());
}
TEST_F(P2PTransportChannelPingTest, TestSignalStateChanged) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("state change", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
// Pruning the connection reduces the set of active connections and changes
// the channel state.
conn1->Prune();
EXPECT_EQ_WAIT(IceTransportState::STATE_FAILED, channel_state(),
kDefaultTimeout);
}
// Test adding remote candidates with different ufrags. If a remote candidate
// is added with an old ufrag, it will be discarded. If it is added with a
// ufrag that was not seen before, it will be used to create connections
// although the ICE pwd in the remote candidate will be set when the ICE
// parameters arrive. If a remote candidate is added with the current ICE
// ufrag, its pwd and generation will be set properly.
TEST_F(P2PTransportChannelPingTest, TestAddRemoteCandidateWithVariousUfrags) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("add candidate", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
// Add a candidate with a future ufrag.
ch.AddRemoteCandidate(
CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1, kIceUfrag[2]));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
const Candidate& candidate = conn1->remote_candidate();
EXPECT_EQ(kIceUfrag[2], candidate.username());
EXPECT_TRUE(candidate.password().empty());
EXPECT_TRUE(FindNextPingableConnectionAndPingIt(&ch) == nullptr);
// Set the remote ICE parameters with the "future" ufrag.
// This should set the ICE pwd in the remote candidate of |conn1|, making
// it pingable.
ch.SetRemoteIceParameters(kIceParams[2]);
EXPECT_EQ(kIceUfrag[2], candidate.username());
EXPECT_EQ(kIcePwd[2], candidate.password());
EXPECT_EQ(conn1, FindNextPingableConnectionAndPingIt(&ch));
// Add a candidate with an old ufrag. No connection will be created.
ch.AddRemoteCandidate(
CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2, kIceUfrag[1]));
rtc::Thread::Current()->ProcessMessages(500);
EXPECT_TRUE(GetConnectionTo(&ch, "2.2.2.2", 2) == nullptr);
// Add a candidate with the current ufrag, its pwd and generation will be
// assigned, even if the generation is not set.
ch.AddRemoteCandidate(
CreateUdpCandidate(LOCAL_PORT_TYPE, "3.3.3.3", 3, 0, kIceUfrag[2]));
Connection* conn3 = nullptr;
ASSERT_TRUE_WAIT((conn3 = GetConnectionTo(&ch, "3.3.3.3", 3)) != nullptr,
kMediumTimeout);
const Candidate& new_candidate = conn3->remote_candidate();
EXPECT_EQ(kIcePwd[2], new_candidate.password());
EXPECT_EQ(1U, new_candidate.generation());
// Check that the pwd of all remote candidates are properly assigned.
for (const RemoteCandidate& candidate : ch.remote_candidates()) {
EXPECT_TRUE(candidate.username() == kIceUfrag[1] ||
candidate.username() == kIceUfrag[2]);
if (candidate.username() == kIceUfrag[1]) {
EXPECT_EQ(kIcePwd[1], candidate.password());
} else if (candidate.username() == kIceUfrag[2]) {
EXPECT_EQ(kIcePwd[2], candidate.password());
}
}
}
TEST_F(P2PTransportChannelPingTest, ConnectionResurrection) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("connection resurrection", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
// Create conn1 and keep track of original candidate priority.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
uint32_t remote_priority = conn1->remote_candidate().priority();
// Create a higher priority candidate and make the connection
// receiving/writable. This will prune conn1.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn2 != nullptr);
conn2->ReceivedPing();
conn2->ReceivedPingResponse(LOW_RTT, "id");
// Wait for conn2 to be selected.
EXPECT_EQ_WAIT(conn2, ch.selected_connection(), kMediumTimeout);
// Destroy the connection to test SignalUnknownAddress.
conn1->Destroy();
EXPECT_TRUE_WAIT(GetConnectionTo(&ch, "1.1.1.1", 1) == nullptr,
kMediumTimeout);
// Create a minimal STUN message with prflx priority.
IceMessage request;
request.SetType(STUN_BINDING_REQUEST);
request.AddAttribute(std::make_unique<StunByteStringAttribute>(
STUN_ATTR_USERNAME, kIceUfrag[1]));
uint32_t prflx_priority = ICE_TYPE_PREFERENCE_PRFLX << 24;
request.AddAttribute(std::make_unique<StunUInt32Attribute>(STUN_ATTR_PRIORITY,
prflx_priority));
EXPECT_NE(prflx_priority, remote_priority);
Port* port = GetPort(&ch);
// conn1 should be resurrected with original priority.
port->SignalUnknownAddress(port, rtc::SocketAddress("1.1.1.1", 1), PROTO_UDP,
&request, kIceUfrag[1], false);
conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(conn1->remote_candidate().priority(), remote_priority);
// conn3, a real prflx connection, should have prflx priority.
port->SignalUnknownAddress(port, rtc::SocketAddress("3.3.3.3", 1), PROTO_UDP,
&request, kIceUfrag[1], false);
Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 1);
ASSERT_TRUE(conn3 != nullptr);
EXPECT_EQ(conn3->remote_candidate().priority(), prflx_priority);
}
TEST_F(P2PTransportChannelPingTest, TestReceivingStateChange) {
rtc::ScopedFakeClock clock;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("receiving state change", 1, &pa);
PrepareChannel(&ch);
// Default receiving timeout and checking receiving interval should not be too
// small.
EXPECT_LE(1000, ch.config().receiving_timeout_or_default());
EXPECT_LE(200, ch.check_receiving_interval());
ch.SetIceConfig(CreateIceConfig(500, GATHER_ONCE));
EXPECT_EQ(500, ch.config().receiving_timeout_or_default());
EXPECT_EQ(50, ch.check_receiving_interval());
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
ASSERT_TRUE(conn1 != nullptr);
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
conn1->ReceivedPing();
conn1->OnReadPacket("ABC", 3, rtc::TimeMicros());
EXPECT_TRUE_SIMULATED_WAIT(ch.receiving(), kShortTimeout, clock);
EXPECT_TRUE_SIMULATED_WAIT(!ch.receiving(), kShortTimeout, clock);
}
// The controlled side will select a connection as the "selected connection"
// based on priority until the controlling side nominates a connection, at which
// point the controlled side will select that connection as the
// "selected connection". Plus, SignalNetworkRouteChanged will be fired if the
// selected connection changes and SignalReadyToSend will be fired if the new
// selected connection is writable.
TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBeforeNomination) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("receiving state change", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
// Channel is not ready to send because it is not writable.
EXPECT_FALSE(channel_ready_to_send());
int last_packet_id = 0;
const char* data = "ABCDEFGH";
int len = static_cast<int>(strlen(data));
EXPECT_EQ(-1, SendData(&ch, data, len, ++last_packet_id));
EXPECT_EQ(-1, last_sent_packet_id());
// A connection needs to be writable before it is selected for transmission.
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_WAIT(conn1, ch.selected_connection(), kDefaultTimeout);
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1));
EXPECT_TRUE(ConnectionMatchesChangeEvent(
conn1, "remote candidate generation maybe changed"));
EXPECT_EQ(len, SendData(&ch, data, len, ++last_packet_id));
// When a higher priority candidate comes in, the new connection is chosen
// as the selected connection.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 10));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn2 != nullptr);
conn2->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_WAIT(conn2, ch.selected_connection(), kDefaultTimeout);
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
EXPECT_TRUE(
ConnectionMatchesChangeEvent(conn2, "candidate pair state changed"));
EXPECT_TRUE(channel_ready_to_send());
EXPECT_EQ(last_packet_id, last_sent_packet_id());
// If a stun request with use-candidate attribute arrives, the receiving
// connection will be set as the selected connection, even though
// its priority is lower.
EXPECT_EQ(len, SendData(&ch, data, len, ++last_packet_id));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "3.3.3.3", 3, 1));
Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3);
ASSERT_TRUE(conn3 != nullptr);
// Because it has a lower priority, the selected connection is still conn2.
EXPECT_EQ(conn2, ch.selected_connection());
conn3->ReceivedPingResponse(LOW_RTT, "id"); // Become writable.
// But if it is nominated via use_candidate, it is chosen as the selected
// connection.
NominateConnection(conn3);
ASSERT_EQ(conn3, ch.selected_connection());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn3));
EXPECT_TRUE(
ConnectionMatchesChangeEvent(conn3, "nomination on the controlled side"));
EXPECT_EQ(last_packet_id, last_sent_packet_id());
EXPECT_TRUE(channel_ready_to_send());
// Even if another higher priority candidate arrives, it will not be set as
// the selected connection because the selected connection is nominated by
// the controlling side.
EXPECT_EQ(len, SendData(&ch, data, len, ++last_packet_id));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "4.4.4.4", 4, 100));
Connection* conn4 = WaitForConnectionTo(&ch, "4.4.4.4", 4);
ASSERT_TRUE(conn4 != nullptr);
EXPECT_EQ(conn3, ch.selected_connection());
// But if it is nominated via use_candidate and writable, it will be set as
// the selected connection.
NominateConnection(conn4);
// Not switched yet because conn4 is not writable.
EXPECT_EQ(conn3, ch.selected_connection());
reset_channel_ready_to_send();
// The selected connection switches after conn4 becomes writable.
conn4->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_WAIT(conn4, ch.selected_connection(), kDefaultTimeout);
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn4));
EXPECT_TRUE(
ConnectionMatchesChangeEvent(conn4, "candidate pair state changed"));
EXPECT_EQ(last_packet_id, last_sent_packet_id());
// SignalReadyToSend is fired again because conn4 is writable.
EXPECT_TRUE(channel_ready_to_send());
}
// The controlled side will select a connection as the "selected connection"
// based on requests from an unknown address before the controlling side
// nominates a connection, and will nominate a connection from an unknown
// address if the request contains the use_candidate attribute. Plus, it will
// also sends back a ping response and set the ICE pwd in the remote candidate
// appropriately.
TEST_F(P2PTransportChannelPingTest, TestSelectConnectionFromUnknownAddress) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("receiving state change", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
// A minimal STUN message with prflx priority.
IceMessage request;
request.SetType(STUN_BINDING_REQUEST);
request.AddAttribute(std::make_unique<StunByteStringAttribute>(
STUN_ATTR_USERNAME, kIceUfrag[1]));
uint32_t prflx_priority = ICE_TYPE_PREFERENCE_PRFLX << 24;
request.AddAttribute(std::make_unique<StunUInt32Attribute>(STUN_ATTR_PRIORITY,
prflx_priority));
TestUDPPort* port = static_cast<TestUDPPort*>(GetPort(&ch));
port->SignalUnknownAddress(port, rtc::SocketAddress("1.1.1.1", 1), PROTO_UDP,
&request, kIceUfrag[1], false);
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(conn1->stats().sent_ping_responses, 1u);
EXPECT_NE(conn1, ch.selected_connection());
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_WAIT(conn1, ch.selected_connection(), kDefaultTimeout);
// Another connection is nominated via use_candidate.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 1));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn2 != nullptr);
// Because it has a lower priority, the selected connection is still conn1.
EXPECT_EQ(conn1, ch.selected_connection());
// When it is nominated via use_candidate and writable, it is chosen as the
// selected connection.
conn2->ReceivedPingResponse(LOW_RTT, "id"); // Become writable.
NominateConnection(conn2);
EXPECT_EQ(conn2, ch.selected_connection());
// Another request with unknown address, it will not be set as the selected
// connection because the selected connection was nominated by the controlling
// side.
port->SignalUnknownAddress(port, rtc::SocketAddress("3.3.3.3", 3), PROTO_UDP,
&request, kIceUfrag[1], false);
Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3);
ASSERT_TRUE(conn3 != nullptr);
EXPECT_EQ(conn3->stats().sent_ping_responses, 1u);
conn3->ReceivedPingResponse(LOW_RTT, "id"); // Become writable.
EXPECT_EQ(conn2, ch.selected_connection());
// However if the request contains use_candidate attribute, it will be
// selected as the selected connection.
request.AddAttribute(
std::make_unique<StunByteStringAttribute>(STUN_ATTR_USE_CANDIDATE));
port->SignalUnknownAddress(port, rtc::SocketAddress("4.4.4.4", 4), PROTO_UDP,
&request, kIceUfrag[1], false);
Connection* conn4 = WaitForConnectionTo(&ch, "4.4.4.4", 4);
ASSERT_TRUE(conn4 != nullptr);
EXPECT_EQ(conn4->stats().sent_ping_responses, 1u);
// conn4 is not the selected connection yet because it is not writable.
EXPECT_EQ(conn2, ch.selected_connection());
conn4->ReceivedPingResponse(LOW_RTT, "id"); // Become writable.
EXPECT_EQ_WAIT(conn4, ch.selected_connection(), kDefaultTimeout);
// Test that the request from an unknown address contains a ufrag from an old
// generation.
// port->set_sent_binding_response(false);
ch.SetRemoteIceParameters(kIceParams[2]);
ch.SetRemoteIceParameters(kIceParams[3]);
port->SignalUnknownAddress(port, rtc::SocketAddress("5.5.5.5", 5), PROTO_UDP,
&request, kIceUfrag[2], false);
Connection* conn5 = WaitForConnectionTo(&ch, "5.5.5.5", 5);
ASSERT_TRUE(conn5 != nullptr);
EXPECT_EQ(conn5->stats().sent_ping_responses, 1u);
EXPECT_EQ(kIcePwd[2], conn5->remote_candidate().password());
}
// The controlled side will select a connection as the "selected connection"
// based on media received until the controlling side nominates a connection,
// at which point the controlled side will select that connection as
// the "selected connection".
TEST_F(P2PTransportChannelPingTest, TestSelectConnectionBasedOnMediaReceived) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("receiving state change", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 10));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_WAIT(conn1, ch.selected_connection(), kDefaultTimeout);
// If a data packet is received on conn2, the selected connection should
// switch to conn2 because the controlled side must mirror the media path
// chosen by the controlling side.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 1));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn2 != nullptr);
conn2->ReceivedPingResponse(LOW_RTT, "id"); // Become writable and receiving.
conn2->OnReadPacket("ABC", 3, rtc::TimeMicros());
EXPECT_EQ(conn2, ch.selected_connection());
conn2->ReceivedPingResponse(LOW_RTT, "id"); // Become writable.
// Now another STUN message with an unknown address and use_candidate will
// nominate the selected connection.
IceMessage request;
request.SetType(STUN_BINDING_REQUEST);
request.AddAttribute(std::make_unique<StunByteStringAttribute>(
STUN_ATTR_USERNAME, kIceUfrag[1]));
uint32_t prflx_priority = ICE_TYPE_PREFERENCE_PRFLX << 24;
request.AddAttribute(std::make_unique<StunUInt32Attribute>(STUN_ATTR_PRIORITY,
prflx_priority));
request.AddAttribute(
std::make_unique<StunByteStringAttribute>(STUN_ATTR_USE_CANDIDATE));
Port* port = GetPort(&ch);
port->SignalUnknownAddress(port, rtc::SocketAddress("3.3.3.3", 3), PROTO_UDP,
&request, kIceUfrag[1], false);
Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3);
ASSERT_TRUE(conn3 != nullptr);
EXPECT_NE(conn3, ch.selected_connection()); // Not writable yet.
conn3->ReceivedPingResponse(LOW_RTT, "id"); // Become writable.
EXPECT_EQ_WAIT(conn3, ch.selected_connection(), kDefaultTimeout);
// Now another data packet will not switch the selected connection because the
// selected connection was nominated by the controlling side.
conn2->ReceivedPing();
conn2->ReceivedPingResponse(LOW_RTT, "id");
conn2->OnReadPacket("XYZ", 3, rtc::TimeMicros());
EXPECT_EQ_WAIT(conn3, ch.selected_connection(), kDefaultTimeout);
}
TEST_F(P2PTransportChannelPingTest,
TestControlledAgentDataReceivingTakesHigherPrecedenceThanPriority) {
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("SwitchSelectedConnection", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
// The connections have decreasing priority.
Connection* conn1 =
CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 10, true);
ASSERT_TRUE(conn1 != nullptr);
Connection* conn2 =
CreateConnectionWithCandidate(&ch, &clock, "2.2.2.2", 2, 9, true);
ASSERT_TRUE(conn2 != nullptr);
// Initially, connections are selected based on priority.
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1));
// conn2 receives data; it becomes selected.
// Advance the clock by 1ms so that the last data receiving timestamp of
// conn2 is larger.
SIMULATED_WAIT(false, 1, clock);
conn2->OnReadPacket("XYZ", 3, rtc::TimeMicros());
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// conn1 also receives data; it becomes selected due to priority again.
conn1->OnReadPacket("XYZ", 3, rtc::TimeMicros());
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// conn2 received data more recently; it is selected now because it
// received data more recently.
SIMULATED_WAIT(false, 1, clock);
// Need to become writable again because it was pruned.
conn2->ReceivedPingResponse(LOW_RTT, "id");
conn2->OnReadPacket("XYZ", 3, rtc::TimeMicros());
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// Make sure sorting won't reselect candidate pair.
SIMULATED_WAIT(false, 10, clock);
EXPECT_EQ(0, reset_selected_candidate_pair_switches());
}
TEST_F(P2PTransportChannelPingTest,
TestControlledAgentNominationTakesHigherPrecedenceThanDataReceiving) {
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("SwitchSelectedConnection", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
// The connections have decreasing priority.
Connection* conn1 =
CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 10, true);
ASSERT_TRUE(conn1 != nullptr);
Connection* conn2 =
CreateConnectionWithCandidate(&ch, &clock, "2.2.2.2", 2, 9, true);
ASSERT_TRUE(conn2 != nullptr);
// conn1 received data; it is the selected connection.
// Advance the clock to have a non-zero last-data-receiving time.
SIMULATED_WAIT(false, 1, clock);
conn1->OnReadPacket("XYZ", 3, rtc::TimeMicros());
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1));
// conn2 is nominated; it becomes the selected connection.
NominateConnection(conn2);
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// conn1 is selected because it has higher priority and also nominated.
NominateConnection(conn1);
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// Make sure sorting won't reselect candidate pair.
SIMULATED_WAIT(false, 10, clock);
EXPECT_EQ(0, reset_selected_candidate_pair_switches());
}
TEST_F(P2PTransportChannelPingTest,
TestControlledAgentSelectsConnectionWithHigherNomination) {
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
// The connections have decreasing priority.
Connection* conn1 =
CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 10, true);
ASSERT_TRUE(conn1 != nullptr);
Connection* conn2 =
CreateConnectionWithCandidate(&ch, &clock, "2.2.2.2", 2, 9, true);
ASSERT_TRUE(conn2 != nullptr);
// conn1 is the selected connection because it has a higher priority,
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), kDefaultTimeout,
clock);
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1));
reset_selected_candidate_pair_switches();
// conn2 is nominated; it becomes selected.
NominateConnection(conn2);
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_EQ(conn2, ch.selected_connection());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// conn1 is selected because of its priority.
NominateConnection(conn1);
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_EQ(conn1, ch.selected_connection());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1));
// conn2 gets higher remote nomination; it is selected again.
NominateConnection(conn2, 2U);
EXPECT_EQ(1, reset_selected_candidate_pair_switches());
EXPECT_EQ(conn2, ch.selected_connection());
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// Make sure sorting won't reselect candidate pair.
SIMULATED_WAIT(false, 100, clock);
EXPECT_EQ(0, reset_selected_candidate_pair_switches());
}
TEST_F(P2PTransportChannelPingTest,
TestControlledAgentIgnoresSmallerNomination) {
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
Connection* conn =
CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 10, false);
ReceivePingOnConnection(conn, kIceUfrag[1], 1, 2U);
EXPECT_EQ(2U, conn->remote_nomination());
// Smaller nomination is ignored.
ReceivePingOnConnection(conn, kIceUfrag[1], 1, 1U);
EXPECT_EQ(2U, conn->remote_nomination());
}
TEST_F(P2PTransportChannelPingTest,
TestControlledAgentWriteStateTakesHigherPrecedenceThanNomination) {
rtc::ScopedFakeClock clock;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("SwitchSelectedConnection", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
// The connections have decreasing priority.
Connection* conn1 =
CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 10, false);
ASSERT_TRUE(conn1 != nullptr);
Connection* conn2 =
CreateConnectionWithCandidate(&ch, &clock, "2.2.2.2", 2, 9, false);
ASSERT_TRUE(conn2 != nullptr);
NominateConnection(conn1);
// There is no selected connection because no connection is writable.
EXPECT_EQ(0, reset_selected_candidate_pair_switches());
// conn2 becomes writable; it is selected even though it is not nominated.
conn2->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_SIMULATED_WAIT(1, reset_selected_candidate_pair_switches(),
kDefaultTimeout, clock);
EXPECT_EQ_SIMULATED_WAIT(conn2, ch.selected_connection(), kDefaultTimeout,
clock);
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn2));
// If conn1 is also writable, it will become selected.
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_SIMULATED_WAIT(1, reset_selected_candidate_pair_switches(),
kDefaultTimeout, clock);
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), kDefaultTimeout,
clock);
EXPECT_TRUE(CandidatePairMatchesNetworkRoute(conn1));
// Make sure sorting won't reselect candidate pair.
SIMULATED_WAIT(false, 10, clock);
EXPECT_EQ(0, reset_selected_candidate_pair_switches());
}
// Test that if a new remote candidate has the same address and port with
// an old one, it will be used to create a new connection.
TEST_F(P2PTransportChannelPingTest, TestAddRemoteCandidateWithAddressReuse) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("candidate reuse", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
const std::string host_address = "1.1.1.1";
const int port_num = 1;
// kIceUfrag[1] is the current generation ufrag.
Candidate candidate = CreateUdpCandidate(LOCAL_PORT_TYPE, host_address,
port_num, 1, kIceUfrag[1]);
ch.AddRemoteCandidate(candidate);
Connection* conn1 = WaitForConnectionTo(&ch, host_address, port_num);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(0u, conn1->remote_candidate().generation());
// Simply adding the same candidate again won't create a new connection.
ch.AddRemoteCandidate(candidate);
Connection* conn2 = GetConnectionTo(&ch, host_address, port_num);
EXPECT_EQ(conn1, conn2);
// Update the ufrag of the candidate and add it again.
candidate.set_username(kIceUfrag[2]);
ch.AddRemoteCandidate(candidate);
conn2 = GetConnectionTo(&ch, host_address, port_num);
EXPECT_NE(conn1, conn2);
EXPECT_EQ(kIceUfrag[2], conn2->remote_candidate().username());
EXPECT_EQ(1u, conn2->remote_candidate().generation());
// Verify that a ping with the new ufrag can be received on the new
// connection.
EXPECT_EQ(0, conn2->last_ping_received());
ReceivePingOnConnection(conn2, kIceUfrag[2], 1 /* priority */);
EXPECT_GT(conn2->last_ping_received(), 0);
}
// When the current selected connection is strong, lower-priority connections
// will be pruned. Otherwise, lower-priority connections are kept.
TEST_F(P2PTransportChannelPingTest, TestDontPruneWhenWeak) {
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(nullptr, ch.selected_connection());
conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
// When a higher-priority, nominated candidate comes in, the connections with
// lower-priority are pruned.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 10));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2, &clock);
ASSERT_TRUE(conn2 != nullptr);
conn2->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
NominateConnection(conn2);
EXPECT_TRUE_SIMULATED_WAIT(conn1->pruned(), kMediumTimeout, clock);
ch.SetIceConfig(CreateIceConfig(500, GATHER_ONCE));
// Wait until conn2 becomes not receiving.
EXPECT_TRUE_SIMULATED_WAIT(!conn2->receiving(), kMediumTimeout, clock);
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "3.3.3.3", 3, 1));
Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3, &clock);
ASSERT_TRUE(conn3 != nullptr);
// The selected connection should still be conn2. Even through conn3 has lower
// priority and is not receiving/writable, it is not pruned because the
// selected connection is not receiving.
SIMULATED_WAIT(conn3->pruned(), kShortTimeout, clock);
EXPECT_FALSE(conn3->pruned());
}
TEST_F(P2PTransportChannelPingTest, TestDontPruneHighPriorityConnections) {
rtc::ScopedFakeClock clock;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
Connection* conn1 =
CreateConnectionWithCandidate(&ch, &clock, "1.1.1.1", 1, 100, true);
ASSERT_TRUE(conn1 != nullptr);
Connection* conn2 =
CreateConnectionWithCandidate(&ch, &clock, "2.2.2.2", 2, 200, false);
ASSERT_TRUE(conn2 != nullptr);
// Even if conn1 is writable, nominated, receiving data, it should not prune
// conn2.
NominateConnection(conn1);
SIMULATED_WAIT(false, 1, clock);
conn1->OnReadPacket("XYZ", 3, rtc::TimeMicros());
SIMULATED_WAIT(conn2->pruned(), 100, clock);
EXPECT_FALSE(conn2->pruned());
}
// Test that GetState returns the state correctly.
TEST_F(P2PTransportChannelPingTest, TestGetState) {
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
EXPECT_EQ(webrtc::IceTransportState::kNew, ch.GetIceTransportState());
PrepareChannel(&ch);
ch.MaybeStartGathering();
// After gathering we are still in the kNew state because we aren't checking
// any connections yet.
EXPECT_EQ(webrtc::IceTransportState::kNew, ch.GetIceTransportState());
EXPECT_EQ(IceTransportState::STATE_INIT, ch.GetState());
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 1));
// Checking candidates that have been added with gathered candidates.
ASSERT_GT(ch.connections().size(), 0u);
EXPECT_EQ(webrtc::IceTransportState::kChecking, ch.GetIceTransportState());
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2, &clock);
ASSERT_TRUE(conn1 != nullptr);
ASSERT_TRUE(conn2 != nullptr);
// Now there are two connections, so the transport channel is connecting.
EXPECT_EQ(IceTransportState::STATE_CONNECTING, ch.GetState());
// No connections are writable yet, so we should still be in the kChecking
// state.
EXPECT_EQ(webrtc::IceTransportState::kChecking, ch.GetIceTransportState());
// |conn1| becomes writable and receiving; it then should prune |conn2|.
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_TRUE_SIMULATED_WAIT(conn2->pruned(), kShortTimeout, clock);
EXPECT_EQ(IceTransportState::STATE_COMPLETED, ch.GetState());
EXPECT_EQ(webrtc::IceTransportState::kConnected, ch.GetIceTransportState());
conn1->Prune(); // All connections are pruned.
// Need to wait until the channel state is updated.
EXPECT_EQ_SIMULATED_WAIT(IceTransportState::STATE_FAILED, ch.GetState(),
kShortTimeout, clock);
EXPECT_EQ(webrtc::IceTransportState::kFailed, ch.GetIceTransportState());
}
// Test that when a low-priority connection is pruned, it is not deleted
// right away, and it can become active and be pruned again.
TEST_F(P2PTransportChannelPingTest, TestConnectionPrunedAgain) {
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
IceConfig config = CreateIceConfig(1000, GATHER_ONCE);
config.receiving_switching_delay = 800;
ch.SetIceConfig(config);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(nullptr, ch.selected_connection());
conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), kDefaultTimeout,
clock);
// Add a low-priority connection |conn2|, which will be pruned, but it will
// not be deleted right away. Once the current selected connection becomes not
// receiving, |conn2| will start to ping and upon receiving the ping response,
// it will become the selected connection.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 1));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2, &clock);
ASSERT_TRUE(conn2 != nullptr);
EXPECT_TRUE_SIMULATED_WAIT(!conn2->active(), kDefaultTimeout, clock);
// |conn2| should not send a ping yet.
EXPECT_EQ(IceCandidatePairState::WAITING, conn2->state());
EXPECT_EQ(IceTransportState::STATE_COMPLETED, ch.GetState());
// Wait for |conn1| becoming not receiving.
EXPECT_TRUE_SIMULATED_WAIT(!conn1->receiving(), kMediumTimeout, clock);
// Make sure conn2 is not deleted.
conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2, &clock);
ASSERT_TRUE(conn2 != nullptr);
EXPECT_EQ_SIMULATED_WAIT(IceCandidatePairState::IN_PROGRESS, conn2->state(),
kDefaultTimeout, clock);
conn2->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_SIMULATED_WAIT(conn2, ch.selected_connection(), kDefaultTimeout,
clock);
EXPECT_EQ(IceTransportState::STATE_CONNECTING, ch.GetState());
// When |conn1| comes back again, |conn2| will be pruned again.
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), kDefaultTimeout,
clock);
EXPECT_TRUE_SIMULATED_WAIT(!conn2->active(), kDefaultTimeout, clock);
EXPECT_EQ(IceTransportState::STATE_COMPLETED, ch.GetState());
}
// Test that if all connections in a channel has timed out on writing, they
// will all be deleted. We use Prune to simulate write_time_out.
TEST_F(P2PTransportChannelPingTest, TestDeleteConnectionsIfAllWriteTimedout) {
rtc::ScopedFakeClock clock;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.MaybeStartGathering();
// Have one connection only but later becomes write-time-out.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
ASSERT_TRUE(conn1 != nullptr);
conn1->ReceivedPing(); // Becomes receiving
conn1->Prune();
EXPECT_TRUE_SIMULATED_WAIT(ch.connections().empty(), kShortTimeout, clock);
// Have two connections but both become write-time-out later.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 1));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2, &clock);
ASSERT_TRUE(conn2 != nullptr);
conn2->ReceivedPing(); // Becomes receiving
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "3.3.3.3", 3, 2));
Connection* conn3 = WaitForConnectionTo(&ch, "3.3.3.3", 3, &clock);
ASSERT_TRUE(conn3 != nullptr);
conn3->ReceivedPing(); // Becomes receiving
// Now prune both conn2 and conn3; they will be deleted soon.
conn2->Prune();
conn3->Prune();
EXPECT_TRUE_SIMULATED_WAIT(ch.connections().empty(), kShortTimeout, clock);
}
// Tests that after a port allocator session is started, it will be stopped
// when a new connection becomes writable and receiving. Also tests that if a
// connection belonging to an old session becomes writable, it won't stop
// the current port allocator session.
TEST_F(P2PTransportChannelPingTest, TestStopPortAllocatorSessions) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.SetIceConfig(CreateIceConfig(2000, GATHER_ONCE));
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn1 != nullptr);
conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
EXPECT_TRUE(!ch.allocator_session()->IsGettingPorts());
// Start a new session. Even though conn1, which belongs to an older
// session, becomes unwritable and writable again, it should not stop the
// current session.
ch.SetIceParameters(kIceParams[1]);
ch.MaybeStartGathering();
conn1->Prune();
conn1->ReceivedPingResponse(LOW_RTT, "id");
EXPECT_TRUE(ch.allocator_session()->IsGettingPorts());
// But if a new connection created from the new session becomes writable,
// it will stop the current session.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 100));
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn2 != nullptr);
conn2->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
EXPECT_TRUE(!ch.allocator_session()->IsGettingPorts());
}
// Test that the ICE role is updated even on ports that has been removed.
// These ports may still have connections that need a correct role, in case that
// the connections on it may still receive stun pings.
TEST_F(P2PTransportChannelPingTest, TestIceRoleUpdatedOnRemovedPort) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", ICE_CANDIDATE_COMPONENT_DEFAULT, &pa);
// Starts with ICEROLE_CONTROLLING.
PrepareChannel(&ch);
IceConfig config = CreateIceConfig(1000, GATHER_CONTINUALLY);
ch.SetIceConfig(config);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn != nullptr);
// Make a fake signal to remove the ports in the p2ptransportchannel. then
// change the ICE role and expect it to be updated.
std::vector<PortInterface*> ports(1, conn->PortForTest());
ch.allocator_session()->SignalPortsPruned(ch.allocator_session(), ports);
ch.SetIceRole(ICEROLE_CONTROLLED);
EXPECT_EQ(ICEROLE_CONTROLLED, conn->PortForTest()->GetIceRole());
}
// Test that the ICE role is updated even on ports with inactive networks.
// These ports may still have connections that need a correct role, for the
// pings sent by those connections until they're replaced by newer-generation
// connections.
TEST_F(P2PTransportChannelPingTest, TestIceRoleUpdatedOnPortAfterIceRestart) {
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", ICE_CANDIDATE_COMPONENT_DEFAULT, &pa);
// Starts with ICEROLE_CONTROLLING.
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn != nullptr);
// Do an ICE restart, change the role, and expect the old port to have its
// role updated.
ch.SetIceParameters(kIceParams[1]);
ch.MaybeStartGathering();
ch.SetIceRole(ICEROLE_CONTROLLED);
EXPECT_EQ(ICEROLE_CONTROLLED, conn->PortForTest()->GetIceRole());
}
// Test that after some amount of time without receiving data, the connection
// will be destroyed. The port will only be destroyed after it is marked as
// "pruned."
TEST_F(P2PTransportChannelPingTest, TestPortDestroyedAfterTimeoutAndPruned) {
rtc::ScopedFakeClock fake_clock;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", ICE_CANDIDATE_COMPONENT_DEFAULT, &pa);
PrepareChannel(&ch);
ch.SetIceRole(ICEROLE_CONTROLLED);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
Connection* conn = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn != nullptr);
// Simulate 2 minutes going by. This should be enough time for the port to
// time out.
for (int second = 0; second < 120; ++second) {
fake_clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
}
EXPECT_EQ(nullptr, GetConnectionTo(&ch, "1.1.1.1", 1));
// Port will not be removed because it is not pruned yet.
PortInterface* port = GetPort(&ch);
ASSERT_NE(nullptr, port);
// If the session prunes all ports, the port will be destroyed.
ch.allocator_session()->PruneAllPorts();
EXPECT_EQ_SIMULATED_WAIT(nullptr, GetPort(&ch), 1, fake_clock);
EXPECT_EQ_SIMULATED_WAIT(nullptr, GetPrunedPort(&ch), 1, fake_clock);
}
TEST_F(P2PTransportChannelPingTest, TestMaxOutstandingPingsFieldTrial) {
webrtc::test::ScopedFieldTrials field_trials(
"WebRTC-IceFieldTrials/max_outstanding_pings:3/");
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("max", 1, &pa);
ch.SetIceConfig(ch.config());
PrepareChannel(&ch);
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn1 != nullptr);
ASSERT_TRUE(conn2 != nullptr);
EXPECT_TRUE_WAIT(conn1->num_pings_sent() == 3 && conn2->num_pings_sent() == 3,
kDefaultTimeout);
// Check that these connections don't send any more pings.
EXPECT_EQ(nullptr, ch.FindNextPingableConnection());
}
class P2PTransportChannelMostLikelyToWorkFirstTest
: public P2PTransportChannelPingTest {
public:
P2PTransportChannelMostLikelyToWorkFirstTest()
: turn_server_(rtc::Thread::Current(), kTurnUdpIntAddr, kTurnUdpExtAddr) {
network_manager_.AddInterface(kPublicAddrs[0]);
allocator_.reset(
CreateBasicPortAllocator(&network_manager_, ServerAddresses(),
kTurnUdpIntAddr, rtc::SocketAddress()));
allocator_->set_flags(allocator_->flags() | PORTALLOCATOR_DISABLE_STUN |
PORTALLOCATOR_DISABLE_TCP);
allocator_->set_step_delay(kMinimumStepDelay);
}
P2PTransportChannel& StartTransportChannel(
bool prioritize_most_likely_to_work,
int stable_writable_connection_ping_interval) {
channel_.reset(new P2PTransportChannel("checks", 1, allocator()));
IceConfig config = channel_->config();
config.prioritize_most_likely_candidate_pairs =
prioritize_most_likely_to_work;
config.stable_writable_connection_ping_interval =
stable_writable_connection_ping_interval;
channel_->SetIceConfig(config);
PrepareChannel(channel_.get());
channel_->MaybeStartGathering();
return *channel_.get();
}
BasicPortAllocator* allocator() { return allocator_.get(); }
TestTurnServer* turn_server() { return &turn_server_; }
// This verifies the next pingable connection has the expected candidates'
// types and, for relay local candidate, the expected relay protocol and ping
// it.
void VerifyNextPingableConnection(
const std::string& local_candidate_type,
const std::string& remote_candidate_type,
const std::string& relay_protocol_type = UDP_PROTOCOL_NAME) {
Connection* conn = FindNextPingableConnectionAndPingIt(channel_.get());
ASSERT_TRUE(conn != nullptr);
EXPECT_EQ(conn->local_candidate().type(), local_candidate_type);
if (conn->local_candidate().type() == RELAY_PORT_TYPE) {
EXPECT_EQ(conn->local_candidate().relay_protocol(), relay_protocol_type);
}
EXPECT_EQ(conn->remote_candidate().type(), remote_candidate_type);
}
private:
std::unique_ptr<BasicPortAllocator> allocator_;
rtc::FakeNetworkManager network_manager_;
TestTurnServer turn_server_;
std::unique_ptr<P2PTransportChannel> channel_;
};
// Test that Relay/Relay connections will be pinged first when no other
// connections have been pinged yet, unless we need to ping a trigger check or
// we have a selected connection.
TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest,
TestRelayRelayFirstWhenNothingPingedYet) {
const int max_strong_interval = 500;
P2PTransportChannel& ch = StartTransportChannel(true, max_strong_interval);
EXPECT_TRUE_WAIT(ch.ports().size() == 2, kDefaultTimeout);
EXPECT_EQ(ch.ports()[0]->Type(), LOCAL_PORT_TYPE);
EXPECT_EQ(ch.ports()[1]->Type(), RELAY_PORT_TYPE);
ch.AddRemoteCandidate(CreateUdpCandidate(RELAY_PORT_TYPE, "1.1.1.1", 1, 1));
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
EXPECT_TRUE_WAIT(ch.connections().size() == 4, kDefaultTimeout);
// Relay/Relay should be the first pingable connection.
Connection* conn = FindNextPingableConnectionAndPingIt(&ch);
ASSERT_TRUE(conn != nullptr);
EXPECT_EQ(conn->local_candidate().type(), RELAY_PORT_TYPE);
EXPECT_EQ(conn->remote_candidate().type(), RELAY_PORT_TYPE);
// Unless that we have a trigger check waiting to be pinged.
Connection* conn2 = WaitForConnectionTo(&ch, "2.2.2.2", 2);
ASSERT_TRUE(conn2 != nullptr);
EXPECT_EQ(conn2->local_candidate().type(), LOCAL_PORT_TYPE);
EXPECT_EQ(conn2->remote_candidate().type(), LOCAL_PORT_TYPE);
conn2->ReceivedPing();
EXPECT_EQ(conn2, FindNextPingableConnectionAndPingIt(&ch));
// Make conn3 the selected connection.
Connection* conn3 = WaitForConnectionTo(&ch, "1.1.1.1", 1);
ASSERT_TRUE(conn3 != nullptr);
EXPECT_EQ(conn3->local_candidate().type(), LOCAL_PORT_TYPE);
EXPECT_EQ(conn3->remote_candidate().type(), RELAY_PORT_TYPE);
conn3->ReceivedPingResponse(LOW_RTT, "id");
ASSERT_TRUE(conn3->writable());
conn3->ReceivedPing();
/*
TODO(honghaiz): Re-enable this once we use fake clock for this test to fix
the flakiness. The following test becomes flaky because we now ping the
connections with fast rates until every connection is pinged at least three
times. The selected connection may have been pinged before
|max_strong_interval|, so it may not be the next connection to be pinged as
expected in the test.
// Verify that conn3 will be the "selected connection" since it is readable
// and writable. After |MAX_CURRENT_STRONG_INTERVAL|, it should be the next
// pingable connection.
EXPECT_TRUE_WAIT(conn3 == ch.selected_connection(), kDefaultTimeout);
WAIT(false, max_strong_interval + 100);
conn3->ReceivedPingResponse(LOW_RTT, "id");
ASSERT_TRUE(conn3->writable());
EXPECT_EQ(conn3, FindNextPingableConnectionAndPingIt(&ch));
*/
}
// Test that Relay/Relay connections will be pinged first when everything has
// been pinged even if the Relay/Relay connection wasn't the first to be pinged
// in the first round.
TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest,
TestRelayRelayFirstWhenEverythingPinged) {
P2PTransportChannel& ch = StartTransportChannel(true, 500);
EXPECT_TRUE_WAIT(ch.ports().size() == 2, kDefaultTimeout);
EXPECT_EQ(ch.ports()[0]->Type(), LOCAL_PORT_TYPE);
EXPECT_EQ(ch.ports()[1]->Type(), RELAY_PORT_TYPE);
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 1));
EXPECT_TRUE_WAIT(ch.connections().size() == 2, kDefaultTimeout);
// Initially, only have Local/Local and Local/Relay.
VerifyNextPingableConnection(LOCAL_PORT_TYPE, LOCAL_PORT_TYPE);
VerifyNextPingableConnection(RELAY_PORT_TYPE, LOCAL_PORT_TYPE);
// Remote Relay candidate arrives.
ch.AddRemoteCandidate(CreateUdpCandidate(RELAY_PORT_TYPE, "2.2.2.2", 2, 2));
EXPECT_TRUE_WAIT(ch.connections().size() == 4, kDefaultTimeout);
// Relay/Relay should be the first since it hasn't been pinged before.
VerifyNextPingableConnection(RELAY_PORT_TYPE, RELAY_PORT_TYPE);
// Local/Relay is the final one.
VerifyNextPingableConnection(LOCAL_PORT_TYPE, RELAY_PORT_TYPE);
// Now, every connection has been pinged once. The next one should be
// Relay/Relay.
VerifyNextPingableConnection(RELAY_PORT_TYPE, RELAY_PORT_TYPE);
}
// Test that when we receive a new remote candidate, they will be tried first
// before we re-ping Relay/Relay connections again.
TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest,
TestNoStarvationOnNonRelayConnection) {
P2PTransportChannel& ch = StartTransportChannel(true, 500);
EXPECT_TRUE_WAIT(ch.ports().size() == 2, kDefaultTimeout);
EXPECT_EQ(ch.ports()[0]->Type(), LOCAL_PORT_TYPE);
EXPECT_EQ(ch.ports()[1]->Type(), RELAY_PORT_TYPE);
ch.AddRemoteCandidate(CreateUdpCandidate(RELAY_PORT_TYPE, "1.1.1.1", 1, 1));
EXPECT_TRUE_WAIT(ch.connections().size() == 2, kDefaultTimeout);
// Initially, only have Relay/Relay and Local/Relay. Ping Relay/Relay first.
VerifyNextPingableConnection(RELAY_PORT_TYPE, RELAY_PORT_TYPE);
// Next, ping Local/Relay.
VerifyNextPingableConnection(LOCAL_PORT_TYPE, RELAY_PORT_TYPE);
// Remote Local candidate arrives.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
EXPECT_TRUE_WAIT(ch.connections().size() == 4, kDefaultTimeout);
// Local/Local should be the first since it hasn't been pinged before.
VerifyNextPingableConnection(LOCAL_PORT_TYPE, LOCAL_PORT_TYPE);
// Relay/Local is the final one.
VerifyNextPingableConnection(RELAY_PORT_TYPE, LOCAL_PORT_TYPE);
// Now, every connection has been pinged once. The next one should be
// Relay/Relay.
VerifyNextPingableConnection(RELAY_PORT_TYPE, RELAY_PORT_TYPE);
}
// Test skip_relay_to_non_relay_connections field-trial.
// I.e that we never create connection between relay and non-relay.
TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest,
TestSkipRelayToNonRelayConnectionsFieldTrial) {
webrtc::test::ScopedFieldTrials field_trials(
"WebRTC-IceFieldTrials/skip_relay_to_non_relay_connections:true/");
P2PTransportChannel& ch = StartTransportChannel(true, 500);
EXPECT_TRUE_WAIT(ch.ports().size() == 2, kDefaultTimeout);
EXPECT_EQ(ch.ports()[0]->Type(), LOCAL_PORT_TYPE);
EXPECT_EQ(ch.ports()[1]->Type(), RELAY_PORT_TYPE);
// Remote Relay candidate arrives.
ch.AddRemoteCandidate(CreateUdpCandidate(RELAY_PORT_TYPE, "1.1.1.1", 1, 1));
EXPECT_TRUE_WAIT(ch.connections().size() == 1, kDefaultTimeout);
// Remote Local candidate arrives.
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "2.2.2.2", 2, 2));
EXPECT_TRUE_WAIT(ch.connections().size() == 2, kDefaultTimeout);
}
// Test the ping sequence is UDP Relay/Relay followed by TCP Relay/Relay,
// followed by the rest.
TEST_F(P2PTransportChannelMostLikelyToWorkFirstTest, TestTcpTurn) {
// Add a Tcp Turn server.
turn_server()->AddInternalSocket(kTurnTcpIntAddr, PROTO_TCP);
RelayServerConfig config;
config.credentials = kRelayCredentials;
config.ports.push_back(ProtocolAddress(kTurnTcpIntAddr, PROTO_TCP));
allocator()->AddTurnServer(config);
P2PTransportChannel& ch = StartTransportChannel(true, 500);
EXPECT_TRUE_WAIT(ch.ports().size() == 3, kDefaultTimeout);
EXPECT_EQ(ch.ports()[0]->Type(), LOCAL_PORT_TYPE);
EXPECT_EQ(ch.ports()[1]->Type(), RELAY_PORT_TYPE);
EXPECT_EQ(ch.ports()[2]->Type(), RELAY_PORT_TYPE);
// Remote Relay candidate arrives.
ch.AddRemoteCandidate(CreateUdpCandidate(RELAY_PORT_TYPE, "1.1.1.1", 1, 1));
EXPECT_TRUE_WAIT(ch.connections().size() == 3, kDefaultTimeout);
// UDP Relay/Relay should be pinged first.
VerifyNextPingableConnection(RELAY_PORT_TYPE, RELAY_PORT_TYPE);
// TCP Relay/Relay is the next.
VerifyNextPingableConnection(RELAY_PORT_TYPE, RELAY_PORT_TYPE,
TCP_PROTOCOL_NAME);
// Finally, Local/Relay will be pinged.
VerifyNextPingableConnection(LOCAL_PORT_TYPE, RELAY_PORT_TYPE);
}
// Test that a resolver is created, asked for a result, and destroyed
// when the address is a hostname. The destruction should happen even
// if the channel is not destroyed.
TEST(P2PTransportChannelResolverTest, HostnameCandidateIsResolved) {
rtc::MockAsyncResolver mock_async_resolver;
EXPECT_CALL(mock_async_resolver, GetError()).WillOnce(Return(0));
EXPECT_CALL(mock_async_resolver, GetResolvedAddress(_, _))
.WillOnce(Return(true));
// Destroy is called asynchronously after the address is resolved,
// so we need a variable to wait on.
bool destroy_called = false;
EXPECT_CALL(mock_async_resolver, Destroy(_))
.WillOnce(Assign(&destroy_called, true));
webrtc::MockAsyncResolverFactory mock_async_resolver_factory;
EXPECT_CALL(mock_async_resolver_factory, Create())
.WillOnce(Return(&mock_async_resolver));
FakePortAllocator allocator(rtc::Thread::Current(), nullptr);
P2PTransportChannel channel("tn", 0, &allocator,
&mock_async_resolver_factory);
Candidate hostname_candidate;
SocketAddress hostname_address("fake.test", 1000);
hostname_candidate.set_address(hostname_address);
channel.AddRemoteCandidate(hostname_candidate);
ASSERT_EQ_WAIT(1u, channel.remote_candidates().size(), kDefaultTimeout);
const RemoteCandidate& candidate = channel.remote_candidates()[0];
EXPECT_FALSE(candidate.address().IsUnresolvedIP());
WAIT(destroy_called, kShortTimeout);
}
// Test that if we signal a hostname candidate after the remote endpoint
// discovers a prflx remote candidate with the same underlying IP address, the
// prflx candidate is updated to a host candidate after the name resolution is
// done.
TEST_F(P2PTransportChannelTest,
PeerReflexiveCandidateBeforeSignalingWithMdnsName) {
rtc::MockAsyncResolver mock_async_resolver;
webrtc::MockAsyncResolverFactory mock_async_resolver_factory;
EXPECT_CALL(mock_async_resolver_factory, Create())
.WillOnce(Return(&mock_async_resolver));
// ep1 and ep2 will only gather host candidates with addresses
// kPublicAddrs[0] and kPublicAddrs[1], respectively.
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// ICE parameter will be set up when creating the channels.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
GetEndpoint(0)->network_manager_.set_mdns_responder(
std::make_unique<webrtc::FakeMdnsResponder>(rtc::Thread::Current()));
GetEndpoint(1)->async_resolver_factory_ = &mock_async_resolver_factory;
CreateChannels();
// Pause sending candidates from both endpoints until we find out what port
// number is assgined to ep1's host candidate.
PauseCandidates(0);
PauseCandidates(1);
ASSERT_EQ_WAIT(1u, GetEndpoint(0)->saved_candidates_.size(), kMediumTimeout);
ASSERT_EQ(1u, GetEndpoint(0)->saved_candidates_[0]->candidates.size());
const auto& local_candidate =
GetEndpoint(0)->saved_candidates_[0]->candidates[0];
// The IP address of ep1's host candidate should be obfuscated.
EXPECT_TRUE(local_candidate.address().IsUnresolvedIP());
// This is the underlying private IP address of the same candidate at ep1.
const auto local_address = rtc::SocketAddress(
kPublicAddrs[0].ipaddr(), local_candidate.address().port());
// Let ep2 signal its candidate to ep1. ep1 should form a candidate
// pair and start to ping. After receiving the ping, ep2 discovers a prflx
// remote candidate and form a candidate pair as well.
ResumeCandidates(1);
ASSERT_TRUE_WAIT(ep1_ch1()->selected_connection() != nullptr, kMediumTimeout);
// ep2 should have the selected connection connected to the prflx remote
// candidate.
const Connection* selected_connection = nullptr;
ASSERT_TRUE_WAIT(
(selected_connection = ep2_ch1()->selected_connection()) != nullptr,
kMediumTimeout);
EXPECT_EQ(PRFLX_PORT_TYPE, selected_connection->remote_candidate().type());
EXPECT_EQ(kIceUfrag[0], selected_connection->remote_candidate().username());
EXPECT_EQ(kIcePwd[0], selected_connection->remote_candidate().password());
// Set expectation before ep1 signals a hostname candidate.
{
InSequence sequencer;
EXPECT_CALL(mock_async_resolver, Start(_));
EXPECT_CALL(mock_async_resolver, GetError()).WillOnce(Return(0));
// Let the mock resolver of ep2 receives the correct resolution.
EXPECT_CALL(mock_async_resolver, GetResolvedAddress(_, _))
.WillOnce(DoAll(SetArgPointee<1>(local_address), Return(true)));
}
// Destroy is called asynchronously after the address is resolved,
// so we need a variable to wait on.
bool destroy_called = false;
EXPECT_CALL(mock_async_resolver, Destroy(_))
.WillOnce(Assign(&destroy_called, true));
ResumeCandidates(0);
// Verify ep2's selected connection is updated to use the 'local' candidate.
EXPECT_EQ_WAIT(LOCAL_PORT_TYPE,
ep2_ch1()->selected_connection()->remote_candidate().type(),
kMediumTimeout);
EXPECT_EQ(selected_connection, ep2_ch1()->selected_connection());
WAIT(destroy_called, kShortTimeout);
DestroyChannels();
}
// Test that if we discover a prflx candidate during the process of name
// resolution for a remote hostname candidate, we update the prflx candidate to
// a host candidate if the hostname candidate turns out to have the same IP
// address after the resolution completes.
TEST_F(P2PTransportChannelTest,
PeerReflexiveCandidateDuringResolvingHostCandidateWithMdnsName) {
NiceMock<rtc::MockAsyncResolver> mock_async_resolver;
webrtc::MockAsyncResolverFactory mock_async_resolver_factory;
EXPECT_CALL(mock_async_resolver_factory, Create())
.WillOnce(Return(&mock_async_resolver));
// ep1 and ep2 will only gather host candidates with addresses
// kPublicAddrs[0] and kPublicAddrs[1], respectively.
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// ICE parameter will be set up when creating the channels.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
GetEndpoint(0)->network_manager_.set_mdns_responder(
std::make_unique<webrtc::FakeMdnsResponder>(rtc::Thread::Current()));
GetEndpoint(1)->async_resolver_factory_ = &mock_async_resolver_factory;
CreateChannels();
// Pause sending candidates from both endpoints until we find out what port
// number is assgined to ep1's host candidate.
PauseCandidates(0);
PauseCandidates(1);
ASSERT_EQ_WAIT(1u, GetEndpoint(0)->saved_candidates_.size(), kMediumTimeout);
ASSERT_EQ(1u, GetEndpoint(0)->saved_candidates_[0]->candidates.size());
const auto& local_candidate =
GetEndpoint(0)->saved_candidates_[0]->candidates[0];
// The IP address of ep1's host candidate should be obfuscated.
ASSERT_TRUE(local_candidate.address().IsUnresolvedIP());
// This is the underlying private IP address of the same candidate at ep1.
const auto local_address = rtc::SocketAddress(
kPublicAddrs[0].ipaddr(), local_candidate.address().port());
bool mock_async_resolver_started = false;
// Not signaling done yet, and only make sure we are in the process of
// resolution.
EXPECT_CALL(mock_async_resolver, Start(_))
.WillOnce(InvokeWithoutArgs([&mock_async_resolver_started]() {
mock_async_resolver_started = true;
}));
// Let ep1 signal its hostname candidate to ep2.
ResumeCandidates(0);
ASSERT_TRUE_WAIT(mock_async_resolver_started, kMediumTimeout);
// Now that ep2 is in the process of resolving the hostname candidate signaled
// by ep1. Let ep2 signal its host candidate with an IP address to ep1, so
// that ep1 can form a candidate pair, select it and start to ping ep2.
ResumeCandidates(1);
ASSERT_TRUE_WAIT(ep1_ch1()->selected_connection() != nullptr, kMediumTimeout);
// Let the mock resolver of ep2 receives the correct resolution.
EXPECT_CALL(mock_async_resolver, GetResolvedAddress(_, _))
.WillOnce(DoAll(SetArgPointee<1>(local_address), Return(true)));
// Upon receiving a ping from ep1, ep2 adds a prflx candidate from the
// unknown address and establishes a connection.
//
// There is a caveat in our implementation associated with this expectation.
// See the big comment in P2PTransportChannel::OnUnknownAddress.
ASSERT_TRUE_WAIT(ep2_ch1()->selected_connection() != nullptr, kMediumTimeout);
EXPECT_EQ(PRFLX_PORT_TYPE,
ep2_ch1()->selected_connection()->remote_candidate().type());
// ep2 should also be able resolve the hostname candidate. The resolved remote
// host candidate should be merged with the prflx remote candidate.
mock_async_resolver.SignalDone(&mock_async_resolver);
EXPECT_EQ_WAIT(LOCAL_PORT_TYPE,
ep2_ch1()->selected_connection()->remote_candidate().type(),
kMediumTimeout);
EXPECT_EQ(1u, ep2_ch1()->remote_candidates().size());
DestroyChannels();
}
// Test that if we only gather and signal a host candidate, the IP address of
// which is obfuscated by an mDNS name, and if the peer can complete the name
// resolution with the correct IP address, we can have a p2p connection.
TEST_F(P2PTransportChannelTest, CanConnectWithHostCandidateWithMdnsName) {
NiceMock<rtc::MockAsyncResolver> mock_async_resolver;
webrtc::MockAsyncResolverFactory mock_async_resolver_factory;
EXPECT_CALL(mock_async_resolver_factory, Create())
.WillOnce(Return(&mock_async_resolver));
// ep1 and ep2 will only gather host candidates with addresses
// kPublicAddrs[0] and kPublicAddrs[1], respectively.
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// ICE parameter will be set up when creating the channels.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
GetEndpoint(0)->network_manager_.set_mdns_responder(
std::make_unique<webrtc::FakeMdnsResponder>(rtc::Thread::Current()));
GetEndpoint(1)->async_resolver_factory_ = &mock_async_resolver_factory;
CreateChannels();
// Pause sending candidates from both endpoints until we find out what port
// number is assgined to ep1's host candidate.
PauseCandidates(0);
PauseCandidates(1);
ASSERT_EQ_WAIT(1u, GetEndpoint(0)->saved_candidates_.size(), kMediumTimeout);
ASSERT_EQ(1u, GetEndpoint(0)->saved_candidates_[0]->candidates.size());
const auto& local_candidate_ep1 =
GetEndpoint(0)->saved_candidates_[0]->candidates[0];
// The IP address of ep1's host candidate should be obfuscated.
EXPECT_TRUE(local_candidate_ep1.address().IsUnresolvedIP());
// This is the underlying private IP address of the same candidate at ep1,
// and let the mock resolver of ep2 receive the correct resolution.
rtc::SocketAddress resolved_address_ep1(local_candidate_ep1.address());
resolved_address_ep1.SetResolvedIP(kPublicAddrs[0].ipaddr());
EXPECT_CALL(mock_async_resolver, GetResolvedAddress(_, _))
.WillOnce(DoAll(SetArgPointee<1>(resolved_address_ep1), Return(true)));
// Let ep1 signal its hostname candidate to ep2.
ResumeCandidates(0);
// We should be able to receive a ping from ep2 and establish a connection
// with a peer reflexive candidate from ep2.
ASSERT_TRUE_WAIT((ep1_ch1()->selected_connection()) != nullptr,
kMediumTimeout);
EXPECT_EQ(LOCAL_PORT_TYPE,
ep1_ch1()->selected_connection()->local_candidate().type());
EXPECT_EQ(PRFLX_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type());
DestroyChannels();
}
// Test that when the IP of a host candidate is concealed by an mDNS name, the
// stats from the gathering ICE endpoint do not reveal the address of this local
// host candidate or the related address of a local srflx candidate from the
// same endpoint. Also, the remote ICE endpoint that successfully resolves a
// signaled host candidate with an mDNS name should not reveal the address of
// this remote host candidate in stats.
TEST_F(P2PTransportChannelTest,
CandidatesSanitizedInStatsWhenMdnsObfuscationEnabled) {
NiceMock<rtc::MockAsyncResolver> mock_async_resolver;
webrtc::MockAsyncResolverFactory mock_async_resolver_factory;
EXPECT_CALL(mock_async_resolver_factory, Create())
.WillOnce(Return(&mock_async_resolver));
// ep1 and ep2 will gather host candidates with addresses
// kPublicAddrs[0] and kPublicAddrs[1], respectively. ep1 also gathers a srflx
// and a relay candidates.
ConfigureEndpoints(OPEN, OPEN,
kDefaultPortAllocatorFlags | PORTALLOCATOR_DISABLE_TCP,
kOnlyLocalPorts);
// ICE parameter will be set up when creating the channels.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
GetEndpoint(0)->network_manager_.set_mdns_responder(
std::make_unique<webrtc::FakeMdnsResponder>(rtc::Thread::Current()));
GetEndpoint(1)->async_resolver_factory_ = &mock_async_resolver_factory;
CreateChannels();
// Pause sending candidates from both endpoints until we find out what port
// number is assigned to ep1's host candidate.
PauseCandidates(0);
PauseCandidates(1);
// Ep1 has a UDP host, a srflx and a relay candidates.
ASSERT_EQ_WAIT(3u, GetEndpoint(0)->saved_candidates_.size(), kMediumTimeout);
ASSERT_EQ_WAIT(1u, GetEndpoint(1)->saved_candidates_.size(), kMediumTimeout);
for (const auto& candidates_data : GetEndpoint(0)->saved_candidates_) {
ASSERT_EQ(1u, candidates_data->candidates.size());
const auto& local_candidate_ep1 = candidates_data->candidates[0];
if (local_candidate_ep1.type() == LOCAL_PORT_TYPE) {
// This is the underlying private IP address of the same candidate at ep1,
// and let the mock resolver of ep2 receive the correct resolution.
rtc::SocketAddress resolved_address_ep1(local_candidate_ep1.address());
resolved_address_ep1.SetResolvedIP(kPublicAddrs[0].ipaddr());
EXPECT_CALL(mock_async_resolver, GetResolvedAddress(_, _))
.WillOnce(
DoAll(SetArgPointee<1>(resolved_address_ep1), Return(true)));
break;
}
}
ResumeCandidates(0);
ResumeCandidates(1);
ASSERT_EQ_WAIT(kIceGatheringComplete, ep1_ch1()->gathering_state(),
kMediumTimeout);
// We should have the following candidate pairs on both endpoints:
// ep1_host <-> ep2_host, ep1_srflx <-> ep2_host, ep1_relay <-> ep2_host
ASSERT_EQ_WAIT(3u, ep1_ch1()->connections().size(), kMediumTimeout);
ASSERT_EQ_WAIT(3u, ep2_ch1()->connections().size(), kMediumTimeout);
IceTransportStats ice_transport_stats1;
IceTransportStats ice_transport_stats2;
ep1_ch1()->GetStats(&ice_transport_stats1);
ep2_ch1()->GetStats(&ice_transport_stats2);
EXPECT_EQ(3u, ice_transport_stats1.connection_infos.size());
EXPECT_EQ(3u, ice_transport_stats1.candidate_stats_list.size());
EXPECT_EQ(3u, ice_transport_stats2.connection_infos.size());
// Check the stats of ep1 seen by ep1.
for (const auto& connection_info : ice_transport_stats1.connection_infos) {
const auto& local_candidate = connection_info.local_candidate;
if (local_candidate.type() == LOCAL_PORT_TYPE) {
EXPECT_TRUE(local_candidate.address().IsUnresolvedIP());
} else if (local_candidate.type() == STUN_PORT_TYPE) {
EXPECT_TRUE(local_candidate.related_address().IsAnyIP());
} else if (local_candidate.type() == RELAY_PORT_TYPE) {
// The related address of the relay candidate should be equal to the
// srflx address. Note that NAT is not configured, hence the following
// expectation.
EXPECT_EQ(kPublicAddrs[0].ipaddr(),
local_candidate.related_address().ipaddr());
} else {
FAIL();
}
}
// Check the stats of ep1 seen by ep2.
for (const auto& connection_info : ice_transport_stats2.connection_infos) {
const auto& remote_candidate = connection_info.remote_candidate;
if (remote_candidate.type() == LOCAL_PORT_TYPE) {
EXPECT_TRUE(remote_candidate.address().IsUnresolvedIP());
} else if (remote_candidate.type() == STUN_PORT_TYPE) {
EXPECT_TRUE(remote_candidate.related_address().IsAnyIP());
} else if (remote_candidate.type() == RELAY_PORT_TYPE) {
EXPECT_EQ(kPublicAddrs[0].ipaddr(),
remote_candidate.related_address().ipaddr());
} else {
FAIL();
}
}
DestroyChannels();
}
TEST_F(P2PTransportChannelTest,
ConnectingIncreasesSelectedCandidatePairChanges) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
CreateChannels();
IceTransportStats ice_transport_stats;
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_EQ(0u, ice_transport_stats.selected_candidate_pair_changes);
// Let the channels connect.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection() != nullptr,
kMediumTimeout, clock);
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_EQ(1u, ice_transport_stats.selected_candidate_pair_changes);
DestroyChannels();
}
TEST_F(P2PTransportChannelTest,
DisconnectedIncreasesSelectedCandidatePairChanges) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
CreateChannels();
IceTransportStats ice_transport_stats;
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_EQ(0u, ice_transport_stats.selected_candidate_pair_changes);
// Let the channels connect.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection() != nullptr,
kMediumTimeout, clock);
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_EQ(1u, ice_transport_stats.selected_candidate_pair_changes);
// Prune connections and wait for disconnect.
for (Connection* con : ep1_ch1()->connections()) {
con->Prune();
}
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection() == nullptr,
kMediumTimeout, clock);
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_EQ(2u, ice_transport_stats.selected_candidate_pair_changes);
DestroyChannels();
}
TEST_F(P2PTransportChannelTest,
NewSelectionIncreasesSelectedCandidatePairChanges) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(OPEN, OPEN, kDefaultPortAllocatorFlags,
kDefaultPortAllocatorFlags);
CreateChannels();
IceTransportStats ice_transport_stats;
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_EQ(0u, ice_transport_stats.selected_candidate_pair_changes);
// Let the channels connect.
EXPECT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection() != nullptr,
kMediumTimeout, clock);
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_EQ(1u, ice_transport_stats.selected_candidate_pair_changes);
// Prune the currently selected connection and wait for selection
// of a new one.
const Connection* selected_connection = ep1_ch1()->selected_connection();
for (Connection* con : ep1_ch1()->connections()) {
if (con == selected_connection) {
con->Prune();
}
}
EXPECT_TRUE_SIMULATED_WAIT(
ep1_ch1()->selected_connection() != nullptr &&
(ep1_ch1()->GetStats(&ice_transport_stats),
ice_transport_stats.selected_candidate_pair_changes >= 2u),
kMediumTimeout, clock);
ASSERT_TRUE(ep1_ch1()->GetStats(&ice_transport_stats));
EXPECT_GE(ice_transport_stats.selected_candidate_pair_changes, 2u);
DestroyChannels();
}
// A similar test as above to check the selected candidate pair is sanitized
// when it is queried via GetSelectedCandidatePair.
TEST_F(P2PTransportChannelTest,
SelectedCandidatePairSanitizedWhenMdnsObfuscationEnabled) {
NiceMock<rtc::MockAsyncResolver> mock_async_resolver;
webrtc::MockAsyncResolverFactory mock_async_resolver_factory;
EXPECT_CALL(mock_async_resolver_factory, Create())
.WillOnce(Return(&mock_async_resolver));
// ep1 and ep2 will gather host candidates with addresses
// kPublicAddrs[0] and kPublicAddrs[1], respectively.
ConfigureEndpoints(OPEN, OPEN, kOnlyLocalPorts, kOnlyLocalPorts);
// ICE parameter will be set up when creating the channels.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
GetEndpoint(0)->network_manager_.set_mdns_responder(
std::make_unique<webrtc::FakeMdnsResponder>(rtc::Thread::Current()));
GetEndpoint(1)->async_resolver_factory_ = &mock_async_resolver_factory;
CreateChannels();
// Pause sending candidates from both endpoints until we find out what port
// number is assigned to ep1's host candidate.
PauseCandidates(0);
PauseCandidates(1);
ASSERT_EQ_WAIT(1u, GetEndpoint(0)->saved_candidates_.size(), kMediumTimeout);
const auto& candidates_data = GetEndpoint(0)->saved_candidates_[0];
ASSERT_EQ(1u, candidates_data->candidates.size());
const auto& local_candidate_ep1 = candidates_data->candidates[0];
ASSERT_TRUE(local_candidate_ep1.type() == LOCAL_PORT_TYPE);
// This is the underlying private IP address of the same candidate at ep1,
// and let the mock resolver of ep2 receive the correct resolution.
rtc::SocketAddress resolved_address_ep1(local_candidate_ep1.address());
resolved_address_ep1.SetResolvedIP(kPublicAddrs[0].ipaddr());
EXPECT_CALL(mock_async_resolver, GetResolvedAddress(_, _))
.WillOnce(DoAll(SetArgPointee<1>(resolved_address_ep1), Return(true)));
ResumeCandidates(0);
ResumeCandidates(1);
ASSERT_TRUE_WAIT(ep1_ch1()->selected_connection() != nullptr &&
ep2_ch1()->selected_connection() != nullptr,
kMediumTimeout);
const auto pair_ep1 = ep1_ch1()->GetSelectedCandidatePair();
ASSERT_TRUE(pair_ep1.has_value());
EXPECT_EQ(LOCAL_PORT_TYPE, pair_ep1->local_candidate().type());
EXPECT_TRUE(pair_ep1->local_candidate().address().IsUnresolvedIP());
const auto pair_ep2 = ep2_ch1()->GetSelectedCandidatePair();
ASSERT_TRUE(pair_ep2.has_value());
EXPECT_EQ(LOCAL_PORT_TYPE, pair_ep2->remote_candidate().type());
EXPECT_TRUE(pair_ep2->remote_candidate().address().IsUnresolvedIP());
DestroyChannels();
}
TEST_F(P2PTransportChannelTest,
NoPairOfLocalRelayCandidateWithRemoteMdnsCandidate) {
const int kOnlyRelayPorts = cricket::PORTALLOCATOR_DISABLE_UDP |
cricket::PORTALLOCATOR_DISABLE_STUN |
cricket::PORTALLOCATOR_DISABLE_TCP;
// We use one endpoint to test the behavior of adding remote candidates, and
// this endpoint only gathers relay candidates.
ConfigureEndpoints(OPEN, OPEN, kOnlyRelayPorts, kDefaultPortAllocatorFlags);
GetEndpoint(0)->cd1_.ch_.reset(CreateChannel(
0, ICE_CANDIDATE_COMPONENT_DEFAULT, kIceParams[0], kIceParams[1]));
IceConfig config;
// Start gathering and we should have only a single relay port.
ep1_ch1()->SetIceConfig(config);
ep1_ch1()->MaybeStartGathering();
EXPECT_EQ_WAIT(IceGatheringState::kIceGatheringComplete,
ep1_ch1()->gathering_state(), kDefaultTimeout);
EXPECT_EQ(1u, ep1_ch1()->ports().size());
// Add a plain remote host candidate and three remote mDNS candidates with the
// host, srflx and relay types. Note that the candidates differ in their
// ports.
cricket::Candidate host_candidate = CreateUdpCandidate(
LOCAL_PORT_TYPE, "1.1.1.1", 1 /* port */, 0 /* priority */);
ep1_ch1()->AddRemoteCandidate(host_candidate);
std::vector<cricket::Candidate> mdns_candidates;
mdns_candidates.push_back(CreateUdpCandidate(LOCAL_PORT_TYPE, "example.local",
2 /* port */, 0 /* priority */));
mdns_candidates.push_back(CreateUdpCandidate(STUN_PORT_TYPE, "example.local",
3 /* port */, 0 /* priority */));
mdns_candidates.push_back(CreateUdpCandidate(RELAY_PORT_TYPE, "example.local",
4 /* port */, 0 /* priority */));
// We just resolve the hostname to 1.1.1.1, and add the candidates with this
// address directly to simulate the process of adding remote candidates with
// the name resolution.
for (auto& mdns_candidate : mdns_candidates) {
rtc::SocketAddress resolved_address(mdns_candidate.address());
resolved_address.SetResolvedIP(0x1111); // 1.1.1.1
mdns_candidate.set_address(resolved_address);
EXPECT_FALSE(mdns_candidate.address().IsUnresolvedIP());
ep1_ch1()->AddRemoteCandidate(mdns_candidate);
}
// All remote candidates should have been successfully added.
EXPECT_EQ(4u, ep1_ch1()->remote_candidates().size());
// Expect that there is no connection paired with any mDNS candidate.
ASSERT_EQ(1u, ep1_ch1()->connections().size());
ASSERT_NE(nullptr, ep1_ch1()->connections()[0]);
EXPECT_EQ(
"1.1.1.1:1",
ep1_ch1()->connections()[0]->remote_candidate().address().ToString());
DestroyChannels();
}
class MockMdnsResponder : public webrtc::MdnsResponderInterface {
public:
MOCK_METHOD2(CreateNameForAddress,
void(const rtc::IPAddress&, NameCreatedCallback));
MOCK_METHOD2(RemoveNameForAddress,
void(const rtc::IPAddress&, NameRemovedCallback));
};
TEST_F(P2PTransportChannelTest,
SrflxCandidateCanBeGatheredBeforeMdnsCandidateToCreateConnection) {
// ep1 and ep2 will only gather host and srflx candidates with base addresses
// kPublicAddrs[0] and kPublicAddrs[1], respectively, and we use a shared
// socket in gathering.
const auto kOnlyLocalAndStunPorts =
cricket::PORTALLOCATOR_DISABLE_RELAY |
cricket::PORTALLOCATOR_DISABLE_TCP |
cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET;
// ep1 is configured with a NAT so that we do gather a srflx candidate.
ConfigureEndpoints(NAT_FULL_CONE, OPEN, kOnlyLocalAndStunPorts,
kOnlyLocalAndStunPorts);
// ICE parameter will be set up when creating the channels.
set_remote_ice_parameter_source(FROM_SETICEPARAMETERS);
// Use a mock mDNS responder, which does not complete the name registration by
// ignoring the completion callback.
auto mock_mdns_responder = std::make_unique<MockMdnsResponder>();
EXPECT_CALL(*mock_mdns_responder, CreateNameForAddress(_, _))
.Times(1)
.WillOnce(Return());
GetEndpoint(0)->network_manager_.set_mdns_responder(
std::move(mock_mdns_responder));
CreateChannels();
// We should be able to form a srflx-host connection to ep2.
ASSERT_TRUE_WAIT((ep1_ch1()->selected_connection()) != nullptr,
kMediumTimeout);
EXPECT_EQ(STUN_PORT_TYPE,
ep1_ch1()->selected_connection()->local_candidate().type());
EXPECT_EQ(LOCAL_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type());
DestroyChannels();
}
// Test that after changing the candidate filter from relay-only to allowing all
// types of candidates when doing continual gathering, we can gather without ICE
// restart the other types of candidates that are now enabled and form candidate
// pairs. Also, we verify that the relay candidates gathered previously are not
// removed and are still usable for necessary route switching.
TEST_F(P2PTransportChannelTest,
SurfaceHostCandidateOnCandidateFilterChangeFromRelayToAll) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(
OPEN, OPEN,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET);
auto* ep1 = GetEndpoint(0);
auto* ep2 = GetEndpoint(1);
ep1->allocator_->SetCandidateFilter(CF_RELAY);
ep2->allocator_->SetCandidateFilter(CF_RELAY);
// Enable continual gathering and also resurfacing gathered candidates upon
// the candidate filter changed in the ICE configuration.
IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY);
ice_config.surface_ice_candidates_on_ice_transport_type_changed = true;
CreateChannels(ice_config, ice_config);
ASSERT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection() != nullptr,
kDefaultTimeout, clock);
ASSERT_TRUE_SIMULATED_WAIT(ep2_ch1()->selected_connection() != nullptr,
kDefaultTimeout, clock);
EXPECT_EQ(RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->local_candidate().type());
EXPECT_EQ(RELAY_PORT_TYPE,
ep2_ch1()->selected_connection()->local_candidate().type());
// Loosen the candidate filter at ep1.
ep1->allocator_->SetCandidateFilter(CF_ALL);
EXPECT_TRUE_SIMULATED_WAIT(
ep1_ch1()->selected_connection() != nullptr &&
ep1_ch1()->selected_connection()->local_candidate().type() ==
LOCAL_PORT_TYPE,
kDefaultTimeout, clock);
EXPECT_EQ(RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type());
// Loosen the candidate filter at ep2.
ep2->allocator_->SetCandidateFilter(CF_ALL);
EXPECT_TRUE_SIMULATED_WAIT(
ep2_ch1()->selected_connection() != nullptr &&
ep2_ch1()->selected_connection()->local_candidate().type() ==
LOCAL_PORT_TYPE,
kDefaultTimeout, clock);
// We have migrated to a host-host candidate pair.
EXPECT_EQ(LOCAL_PORT_TYPE,
ep2_ch1()->selected_connection()->remote_candidate().type());
// Block the traffic over non-relay-to-relay routes and expect a route change.
fw()->AddRule(false, rtc::FP_ANY, kPublicAddrs[0], kPublicAddrs[1]);
fw()->AddRule(false, rtc::FP_ANY, kPublicAddrs[1], kPublicAddrs[0]);
fw()->AddRule(false, rtc::FP_ANY, kPublicAddrs[0], kTurnUdpExtAddr);
fw()->AddRule(false, rtc::FP_ANY, kPublicAddrs[1], kTurnUdpExtAddr);
// We should be able to reuse the previously gathered relay candidates.
EXPECT_EQ_SIMULATED_WAIT(
RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->local_candidate().type(),
kDefaultTimeout, clock);
EXPECT_EQ(RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type());
DestroyChannels();
}
// A similar test as SurfaceHostCandidateOnCandidateFilterChangeFromRelayToAll,
// and we should surface server-reflexive candidates that are enabled after
// changing the candidate filter.
TEST_F(P2PTransportChannelTest,
SurfaceSrflxCandidateOnCandidateFilterChangeFromRelayToNoHost) {
rtc::ScopedFakeClock clock;
// We need an actual NAT so that the host candidate is not equivalent to the
// srflx candidate; otherwise, the host candidate would still surface even
// though we disable it via the candidate filter below. This is a result of
// the following limitation in the current implementation:
// 1. We don't generate the srflx candidate when we have public IP.
// 2. We keep the host candidate in this case in CheckCandidateFilter even
// though we intend to filter them.
ConfigureEndpoints(
NAT_FULL_CONE, NAT_FULL_CONE,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET);
auto* ep1 = GetEndpoint(0);
auto* ep2 = GetEndpoint(1);
ep1->allocator_->SetCandidateFilter(CF_RELAY);
ep2->allocator_->SetCandidateFilter(CF_RELAY);
// Enable continual gathering and also resurfacing gathered candidates upon
// the candidate filter changed in the ICE configuration.
IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY);
ice_config.surface_ice_candidates_on_ice_transport_type_changed = true;
CreateChannels(ice_config, ice_config);
ASSERT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection() != nullptr,
kDefaultTimeout, clock);
ASSERT_TRUE_SIMULATED_WAIT(ep2_ch1()->selected_connection() != nullptr,
kDefaultTimeout, clock);
const uint32_t kCandidateFilterNoHost = CF_ALL & ~CF_HOST;
// Loosen the candidate filter at ep1.
ep1->allocator_->SetCandidateFilter(kCandidateFilterNoHost);
EXPECT_TRUE_SIMULATED_WAIT(
ep1_ch1()->selected_connection() != nullptr &&
ep1_ch1()->selected_connection()->local_candidate().type() ==
STUN_PORT_TYPE,
kDefaultTimeout, clock);
EXPECT_EQ(RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type());
// Loosen the candidate filter at ep2.
ep2->allocator_->SetCandidateFilter(kCandidateFilterNoHost);
EXPECT_TRUE_SIMULATED_WAIT(
ep2_ch1()->selected_connection() != nullptr &&
ep2_ch1()->selected_connection()->local_candidate().type() ==
STUN_PORT_TYPE,
kDefaultTimeout, clock);
// We have migrated to a srflx-srflx candidate pair.
EXPECT_EQ(STUN_PORT_TYPE,
ep2_ch1()->selected_connection()->remote_candidate().type());
// Block the traffic over non-relay-to-relay routes and expect a route change.
fw()->AddRule(false, rtc::FP_ANY, kPrivateAddrs[0], kPublicAddrs[1]);
fw()->AddRule(false, rtc::FP_ANY, kPrivateAddrs[1], kPublicAddrs[0]);
fw()->AddRule(false, rtc::FP_ANY, kPrivateAddrs[0], kTurnUdpExtAddr);
fw()->AddRule(false, rtc::FP_ANY, kPrivateAddrs[1], kTurnUdpExtAddr);
// We should be able to reuse the previously gathered relay candidates.
EXPECT_EQ_SIMULATED_WAIT(
RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->local_candidate().type(),
kDefaultTimeout, clock);
EXPECT_EQ(RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type());
DestroyChannels();
}
// This is the complement to
// SurfaceHostCandidateOnCandidateFilterChangeFromRelayToAll, and instead of
// gathering continually we only gather once, which makes the config
// |surface_ice_candidates_on_ice_transport_type_changed| ineffective after the
// gathering stopped.
TEST_F(P2PTransportChannelTest,
CannotSurfaceTheNewlyAllowedOnFilterChangeIfNotGatheringContinually) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(
OPEN, OPEN,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET);
auto* ep1 = GetEndpoint(0);
auto* ep2 = GetEndpoint(1);
ep1->allocator_->SetCandidateFilter(CF_RELAY);
ep2->allocator_->SetCandidateFilter(CF_RELAY);
// Only gather once.
IceConfig ice_config = CreateIceConfig(1000, GATHER_ONCE);
ice_config.surface_ice_candidates_on_ice_transport_type_changed = true;
CreateChannels(ice_config, ice_config);
ASSERT_TRUE_SIMULATED_WAIT(ep1_ch1()->selected_connection() != nullptr,
kDefaultTimeout, clock);
ASSERT_TRUE_SIMULATED_WAIT(ep2_ch1()->selected_connection() != nullptr,
kDefaultTimeout, clock);
// Loosen the candidate filter at ep1.
ep1->allocator_->SetCandidateFilter(CF_ALL);
// Wait for a period for any potential surfacing of new candidates.
SIMULATED_WAIT(false, kDefaultTimeout, clock);
EXPECT_EQ(RELAY_PORT_TYPE,
ep1_ch1()->selected_connection()->local_candidate().type());
// Loosen the candidate filter at ep2.
ep2->allocator_->SetCandidateFilter(CF_ALL);
EXPECT_EQ(RELAY_PORT_TYPE,
ep2_ch1()->selected_connection()->local_candidate().type());
DestroyChannels();
}
// Test that when the candidate filter is updated to be more restrictive,
// candidates that 1) have already been gathered and signaled 2) but no longer
// match the filter, are not removed.
TEST_F(P2PTransportChannelTest,
RestrictingCandidateFilterDoesNotRemoveRegatheredCandidates) {
rtc::ScopedFakeClock clock;
ConfigureEndpoints(
OPEN, OPEN,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET,
kDefaultPortAllocatorFlags | PORTALLOCATOR_ENABLE_SHARED_SOCKET);
auto* ep1 = GetEndpoint(0);
auto* ep2 = GetEndpoint(1);
ep1->allocator_->SetCandidateFilter(CF_ALL);
ep2->allocator_->SetCandidateFilter(CF_ALL);
// Enable continual gathering and also resurfacing gathered candidates upon
// the candidate filter changed in the ICE configuration.
IceConfig ice_config = CreateIceConfig(1000, GATHER_CONTINUALLY);
ice_config.surface_ice_candidates_on_ice_transport_type_changed = true;
// Pause candidates so we can gather all types of candidates. See
// P2PTransportChannel::OnConnectionStateChange, where we would stop the
// gathering when we have a strongly connected candidate pair.
PauseCandidates(0);
PauseCandidates(1);
CreateChannels(ice_config, ice_config);
// We have gathered host, srflx and relay candidates.
EXPECT_TRUE_SIMULATED_WAIT(ep1->saved_candidates_.size() == 3u,
kDefaultTimeout, clock);
ResumeCandidates(0);
ResumeCandidates(1);
ASSERT_TRUE_SIMULATED_WAIT(
ep1_ch1()->selected_connection() != nullptr &&
LOCAL_PORT_TYPE ==
ep1_ch1()->selected_connection()->local_candidate().type() &&
ep2_ch1()->selected_connection() != nullptr &&
LOCAL_PORT_TYPE ==
ep1_ch1()->selected_connection()->remote_candidate().type(),
kDefaultTimeout, clock);
ASSERT_TRUE_SIMULATED_WAIT(ep2_ch1()->selected_connection() != nullptr,
kDefaultTimeout, clock);
// Test that we have a host-host candidate pair selected and the number of
// candidates signaled to the remote peer stays the same.
auto test_invariants = [this]() {
EXPECT_EQ(LOCAL_PORT_TYPE,
ep1_ch1()->selected_connection()->local_candidate().type());
EXPECT_EQ(LOCAL_PORT_TYPE,
ep1_ch1()->selected_connection()->remote_candidate().type());
EXPECT_THAT(ep2_ch1()->remote_candidates(), SizeIs(3));
};
test_invariants();
// Set a more restrictive candidate filter at ep1.
ep1->allocator_->SetCandidateFilter(CF_HOST | CF_REFLEXIVE);
SIMULATED_WAIT(false, kDefaultTimeout, clock);
test_invariants();
ep1->allocator_->SetCandidateFilter(CF_HOST);
SIMULATED_WAIT(false, kDefaultTimeout, clock);
test_invariants();
ep1->allocator_->SetCandidateFilter(CF_NONE);
SIMULATED_WAIT(false, kDefaultTimeout, clock);
test_invariants();
DestroyChannels();
}
TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampening0) {
webrtc::test::ScopedFieldTrials field_trials(
"WebRTC-IceFieldTrials/initial_select_dampening:0/");
constexpr int kMargin = 10;
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.SetIceConfig(ch.config());
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(nullptr, ch.selected_connection());
conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
// It shall not be selected until 0ms has passed....i.e it should be connected
// directly.
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), kMargin, clock);
}
TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampening) {
webrtc::test::ScopedFieldTrials field_trials(
"WebRTC-IceFieldTrials/initial_select_dampening:100/");
constexpr int kMargin = 10;
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.SetIceConfig(ch.config());
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(nullptr, ch.selected_connection());
conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
// It shall not be selected until 100ms has passed.
SIMULATED_WAIT(conn1 == ch.selected_connection(), 100 - kMargin, clock);
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), 2 * kMargin, clock);
}
TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampeningPingReceived) {
webrtc::test::ScopedFieldTrials field_trials(
"WebRTC-IceFieldTrials/initial_select_dampening_ping_received:100/");
constexpr int kMargin = 10;
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.SetIceConfig(ch.config());
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(nullptr, ch.selected_connection());
conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
conn1->ReceivedPing("id1"); //
// It shall not be selected until 100ms has passed.
SIMULATED_WAIT(conn1 == ch.selected_connection(), 100 - kMargin, clock);
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), 2 * kMargin, clock);
}
TEST_F(P2PTransportChannelPingTest, TestInitialSelectDampeningBoth) {
webrtc::test::ScopedFieldTrials field_trials(
"WebRTC-IceFieldTrials/"
"initial_select_dampening:100,initial_select_dampening_ping_received:"
"50/");
constexpr int kMargin = 10;
rtc::ScopedFakeClock clock;
clock.AdvanceTime(webrtc::TimeDelta::Seconds(1));
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
P2PTransportChannel ch("test channel", 1, &pa);
PrepareChannel(&ch);
ch.SetIceConfig(ch.config());
ch.MaybeStartGathering();
ch.AddRemoteCandidate(CreateUdpCandidate(LOCAL_PORT_TYPE, "1.1.1.1", 1, 100));
Connection* conn1 = WaitForConnectionTo(&ch, "1.1.1.1", 1, &clock);
ASSERT_TRUE(conn1 != nullptr);
EXPECT_EQ(nullptr, ch.selected_connection());
conn1->ReceivedPingResponse(LOW_RTT, "id"); // Becomes writable and receiving
// It shall not be selected until 100ms has passed....but only wait ~50 now.
SIMULATED_WAIT(conn1 == ch.selected_connection(), 50 - kMargin, clock);
// Now receiving ping and new timeout should kick in.
conn1->ReceivedPing("id1"); //
EXPECT_EQ_SIMULATED_WAIT(conn1, ch.selected_connection(), 2 * kMargin, clock);
}
TEST(P2PTransportChannel, InjectIceController) {
MockIceControllerFactory factory;
FakePortAllocator pa(rtc::Thread::Current(), nullptr);
EXPECT_CALL(factory, RecordIceControllerCreated()).Times(1);
auto dummy = std::make_unique<cricket::P2PTransportChannel>(
"transport_name",
/* component= */ 77, &pa,
/* async_resolver_factory = */ nullptr,
/* event_log = */ nullptr, &factory);
}
} // namespace cricket
|
// bindgen-flags: --rust-target 1.0
struct Foo_empty {};
struct Foo;
struct Bar {
Foo *f;
};
void baz_struct(Foo* f);
union Union;
void baz_union(Union* u);
class Quux;
void baz_class(Quux* q);
|
//***************************************************************************
//
// Copyright (c) 1999 - 2006 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//***************************************************************************
/*
@file CIFXBoundSphereDataElement.cpp */
#include "CIFXBoundSphereDataElement.h"
CIFXBoundSphereDataElement::CIFXBoundSphereDataElement()
{
m_uRefCount = 0;
m_vBoundingSphere.Set(0.0f,0.0f,0.0f,0.0f);
m_uRenderableDataElementIndex = (U32)-1;
}
CIFXBoundSphereDataElement::~CIFXBoundSphereDataElement()
{
}
IFXRESULT IFXAPI_CALLTYPE CIFXBoundSphereDataElement_Factory(IFXREFIID riid, void **ppv)
{
IFXRESULT result;
if ( ppv )
{
// Create the CIFXClassName component.
CIFXBoundSphereDataElement *pBS = new CIFXBoundSphereDataElement;
if ( pBS )
{
// Perform a temporary AddRef for our usage of the component.
pBS->AddRef();
// Attempt to obtain a pointer to the requested interface.
result = pBS->QueryInterface( riid, ppv );
// Perform a Release since our usage of the component is now
// complete. Note: If the QI fails, this will cause the
// component to be destroyed.
pBS->Release();
}
else result = IFX_E_OUT_OF_MEMORY;
}
else result = IFX_E_INVALID_POINTER;
return result;
}
// IFXUnknown
U32 CIFXBoundSphereDataElement::AddRef()
{
return ++m_uRefCount;
}
U32 CIFXBoundSphereDataElement::Release()
{
if (m_uRefCount == 1)
{
delete this ;
return 0 ;
}
else return (--m_uRefCount);
}
IFXRESULT CIFXBoundSphereDataElement::QueryInterface(IFXREFIID interfaceId, void** ppInterface)
{
IFXRESULT result = IFX_OK;
if ( ppInterface )
{
if ( interfaceId == IID_IFXBoundSphereDataElement )
*ppInterface = ( IFXBoundSphereDataElement* ) this;
else if ( interfaceId == IID_IFXUnknown )
*ppInterface = ( IFXUnknown* ) this;
else
{
*ppInterface = NULL;
result = IFX_E_UNSUPPORTED;
}
if ( IFXSUCCESS( result ) )
AddRef();
}
else
result = IFX_E_INVALID_POINTER;
return result;
}
|
/*
-------------------------------------------------------------------------------
This file is part of FBT (File Binary Tables).
http://gamekit.googlecode.com/
Copyright (c) 2010 Charlie C & Erwin Coumans.
-------------------------------------------------------------------------------
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
-------------------------------------------------------------------------------
*/
#include "fbtApp.h"
#include "fbtTextFile.h"
#include "fbtMainFrame.h"
#define COMMENT_COLOR wxColor(0, 128, 0)
#define NUMBER_COLOR wxColor(0, 0, 0)
#define OPERATOR_COLOR wxColor(0, 0, 0)
#define WORD_COLOR wxColor(0, 0, 255)
const char* WORDS =
"bool break case catch char class const "
"continue default delete do double else enum explicit "
"export extern false float for friend goto if inline int long "
"mutable namespace new operator private protected public register "
" return short signed sizeof static "
"struct switch template this throw true try typedef typeid "
"typename union unsigned using virtual void volatile "
"while privsec";
BEGIN_EVENT_TABLE( fbtTextFile, wxStyledTextCtrl )
EVT_MENU(wxID_UNDO, fbtTextFile::undoEvent)
EVT_MENU(wxID_REDO, fbtTextFile::redoEvent)
EVT_MENU(wxID_CUT, fbtTextFile::cutEvent)
EVT_MENU(wxID_COPY, fbtTextFile::copyEvent)
EVT_MENU(wxID_PASTE, fbtTextFile::pasteEvent)
EVT_MENU(wxID_CLEAR, fbtTextFile::deleteEvent)
EVT_MENU(wxID_SELECTALL, fbtTextFile::selectAllEvent)
EVT_STC_SAVEPOINTLEFT(FBT_WINDOW_TXT, fbtTextFile::savePointLeftEvent)
EVT_STC_SAVEPOINTREACHED(FBT_WINDOW_TXT, fbtTextFile::savePointReachedEvent)
EVT_STC_ZOOM(FBT_WINDOW_TXT, fbtTextFile::zoomEvent)
END_EVENT_TABLE()
fbtTextFile::fbtTextFile(fbtMainFrame* parent, fbtText* fp, int id)
: wxStyledTextCtrl(parent, FBT_WINDOW_TXT),
m_file(fp), m_parent(parent)
{
SetViewEOL(false);
SetIndentationGuides(false);
SetEdgeMode(wxSTC_EDGE_NONE);
SetViewWhiteSpace(wxSTC_WS_INVISIBLE);
SetReadOnly(false);
SetTabWidth(4);
SetWrapMode(wxSTC_WRAP_NONE);
wxFont font (10, wxMODERN, wxNORMAL, wxNORMAL);
StyleSetFont(wxSTC_STYLE_DEFAULT, font);
StyleSetForeground(wxSTC_STYLE_DEFAULT, *wxBLACK);
StyleSetBackground(wxSTC_STYLE_DEFAULT, *wxWHITE);
StyleSetForeground(wxSTC_STYLE_LINENUMBER, wxColour (wxT("DARK GREY")));
StyleSetBackground(wxSTC_STYLE_LINENUMBER, *wxWHITE);
StyleSetForeground(wxSTC_STYLE_INDENTGUIDE, wxColour (wxT("DARK GREY")));
SetMarginType(0, wxSTC_MARGIN_NUMBER);
SetMarginWidth(0, TextWidth (wxSTC_STYLE_LINENUMBER, wxT("_99999")));
SetVisiblePolicy(wxSTC_VISIBLE_STRICT | wxSTC_VISIBLE_SLOP, 1);
SetXCaretPolicy(wxSTC_CARET_EVEN | wxSTC_VISIBLE_STRICT | wxSTC_CARET_SLOP, 1);
SetYCaretPolicy(wxSTC_CARET_EVEN | wxSTC_VISIBLE_STRICT | wxSTC_CARET_SLOP, 1);
SetLexer(wxSTC_LEX_CPP);
StyleSetForeground(wxSTC_C_COMMENT, COMMENT_COLOR);
StyleSetForeground(wxSTC_C_COMMENTLINEDOC, COMMENT_COLOR);
StyleSetForeground(wxSTC_C_COMMENTLINE, COMMENT_COLOR);
StyleSetForeground(wxSTC_C_COMMENTDOC, COMMENT_COLOR);
StyleSetForeground(wxSTC_C_NUMBER, NUMBER_COLOR);
StyleSetForeground(wxSTC_C_OPERATOR, OPERATOR_COLOR);
StyleSetForeground(wxSTC_C_WORD, WORD_COLOR);
StyleSetForeground(wxSTC_C_PREPROCESSOR, WORD_COLOR);
SetKeyWords(0, WORDS);
SetSelBackground(true, wxColor(51, 94, 168));
SetSelForeground(true, wxColor(255, 255, 255));
m_file->m_textFile = this;
m_file->m_flag |= fbtText::FILE_IS_OPEN;
}
fbtTextFile::~fbtTextFile()
{
if (m_file)
{
m_file->m_flag &= ~(fbtText::FILE_IS_OPEN);
m_file->m_textFile = 0;
}
}
void fbtTextFile::undoEvent(wxCommandEvent& evt)
{
if (!CanUndo())
return;
Undo();
}
void fbtTextFile::redoEvent(wxCommandEvent& evt)
{
if (!CanRedo())
return;
Redo();
}
void fbtTextFile::cutEvent(wxCommandEvent& evt)
{
if (GetReadOnly() || GetSelectionEnd() - GetSelectionStart() <= 0)
return;
Cut();
}
void fbtTextFile::copyEvent(wxCommandEvent& evt)
{
if (GetSelectionEnd() - GetSelectionStart() <= 0)
return;
Copy();
}
void fbtTextFile::pasteEvent(wxCommandEvent& evt)
{
if (!CanPaste())
return;
Paste();
}
void fbtTextFile::deleteEvent(wxCommandEvent& evt)
{
if (GetReadOnly())
return;
Clear();
}
void fbtTextFile::selectAllEvent(wxCommandEvent& evt)
{
SetSelection(0, GetTextLength());
}
void fbtTextFile::savePointLeftEvent(wxStyledTextEvent& evt)
{
if (m_file)
{
if (!m_file->isModified())
{
m_file->modify(true);
m_parent->notifyFileModified(this);
}
}
}
void fbtTextFile::savePointReachedEvent(wxStyledTextEvent& evt)
{
if (m_file)
{
if (m_file->isModified())
{
m_file->modify(false);
m_parent->notifyFileModified(this);
}
}
}
void fbtTextFile::zoomEvent(wxStyledTextEvent& evt)
{
evt.Skip();
// dsiable zoom
if (GetZoom() != 0) SetZoom(0);
}
|
/**
* SCILL API
* SCILL gives you the tools to activate, retain and grow your user base in your app or game by bringing you features well known in the gaming industry: Gamification. We take care of the services and technology involved so you can focus on your game and content.
*
* OpenAPI spec version: 1.0.0
* Contact: support@scillgame.com
*
* NOTE: This class is auto generated by OpenAPI Generator
* https://github.com/OpenAPITools/openapi-generator
* Do not edit the class manually.
*/
#include "ScillApiWrapper/ScillApiLeaderboardV2MemberTypeRanking.h"
#include "ScillSDKModule.h"
#include "ScillApiWrapper/ScillApiHelpers.h"
#include "Templates/SharedPointer.h"
namespace ScillSDK
{
void ScillApiLeaderboardV2MemberTypeRanking::WriteJson(JsonWriter& Writer) const
{
Writer->WriteObjectStart();
if (Count.IsSet())
{
Writer->WriteIdentifierPrefix(TEXT("count")); WriteJsonValue(Writer, Count.GetValue());
}
if (Members.IsSet())
{
Writer->WriteIdentifierPrefix(TEXT("members")); WriteJsonValue(Writer, Members.GetValue());
}
Writer->WriteObjectEnd();
}
bool ScillApiLeaderboardV2MemberTypeRanking::FromJson(const TSharedPtr<FJsonValue>& JsonValue)
{
const TSharedPtr<FJsonObject>* Object;
if (!JsonValue->TryGetObject(Object))
return false;
bool ParseSuccess = true;
ParseSuccess &= TryGetJsonValue(*Object, TEXT("count"), Count);
ParseSuccess &= TryGetJsonValue(*Object, TEXT("members"), Members);
return ParseSuccess;
}
}
|
/**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER 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.
\**************************************************************************/
/*!
\class SoGLViewportRegionElement Inventor/elements/SoGLViewportRegionElement.h
\brief The SoGLViewportRegionElement class is yet to be documented.
\ingroup elements
FIXME: write doc.
*/
#include <Inventor/elements/SoGLViewportRegionElement.h>
#include <cassert>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif // HAVE_CONFIG_H
#include <Inventor/system/gl.h>
#if COIN_DEBUG
#include <Inventor/errors/SoDebugError.h>
#endif // COIN_DEBUG
SO_ELEMENT_SOURCE(SoGLViewportRegionElement);
/*!
This static method initializes static data for the
SoGLViewportRegionElement class.
*/
void
SoGLViewportRegionElement::initClass(void)
{
SO_ELEMENT_INIT_CLASS(SoGLViewportRegionElement, inherited);
}
/*!
The destructor.
*/
SoGLViewportRegionElement::~SoGLViewportRegionElement()
{
}
//! FIXME: write doc.
void
SoGLViewportRegionElement::init(SoState * state)
{
inherited::init(state);
this->initialized = FALSE;
}
//! FIXME: write doc.
void
SoGLViewportRegionElement::push(SoState * state)
{
inherited::push(state);
SoGLViewportRegionElement * prev = (SoGLViewportRegionElement*)
this->getNextInStack();
this->viewportRegion = prev->viewportRegion;
this->initialized = TRUE;
}
//! FIXME: write doc.
void
SoGLViewportRegionElement::pop(SoState * state,
const SoElement * prevTopElement)
{
SoGLViewportRegionElement * prev =
(SoGLViewportRegionElement *)prevTopElement;
if (!(this->viewportRegion == prev->viewportRegion))
this->updategl();
prev->capture(state);
}
//! FIXME: write doc.
void
SoGLViewportRegionElement::setElt(const SbViewportRegion & viewportRegionarg)
{
this->viewportRegion = viewportRegionarg;
this->initialized = TRUE;
this->updategl();
}
//! FIXME: write doc.
void
SoGLViewportRegionElement::updategl() const
{
if (this->initialized) {
SbVec2s origin = this->viewportRegion.getViewportOriginPixels();
SbVec2s size = this->viewportRegion.getViewportSizePixels();
glViewport(origin[0], origin[1], size[0], size[1]);
#if COIN_DEBUG && 0 // debug
SoDebugError::postInfo("SoGLViewportRegionElement::updategl",
"glViewport: %d %d %d %d",
origin[0], origin[1], size[0], size[1]);
#endif // debug
}
}
|
#include "envlight.h"
#include "image.h"
#include "distribution.h"
#include "transform.h"
#include "sampling.h"
int GetEnvLightSerializedSize() {
return 1 + // type
16 + // toWorld
16 + // toLight
1 + // uCDF0
1 + // uCDF1
1 + // vCDF0
1 + // vCDF1
1 + // col
1 + // row
2 + // pixelSize
4 * 3 + // img00~img11
2 + // rowWeight0 & rowWeight1
1; // normalization
}
std::unique_ptr<const EnvmapSampleInfo> CreateEnvmapSampleInfo(const Image3 *image) {
int height = image->pixelHeight;
int width = image->pixelWidth;
size_t nEntries = (size_t)(width + 1) * (size_t)height;
std::vector<Float> cdfCols(nEntries);
std::vector<Float> cdfRows(height + 1);
std::vector<Float> rowWeights(height);
size_t colPos = 0, rowPos = 0;
Float rowSum = Float(0.0);
cdfRows[rowPos++] = Float(0.0);
for (int y = 0; y < height; y++) {
Float colSum = Float(0.0);
cdfCols[colPos++] = Float(0.0);
for (int x = 0; x < width; x++) {
Vector3 value = image->At(x, y);
colSum += Luminance(value);
cdfCols[colPos++] = colSum;
}
Float normalization = inverse(colSum);
for (int x = 1; x < width; x++) {
cdfCols[colPos - x - 1] *= normalization;
}
cdfCols[colPos - 1] = Float(1.0);
Float weight = sin((y + Float(0.5)) * c_PI / (Float)height);
rowWeights[y] = weight;
rowSum += colSum * weight;
cdfRows[rowPos++] = rowSum;
}
Float normalization = inverse(rowSum);
for (int y = 1; y < height; y++) {
cdfRows[rowPos - y - 1] *= normalization;
}
cdfRows[rowPos - 1] = Float(1.0);
if (rowSum == 0 || !std::isfinite(rowSum)) {
Error("Invalid environment map");
}
normalization = inverse(rowSum * (c_TWOPI / width) * (c_PI / height));
Vector2 pixelSize = Vector2(c_TWOPI / width, M_PI / height);
return std::unique_ptr<const EnvmapSampleInfo>(
new EnvmapSampleInfo{cdfRows, cdfCols, rowWeights, normalization, pixelSize});
}
EnvLight::EnvLight(const Float &samplingWeight,
const AnimatedTransform &toWorld,
const std::string &filename)
: Light(samplingWeight),
toWorld(toWorld),
toLight(Invert(toWorld)),
image(new Image3(filename)),
sampleInfo(CreateEnvmapSampleInfo(image.get())) {
}
void EnvLight::Serialize(const LightPrimID &lPrimID, const Vector2 &rndDir, Float *buffer) const {
buffer = ::Serialize((Float)LightType::EnvLight, buffer);
buffer = ::Serialize(toWorld, buffer);
buffer = ::Serialize(toLight, buffer);
size_t col = lPrimID % image->pixelWidth;
size_t row = lPrimID / image->pixelWidth;
const Float *cdfCol = &sampleInfo->cdfCols[0] + row * (image->pixelWidth + 1);
Float cdfCol0 = cdfCol[col];
Float cdfCol1 = cdfCol[col + 1];
Float cdfRow0 = sampleInfo->cdfRows[row];
Float cdfRow1 = sampleInfo->cdfRows[row + 1];
Vector2 pixelSize = sampleInfo->pixelSize;
Vector3 img00 = image->RepAt(col, row);
Vector3 img10 = image->RepAt(col + 1, row);
Vector3 img01 = image->RepAt(col, row + 1);
Vector3 img11 = image->RepAt(col + 1, row + 1);
Float rowWeight0 =
sampleInfo->rowWeights[Clamp(row, (size_t)0, (size_t)image->pixelHeight - 1)];
Float rowWeight1 =
sampleInfo->rowWeights[Clamp(row + 1, (size_t)0, (size_t)image->pixelHeight - 1)];
buffer = ::Serialize(cdfCol0, buffer);
buffer = ::Serialize(cdfCol1, buffer);
buffer = ::Serialize(cdfRow0, buffer);
buffer = ::Serialize(cdfRow1, buffer);
buffer = ::Serialize((Float)col, buffer);
buffer = ::Serialize((Float)row, buffer);
buffer = ::Serialize(pixelSize, buffer);
buffer = ::Serialize(img00, buffer);
buffer = ::Serialize(img10, buffer);
buffer = ::Serialize(img01, buffer);
buffer = ::Serialize(img11, buffer);
buffer = ::Serialize(rowWeight0, buffer);
buffer = ::Serialize(rowWeight1, buffer);
::Serialize(sampleInfo->normalization, buffer);
}
void SampleDirection(const EnvLight *light,
const Vector2 rndParam,
const Float time,
LightPrimID &lPrimID,
Vector3 &dirToLight,
Vector3 &value,
Float &pdf) {
Matrix4x4 transform = Interpolate(light->toWorld, time);
auto uToIndex = [](const Float *cdf, const size_t size, Float &u) {
const Float *entry = std::lower_bound(cdf, cdf + size + 1, u);
size_t index = std::min(std::max((ptrdiff_t)0, entry - cdf - 1), (ptrdiff_t)size - 1);
u = (u - (Float)cdf[index]) / (Float)(cdf[index + 1] - cdf[index]);
return index;
};
const EnvmapSampleInfo *sampleInfo = light->sampleInfo.get();
const Image3 *image = light->image.get();
int width = image->pixelWidth;
int height = image->pixelHeight;
Float u0 = rndParam[0];
Float u1 = rndParam[1];
int row = uToIndex(&sampleInfo->cdfRows[0], height, u1);
int col = uToIndex(&sampleInfo->cdfCols[0] + row * (width + 1), width, u0);
lPrimID = row * width + col;
Vector2 tent = Vector2(Tent(u0), Tent(u1));
Vector2 pl = Vector2((Float)col, (Float)row) + tent;
Float phi = (pl[0] + Float(0.5)) * sampleInfo->pixelSize[0];
Float theta = (pl[1] + Float(0.5)) * sampleInfo->pixelSize[1];
Float sinPhi = sin(phi);
Float cosPhi = cos(phi);
Float sinTheta = sin(theta);
Float cosTheta = cos(theta);
dirToLight = XformVector(transform, Vector3(sinPhi * sinTheta, cosTheta, -cosPhi * sinTheta));
Float dx1 = tent[0], dx2 = Float(1.0) - tent[0], dy1 = tent[1], dy2 = Float(1.0) - tent[1];
Vector3 value1 = image->At(col, row) * dx2 * dy2 + image->At(col + 1, row) * dx1 * dy2;
Vector3 value2 = image->At(col, row + 1) * dx2 * dy1 + image->At(col + 1, row + 1) * dx1 * dy1;
value = (value1 + value2);
Float rowWeight0 = sampleInfo->rowWeights[Clamp(row, 0, image->pixelHeight - 1)];
Float rowWeight1 = sampleInfo->rowWeights[Clamp(row + 1, 0, image->pixelHeight - 1)];
pdf = (Luminance(value1) * rowWeight0 + Luminance(value2) * rowWeight1) *
sampleInfo->normalization / fmax(fabs(sinTheta), Float(1e-7));
}
bool EnvLight::SampleDirect(const BSphere &sceneSphere,
const Vector3 & /*pos*/,
const Vector3 & /*normal*/,
const Vector2 rndParam,
const Float time,
LightPrimID &lPrimID,
Vector3 &dirToLight,
Float &dist,
Vector3 &contrib,
Float &cosAtLight,
Float &directPdf,
Float &emissionPdf) const {
Vector3 value;
SampleDirection(this, rndParam, time, lPrimID, dirToLight, value, directPdf);
dist = std::numeric_limits<Float>::infinity();
contrib = value * inverse(directPdf);
cosAtLight = Float(1.0);
Float positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
return true;
}
void EnvLight::Emission(const BSphere &sceneSphere,
const Vector3 &dirToLight,
const Vector3 & /*normalOnLight*/,
const Float time,
LightPrimID &lPrimID,
Vector3 &emission,
Float &directPdf,
Float &emissionPdf) const {
Matrix4x4 transform = Interpolate(toLight, time);
Vector3 d = XformVector(transform, dirToLight);
Vector2 uv(atan2(d[0], -d[2]) * c_INVTWOPI * (Float)image->pixelWidth - Float(0.5),
acos(d[1]) * c_INVPI * (Float)image->pixelHeight - Float(0.5));
int col = int(floor(uv[0]));
int row = int(floor(uv[1]));
lPrimID = Modulo(row, image->pixelHeight) * image->pixelWidth + Modulo(col, image->pixelWidth);
Float dx1 = uv[0] - col, dx2 = Float(1.0) - dx1, dy1 = uv[1] - row, dy2 = Float(1.0) - dy1;
Vector3 value1 = image->RepAt(col, row) * dx2 * dy2 + image->RepAt(col + 1, row) * dx1 * dy2;
Vector3 value2 =
image->RepAt(col, row + 1) * dx2 * dy1 + image->RepAt(col + 1, row + 1) * dx1 * dy1;
emission = value1 + value2;
Float sinTheta = sqrt(Float(1.0) - square(d[1]));
Float rowWeight0 = sampleInfo->rowWeights[Clamp(row, 0, image->pixelHeight - 1)];
Float rowWeight1 = sampleInfo->rowWeights[Clamp(row + 1, 0, image->pixelHeight - 1)];
directPdf = (Luminance(value1) * rowWeight0 + Luminance(value2) * rowWeight1) *
sampleInfo->normalization / fmax(fabs(sinTheta), Float(1e-7));
Float positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
void EnvLight::Emit(const BSphere &sceneSphere,
const Vector2 rndParamPos,
const Vector2 rndParamDir,
const Float time,
LightPrimID &lPrimID,
Ray &ray,
Vector3 &emission,
Float &cosAtLight,
Float &emissionPdf,
Float &directPdf) const {
SampleDirection(this, rndParamDir, time, lPrimID, ray.dir, emission, directPdf);
ray.dir = -ray.dir;
Vector2 offset = SampleConcentricDisc(rndParamPos);
Vector3 b0, b1;
CoordinateSystem(ray.dir, b0, b1);
Vector3 perpOffset = offset[0] * b0 + offset[1] * b1;
ray.org = sceneSphere.center + (perpOffset - ray.dir) * sceneSphere.radius;
cosAtLight = Float(1.0);
Float positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
struct ADEnvLight {
ADAnimatedTransform toWorld;
ADAnimatedTransform toLight;
ADFloat cdfCol0;
ADFloat cdfCol1;
ADFloat cdfRow0;
ADFloat cdfRow1;
ADFloat col;
ADFloat row;
ADVector2 pixelSize;
ADVector3 img00;
ADVector3 img10;
ADVector3 img01;
ADVector3 img11;
ADFloat rowWeight0;
ADFloat rowWeight1;
ADFloat normalization;
};
const ADFloat *Deserialize(const ADFloat *buffer, ADEnvLight &envLight) {
buffer = Deserialize(buffer, envLight.toWorld);
buffer = Deserialize(buffer, envLight.toLight);
buffer = Deserialize(buffer, envLight.cdfCol0);
buffer = Deserialize(buffer, envLight.cdfCol1);
buffer = Deserialize(buffer, envLight.cdfRow0);
buffer = Deserialize(buffer, envLight.cdfRow1);
buffer = Deserialize(buffer, envLight.col);
buffer = Deserialize(buffer, envLight.row);
buffer = Deserialize(buffer, envLight.pixelSize);
buffer = Deserialize(buffer, envLight.img00);
buffer = Deserialize(buffer, envLight.img10);
buffer = Deserialize(buffer, envLight.img01);
buffer = Deserialize(buffer, envLight.img11);
buffer = Deserialize(buffer, envLight.rowWeight0);
buffer = Deserialize(buffer, envLight.rowWeight1);
buffer = Deserialize(buffer, envLight.normalization);
return buffer;
}
void SampleDirection(const ADEnvLight &envLight,
const ADVector2 rndParam,
const ADFloat time,
ADVector3 &dirToLight,
ADVector3 &value,
ADFloat &pdf) {
ADMatrix4x4 transform = Interpolate(envLight.toWorld, time);
ADFloat u0 = (rndParam[0] - envLight.cdfCol0) / (envLight.cdfCol1 - envLight.cdfCol0);
ADFloat u1 = (rndParam[1] - envLight.cdfRow0) / (envLight.cdfRow1 - envLight.cdfRow0);
ADVector2 tent = ADVector2(Tent(u0), Tent(u1));
ADVector2 pl = ADVector2(envLight.col, envLight.row) + tent;
ADFloat phi = (pl[0] + Float(0.5)) * envLight.pixelSize[0];
ADFloat theta = (pl[1] + Float(0.5)) * envLight.pixelSize[1];
ADFloat sinPhi = sin(phi);
ADFloat cosPhi = cos(phi);
ADFloat sinTheta = sin(theta);
ADFloat cosTheta = cos(theta);
dirToLight = XformVector(transform, ADVector3(sinPhi * sinTheta, cosTheta, -cosPhi * sinTheta));
ADFloat dx1 = tent[0], dx2 = Float(1.0) - tent[0], dy1 = tent[1], dy2 = Float(1.0) - tent[1];
ADVector3 value1 = envLight.img00 * dx2 * dy2 + envLight.img10 * dx1 * dy2;
ADVector3 value2 = envLight.img01 * dx2 * dy1 + envLight.img11 * dx1 * dy1;
value = (value1 + value2);
pdf = (Luminance(value1) * envLight.rowWeight0 + Luminance(value2) * envLight.rowWeight1) *
envLight.normalization / fmax(fabs(sinTheta), Float(1e-7));
}
void SampleDirectEnvLight(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector3 &pos,
const ADVector3 &normal,
const ADVector2 rndParam,
const ADFloat time,
const bool isStatic,
ADVector3 &dirToLight,
ADVector3 &lightContrib,
ADFloat &cosAtLight,
ADFloat &directPdf,
ADFloat &emissionPdf) {
ADEnvLight envLight;
Deserialize(buffer, envLight);
ADVector3 value;
SampleDirection(envLight, rndParam, time, dirToLight, value, directPdf);
lightContrib = value * inverse(directPdf);
cosAtLight = Const<ADFloat>(1.0);
ADFloat positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
void EmissionEnvLight(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector3 &dirToLight,
const ADVector3 &normalOnLight,
const ADFloat time,
ADVector3 &emission,
ADFloat &directPdf,
ADFloat &emissionPdf) {
ADEnvLight envLight;
Deserialize(buffer, envLight);
ADMatrix4x4 transform = Interpolate(envLight.toLight, time);
ADVector3 d = XformVector(transform, dirToLight);
ADVector2 uv(atan2(d[0], -d[2]) / envLight.pixelSize[0] - Float(0.5),
acos(d[1]) / envLight.pixelSize[1] - Float(0.5));
ADFloat dx1 = uv[0] - envLight.col, dx2 = Float(1.0) - dx1, dy1 = uv[1] - envLight.row,
dy2 = Float(1.0) - dy1;
ADVector3 value1 = envLight.img00 * dx2 * dy2 + envLight.img10 * dx1 * dy2;
ADVector3 value2 = envLight.img01 * dx2 * dy1 + envLight.img11 * dx1 * dy1;
emission = value1 + value2;
// Ugly hack to avoid undefined derivatives
ADFloat sinTheta = sqrt(fmax(Float(1.0) - square(d[1]), Float(1e-6)));
directPdf =
(Luminance(value1) * envLight.rowWeight0 + Luminance(value2) * envLight.rowWeight1) *
envLight.normalization / fmax(fabs(sinTheta), Float(1e-7));
ADFloat positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
void EmitEnvLight(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector2 rndParamPos,
const ADVector2 rndParamDir,
const ADFloat time,
const bool isStatic,
ADRay &ray,
ADVector3 &emission,
ADFloat &cosAtLight,
ADFloat &emissionPdf,
ADFloat &directPdf) {
ADEnvLight envLight;
Deserialize(buffer, envLight);
SampleDirection(envLight, rndParamDir, time, ray.dir, emission, directPdf);
ray.dir = -ray.dir;
ADVector2 offset = SampleConcentricDisc(rndParamPos);
ADVector3 b0, b1;
CoordinateSystem(ray.dir, b0, b1);
ADVector3 perpOffset = offset[0] * b0 + offset[1] * b1;
ray.org = sceneSphere.center + (perpOffset - ray.dir) * sceneSphere.radius;
cosAtLight = Const<ADFloat>(1.0);
ADFloat positionPdf = c_INVPI / square(sceneSphere.radius);
emissionPdf = directPdf * positionPdf;
}
|
// Copyright Edvard Severin Pettersen 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at
// https://www.boost.org/LICENSE_1_0.txt)
#include <array>
#include <chrono>
#include <iostream>
#include <vector>
#include <proxc.hpp>
using namespace proxc;
constexpr std::size_t NUM = 200;
void writer( Chan< int >::Tx tx )
{
int n = 0;
while ( ! tx.is_closed() ) {
tx << n++;
}
}
void reader( std::array< Chan< int >::Rx, NUM > rxs )
{
constexpr std::size_t num_runs = 100;
constexpr std::size_t num_iter = 1000;
double total_us = 0.;
timer::Egg egg{ std::chrono::milliseconds( 1 ) };
for ( std::size_t run = 0; run < num_runs; ++run ) {
auto start = std::chrono::steady_clock::now();
for ( std::size_t iter = 0; iter < num_iter; ++iter ) {
Alt()
.recv_for( rxs.begin(), rxs.end(),
[]( int ){} )
.select();
}
auto end = std::chrono::steady_clock::now();
std::chrono::duration< double, std::micro > diff = end - start;
total_us += diff.count();
}
std::cout << "Avg. us per alt: " << total_us / num_runs / num_iter << "us" << std::endl;
}
int main()
{
ChanArr< int, NUM > chs;
std::vector< Process > writers;
writers.reserve( NUM );
for ( std::size_t i = 0; i < NUM; ++i ) {
writers.emplace_back( writer, chs[i].move_tx() );
}
parallel(
proc_for( writers.begin(), writers.end() ),
proc( reader, chs.collect_rx() )
);
return 0;
}
|
//===-- StringPool.cpp - Interned string pool -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the StringPool class.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/StringPool.h"
#include "llvm/ADT/StringRef.h"
using namespace llvm;
StringPool::StringPool() {}
StringPool::~StringPool() {
assert(InternTable.empty() && "PooledStringPtr leaked!");
}
PooledStringPtr StringPool::intern(StringRef Key) {
table_t::iterator I = InternTable.find(Key);
if (I != InternTable.end())
return PooledStringPtr(&*I);
entry_t *S = entry_t::Create(Key.begin(), Key.end());
S->getValue().Pool = this;
InternTable.insert(S);
return PooledStringPtr(S);
}
|
/*
* Copyright (c) 2014 Hugh Bailey <obs.jim@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
template<typename T> class CoTaskMemPtr {
T *ptr;
inline void Clear() {if (ptr) CoTaskMemFree(ptr);}
public:
inline CoTaskMemPtr() : ptr(NULL) {}
inline CoTaskMemPtr(T *ptr_) : ptr(ptr_) {}
inline ~CoTaskMemPtr() {Clear();}
inline operator T*() const {return ptr;}
inline T *operator->() const {return ptr;}
inline const T *Get() const {return ptr;}
inline CoTaskMemPtr& operator=(T* val)
{
Clear();
ptr = val;
}
inline T** operator&()
{
Clear();
ptr = NULL;
return &ptr;
}
};
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "GASTemplateCharacter.h"
#include "HeadMountedDisplayFunctionLibrary.h"
#include "Camera/CameraComponent.h"
#include "Components/CapsuleComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
#include "GameFramework/Controller.h"
#include "GameFramework/SpringArmComponent.h"
//////////////////////////////////////////////////////////////////////////
// AGASTemplateCharacter
AGASTemplateCharacter::AGASTemplateCharacter()
{
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// set our turn rates for input
BaseTurnRate = 45.f;
BaseLookUpRate = 45.f;
// Don't rotate when the controller rotates. Let that just affect the camera.
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...
GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
GetCharacterMovement()->JumpZVelocity = 600.f;
GetCharacterMovement()->AirControl = 0.2f;
// Create a camera boom (pulls in towards the player if there is a collision)
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character
CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller
// Create a follow camera
FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
}
//////////////////////////////////////////////////////////////////////////
// Input
void AGASTemplateCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
// Set up gameplay key bindings
check(PlayerInputComponent);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
PlayerInputComponent->BindAxis("MoveForward", this, &AGASTemplateCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AGASTemplateCharacter::MoveRight);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &AGASTemplateCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &AGASTemplateCharacter::LookUpAtRate);
// handle touch devices
PlayerInputComponent->BindTouch(IE_Pressed, this, &AGASTemplateCharacter::TouchStarted);
PlayerInputComponent->BindTouch(IE_Released, this, &AGASTemplateCharacter::TouchStopped);
// VR headset functionality
PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AGASTemplateCharacter::OnResetVR);
}
void AGASTemplateCharacter::OnResetVR()
{
// If GASTemplate is added to a project via 'Add Feature' in the Unreal Editor the dependency on HeadMountedDisplay in GASTemplate.Build.cs is not automatically propagated
// and a linker error will result.
// You will need to either:
// Add "HeadMountedDisplay" to [YourProject].Build.cs PublicDependencyModuleNames in order to build successfully (appropriate if supporting VR).
// or:
// Comment or delete the call to ResetOrientationAndPosition below (appropriate if not supporting VR)
UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition();
}
void AGASTemplateCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location)
{
Jump();
}
void AGASTemplateCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location)
{
StopJumping();
}
void AGASTemplateCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void AGASTemplateCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void AGASTemplateCharacter::MoveForward(float Value)
{
if ((Controller != nullptr) && (Value != 0.0f))
{
// find out which way is forward
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get forward vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
AddMovementInput(Direction, Value);
}
}
void AGASTemplateCharacter::MoveRight(float Value)
{
if ( (Controller != nullptr) && (Value != 0.0f) )
{
// find out which way is right
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0, Rotation.Yaw, 0);
// get right vector
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
// add movement in that direction
AddMovementInput(Direction, Value);
}
}
|
/*
* Copyright 2010-2011 PathScale, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
*/
/**
* memory.cc - Contains stub definition of C++ new/delete operators.
*
* These definitions are intended to be used for testing and are weak symbols
* to allow them to be replaced by definitions from a STL implementation.
* These versions simply wrap malloc() and free(), they do not provide a
* C++-specific allocator.
*/
#ifdef __KERNEL__
extern "C" {
#include <linux/types.h>
#include <linux/slab.h>
}
#else
#include <stddef.h>
#include <stdlib.h>
#endif
#include "stdexcept.h"
#include "atomic.h"
namespace std
{
struct nothrow_t {};
}
/// The type of the function called when allocation fails.
typedef void (*new_handler)();
/**
* The function to call when allocation fails. By default, there is no
* handler and a bad allocation exception is thrown if an allocation fails.
*/
static new_handler new_handl;
namespace std
{
/**
* Sets a function to be called when there is a failure in new.
*/
__attribute__((weak))
new_handler set_new_handler(new_handler handler)
{
return ATOMIC_SWAP(&new_handl, handler);
}
__attribute__((weak))
new_handler get_new_handler(void)
{
return ATOMIC_LOAD(&new_handl);
}
}
__attribute__((weak))
void* operator new(size_t size)
{
if (0 == size)
{
size = 1;
}
#ifdef __KERNEL__
void *mem = kmalloc(size, GFP_ATOMIC);
#else
void * mem = malloc(size);
#endif
while (0 == mem)
{
new_handler h = std::get_new_handler();
if (0 != h)
{
h();
}
else
{
throw std::bad_alloc();
}
#ifdef __KERNEL__
mem = kmalloc(size, GFP_ATOMIC);
#else
mem = malloc(size);
#endif
}
return mem;
}
__attribute__((weak))
void* operator new(size_t size, const std::nothrow_t &) throw()
{
try {
return :: operator new(size);
} catch (...) {
// nothrow operator new should return NULL in case of
// std::bad_alloc exception in new handler
return NULL;
}
}
__attribute__((weak))
void operator delete(void * ptr)
#if __cplusplus < 201000L
throw()
#endif
{
#ifdef __KERNEL__
kfree(ptr);
#else
free(ptr);
#endif
}
__attribute__((weak))
void * operator new[](size_t size)
#if __cplusplus < 201000L
throw(std::bad_alloc)
#endif
{
return ::operator new(size);
}
__attribute__((weak))
void * operator new[](size_t size, const std::nothrow_t &) throw()
{
try {
return ::operator new[](size);
} catch (...) {
// nothrow operator new should return NULL in case of
// std::bad_alloc exception in new handler
return NULL;
}
}
__attribute__((weak))
void operator delete[](void * ptr)
#if __cplusplus < 201000L
throw()
#endif
{
::operator delete(ptr);
}
|
#include "legacy_evaluate.h"
#include "context.h"
#include "evaluate.h"
#include "opcodes/opcodes.h"
#include "options.h"
#include "string_to_int.h"
#include "utils.h"
#include <iostream>
#include <regex>
std::regex not_an_operator{R"(^\s*([^\+\*-/#\s]+)\s*)"};
int symbol_to_int(const Context& context, const std::basic_string<char>& to_parse)
{
if (auto symbol_value = context.get_symbol_value(to_parse); std::get<0>(symbol_value))
{
return std::get<1>(symbol_value);
}
throw CannotFindSymbol(to_parse);
}
int operand_to_int(const Context& context, const std::string& operand)
{
auto front = operand.front();
if ((isalpha(front) || front == '_') && front != '\'')
{
return symbol_to_int(context, operand);
}
else
{
return string_to_int(operand,
EvaluationFlags::get_flags_from_options(context.get_options()));
}
}
int apply_operation(const char& op, int acc, int val)
{
switch (op)
{
case '+':
acc += val;
break;
case '-':
acc -= val;
break;
case '*':
acc *= val;
break;
case '/':
acc /= val;
break;
case '#':
acc = acc * 256 + val;
break;
default:
throw UnknownOperation(op);
}
return acc;
}
class Accumulator
{
public:
void add_operation(char op) { operations.push_back(op); }
void add_operand(std::string_view operand) { operands.emplace_back(operand); }
[[nodiscard]] int resolve(const Context& context) const
{
if (operands.size() != operations.size())
{
throw IllFormedExpression();
}
int sum = 0;
for (int j = 0; j < operands.size(); j++)
{
const auto& operand = operands[j];
int val = operand_to_int(context, operand);
if (context.get_options().debug)
{
std::cout << " for '" << operand << "' got value " << val;
}
{
const auto& op = operations[j];
sum = apply_operation(op, sum, val);
}
}
return sum;
}
private:
std::vector<std::string> operands;
std::vector<char> operations;
};
int legacy_evaluator(const Context& context, std::string_view arg)
{
Accumulator acc;
acc.add_operation('+'); // First operation is to add to the accumulator being 0.
std::string_view arg_to_parse{arg};
while (!arg_to_parse.empty())
{
// Quickly parse quoted char
if (arg_to_parse[0] == '\'' && arg_to_parse.size() >= 3 && arg_to_parse[2] == '\'')
{
acc.add_operand(arg_to_parse.substr(0, 3));
arg_to_parse = arg_to_parse.substr(3);
}
else
{
// Parse Operand
std::string value_to_parse(arg_to_parse);
std::smatch data_match;
bool found = std::regex_search(value_to_parse, data_match, not_an_operator);
if (!found)
{
throw ExpectedValue(arg_to_parse);
}
acc.add_operand(trim_string(data_match.str()));
arg_to_parse = arg_to_parse.substr(data_match.length());
}
// Parse Operator
if (!arg_to_parse.empty())
{
char op = arg_to_parse.front();
switch (op)
{
case '+':
case '-':
case '/':
case '*':
case '#':
acc.add_operation(op);
arg_to_parse = arg_to_parse.substr(1);
break;
default:
throw UnknownOperation(op);
}
}
}
auto result = acc.resolve(context);
return result;
}
|
// Copyright 2017 The Ray Authors.
//
// 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 "ray/raylet/worker_pool.h"
#include <algorithm>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "ray/common/constants.h"
#include "ray/common/network_util.h"
#include "ray/common/ray_config.h"
#include "ray/common/status.h"
#include "ray/gcs/pb_util.h"
#include "ray/stats/stats.h"
#include "ray/util/logging.h"
#include "ray/util/util.h"
namespace {
// A helper function to get a worker from a list.
std::shared_ptr<ray::raylet::WorkerInterface> GetWorker(
const std::unordered_set<std::shared_ptr<ray::raylet::WorkerInterface>> &worker_pool,
const std::shared_ptr<ray::ClientConnection> &connection) {
for (auto it = worker_pool.begin(); it != worker_pool.end(); it++) {
if ((*it)->Connection() == connection) {
return (*it);
}
}
return nullptr;
}
// A helper function to remove a worker from a list. Returns true if the worker
// was found and removed.
bool RemoveWorker(
std::unordered_set<std::shared_ptr<ray::raylet::WorkerInterface>> &worker_pool,
const std::shared_ptr<ray::raylet::WorkerInterface> &worker) {
return worker_pool.erase(worker) > 0;
}
} // namespace
namespace ray {
namespace raylet {
WorkerPool::WorkerPool(boost::asio::io_service &io_service, int num_workers_soft_limit,
int num_initial_python_workers_for_first_job,
int maximum_startup_concurrency, int min_worker_port,
int max_worker_port, const std::vector<int> &worker_ports,
std::shared_ptr<gcs::GcsClient> gcs_client,
const WorkerCommandMap &worker_commands,
const std::unordered_map<std::string, std::string> &raylet_config,
std::function<void()> starting_worker_timeout_callback)
: io_service_(&io_service),
num_workers_soft_limit_(num_workers_soft_limit),
maximum_startup_concurrency_(maximum_startup_concurrency),
gcs_client_(std::move(gcs_client)),
raylet_config_(raylet_config),
starting_worker_timeout_callback_(starting_worker_timeout_callback),
first_job_registered_python_worker_count_(0),
first_job_driver_wait_num_python_workers_(std::min(
num_initial_python_workers_for_first_job, maximum_startup_concurrency)),
num_initial_python_workers_for_first_job_(num_initial_python_workers_for_first_job),
kill_idle_workers_timer_(io_service) {
RAY_CHECK(maximum_startup_concurrency > 0);
#ifndef _WIN32
// Ignore SIGCHLD signals. If we don't do this, then worker processes will
// become zombies instead of dying gracefully.
signal(SIGCHLD, SIG_IGN);
#endif
for (const auto &entry : worker_commands) {
// Initialize the pool state for this language.
auto &state = states_by_lang_[entry.first];
state.multiple_for_warning = maximum_startup_concurrency;
// Set worker command for this language.
state.worker_command = entry.second;
RAY_CHECK(!state.worker_command.empty()) << "Worker command must not be empty.";
}
// Initialize free ports list with all ports in the specified range.
if (!worker_ports.empty()) {
free_ports_ = std::unique_ptr<std::queue<int>>(new std::queue<int>());
for (int port : worker_ports) {
free_ports_->push(port);
}
} else if (min_worker_port != 0) {
if (max_worker_port == 0) {
max_worker_port = 65535; // Maximum valid port number.
}
RAY_CHECK(min_worker_port > 0 && min_worker_port <= 65535);
RAY_CHECK(max_worker_port >= min_worker_port && max_worker_port <= 65535);
free_ports_ = std::unique_ptr<std::queue<int>>(new std::queue<int>());
for (int port = min_worker_port; port <= max_worker_port; port++) {
free_ports_->push(port);
}
}
ScheduleIdleWorkerKilling();
}
WorkerPool::~WorkerPool() {
std::unordered_set<Process> procs_to_kill;
for (const auto &entry : states_by_lang_) {
// Kill all registered workers. NOTE(swang): This assumes that the registered
// workers were started by the pool.
for (const auto &worker : entry.second.registered_workers) {
procs_to_kill.insert(worker->GetProcess());
}
// Kill all the workers that have been started but not registered.
for (const auto &starting_worker : entry.second.starting_worker_processes) {
procs_to_kill.insert(starting_worker.first);
}
}
for (Process proc : procs_to_kill) {
proc.Kill();
// NOTE: Avoid calling Wait() here. It fails with ECHILD, as SIGCHLD is disabled.
}
}
Process WorkerPool::StartWorkerProcess(
const Language &language, const rpc::WorkerType worker_type, const JobID &job_id,
std::vector<std::string> dynamic_options,
std::unordered_map<std::string, std::string> override_environment_variables) {
rpc::JobConfig *job_config = nullptr;
if (!IsIOWorkerType(worker_type)) {
RAY_CHECK(!job_id.IsNil());
auto it = all_jobs_.find(job_id);
if (it == all_jobs_.end()) {
RAY_LOG(DEBUG) << "Job config of job " << job_id << " are not local yet.";
// Will reschedule ready tasks in `NodeManager::HandleJobStarted`.
return Process();
}
job_config = &it->second;
}
auto &state = GetStateForLanguage(language);
// If we are already starting up too many workers, then return without starting
// more.
int starting_workers = 0;
for (auto &entry : state.starting_worker_processes) {
starting_workers += entry.second;
}
// Here we consider both task workers and I/O workers.
if (starting_workers >= maximum_startup_concurrency_) {
// Workers have been started, but not registered. Force start disabled -- returning.
RAY_LOG(DEBUG) << "Worker not started, " << starting_workers
<< " workers of language type " << static_cast<int>(language)
<< " pending registration";
return Process();
}
// Either there are no workers pending registration or the worker start is being forced.
RAY_LOG(DEBUG) << "Starting new worker process, current pool has " << state.idle.size()
<< " workers";
int workers_to_start = 1;
if (dynamic_options.empty()) {
if (language == Language::JAVA) {
workers_to_start = job_config->num_java_workers_per_process();
}
}
if (job_config) {
// Note that we push the item to the front of the vector to make
// sure this is the freshest option than others.
if (!job_config->jvm_options().empty()) {
dynamic_options.insert(dynamic_options.begin(), job_config->jvm_options().begin(),
job_config->jvm_options().end());
}
std::string code_search_path_str;
for (int i = 0; i < job_config->code_search_path_size(); i++) {
auto path = job_config->code_search_path(i);
if (i != 0) {
code_search_path_str += ":";
}
code_search_path_str += path;
}
if (!code_search_path_str.empty()) {
switch (language) {
case Language::PYTHON: {
code_search_path_str = "--code-search-path=" + code_search_path_str;
break;
}
case Language::JAVA: {
code_search_path_str = "-Dray.job.code-search-path=" + code_search_path_str;
break;
}
default:
RAY_LOG(FATAL) << "code_search_path is not supported for worker language "
<< language;
}
dynamic_options.push_back(code_search_path_str);
}
}
// Extract pointers from the worker command to pass into execvp.
std::vector<std::string> worker_command_args;
bool worker_raylet_config_placeholder_found = false;
for (auto const &token : state.worker_command) {
if (token == kWorkerDynamicOptionPlaceholder) {
for (const auto &dynamic_option : dynamic_options) {
auto options = ParseCommandLine(dynamic_option);
worker_command_args.insert(worker_command_args.end(), options.begin(),
options.end());
}
continue;
}
if (token == kWorkerRayletConfigPlaceholder) {
worker_raylet_config_placeholder_found = true;
switch (language) {
case Language::JAVA:
for (auto &entry : raylet_config_) {
std::string arg;
arg.append("-Dray.raylet.config.");
arg.append(entry.first);
arg.append("=");
arg.append(entry.second);
worker_command_args.push_back(arg);
}
worker_command_args.push_back("-Dray.job.num-java-workers-per-process=" +
std::to_string(workers_to_start));
break;
default:
RAY_LOG(FATAL)
<< "Raylet config placeholder is not supported for worker language "
<< language;
}
continue;
}
worker_command_args.push_back(token);
}
// Currently only Java worker process supports multi-worker.
if (language == Language::JAVA) {
RAY_CHECK(worker_raylet_config_placeholder_found)
<< "The " << kWorkerRayletConfigPlaceholder
<< " placeholder is not found in worker command.";
} else if (language == Language::PYTHON) {
RAY_CHECK(worker_type == rpc::WorkerType::WORKER || IsIOWorkerType(worker_type));
if (IsIOWorkerType(worker_type)) {
// Without "--worker-type", by default the worker type is rpc::WorkerType::WORKER.
worker_command_args.push_back("--worker-type=" + rpc::WorkerType_Name(worker_type));
}
}
if (IsIOWorkerType(worker_type)) {
RAY_CHECK(!RayConfig::instance().object_spilling_config().empty());
RAY_LOG(DEBUG) << "Adding object spill config "
<< RayConfig::instance().object_spilling_config();
worker_command_args.push_back("--object-spilling-config=" +
RayConfig::instance().object_spilling_config());
}
ProcessEnvironment env;
if (!IsIOWorkerType(worker_type)) {
// We pass the job ID to worker processes via an environment variable, so we don't
// need to add a new CLI parameter for both Python and Java workers.
env.emplace(kEnvVarKeyJobId, job_id.Hex());
}
if (job_config) {
env.insert(job_config->worker_env().begin(), job_config->worker_env().end());
}
for (const auto &pair : override_environment_variables) {
env[pair.first] = pair.second;
}
// Start a process and measure the startup time.
auto start = std::chrono::high_resolution_clock::now();
Process proc = StartProcess(worker_command_args, env);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
stats::ProcessStartupTimeMs.Record(duration.count());
RAY_LOG(DEBUG) << "Started worker process of " << workers_to_start
<< " worker(s) with pid " << proc.GetId();
MonitorStartingWorkerProcess(proc, language, worker_type);
state.starting_worker_processes.emplace(proc, workers_to_start);
if (IsIOWorkerType(worker_type)) {
auto &io_worker_state = GetIOWorkerStateFromWorkerType(worker_type, state);
io_worker_state.num_starting_io_workers++;
}
return proc;
}
void WorkerPool::MonitorStartingWorkerProcess(const Process &proc,
const Language &language,
const rpc::WorkerType worker_type) {
auto timer = std::make_shared<boost::asio::deadline_timer>(
*io_service_, boost::posix_time::seconds(
RayConfig::instance().worker_register_timeout_seconds()));
// Capture timer in lambda to copy it once, so that it can avoid destructing timer.
timer->async_wait(
[timer, language, proc, worker_type, this](const boost::system::error_code e) {
// check the error code.
auto &state = this->GetStateForLanguage(language);
// Since this process times out to start, remove it from starting_worker_processes
// to avoid the zombie worker.
auto it = state.starting_worker_processes.find(proc);
if (it != state.starting_worker_processes.end()) {
RAY_LOG(INFO) << "Some workers of the worker process(" << proc.GetId()
<< ") have not registered to raylet within timeout.";
state.starting_worker_processes.erase(it);
if (IsIOWorkerType(worker_type)) {
// Mark the I/O worker as failed.
auto &io_worker_state = GetIOWorkerStateFromWorkerType(worker_type, state);
io_worker_state.num_starting_io_workers--;
}
// We may have places to start more workers now.
TryStartIOWorkers(language);
starting_worker_timeout_callback_();
}
});
}
Process WorkerPool::StartProcess(const std::vector<std::string> &worker_command_args,
const ProcessEnvironment &env) {
if (RAY_LOG_ENABLED(DEBUG)) {
std::stringstream stream;
stream << "Starting worker process with command:";
for (const auto &arg : worker_command_args) {
stream << " " << arg;
}
RAY_LOG(DEBUG) << stream.str();
}
// Launch the process to create the worker.
std::error_code ec;
std::vector<const char *> argv;
for (const std::string &arg : worker_command_args) {
argv.push_back(arg.c_str());
}
argv.push_back(NULL);
Process child(argv.data(), io_service_, ec, /*decouple=*/false, env);
if (!child.IsValid() || ec) {
// errorcode 24: Too many files. This is caused by ulimit.
if (ec.value() == 24) {
RAY_LOG(FATAL) << "Too many workers, failed to create a file. Try setting "
<< "`ulimit -n <num_files>` then restart Ray.";
} else {
// The worker failed to start. This is a fatal error.
RAY_LOG(FATAL) << "Failed to start worker with return value " << ec << ": "
<< ec.message();
}
}
return child;
}
Status WorkerPool::GetNextFreePort(int *port) {
if (!free_ports_) {
*port = 0;
return Status::OK();
}
// Try up to the current number of ports.
int current_size = free_ports_->size();
for (int i = 0; i < current_size; i++) {
*port = free_ports_->front();
free_ports_->pop();
if (CheckFree(*port)) {
return Status::OK();
}
// Return to pool to check later.
free_ports_->push(*port);
}
return Status::Invalid(
"No available ports. Please specify a wider port range using --min-worker-port and "
"--max-worker-port.");
}
void WorkerPool::MarkPortAsFree(int port) {
if (free_ports_) {
RAY_CHECK(port != 0) << "";
free_ports_->push(port);
}
}
void WorkerPool::HandleJobStarted(const JobID &job_id, const rpc::JobConfig &job_config) {
all_jobs_[job_id] = job_config;
}
void WorkerPool::HandleJobFinished(const JobID &job_id) {
// Currently we don't erase the job from `all_jobs_` , as a workaround for
// https://github.com/ray-project/ray/issues/11437.
// unfinished_jobs_.erase(job_id);
}
Status WorkerPool::RegisterWorker(const std::shared_ptr<WorkerInterface> &worker,
pid_t pid,
std::function<void(Status, int)> send_reply_callback) {
RAY_CHECK(worker);
auto &state = GetStateForLanguage(worker->GetLanguage());
auto process = Process::FromPid(pid);
if (state.starting_worker_processes.count(process) == 0) {
RAY_LOG(WARNING) << "Received a register request from an unknown worker "
<< process.GetId();
Status status = Status::Invalid("Unknown worker");
send_reply_callback(status, /*port=*/0);
return status;
}
worker->SetProcess(process);
// The port that this worker's gRPC server should listen on. 0 if the worker
// should bind on a random port.
int port = 0;
Status status = GetNextFreePort(&port);
if (!status.ok()) {
send_reply_callback(status, /*port=*/0);
return status;
}
RAY_LOG(DEBUG) << "Registering worker with pid " << pid << ", port: " << port
<< ", worker_type: " << rpc::WorkerType_Name(worker->GetWorkerType());
worker->SetAssignedPort(port);
state.registered_workers.insert(worker);
// Send the reply immediately for worker registrations.
send_reply_callback(Status::OK(), port);
return Status::OK();
}
void WorkerPool::OnWorkerStarted(const std::shared_ptr<WorkerInterface> &worker) {
auto &state = GetStateForLanguage(worker->GetLanguage());
const auto &process = worker->GetProcess();
RAY_CHECK(process.IsValid());
auto it = state.starting_worker_processes.find(process);
if (it != state.starting_worker_processes.end()) {
it->second--;
if (it->second == 0) {
state.starting_worker_processes.erase(it);
// We may have slots to start more workers now.
TryStartIOWorkers(worker->GetLanguage());
}
}
const auto &worker_type = worker->GetWorkerType();
if (IsIOWorkerType(worker_type)) {
auto &io_worker_state = GetIOWorkerStateFromWorkerType(worker_type, state);
io_worker_state.registered_io_workers.insert(worker);
io_worker_state.num_starting_io_workers--;
}
// This is a workaround to finish driver registration after all initial workers are
// registered to Raylet if and only if Raylet is started by a Python driver and the
// job config is not set in `ray.init(...)`.
if (first_job_ == worker->GetAssignedJobId() &&
worker->GetLanguage() == Language::PYTHON) {
if (++first_job_registered_python_worker_count_ ==
first_job_driver_wait_num_python_workers_) {
if (first_job_send_register_client_reply_to_driver_) {
first_job_send_register_client_reply_to_driver_();
first_job_send_register_client_reply_to_driver_ = nullptr;
}
}
}
}
Status WorkerPool::RegisterDriver(const std::shared_ptr<WorkerInterface> &driver,
const rpc::JobConfig &job_config,
std::function<void(Status, int)> send_reply_callback) {
int port;
RAY_CHECK(!driver->GetAssignedTaskId().IsNil());
Status status = GetNextFreePort(&port);
if (!status.ok()) {
send_reply_callback(status, /*port=*/0);
return status;
}
driver->SetAssignedPort(port);
auto &state = GetStateForLanguage(driver->GetLanguage());
state.registered_drivers.insert(std::move(driver));
const auto job_id = driver->GetAssignedJobId();
all_jobs_[job_id] = job_config;
// This is a workaround to start initial workers on this node if and only if Raylet is
// started by a Python driver and the job config is not set in `ray.init(...)`.
// Invoke the `send_reply_callback` later to only finish driver
// registration after all initial workers are registered to Raylet.
bool delay_callback = false;
// If this is the first job.
if (first_job_.IsNil()) {
first_job_ = job_id;
// If the number of Python workers we need to wait is positive.
if (num_initial_python_workers_for_first_job_ > 0) {
delay_callback = true;
// Start initial Python workers for the first job.
for (int i = 0; i < num_initial_python_workers_for_first_job_; i++) {
StartWorkerProcess(Language::PYTHON, rpc::WorkerType::WORKER, job_id);
}
}
}
if (delay_callback) {
RAY_CHECK(!first_job_send_register_client_reply_to_driver_);
first_job_send_register_client_reply_to_driver_ = [send_reply_callback, port]() {
send_reply_callback(Status::OK(), port);
};
} else {
send_reply_callback(Status::OK(), port);
}
return Status::OK();
}
std::shared_ptr<WorkerInterface> WorkerPool::GetRegisteredWorker(
const std::shared_ptr<ClientConnection> &connection) const {
for (const auto &entry : states_by_lang_) {
auto worker = GetWorker(entry.second.registered_workers, connection);
if (worker != nullptr) {
return worker;
}
}
return nullptr;
}
std::shared_ptr<WorkerInterface> WorkerPool::GetRegisteredDriver(
const std::shared_ptr<ClientConnection> &connection) const {
for (const auto &entry : states_by_lang_) {
auto driver = GetWorker(entry.second.registered_drivers, connection);
if (driver != nullptr) {
return driver;
}
}
return nullptr;
}
void WorkerPool::PushSpillWorker(const std::shared_ptr<WorkerInterface> &worker) {
PushIOWorkerInternal(worker, rpc::WorkerType::SPILL_WORKER);
}
void WorkerPool::PopSpillWorker(
std::function<void(std::shared_ptr<WorkerInterface>)> callback) {
PopIOWorkerInternal(rpc::WorkerType::SPILL_WORKER, callback);
}
void WorkerPool::PushRestoreWorker(const std::shared_ptr<WorkerInterface> &worker) {
PushIOWorkerInternal(worker, rpc::WorkerType::RESTORE_WORKER);
}
void WorkerPool::PopRestoreWorker(
std::function<void(std::shared_ptr<WorkerInterface>)> callback) {
PopIOWorkerInternal(rpc::WorkerType::RESTORE_WORKER, callback);
}
void WorkerPool::PushIOWorkerInternal(const std::shared_ptr<WorkerInterface> &worker,
const rpc::WorkerType &worker_type) {
RAY_CHECK(IsIOWorkerType(worker->GetWorkerType()));
auto &state = GetStateForLanguage(Language::PYTHON);
auto &io_worker_state = GetIOWorkerStateFromWorkerType(worker_type, state);
RAY_LOG(DEBUG) << "Pushing an IO worker to the worker pool.";
if (io_worker_state.pending_io_tasks.empty()) {
io_worker_state.idle_io_workers.push(worker);
} else {
auto callback = io_worker_state.pending_io_tasks.front();
io_worker_state.pending_io_tasks.pop();
callback(worker);
}
}
void WorkerPool::PopIOWorkerInternal(
const rpc::WorkerType &worker_type,
std::function<void(std::shared_ptr<WorkerInterface>)> callback) {
auto &state = GetStateForLanguage(Language::PYTHON);
auto &io_worker_state = GetIOWorkerStateFromWorkerType(worker_type, state);
if (io_worker_state.idle_io_workers.empty()) {
// We must fill the pending task first, because 'TryStartIOWorkers' will
// start I/O workers according to the number of pending tasks.
io_worker_state.pending_io_tasks.push(callback);
TryStartIOWorkers(Language::PYTHON, worker_type);
} else {
auto io_worker = io_worker_state.idle_io_workers.front();
io_worker_state.idle_io_workers.pop();
callback(io_worker);
}
}
void WorkerPool::PushDeleteWorker(const std::shared_ptr<WorkerInterface> &worker) {
RAY_CHECK(IsIOWorkerType(worker->GetWorkerType()));
if (worker->GetWorkerType() == rpc::WorkerType::RESTORE_WORKER) {
PushRestoreWorker(worker);
} else {
PushSpillWorker(worker);
}
}
void WorkerPool::PopDeleteWorker(
std::function<void(std::shared_ptr<WorkerInterface>)> callback) {
auto &state = GetStateForLanguage(Language::PYTHON);
// Choose an I/O worker with more idle workers.
size_t num_spill_idle_workers = state.spill_io_worker_state.idle_io_workers.size();
size_t num_restore_idle_workers = state.restore_io_worker_state.idle_io_workers.size();
if (num_restore_idle_workers < num_spill_idle_workers) {
PopSpillWorker(callback);
} else {
PopRestoreWorker(callback);
}
}
void WorkerPool::PushWorker(const std::shared_ptr<WorkerInterface> &worker) {
// Since the worker is now idle, unset its assigned task ID.
RAY_CHECK(worker->GetAssignedTaskId().IsNil())
<< "Idle workers cannot have an assigned task ID";
auto &state = GetStateForLanguage(worker->GetLanguage());
auto it = state.dedicated_workers_to_tasks.find(worker->GetProcess());
if (it != state.dedicated_workers_to_tasks.end()) {
// The worker is used for the actor creation task with dynamic options.
// Put it into idle dedicated worker pool.
const auto task_id = it->second;
state.idle_dedicated_workers[task_id] = worker;
} else {
// The worker is not used for the actor creation task with dynamic options.
// Put the worker to the idle pool.
state.idle.insert(worker);
int64_t now = current_time_ms();
idle_of_all_languages_.emplace_back(worker, now);
idle_of_all_languages_map_[worker] = now;
}
}
void WorkerPool::ScheduleIdleWorkerKilling() {
if (RayConfig::instance().kill_idle_workers_interval_ms() > 0) {
kill_idle_workers_timer_.expires_from_now(boost::posix_time::milliseconds(
RayConfig::instance().kill_idle_workers_interval_ms()));
kill_idle_workers_timer_.async_wait([this](const boost::system::error_code &error) {
if (error == boost::asio::error::operation_aborted) {
return;
}
TryKillingIdleWorkers();
ScheduleIdleWorkerKilling();
});
}
}
void WorkerPool::TryKillingIdleWorkers() {
RAY_CHECK(idle_of_all_languages_.size() == idle_of_all_languages_map_.size());
int64_t now = current_time_ms();
size_t running_size = 0;
for (const auto &worker : GetAllRegisteredWorkers()) {
if (!worker->IsDead()) {
running_size++;
}
}
// Kill idle workers in FIFO order.
for (const auto &idle_pair : idle_of_all_languages_) {
if (running_size <= static_cast<size_t>(num_workers_soft_limit_)) {
break;
}
if (now - idle_pair.second <
RayConfig::instance().idle_worker_killing_time_threshold_ms()) {
break;
}
const auto &idle_worker = idle_pair.first;
if (idle_worker->IsDead()) {
// This worker has already been killed.
// This is possible because a Java worker process may hold multiple workers.
continue;
}
auto process = idle_worker->GetProcess();
auto &worker_state = GetStateForLanguage(idle_worker->GetLanguage());
if (worker_state.starting_worker_processes.count(process) > 0) {
// A Java worker process may hold multiple workers.
// Some workers of this process are pending registration. Skip killing this worker.
continue;
}
// Make sure all workers in this worker process are idle.
// This block of code is needed by Java workers.
auto workers_in_the_same_process = GetWorkersByProcess(process);
bool can_be_killed = true;
for (const auto &worker : workers_in_the_same_process) {
if (worker_state.idle.count(worker) == 0 ||
now - idle_of_all_languages_map_[worker] <
RayConfig::instance().idle_worker_killing_time_threshold_ms()) {
// Another worker in this process isn't idle, or hasn't been idle for a while, so
// this process can't be killed.
can_be_killed = false;
break;
}
}
if (!can_be_killed) {
continue;
}
if (running_size - workers_in_the_same_process.size() <
static_cast<size_t>(num_workers_soft_limit_)) {
// A Java worker process may contain multiple workers. Killing more workers than we
// expect may slow the job.
return;
}
for (const auto &worker : workers_in_the_same_process) {
RAY_LOG(DEBUG) << "The worker pool has " << running_size
<< " registered workers which exceeds the soft limit of "
<< num_workers_soft_limit_ << ", and worker " << worker->WorkerId()
<< " with pid " << process.GetId()
<< " has been idle for a a while. Kill it.";
// To avoid object lost issue caused by forcibly killing, send an RPC request to the
// worker to allow it to do cleanup before exiting.
auto rpc_client = worker->rpc_client();
RAY_CHECK(rpc_client);
rpc::ExitRequest request;
rpc_client->Exit(request, [](const ray::Status &status, const rpc::ExitReply &r) {
if (!status.ok()) {
RAY_LOG(ERROR) << "Failed to send exit request: " << status.ToString();
}
});
// Remove the worker from the idle pool so it can't be popped anymore.
RemoveWorker(worker_state.idle, worker);
if (!worker->IsDead()) {
worker->MarkDead();
running_size--;
}
}
}
std::list<std::pair<std::shared_ptr<WorkerInterface>, int64_t>>
new_idle_of_all_languages;
idle_of_all_languages_map_.clear();
for (const auto &idle_pair : idle_of_all_languages_) {
if (!idle_pair.first->IsDead()) {
new_idle_of_all_languages.push_back(idle_pair);
idle_of_all_languages_map_.emplace(idle_pair);
}
}
idle_of_all_languages_ = std::move(new_idle_of_all_languages);
RAY_CHECK(idle_of_all_languages_.size() == idle_of_all_languages_map_.size());
}
std::shared_ptr<WorkerInterface> WorkerPool::PopWorker(
const TaskSpecification &task_spec) {
auto &state = GetStateForLanguage(task_spec.GetLanguage());
std::shared_ptr<WorkerInterface> worker = nullptr;
Process proc;
if ((task_spec.IsActorCreationTask() && !task_spec.DynamicWorkerOptions().empty()) ||
task_spec.OverrideEnvironmentVariables().size() > 0) {
// Code path of task that needs a dedicated worker: an actor creation task with
// dynamic worker options, or any task with environment variable overrides.
// Try to pop it from idle dedicated pool.
auto it = state.idle_dedicated_workers.find(task_spec.TaskId());
if (it != state.idle_dedicated_workers.end()) {
// There is an idle dedicated worker for this task.
worker = std::move(it->second);
state.idle_dedicated_workers.erase(it);
// Because we found a worker that can perform this task,
// we can remove it from dedicated_workers_to_tasks.
state.dedicated_workers_to_tasks.erase(worker->GetProcess());
state.tasks_to_dedicated_workers.erase(task_spec.TaskId());
} else if (!HasPendingWorkerForTask(task_spec.GetLanguage(), task_spec.TaskId())) {
// We are not pending a registration from a worker for this task,
// so start a new worker process for this task.
std::vector<std::string> dynamic_options = {};
if (task_spec.IsActorCreationTask()) {
dynamic_options = task_spec.DynamicWorkerOptions();
}
proc = StartWorkerProcess(task_spec.GetLanguage(), rpc::WorkerType::WORKER,
task_spec.JobId(), dynamic_options,
task_spec.OverrideEnvironmentVariables());
if (proc.IsValid()) {
state.dedicated_workers_to_tasks[proc] = task_spec.TaskId();
state.tasks_to_dedicated_workers[task_spec.TaskId()] = proc;
}
}
} else if (task_spec.IsActorTask()) {
// Code path of actor task.
RAY_CHECK(false) << "Direct call shouldn't reach here.";
} else {
// Code path of normal task or actor creation task without dynamic worker options.
// Find an available worker which is already assigned to this job.
// Try to pop the most recently pushed worker.
for (auto it = idle_of_all_languages_.rbegin(); it != idle_of_all_languages_.rend();
it++) {
if (task_spec.GetLanguage() != it->first->GetLanguage() ||
it->first->GetAssignedJobId() != task_spec.JobId()) {
continue;
}
state.idle.erase(it->first);
// We can't erase a reverse_iterator.
auto lit = it.base();
lit--;
worker = std::move(lit->first);
idle_of_all_languages_.erase(lit);
idle_of_all_languages_map_.erase(worker);
break;
}
if (worker == nullptr) {
// There are no more non-actor workers available to execute this task.
// Start a new worker process.
proc = StartWorkerProcess(task_spec.GetLanguage(), rpc::WorkerType::WORKER,
task_spec.JobId());
}
}
if (worker == nullptr && proc.IsValid()) {
WarnAboutSize();
}
if (worker) {
RAY_CHECK(worker->GetAssignedJobId() == task_spec.JobId());
}
return worker;
}
void WorkerPool::PrestartWorkers(const TaskSpecification &task_spec,
int64_t backlog_size) {
// Code path of task that needs a dedicated worker: an actor creation task with
// dynamic worker options, or any task with environment variable overrides.
if ((task_spec.IsActorCreationTask() && !task_spec.DynamicWorkerOptions().empty()) ||
task_spec.OverrideEnvironmentVariables().size() > 0) {
return; // Not handled.
}
auto &state = GetStateForLanguage(task_spec.GetLanguage());
// The number of available workers that can be used for this task spec.
int num_usable_workers = state.idle.size();
for (auto &entry : state.starting_worker_processes) {
num_usable_workers += entry.second;
}
// The number of workers total regardless of suitability for this task.
int num_workers_total = 0;
for (const auto &worker : GetAllRegisteredWorkers()) {
if (!worker->IsDead()) {
num_workers_total++;
}
}
auto desired_usable_workers =
std::min<int64_t>(num_workers_soft_limit_ - num_workers_total, backlog_size);
if (num_usable_workers < desired_usable_workers) {
int64_t num_needed = desired_usable_workers - num_usable_workers;
RAY_LOG(DEBUG) << "Prestarting " << num_needed << " workers given task backlog size "
<< backlog_size << " and soft limit " << num_workers_soft_limit_;
for (int i = 0; i < num_needed; i++) {
StartWorkerProcess(task_spec.GetLanguage(), rpc::WorkerType::WORKER,
task_spec.JobId());
}
}
}
bool WorkerPool::DisconnectWorker(const std::shared_ptr<WorkerInterface> &worker) {
auto &state = GetStateForLanguage(worker->GetLanguage());
RAY_CHECK(RemoveWorker(state.registered_workers, worker));
for (auto it = idle_of_all_languages_.begin(); it != idle_of_all_languages_.end();
it++) {
if (it->first == worker) {
idle_of_all_languages_.erase(it);
idle_of_all_languages_map_.erase(worker);
break;
}
}
MarkPortAsFree(worker->AssignedPort());
return RemoveWorker(state.idle, worker);
}
void WorkerPool::DisconnectDriver(const std::shared_ptr<WorkerInterface> &driver) {
auto &state = GetStateForLanguage(driver->GetLanguage());
RAY_CHECK(RemoveWorker(state.registered_drivers, driver));
MarkPortAsFree(driver->AssignedPort());
}
inline WorkerPool::State &WorkerPool::GetStateForLanguage(const Language &language) {
auto state = states_by_lang_.find(language);
RAY_CHECK(state != states_by_lang_.end()) << "Required Language isn't supported.";
return state->second;
}
inline bool WorkerPool::IsIOWorkerType(const rpc::WorkerType &worker_type) {
return worker_type == rpc::WorkerType::SPILL_WORKER ||
worker_type == rpc::WorkerType::RESTORE_WORKER;
}
std::vector<std::shared_ptr<WorkerInterface>> WorkerPool::GetWorkersRunningTasksForJob(
const JobID &job_id) const {
std::vector<std::shared_ptr<WorkerInterface>> workers;
for (const auto &entry : states_by_lang_) {
for (const auto &worker : entry.second.registered_workers) {
if (worker->GetAssignedJobId() == job_id) {
workers.push_back(worker);
}
}
}
return workers;
}
const std::vector<std::shared_ptr<WorkerInterface>> WorkerPool::GetAllRegisteredWorkers(
bool filter_dead_workers) const {
std::vector<std::shared_ptr<WorkerInterface>> workers;
for (const auto &entry : states_by_lang_) {
for (const auto &worker : entry.second.registered_workers) {
if (!worker->IsRegistered()) {
continue;
}
if (filter_dead_workers && worker->IsDead()) {
continue;
}
workers.push_back(worker);
}
}
return workers;
}
const std::vector<std::shared_ptr<WorkerInterface>> WorkerPool::GetAllRegisteredDrivers(
bool filter_dead_drivers) const {
std::vector<std::shared_ptr<WorkerInterface>> drivers;
for (const auto &entry : states_by_lang_) {
for (const auto &driver : entry.second.registered_drivers) {
if (!driver->IsRegistered()) {
continue;
}
if (filter_dead_drivers && driver->IsDead()) {
continue;
}
drivers.push_back(driver);
}
}
return drivers;
}
void WorkerPool::WarnAboutSize() {
for (auto &entry : states_by_lang_) {
auto &state = entry.second;
int64_t num_workers_started_or_registered = 0;
num_workers_started_or_registered +=
static_cast<int64_t>(state.registered_workers.size());
for (const auto &starting_process : state.starting_worker_processes) {
num_workers_started_or_registered += starting_process.second;
}
int64_t multiple = num_workers_started_or_registered / state.multiple_for_warning;
std::stringstream warning_message;
if (multiple >= 3 && multiple > state.last_warning_multiple) {
// Push an error message to the user if the worker pool tells us that it is
// getting too big.
state.last_warning_multiple = multiple;
warning_message << "WARNING: " << num_workers_started_or_registered << " "
<< Language_Name(entry.first)
<< " workers have been started. This could be a result of using "
<< "a large number of actors, or it could be a consequence of "
<< "using nested tasks "
<< "(see https://github.com/ray-project/ray/issues/3644) for "
<< "some a discussion of workarounds.";
auto error_data_ptr = gcs::CreateErrorTableData(
"worker_pool_large", warning_message.str(), current_time_ms());
RAY_CHECK_OK(gcs_client_->Errors().AsyncReportJobError(error_data_ptr, nullptr));
}
}
}
bool WorkerPool::HasPendingWorkerForTask(const Language &language,
const TaskID &task_id) {
auto &state = GetStateForLanguage(language);
auto it = state.tasks_to_dedicated_workers.find(task_id);
return it != state.tasks_to_dedicated_workers.end();
}
void WorkerPool::TryStartIOWorkers(const Language &language) {
TryStartIOWorkers(language, rpc::WorkerType::RESTORE_WORKER);
TryStartIOWorkers(language, rpc::WorkerType::SPILL_WORKER);
}
void WorkerPool::TryStartIOWorkers(const Language &language,
const rpc::WorkerType &worker_type) {
if (language != Language::PYTHON) {
return;
}
auto &state = GetStateForLanguage(language);
auto &io_worker_state = GetIOWorkerStateFromWorkerType(worker_type, state);
int available_io_workers_num = io_worker_state.num_starting_io_workers +
io_worker_state.registered_io_workers.size();
int max_workers_to_start =
RayConfig::instance().max_io_workers() - available_io_workers_num;
// Compare first to prevent unsigned underflow.
if (io_worker_state.pending_io_tasks.size() > io_worker_state.idle_io_workers.size()) {
int expected_workers_num =
io_worker_state.pending_io_tasks.size() - io_worker_state.idle_io_workers.size();
if (expected_workers_num > max_workers_to_start) {
expected_workers_num = max_workers_to_start;
}
for (; expected_workers_num > 0; expected_workers_num--) {
Process proc = StartWorkerProcess(ray::Language::PYTHON, worker_type, JobID::Nil());
if (!proc.IsValid()) {
// We may hit the maximum worker start up concurrency limit. Stop.
return;
}
}
}
}
std::unordered_set<std::shared_ptr<WorkerInterface>> WorkerPool::GetWorkersByProcess(
const Process &process) {
std::unordered_set<std::shared_ptr<WorkerInterface>> workers_of_process;
for (auto &entry : states_by_lang_) {
auto &worker_state = entry.second;
for (const auto &worker : worker_state.registered_workers) {
if (worker->GetProcess().GetId() == process.GetId()) {
workers_of_process.insert(worker);
}
}
}
return workers_of_process;
}
std::string WorkerPool::DebugString() const {
std::stringstream result;
result << "WorkerPool:";
for (const auto &entry : states_by_lang_) {
result << "\n- num " << Language_Name(entry.first)
<< " workers: " << entry.second.registered_workers.size();
result << "\n- num " << Language_Name(entry.first)
<< " drivers: " << entry.second.registered_drivers.size();
result << "\n- num object spill callbacks queued: "
<< entry.second.spill_io_worker_state.pending_io_tasks.size();
result << "\n- num object restore queued: "
<< entry.second.restore_io_worker_state.pending_io_tasks.size();
}
result << "\n- num idle workers: " << idle_of_all_languages_.size();
return result.str();
}
WorkerPool::IOWorkerState &WorkerPool::GetIOWorkerStateFromWorkerType(
const rpc::WorkerType &worker_type, WorkerPool::State &state) const {
RAY_CHECK(worker_type != rpc::WorkerType::WORKER)
<< worker_type << " type cannot be used to retrieve io_worker_state";
if (worker_type == rpc::WorkerType::SPILL_WORKER) {
return state.spill_io_worker_state;
} else {
return state.restore_io_worker_state;
}
}
} // namespace raylet
} // namespace ray
|
// TnzCore includes
#include "tstream.h"
#include "trop.h"
#include "tflash.h"
// TnzBase includes
#include "tdoubleparam.h"
#include "tnotanimatableparam.h"
#include "tfxparam.h"
#include "trasterfx.h"
#include "tbasefx.h"
//******************************************************************************************
// Local namespace
//******************************************************************************************
namespace {
void makeRectCoherent(TRectD &rect, const TPointD &pos) {
rect -= pos;
rect.x0 = tfloor(rect.x0);
rect.y0 = tfloor(rect.y0);
rect.x1 = tceil(rect.x1);
rect.y1 = tceil(rect.y1);
rect += pos;
}
}
//******************************************************************************************
// TImageCombinationFx declaration
//******************************************************************************************
class TImageCombinationFx : public TBaseRasterFx {
TFxPortDG m_group;
public:
TImageCombinationFx();
virtual ~TImageCombinationFx() {}
public:
// Virtual interface for heirs
//! The raster processing function that must be reimplemented to perform the
//! fx
virtual void process(const TRasterP &up, const TRasterP &down,
double frame) = 0;
//! Whether the 'up' rasters of process() invocations must be allocated to
//! entirely cover the 'down' counterpart. Should be enabled if the process()
//! function affects 'down' pixels when the 'up's are fully transparent.
virtual bool requiresFullRect() { return false; }
public:
// Low-level TRasterFx-related functions
int dynamicPortGroupsCount() const override { return 1; }
const TFxPortDG *dynamicPortGroup(int g) const override {
return (g == 0) ? &m_group : 0;
}
bool canHandle(const TRenderSettings &info, double frame) override {
return true;
}
int getMemoryRequirement(const TRectD &rect, double frame,
const TRenderSettings &info) override {
// At max the memory of another tile with the same infos may be allocated
// apart from
// the externally supplied one.
return TRasterFx::memorySize(rect, info.m_bpp);
}
bool doGetBBox(double frame, TRectD &bBox,
const TRenderSettings &info) override;
void doDryCompute(TRectD &rect, double frame,
const TRenderSettings &info) override;
void doCompute(TTile &tile, double frame,
const TRenderSettings &info) override;
void compatibilityTranslatePort(int majorVersion, int minorVersion,
std::string &portName) override;
int getPreferredInputPort() override { return 1; }
};
//******************************************************************************************
// TImageCombinationFx implementation
//******************************************************************************************
TImageCombinationFx::TImageCombinationFx() : m_group("Source", 2) {
addInputPort("Source1", new TRasterFxPort, 0);
addInputPort("Source2", new TRasterFxPort, 0);
setName(L"ImageCombinationFx");
}
//---------------------------------------------------------------------------
bool TImageCombinationFx::doGetBBox(double frame, TRectD &bBox,
const TRenderSettings &info) {
bBox = TRectD();
int p, pCount = getInputPortCount();
for (p = 0; p != pCount; ++p) {
TRasterFxPort *port = static_cast<TRasterFxPort *>(getInputPort(p));
TRectD inputBBox;
bool hasInput = (port && port->isConnected())
? (*port)->doGetBBox(frame, inputBBox, info)
: false;
if (hasInput) bBox += inputBBox;
}
return (bBox.getLx() >= 0) && (bBox.getLy() >= 0);
}
//---------------------------------------------------------------------------
void TImageCombinationFx::doCompute(TTile &tile, double frame,
const TRenderSettings &info) {
int p, pCount = getInputPortCount();
TRasterFxPort *port = 0;
// Skip empty ports
for (p = pCount - 1; p >= 0;
--p) // Reverse iteration - bottom ports have high indices
{
port = static_cast<TRasterFxPort *>(getInputPort(p));
if (port && port->getFx()) break;
}
// If there is no input, clear and return
if (p < 0) {
tile.getRaster()
->clear(); // Probably not necessary unless externally invocation
return; // deliberately soiled tile - however, should be rare anyway.
}
// Calculate the tiles' geometries
const TRect &tileRect(tile.getRaster()->getBounds());
const TDimension &tileSize(tileRect.getSize());
TRectD tileRectD(tile.m_pos, TDimensionD(tileSize.lx, tileSize.ly));
// Render the first viable port directly on tile
(*port)->compute(tile, frame,
info); // Should we do it only if the bbox is not empty?
// Then, render each subsequent port and process() it on top of tile
bool canRestrict = !requiresFullRect();
for (--p; p >= 0; --p) {
port = static_cast<TRasterFxPort *>(getInputPort(p));
if (!(port && port->getFx())) // Skip empty ports
continue;
// Will allocate a new tile to calculate the input contribution - so, if
// possible
// we'll restrict allocation to the input port's bbox
TRectD computeRect(tileRectD);
if (canRestrict) {
TRectD inBBox;
(*port)->getBBox(frame, inBBox, info);
computeRect *= inBBox;
makeRectCoherent(
computeRect,
tile.m_pos); // Make it coherent with tile's pixel geometry
}
// Calculate the input port and perform processing
TDimension computeSize(tround(computeRect.getLx()),
tround(computeRect.getLy()));
if ((computeSize.lx > 0) && (computeSize.ly > 0)) {
TTile inTile; // Observe its locality - not incidental
(*port)->allocateAndCompute(inTile, computeRect.getP00(), computeSize,
tile.getRaster(), frame, info);
// Invoke process() to deal with the actual fx processing
TRasterP up(inTile.getRaster()), down(tile.getRaster());
if (canRestrict) {
// Extract from tile the part corresponding to inTile
TRect downRect(convert(computeRect.getP00() - tile.m_pos), computeSize);
down = down->extract(downRect);
}
assert(up->getSize() == down->getSize());
process(up, down, frame); // This is the point with the max concentration
// of allocated resources
}
}
}
//-------------------------------------------------------------------------------------
void TImageCombinationFx::doDryCompute(TRectD &rect, double frame,
const TRenderSettings &info) {
// Mere copy of doCompute(), stripped of the actual computations
int p, pCount = getInputPortCount();
TRasterFxPort *port = 0;
for (p = pCount - 1; p >= 0; --p) {
port = static_cast<TRasterFxPort *>(getInputPort(p));
if (port && port->getFx()) break;
}
if (p < 0) return;
(*port)->dryCompute(rect, frame, info);
bool canRestrict = !requiresFullRect();
for (--p; p >= 0; --p) {
port = static_cast<TRasterFxPort *>(getInputPort(p));
if (!(port && port->getFx())) continue;
TRectD computeRect(rect);
if (canRestrict) {
TRectD inBBox;
(*port)->getBBox(frame, inBBox, info);
computeRect *= inBBox;
makeRectCoherent(computeRect, rect.getP00());
}
TDimension computeSize(tround(computeRect.getLx()),
tround(computeRect.getLy()));
if ((computeSize.lx > 0) && (computeSize.ly > 0))
(*port)->dryCompute(computeRect, frame, info);
}
}
//-------------------------------------------------------------------------------------
void TImageCombinationFx::compatibilityTranslatePort(int major, int minor,
std::string &portName) {
if (VersionNumber(major, minor) < VersionNumber(1, 20)) {
if (portName == "Up")
portName = "Source1";
else if (portName == "Down")
portName = "Source2";
}
}
//******************************************************************************************
// TImageCombinationFx heir classes
//******************************************************************************************
class OverFx final : public TImageCombinationFx {
FX_DECLARATION(OverFx)
public:
OverFx() { setName(L"OverFx"); }
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::over(down, up);
}
};
//==================================================================
class AddFx final : public TImageCombinationFx {
FX_DECLARATION(AddFx)
TDoubleParamP m_value;
public:
AddFx() : m_value(100.0) { bindParam(this, "value", m_value); }
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
double value = m_value->getValue(frame) / 100.0;
if (value != 1.0)
TRop::add(up, down, down, value);
else
TRop::add(up, down, down);
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class ColorDodgeFx final : public TImageCombinationFx {
FX_DECLARATION(AddFx)
public:
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::colordodge(up, down, down);
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class ColorBurnFx final : public TImageCombinationFx {
FX_DECLARATION(AddFx)
public:
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::colorburn(up, down, down);
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class ScreenFx final : public TImageCombinationFx {
FX_DECLARATION(AddFx)
public:
bool requiresFullRect() override { return true; }
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::screen(up, down, down);
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class SubFx final : public TImageCombinationFx {
FX_DECLARATION(SubFx)
TBoolParamP m_matte;
public:
SubFx() : m_matte(false) { bindParam(this, "matte", m_matte); }
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::sub(up, down, down, m_matte->getValue());
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class MultFx final : public TImageCombinationFx {
FX_DECLARATION(MultFx)
TDoubleParamP m_value;
TBoolParamP m_matte;
public:
MultFx() : m_value(0.0), m_matte(false) {
bindParam(this, "value", m_value);
bindParam(this, "matte", m_matte);
}
bool requiresFullRect() override { return m_matte->getValue(); }
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::mult(up, down, down, m_value->getValue(frame), m_matte->getValue());
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class MinFx final : public TImageCombinationFx {
FX_DECLARATION(MinFx)
TBoolParamP m_matte;
public:
MinFx() : m_matte(true) { bindParam(this, "matte", m_matte); }
bool requiresFullRect() override { return true; }
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::ropmin(up, down, down, m_matte->getValue());
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class MaxFx final : public TImageCombinationFx {
FX_DECLARATION(MaxFx)
public:
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::ropmax(up, down, down);
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
class LinearBurnFx final : public TImageCombinationFx {
FX_DECLARATION(LinearBurnFx)
public:
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::linearburn(up, down, down);
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//==================================================================
// This Fx is probably unused...!
class OverlayFx final : public TImageCombinationFx {
FX_DECLARATION(OverlayFx)
public:
OverlayFx() {}
~OverlayFx() {}
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
TRop::overlay(up, down, down);
}
};
//==================================================================
class BlendFx final : public TImageCombinationFx {
FX_DECLARATION(BlendFx)
TDoubleParamP m_value;
public:
BlendFx() : m_value(0.0) {
bindParam(this, "value", m_value);
m_value->setValueRange(0.0, 100.0);
}
bool requiresFullRect() override { return true; }
void process(const TRasterP &up, const TRasterP &down,
double frame) override {
double value = 0.01 * m_value->getValue(frame);
UCHAR matteValue = (UCHAR)(value * 255.0 + 0.5);
TRop::crossDissolve(up, down, down, matteValue);
}
TFxPort *getXsheetPort() const override { return getInputPort(1); }
};
//******************************************************************************************
// Matte Fxs definition
//******************************************************************************************
class InFx final : public TBaseRasterFx {
FX_DECLARATION(InFx)
TRasterFxPort m_source, m_matte;
public:
InFx() {
addInputPort("Source", m_source);
addInputPort("Matte", m_matte);
setName(L"InFx");
}
~InFx() {}
bool doGetBBox(double frame, TRectD &bbox,
const TRenderSettings &info) override {
if (m_matte.isConnected() && m_source.isConnected()) {
bool ret = m_matte->doGetBBox(frame, bbox, info);
if (bbox == TConsts::infiniteRectD)
return m_source->doGetBBox(frame, bbox, info);
else
return ret;
}
bbox = TRectD();
return false;
}
bool canHandle(const TRenderSettings &info, double frame) override {
return true;
}
void doCompute(TTile &tile, double frame,
const TRenderSettings &ri) override {
// This fx is not visible if either the source or the matte tiles are empty.
// It's because only source is visible, and only where matte is opaque.
if (!(m_source.isConnected() && m_matte.isConnected())) return;
TTile srcTile;
m_source->allocateAndCompute(srcTile, tile.m_pos,
tile.getRaster()->getSize(), tile.getRaster(),
frame, ri);
m_matte->compute(tile, frame, ri);
TRop::ropin(srcTile.getRaster(), tile.getRaster(), tile.getRaster());
}
void doDryCompute(TRectD &rect, double frame,
const TRenderSettings &info) override {
if (!(m_source.isConnected() && m_matte.isConnected())) return;
m_source->dryCompute(rect, frame, info);
m_matte->dryCompute(rect, frame, info);
}
int getMemoryRequirement(const TRectD &rect, double frame,
const TRenderSettings &info) override {
return TRasterFx::memorySize(rect, info.m_bpp);
}
void compute(TFlash &flash, int frame) override {
if (m_matte.isConnected()) {
flash.pushMatrix();
flash.beginMask();
((TRasterFxP)(m_matte.getFx()))->compute(flash, frame);
flash.endMask();
flash.popMatrix();
}
if (m_source.isConnected()) {
flash.pushMatrix();
flash.enableMask();
((TRasterFxP)(m_source.getFx()))->compute(flash, frame);
flash.disableMask();
flash.popMatrix();
}
}
};
//==================================================================
class OutFx final : public TBaseRasterFx {
FX_DECLARATION(OutFx)
TRasterFxPort m_source, m_matte;
public:
OutFx() {
addInputPort("Source", m_source);
addInputPort("Matte", m_matte);
setName(L"OutFx");
}
~OutFx() {}
bool doGetBBox(double frame, TRectD &bbox,
const TRenderSettings &info) override {
if (m_source.isConnected()) return m_source->doGetBBox(frame, bbox, info);
return false;
}
bool canHandle(const TRenderSettings &info, double frame) override {
return true;
}
void doCompute(TTile &tile, double frame,
const TRenderSettings &ri) override {
// If there is no source, do nothing
if (!m_source.isConnected()) return;
// Here, source is visible where matte is transparent. So if there is
// no matte, just build source.
if (!m_matte.isConnected()) {
m_source->compute(tile, frame, ri);
return;
}
TTile srcTile;
m_source->allocateAndCompute(srcTile, tile.m_pos,
tile.getRaster()->getSize(), tile.getRaster(),
frame, ri);
m_matte->compute(tile, frame, ri);
TRop::ropout(srcTile.getRaster(), tile.getRaster(), tile.getRaster());
}
void doDryCompute(TRectD &rect, double frame,
const TRenderSettings &info) override {
if (!m_source.isConnected()) return;
if (!m_matte.isConnected()) {
m_source->dryCompute(rect, frame, info);
return;
}
m_source->dryCompute(rect, frame, info);
m_matte->dryCompute(rect, frame, info);
}
int getMemoryRequirement(const TRectD &rect, double frame,
const TRenderSettings &info) override {
return TRasterFx::memorySize(rect, info.m_bpp);
}
};
//==================================================================
class AtopFx final : public TBaseRasterFx {
FX_DECLARATION(AtopFx)
TRasterFxPort m_up, m_dn;
public:
AtopFx() {
addInputPort("Up", m_up);
addInputPort("Down", m_dn);
}
bool canHandle(const TRenderSettings &info, double frame) override {
return true;
}
bool doGetBBox(double frame, TRectD &bBox,
const TRenderSettings &info) override {
bBox = TRectD();
{
TRectD inputBBox;
bool hasInput =
m_up.isConnected() ? m_up->doGetBBox(frame, inputBBox, info) : false;
if (hasInput) bBox += inputBBox;
}
{
TRectD inputBBox;
bool hasInput =
m_dn.isConnected() ? m_dn->doGetBBox(frame, inputBBox, info) : false;
if (hasInput) bBox += inputBBox;
}
return (bBox.getLx() >= 0) && (bBox.getLy() >= 0);
}
void doCompute(TTile &tile, double frame,
const TRenderSettings &ri) override {
// Here it's just like matte in, but the matte is visible under up.
if (!m_dn.isConnected()) return;
if (!m_up.isConnected()) {
m_dn->compute(tile, frame, ri);
return;
}
TTile upTile;
m_up->allocateAndCompute(upTile, tile.m_pos, tile.getRaster()->getSize(),
tile.getRaster(), frame, ri);
m_dn->compute(tile, frame, ri);
TRop::atop(upTile.getRaster(), tile.getRaster(), tile.getRaster());
}
void doDryCompute(TRectD &rect, double frame,
const TRenderSettings &info) override {
if (!m_dn.isConnected()) return;
if (!m_up.isConnected()) {
m_dn->dryCompute(rect, frame, info);
return;
}
m_up->dryCompute(rect, frame, info);
m_dn->dryCompute(rect, frame, info);
}
int getMemoryRequirement(const TRectD &rect, double frame,
const TRenderSettings &info) override {
return TRasterFx::memorySize(rect, info.m_bpp);
}
};
//==================================================================
//=======================
// Fx identifiers
//-----------------------
FX_IDENTIFIER(OverFx, "overFx")
FX_IDENTIFIER(AddFx, "addFx")
FX_IDENTIFIER(SubFx, "subFx")
FX_IDENTIFIER(MultFx, "multFx")
FX_IDENTIFIER(InFx, "inFx")
FX_IDENTIFIER(OutFx, "outFx")
FX_IDENTIFIER(AtopFx, "atopFx")
// FX_IDENTIFIER(XorFx, "xorFx")
FX_IDENTIFIER(MinFx, "minFx")
FX_IDENTIFIER(MaxFx, "maxFx")
FX_IDENTIFIER(LinearBurnFx, "linearBurnFx")
FX_IDENTIFIER(OverlayFx, "overlayFx")
FX_IDENTIFIER(BlendFx, "blendFx")
FX_IDENTIFIER(ColorDodgeFx, "colorDodgeFx")
FX_IDENTIFIER(ColorBurnFx, "colorBurnFx")
FX_IDENTIFIER(ScreenFx, "screenFx")
|
#include "pch.hxx"
#include "strconst.h"
#include "mimeole.h"
#include "mimeutil.h"
#include <error.h>
#include <imnapi.h>
#include "goptions.h"
#include <resource.h>
#include <mso.h>
#include <envelope.h>
#include "ipab.h"
#define NO_IMPORT_ERROR
#include <newimp.h>
#include <impapi.h>
#include "storutil.h"
#include "demand.h"
#include "msgfldr.h"
#include "store.h"
class CMailImporter : public IMailImporter
{
private:
ULONG m_cRef;
public:
CMailImporter(void);
~CMailImporter(void);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject);
ULONG STDMETHODCALLTYPE AddRef(void);
ULONG STDMETHODCALLTYPE Release(void);
HRESULT Initialize(HWND hwnd);
STDMETHODIMP OpenFolder(DWORD_PTR dwCookie, const TCHAR *szFolder, IMPORTFOLDERTYPE type, DWORD dwFlags, IFolderImport **ppFldrImp, DWORD_PTR *pdwCookie);
};
class CFolderImport : public IFolderImport
{
private:
ULONG m_cRef;
IMessageFolder *m_pFolder;
STDMETHODIMP ImportMessage(MSGTYPE type, DWORD dwState, LPSTREAM pstm);
public:
CFolderImport(void);
~CFolderImport(void);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject);
ULONG STDMETHODCALLTYPE AddRef(void);
ULONG STDMETHODCALLTYPE Release(void);
HRESULT Initialize(IMessageFolder *pFolder);
STDMETHODIMP SetMessageCount(ULONG cMsg);
STDMETHODIMP ImportMessage(MSGTYPE type, DWORD dwState, LPSTREAM pstm, const TCHAR **rgszAttach, DWORD cAttach);
STDMETHODIMP ImportMessage(IMSG *pimsg);
};
HRESULT GetImsgFromFolder(IMessageFolder *pfldr, LPMESSAGEINFO pMsgInfo, IMSG *pimsg);
CFolderImport::CFolderImport()
{
m_cRef = 1;
m_pFolder = NULL;
}
CFolderImport::~CFolderImport()
{
SafeRelease(m_pFolder);
}
ULONG CFolderImport::AddRef()
{
m_cRef++;
return(m_cRef);
}
ULONG CFolderImport::Release()
{
ULONG cRef;
cRef = --m_cRef;
if (cRef == 0)
delete this;
return(cRef);
}
HRESULT CFolderImport::QueryInterface(REFIID riid, LPVOID *ppv)
{
HRESULT hr = S_OK;
if (ppv == NULL)
return(E_INVALIDARG);
*ppv = NULL;
if (IID_IFolderImport == riid)
*ppv = (IFolderImport *)this;
else if (IID_IUnknown == riid)
*ppv = (IFolderImport *)this;
else
hr = E_NOINTERFACE;
if (*ppv != NULL)
((LPUNKNOWN)*ppv)->AddRef();
return(hr);
}
HRESULT CFolderImport::Initialize(IMessageFolder *pFolder)
{
Assert(pFolder != NULL);
m_pFolder = pFolder;
m_pFolder->AddRef();
return(S_OK);
}
HRESULT CFolderImport::SetMessageCount(ULONG cMsg)
{
return(S_OK);
}
HRESULT CFolderImport::ImportMessage(MSGTYPE type, DWORD dwState, LPSTREAM pstm, const TCHAR **rgszAttach, DWORD cAttach)
{
IMimeMessage *pMsg;
HRESULT hr;
DWORD iAttach, dwPri;
PROPVARIANT rVariant;
DWORD dwMsgFlags;
Assert(pstm != NULL);
Assert(m_pFolder != NULL);
if (rgszAttach == NULL)
{
Assert(cAttach == 0);
return(ImportMessage(type, dwState, pstm));
}
Assert(cAttach > 0);
hr = HrRewindStream(pstm);
if (FAILED(hr))
return(hr);
hr = HrCreateMessage(&pMsg);
if (SUCCEEDED(hr))
{
hr = pMsg->Load(pstm);
if (SUCCEEDED(hr))
{
for (iAttach = 0; iAttach < cAttach; iAttach++)
{
Assert(rgszAttach[iAttach] != NULL);
pMsg->AttachFile(rgszAttach[iAttach], NULL, NULL);
}
dwPri = dwState & MSG_PRI_MASK;
if (dwPri != 0)
{
if (dwPri == MSG_PRI_HIGH)
rVariant.ulVal = IMSG_PRI_HIGH;
else if (dwPri == MSG_PRI_LOW)
rVariant.ulVal = IMSG_PRI_LOW;
else
rVariant.ulVal = IMSG_PRI_NORMAL;
rVariant.vt = VT_UI4;
pMsg->SetProp(PIDTOSTR(PID_ATT_PRIORITY), 0, &rVariant);
}
// Compute the Default arf flags
dwMsgFlags = 0;
// Is the Message Read ?
if (FALSE == ISFLAGSET(dwState, MSG_STATE_UNREAD))
FLAGSET(dwMsgFlags, ARF_READ);
// Unsent
if (ISFLAGSET(dwState, MSG_STATE_UNSENT))
FLAGSET(dwMsgFlags, ARF_UNSENT);
// Submitted
// if (ISFLAGSET(dwState, MSG_STATE_SUBMITTED))
// FLAGSET(dwMsgFlags, ARF_SUBMITTED);
if (type == MSG_TYPE_NEWS)
FLAGSET(dwMsgFlags, ARF_NEWSMSG);
// Insert the message
hr = m_pFolder->SaveMessage(NULL, SAVE_MESSAGE_GENID, dwMsgFlags, 0, pMsg, NOSTORECALLBACK);
Assert(hr != E_PENDING);
}
pMsg->Release();
}
return(hr);
}
HRESULT CFolderImport::ImportMessage(MSGTYPE type, DWORD dwState, LPSTREAM pstm)
{
WORD pri;
IMimeMessage *pMsg;
HRESULT hr;
DWORD dwPri;
PROPVARIANT rVariant;
DWORD dwMsgFlags;
Assert(pstm != NULL);
Assert(m_pFolder != NULL);
hr = HrRewindStream(pstm);
if (FAILED(hr))
return(hr);
hr = HrCreateMessage(&pMsg);
if (SUCCEEDED(hr))
{
if (SUCCEEDED(hr = pMsg->Load(pstm)))
{
dwPri = dwState & MSG_PRI_MASK;
if (dwPri != 0)
{
if (dwPri == MSG_PRI_HIGH)
rVariant.ulVal = IMSG_PRI_HIGH;
else if (dwPri == MSG_PRI_LOW)
rVariant.ulVal = IMSG_PRI_LOW;
else
rVariant.ulVal = IMSG_PRI_NORMAL;
rVariant.vt = VT_UI4;
pMsg->SetProp(PIDTOSTR(PID_ATT_PRIORITY), 0, &rVariant);
}
// Compute the Default arf flags
dwMsgFlags = 0;
// Is the Message Read ?
if (FALSE == ISFLAGSET(dwState, MSG_STATE_UNREAD))
FLAGSET(dwMsgFlags, ARF_READ);
// Unsent
if (ISFLAGSET(dwState, MSG_STATE_UNSENT))
FLAGSET(dwMsgFlags, ARF_UNSENT);
// Submitted
// if (ISFLAGSET(dwState, MSG_STATE_SUBMITTED))
// FLAGSET(dwMsgFlags, ARF_SUBMITTED);
if (type == MSG_TYPE_NEWS)
FLAGSET(dwMsgFlags, ARF_NEWSMSG);
// Insert the message
hr = m_pFolder->SaveMessage(NULL, SAVE_MESSAGE_GENID, dwMsgFlags, 0, pMsg, NOSTORECALLBACK);
Assert(hr != E_PENDING);
}
pMsg->Release();
}
return(hr);
}
HRESULT CFolderImport::ImportMessage(IMSG *pimsg)
{
HRESULT hr;
MESSAGEID id;
MESSAGEINFO info;
LPMIMEMESSAGE pMsg;
Assert(pimsg != NULL);
hr = HrImsgToMailMsg(pimsg, &pMsg, NULL);
if (!FAILED(hr))
{
hr = m_pFolder->SaveMessage(&id, SAVE_MESSAGE_GENID, ISFLAGSET(pimsg->uFlags, MSGFLAG_READ) ? ARF_READ : 0, 0, pMsg, NOSTORECALLBACK);
Assert(hr != E_PENDING);
if (SUCCEEDED(hr))
{
// handle receive time
ZeroMemory(&info, sizeof(MESSAGEINFO));
info.idMessage = id;
if (DB_S_FOUND == m_pFolder->FindRecord(IINDEX_PRIMARY, COLUMNS_ALL, &info, NULL))
{
Assert(pimsg->ftReceive.dwLowDateTime != 0 || pimsg->ftReceive.dwHighDateTime != 0);
CopyMemory(&info.ftReceived, &pimsg->ftReceive, sizeof(FILETIME));
m_pFolder->UpdateRecord(&info);
m_pFolder->FreeRecord(&info);
}
}
pMsg->Release();
}
return(hr);
}
CMailImporter::CMailImporter()
{
m_cRef = 1;
}
CMailImporter::~CMailImporter()
{
}
HRESULT CMailImporter::QueryInterface(REFIID riid, LPVOID *ppv)
{
HRESULT hr = S_OK;
if (ppv == NULL)
return(E_INVALIDARG);
*ppv = NULL;
if (IID_IMailImporter == riid)
*ppv = (IMailImporter *)this;
else if (IID_IUnknown == riid)
*ppv = (IMailImporter *)this;
else
hr = E_NOINTERFACE;
if (*ppv != NULL)
((LPUNKNOWN)*ppv)->AddRef();
return(hr);
}
ULONG CMailImporter::AddRef()
{
m_cRef++;
return(m_cRef);
}
ULONG CMailImporter::Release()
{
ULONG cRef;
cRef = --m_cRef;
if (cRef == 0)
delete this;
return(cRef);
}
HRESULT CMailImporter::Initialize(HWND hwnd)
{
return S_OK;
}
HRESULT CMailImporter::OpenFolder(DWORD_PTR dwCookie, const TCHAR *szFolder, IMPORTFOLDERTYPE type, DWORD dwFlags, IFolderImport **ppFldrImp, DWORD_PTR *pdwCookie)
{
HRESULT hr;
FOLDERID idFolder, idFolderNew;
CFolderImport *pFldrImp;
IMessageFolder *pFolder;
TCHAR sz[CCHMAX_FOLDER_NAME + 1];
Assert(szFolder != NULL);
Assert(ppFldrImp != NULL);
Assert(dwFlags == 0);
*ppFldrImp = NULL;
if (dwCookie == COOKIE_ROOT)
idFolder = FOLDERID_LOCAL_STORE;
else
idFolder = (FOLDERID)dwCookie;
idFolderNew = FOLDERID_INVALID;
if (type != FOLDER_TYPE_NORMAL)
{
LoadString(g_hLocRes, idsInbox + (type - FOLDER_TYPE_INBOX), sz, ARRAYSIZE(sz));
szFolder = sz;
}
if (FAILED(GetFolderIdFromName(g_pStore, szFolder, idFolder, &idFolderNew)))
{
FOLDERINFO Folder={0};
Folder.idParent = idFolder;
Folder.tySpecial = FOLDER_NOTSPECIAL;
Folder.pszName = (LPSTR)szFolder;
Folder.dwFlags = FOLDER_SUBSCRIBED;
hr = g_pStore->CreateFolder(NOFLAGS, &Folder, NOSTORECALLBACK);
Assert(hr != E_PENDING);
if (FAILED(hr))
return(hr);
idFolderNew = Folder.idFolder;
}
hr = g_pStore->OpenFolder(idFolderNew, NULL, NOFLAGS, &pFolder);
if (FAILED(hr))
return(hr);
pFldrImp = new CFolderImport;
if (pFldrImp == NULL)
{
hr = E_OUTOFMEMORY;
}
else
{
hr = pFldrImp->Initialize(pFolder);
if (FAILED(hr))
{
pFldrImp->Release();
pFldrImp = NULL;
}
}
pFolder->Release();
*ppFldrImp = pFldrImp;
*pdwCookie = (DWORD_PTR)idFolderNew;
return(S_OK);
}
void DoImport(HWND hwnd)
{
HRESULT hr;
HMODULE hlibImport;
PFNPERFORMIMPORT lpfnPerformImport;
CMailImporter *pImp;
hr = hrImportLoad;
hlibImport = LoadLibrary(c_szImnimpDll);
if (hlibImport != NULL)
{
lpfnPerformImport = (PFNPERFORMIMPORT)GetProcAddress(hlibImport, achPerformImport);
if (lpfnPerformImport != NULL)
{
pImp = new CMailImporter;
if (pImp == NULL)
{
hr = E_OUTOFMEMORY;
}
else
{
hr = pImp->Initialize(hwnd);
if (SUCCEEDED(hr))
lpfnPerformImport(hwnd, pImp, 0);
pImp->Release();
}
}
FreeLibrary(hlibImport);
}
if (FAILED(hr))
{
AthErrorMessageW(hwnd, MAKEINTRESOURCEW(idsAthenaMail), MAKEINTRESOURCEW(idsErrImport), hr);
}
}
// EXPORT STUFF
IMPFOLDERNODE *InsertFolderNode(IMPFOLDERNODE *plist, IMPFOLDERNODE *pnode)
{
BOOL fNodeNormal, fCurrNormal;
IMPFOLDERNODE *pprev, *pcurr;
Assert(pnode != NULL);
pnode->pnext = NULL;
if (plist == NULL)
return(pnode);
pprev = NULL;
pcurr = plist;
while (pcurr != NULL)
{
fNodeNormal = pnode->type == FOLDER_TYPE_NORMAL;
fCurrNormal = pcurr->type == FOLDER_TYPE_NORMAL;
if (!fNodeNormal &&
fCurrNormal)
break;
if (fNodeNormal == fCurrNormal &&
lstrcmpi(pnode->szName, pcurr->szName) <= 0)
break;
pprev = pcurr;
pcurr = pcurr->pnext;
}
if (pcurr == NULL)
{
// insert at end of list
Assert(pprev != NULL);
pprev->pnext = pnode;
}
else if (pprev == NULL)
{
// insert at beginning of list
pnode->pnext = plist;
plist = pnode;
}
else
{
pprev->pnext = pnode;
pnode->pnext = pcurr;
}
return(plist);
}
HRESULT ExpGetSubFolders(IMPFOLDERNODE *pparent, FOLDERID idParent, IMPFOLDERNODE **pplist)
{
HRESULT hr;
TCHAR *sz;
IMPFOLDERNODE *pnode, *plist;
HANDLE_16 hnd;
FOLDERINFO Folder={0};
IEnumerateFolders *pEnum;
Assert(pplist != NULL);
Assert(idParent != FOLDERID_INVALID);
*pplist = NULL;
plist = NULL;
hr = g_pStore->EnumChildren(idParent, FALSE, &pEnum);
if (SUCCEEDED(hr))
{
while (S_OK == pEnum->Next(1, &Folder, NULL))
{
if (!MemAlloc((void **)&pnode, sizeof(IMPFOLDERNODE) + CCHMAX_FOLDER_NAME * sizeof(TCHAR)))
{
hr = E_OUTOFMEMORY;
break;
}
ZeroMemory(pnode, sizeof(IMPFOLDERNODE));
sz = (TCHAR *)((BYTE *)pnode + sizeof(IMPFOLDERNODE));
pnode->pparent = pparent;
pnode->depth = (pparent != NULL) ? (pparent->depth + 1) : 0;
pnode->szName = sz;
StrCpyN(sz, Folder.pszName, CCHMAX_FOLDER_NAME);
pnode->lparam = (LPARAM)Folder.idFolder;
pnode->cMsg = Folder.cMessages;
if (Folder.tySpecial == FOLDER_INBOX)
pnode->type = FOLDER_TYPE_INBOX;
else if (Folder.tySpecial == FOLDER_OUTBOX)
pnode->type = FOLDER_TYPE_OUTBOX;
else if (Folder.tySpecial == FOLDER_SENT)
pnode->type = FOLDER_TYPE_SENT;
else if (Folder.tySpecial == FOLDER_DELETED)
pnode->type = FOLDER_TYPE_DELETED;
else if (Folder.tySpecial == FOLDER_DRAFT)
pnode->type = FOLDER_TYPE_DRAFT;
plist = InsertFolderNode(plist, pnode);
hr = ExpGetSubFolders(pnode, Folder.idFolder, &pnode->pchild);
if (FAILED(hr))
break;
g_pStore->FreeRecord(&Folder);
}
pEnum->Release();
}
*pplist = plist;
g_pStore->FreeRecord(&Folder);
return(hr);
}
HRESULT WINAPI_16 ExpGetFolderList(IMPFOLDERNODE **pplist)
{
IMPFOLDERNODE *plist;
HRESULT hr;
if (pplist == NULL)
return(E_INVALIDARG);
plist = NULL;
hr = ExpGetSubFolders(NULL, FOLDERID_LOCAL_STORE, &plist);
if (FAILED(hr))
{
ExpFreeFolderList(plist);
plist = NULL;
}
*pplist = plist;
return(hr);
}
void WINAPI_16 ExpFreeFolderList(IMPFOLDERNODE *plist)
{
IMPFOLDERNODE *pnode;
while (plist != NULL)
{
if (plist->pchild != NULL)
ExpFreeFolderList(plist->pchild);
pnode = plist;
plist = plist->pnext;
MemFree(pnode);
}
}
void DoExport(HWND hwnd)
{
HRESULT hr;
HMODULE hlibImport;
PFNEXPMSGS lpfnExportMessages;
hr = hrImportLoad;
hlibImport = LoadLibrary(c_szImnimpDll);
if (hlibImport != NULL)
{
lpfnExportMessages = (PFNEXPMSGS)GetProcAddress(hlibImport, MAKEINTRESOURCE(MAKELONG(3, 0)));
if (lpfnExportMessages != NULL)
{
lpfnExportMessages(hwnd);
hr = S_OK;
}
FreeLibrary(hlibImport);
}
if (FAILED(hr))
{
AthErrorMessageW(hwnd, MAKEINTRESOURCEW(idsAthenaMail), MAKEINTRESOURCEW(idsErrExport), hr);
}
}
typedef struct tagEXPENUM
{
IMessageFolder *pFolder;
HROWSET hRowset;
} EXPENUM;
HRESULT WINAPI_16 ExpGetFirstImsg(HANDLE idFolder, IMSG *pimsg, HANDLE_16 *phnd)
{
EXPENUM *penum;
HRESULT hr;
MESSAGEINFO MsgInfo;
Assert(pimsg != NULL);
Assert(phnd != NULL);
*phnd = NULL;
hr = E_FAIL;
penum = NULL;
if (!MemAlloc((void **)&penum, sizeof(EXPENUM)))
{
hr = E_OUTOFMEMORY;
}
else
{
ZeroMemory(penum, sizeof(EXPENUM));
hr = g_pStore->OpenFolder((FOLDERID)idFolder, NULL, NOFLAGS, &penum->pFolder);
if (!FAILED(hr))
{
hr = penum->pFolder->CreateRowset(IINDEX_PRIMARY, NOFLAGS, &penum->hRowset);
if (!FAILED(hr))
{
hr = penum->pFolder->QueryRowset(penum->hRowset, 1, (LPVOID *)&MsgInfo, NULL);
if (!FAILED(hr))
{
if (S_OK == hr)
{
hr = GetImsgFromFolder(penum->pFolder, &MsgInfo, pimsg);
penum->pFolder->FreeRecord(&MsgInfo);
}
else
Assert(S_FALSE == hr);
}
}
}
}
if (hr != S_OK)
{
ExpGetImsgClose((HANDLE_16)penum);
penum = NULL;
}
*phnd = (HANDLE_16)penum;
return(hr);
}
HRESULT WINAPI_16 ExpGetNextImsg(IMSG *pimsg, HANDLE_16 hnd)
{
HRESULT hr;
EXPENUM *pee;
MESSAGEINFO MsgInfo;
Assert(pimsg != NULL);
Assert(hnd != NULL);
pee = (EXPENUM *)hnd;
hr = pee->pFolder->QueryRowset(pee->hRowset, 1, (LPVOID *)&MsgInfo, NULL);
if (hr == S_OK)
{
hr = GetImsgFromFolder(pee->pFolder, &MsgInfo, pimsg);
pee->pFolder->FreeRecord(&MsgInfo);
}
return(hr);
}
void WINAPI_16 ExpGetImsgClose(HANDLE_16 hnd)
{
EXPENUM *pee;
pee = (EXPENUM *)hnd;
if (pee != NULL)
{
if (pee->pFolder != NULL)
{
pee->pFolder->CloseRowset(&pee->hRowset);
pee->pFolder->Release();
}
MemFree(pee);
}
}
HRESULT GetImsgFromFolder(IMessageFolder *pfldr, LPMESSAGEINFO pMsgInfo, IMSG *pimsg)
{
LPMIMEMESSAGE pMsg;
HRESULT hr = E_OUTOFMEMORY;
// for import/export we want the secure message, so pass TRUE
hr = pfldr->OpenMessage(pMsgInfo->idMessage, OPEN_MESSAGE_SECURE, &pMsg, NOSTORECALLBACK);
if (SUCCEEDED(hr))
{
hr = HrMailMsgToImsg(pMsg, pMsgInfo, pimsg);
pMsg->Release();
}
return(hr);
}
void DoMigration(HWND hwnd)
{
HMODULE hlibImport;
PFNPERFORMMIGRATION lpfnPerformMigration;
CMailImporter *pImp;
if (!!DwGetOption(OPT_MIGRATION_PERFORMED))
return;
hlibImport = LoadLibrary(c_szImnimpDll);
if (hlibImport != NULL)
{
lpfnPerformMigration = (PFNPERFORMMIGRATION)GetProcAddress(hlibImport, achPerformMigration);
if (lpfnPerformMigration != NULL)
{
pImp = new CMailImporter;
if (pImp != NULL)
{
if (SUCCEEDED(pImp->Initialize(hwnd)) &&
SUCCEEDED(lpfnPerformMigration(hwnd, pImp, 0)))
{
SetDwOption(OPT_MIGRATION_PERFORMED, TRUE, NULL, 0);
}
pImp->Release();
}
}
FreeLibrary(hlibImport);
}
}
HRESULT SimpleImportMailFolders(
IMailImporter *pMailImporter,
IMailImport *pMailImport,
DWORD_PTR dwSourceCookie,
DWORD_PTR dwParentDestCookie)
{
HRESULT hr = S_OK;
DWORD_PTR cookie;
IMPORTFOLDER folder;
IFolderImport *pFolderImport = NULL;
IEnumFOLDERS *pFolderEnum = NULL;
// Enumerate source folders
IF_FAILEXIT(hr = pMailImport->EnumerateFolders(dwSourceCookie, &pFolderEnum));
do {
// Get next source folder
hr = pFolderEnum->Next(&folder);
if (hr == S_OK) {
// Open the destination folder by this name in this hierarchy position
hr = pMailImporter->OpenFolder(dwParentDestCookie,
folder.szName,
FOLDER_TYPE_NORMAL,
0,
&pFolderImport,
&cookie);
if (!FAILED(hr)) {
// Import the enumerated source folder into the opened destination folder
pMailImport->ImportFolder(folder.dwCookie, pFolderImport);
// Close the destination folder
SafeRelease(pFolderImport);
if (folder.fSubFolders > 0) {
// Recursively import subfolders
SimpleImportMailFolders(pMailImporter, pMailImport, folder.dwCookie, cookie);
}
}
}
} while (hr == S_OK);
exit:
SafeRelease(pFolderImport);
SafeRelease(pFolderEnum);
return hr;
}
HRESULT SimpleImportNewsList(CMessageStore *pSrcStore)
{
HRESULT hr = S_OK;
IEnumerateFolders *pEnum = NULL;
FOLDERINFO info;
IF_FAILEXIT(hr = pSrcStore->EnumChildren(FOLDERID_ROOT, TRUE, &pEnum));
while (S_OK == pEnum->Next(1, &info, NULL)) {
// info.pszName is the server/account name
// info.pszAccountId is the source's account ID
// info.idFolder is this account's folder ID
// info.dwFlags contains FOLDER_HASCHILDREN
// info.tyFolder specifies FOLDER_NEWS
if ((info.tyFolder == FOLDER_NEWS) &&
(info.dwFlags & FOLDER_HASCHILDREN)) {
IImnAccount *pAccount = NULL;
// Match this account to the destination
hr = g_pAcctMan->FindAccount(AP_ACCOUNT_NAME, info.pszName, &pAccount);
if ((hr == S_OK) && (pAccount != NULL)) {
TCHAR szID[CCHMAX_ACCOUNT_NAME];
hr = pAccount->GetPropSz(AP_ACCOUNT_ID, szID, ARRAYSIZE(szID));
if (hr == S_OK) {
IEnumerateFolders *pEnumDest = NULL;
IEnumerateFolders *pEnumChild = NULL;
FOLDERID destFolderID = 0;
// Lookup destination folder id for this account name
hr = g_pStore->EnumChildren(FOLDERID_ROOT, TRUE, &pEnumDest);
if ((hr == S_OK) && (pEnumDest != NULL)) {
FOLDERINFO infoDest;
while (S_OK == pEnumDest->Next(1, &infoDest, NULL)) {
if ((destFolderID == 0) &&
(_tcscmp(info.pszName, infoDest.pszName) == 0)) {
destFolderID = infoDest.idFolder;
}
g_pStore->FreeRecord(&infoDest);
}
}
SafeRelease(pEnumDest);
// Read in source newsgroups
hr = pSrcStore->EnumChildren(info.idFolder, TRUE, &pEnumChild);
if ((hr == S_OK) && (pEnumChild != NULL)) {
FOLDERINFO infoChild;
// Add folders to destination account
while(S_OK == pEnumChild->Next(1, &infoChild, NULL)) {
LPSTR oldID;
// infoChild.idParent needs to be the dest server folder ID
oldID = infoChild.pszAccountId;
infoChild.pszAccountId = szID;
infoChild.idParent = destFolderID;
hr = g_pStore->CreateFolder(CREATE_FOLDER_LOCALONLY, &infoChild, NOSTORECALLBACK);
if (SUCCEEDED(hr)) {
hr = g_pStore->SubscribeToFolder(infoChild.idFolder, TRUE, NULL);
}
infoChild.pszAccountId = oldID;
pSrcStore->FreeRecord(&infoChild);
}
}
SafeRelease(pEnumChild);
}
}
SafeRelease(pAccount);
}
pSrcStore->FreeRecord(&info);
}
exit:
SafeRelease(pEnum);
return hr;
}
HRESULT ImportMailStoreToGUID(IMailImport *pMailImport, GUID *pDestUUID, LPCSTR pszDestStoreDir)
{
HRESULT hr = S_OK;
CMailImporter *pNew=NULL;
pNew = new CMailImporter;
IF_NULLEXIT(pNew);
// Sometimes during the SimpleStoreInit, Wab is initialized as well.
// Since it is never terminated, some registry key will remain opened.
// The consumer of this function will not be able to unload a mapped user
// hive because of this. To fix this problem, we added the Wab init here
// and an corresponding Wab done later on.
HrInitWab (TRUE);
IF_FAILEXIT(SimpleStoreInit(pDestUUID, pszDestStoreDir));
IF_FAILEXIT(SimpleImportMailFolders(pNew, pMailImport, COOKIE_ROOT, COOKIE_ROOT));
exit:
SimpleStoreRelease();
HrInitWab (FALSE);
SafeRelease(pNew);
return hr;
}
HRESULT ImportNewsListToGUID(LPCSTR pszSrcPath, GUID *pDestUUID, LPCSTR pszDestStoreDir)
{
HRESULT hr = S_OK;
CMessageStore *pSrcStore=NULL;
pSrcStore = new CMessageStore(FALSE);
IF_NULLEXIT(pSrcStore);
IF_FAILEXIT(pSrcStore->Initialize(pszSrcPath));
// Sometimes during the SimpleStoreInit, Wab is initialized as well.
// Since it is never terminated, some registry key will remain opened.
// The consumer of this function will not be able to unload a mapped user
// hive because of this. To fix this problem, we added the Wab init here
// and an corresponding Wab done later on.
HrInitWab (TRUE);
IF_FAILEXIT(SimpleStoreInit(pDestUUID, pszDestStoreDir));
IF_FAILEXIT(SimpleImportNewsList(pSrcStore));
exit:
SimpleStoreRelease();
HrInitWab (FALSE);
SafeRelease(pSrcStore);
return hr;
}
|
// - lambda_traits.hpp --- Boost Lambda Library ----------------------------
//
// Copyright (C) 1999, 2000 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see www.boost.org
// -------------------------------------------------------------------------
#ifndef BOOST_LAMBDA_LAMBDA_TRAITS_HPP
#define BOOST_LAMBDA_LAMBDA_TRAITS_HPP
#include "boost/type_traits/transform_traits.hpp"
#include "boost/type_traits/cv_traits.hpp"
#include "boost/type_traits/function_traits.hpp"
#include "boost/type_traits/object_traits.hpp"
#include "boost/tuple/tuple.hpp"
namespace boost {
namespace lambda {
// -- if construct ------------------------------------------------
// Proposed by Krzysztof Czarnecki and Ulrich Eisenecker
namespace detail {
template <bool If, class Then, class Else> struct IF { typedef Then RET; };
template <class Then, class Else> struct IF<false, Then, Else> {
typedef Else RET;
};
// An if construct that doesn't instantiate the non-matching template:
// Called as:
// IF_type<condition, A, B>::type
// The matching template must define the typeded 'type'
// I.e. A::type if condition is true, B::type if condition is false
// Idea from Vesa Karvonen (from C&E as well I guess)
template<class T>
struct IF_type_
{
typedef typename T::type type;
};
template<bool C, class T, class E>
struct IF_type
{
typedef typename
IF_type_<typename IF<C, T, E>::RET >::type type;
};
// helper that can be used to give typedef T to some type
template <class T> struct identity_mapping { typedef T type; };
// An if construct for finding an integral constant 'value'
// Does not instantiate the non-matching branch
// Called as IF_value<condition, A, B>::value
// If condition is true A::value must be defined, otherwise B::value
template<class T>
struct IF_value_
{
BOOST_STATIC_CONSTANT(int, value = T::value);
};
template<bool C, class T, class E>
struct IF_value
{
BOOST_STATIC_CONSTANT(int, value = (IF_value_<typename IF<C, T, E>::RET>::value));
};
// --------------------------------------------------------------
// removes reference from other than function types:
template<class T> class remove_reference_if_valid
{
typedef typename boost::remove_reference<T>::type plainT;
public:
typedef typename IF<
boost::is_function<plainT>::value,
T,
plainT
>::RET type;
};
template<class T> struct remove_reference_and_cv {
typedef typename boost::remove_cv<
typename boost::remove_reference<T>::type
>::type type;
};
// returns a reference to the element of tuple T
template<int N, class T> struct tuple_element_as_reference {
typedef typename
boost::tuples::access_traits<
typename boost::tuples::element<N, T>::type
>::non_const_type type;
};
// returns the cv and reverence stripped type of a tuple element
template<int N, class T> struct tuple_element_stripped {
typedef typename
remove_reference_and_cv<
typename boost::tuples::element<N, T>::type
>::type type;
};
// is_lambda_functor -------------------------------------------------
template <class T> struct is_lambda_functor_ {
BOOST_STATIC_CONSTANT(bool, value = false);
};
template <class Arg> struct is_lambda_functor_<lambda_functor<Arg> > {
BOOST_STATIC_CONSTANT(bool, value = true);
};
} // end detail
template <class T> struct is_lambda_functor {
BOOST_STATIC_CONSTANT(bool,
value =
detail::is_lambda_functor_<
typename detail::remove_reference_and_cv<T>::type
>::value);
};
namespace detail {
// -- parameter_traits_ ---------------------------------------------
// An internal parameter type traits class that respects
// the reference_wrapper class.
// The conversions performed are:
// references -> compile_time_error
// T1 -> T2,
// reference_wrapper<T> -> T&
// const array -> ref to const array
// array -> ref to array
// function -> ref to function
// ------------------------------------------------------------------------
template<class T1, class T2>
struct parameter_traits_ {
typedef T2 type;
};
// Do not instantiate with reference types
template<class T, class Any> struct parameter_traits_<T&, Any> {
typedef typename
generate_error<T&>::
parameter_traits_class_instantiated_with_reference_type type;
};
// Arrays can't be stored as plain types; convert them to references
template<class T, int n, class Any> struct parameter_traits_<T[n], Any> {
typedef T (&type)[n];
};
template<class T, int n, class Any>
struct parameter_traits_<const T[n], Any> {
typedef const T (&type)[n];
};
template<class T, int n, class Any>
struct parameter_traits_<volatile T[n], Any> {
typedef volatile T (&type)[n];
};
template<class T, int n, class Any>
struct parameter_traits_<const volatile T[n], Any> {
typedef const volatile T (&type)[n];
};
template<class T, class Any>
struct parameter_traits_<boost::reference_wrapper<T>, Any >{
typedef T& type;
};
template<class T, class Any>
struct parameter_traits_<const boost::reference_wrapper<T>, Any >{
typedef T& type;
};
template<class T, class Any>
struct parameter_traits_<volatile boost::reference_wrapper<T>, Any >{
typedef T& type;
};
template<class T, class Any>
struct parameter_traits_<const volatile boost::reference_wrapper<T>, Any >{
typedef T& type;
};
template<class Any>
struct parameter_traits_<void, Any> {
typedef void type;
};
template<class Arg, class Any>
struct parameter_traits_<lambda_functor<Arg>, Any > {
typedef lambda_functor<Arg> type;
};
template<class Arg, class Any>
struct parameter_traits_<const lambda_functor<Arg>, Any > {
typedef lambda_functor<Arg> type;
};
// Are the volatile versions needed?
template<class Arg, class Any>
struct parameter_traits_<volatile lambda_functor<Arg>, Any > {
typedef lambda_functor<Arg> type;
};
template<class Arg, class Any>
struct parameter_traits_<const volatile lambda_functor<Arg>, Any > {
typedef lambda_functor<Arg> type;
};
} // end namespace detail
// ------------------------------------------------------------------------
// traits classes for lambda expressions (bind functions, operators ...)
// must be instantiated with non-reference types
// The default is const plain type -------------------------
// const T -> const T,
// T -> const T,
// references -> compile_time_error
// reference_wrapper<T> -> T&
// array -> const ref array
template<class T>
struct const_copy_argument {
typedef typename
detail::parameter_traits_<
T,
typename detail::IF<boost::is_function<T>::value, T&, const T>::RET
>::type type;
};
// T may be a function type. Without the IF test, const would be added
// to a function type, which is illegal.
// all arrays are converted to const.
// This traits template is used for 'const T&' parameter passing
// and thus the knowledge of the potential
// non-constness of an actual argument is lost.
template<class T, int n> struct const_copy_argument <T[n]> {
typedef const T (&type)[n];
};
template<class T, int n> struct const_copy_argument <volatile T[n]> {
typedef const volatile T (&type)[n];
};
template<class T>
struct const_copy_argument<T&> {};
// do not instantiate with references
// typedef typename detail::generate_error<T&>::references_not_allowed type;
template<>
struct const_copy_argument<void> {
typedef void type;
};
template<>
struct const_copy_argument<void const> {
typedef void type;
};
// Does the same as const_copy_argument, but passes references through as such
template<class T>
struct bound_argument_conversion {
typedef typename const_copy_argument<T>::type type;
};
template<class T>
struct bound_argument_conversion<T&> {
typedef T& type;
};
// The default is non-const reference -------------------------
// const T -> const T&,
// T -> T&,
// references -> compile_time_error
// reference_wrapper<T> -> T&
template<class T>
struct reference_argument {
typedef typename detail::parameter_traits_<T, T&>::type type;
};
template<class T>
struct reference_argument<T&> {
typedef typename detail::generate_error<T&>::references_not_allowed type;
};
template<class Arg>
struct reference_argument<lambda_functor<Arg> > {
typedef lambda_functor<Arg> type;
};
template<class Arg>
struct reference_argument<const lambda_functor<Arg> > {
typedef lambda_functor<Arg> type;
};
// Are the volatile versions needed?
template<class Arg>
struct reference_argument<volatile lambda_functor<Arg> > {
typedef lambda_functor<Arg> type;
};
template<class Arg>
struct reference_argument<const volatile lambda_functor<Arg> > {
typedef lambda_functor<Arg> type;
};
template<>
struct reference_argument<void> {
typedef void type;
};
namespace detail {
// Array to pointer conversion
template <class T>
struct array_to_pointer {
typedef T type;
};
template <class T, int N>
struct array_to_pointer <const T[N]> {
typedef const T* type;
};
template <class T, int N>
struct array_to_pointer <T[N]> {
typedef T* type;
};
template <class T, int N>
struct array_to_pointer <const T (&) [N]> {
typedef const T* type;
};
template <class T, int N>
struct array_to_pointer <T (&) [N]> {
typedef T* type;
};
// ---------------------------------------------------------------------------
// The call_traits for bind
// Respects the reference_wrapper class.
// These templates are used outside of bind functions as well.
// the bind_tuple_mapper provides a shorter notation for default
// bound argument storing semantics, if all arguments are treated
// uniformly.
// from template<class T> foo(const T& t) : bind_traits<const T>::type
// from template<class T> foo(T& t) : bind_traits<T>::type
// Conversions:
// T -> const T,
// cv T -> cv T,
// T& -> T&
// reference_wrapper<T> -> T&
// const reference_wrapper<T> -> T&
// array -> const ref array
// make bound arguments const, this is a deliberate design choice, the
// purpose is to prevent side effects to bound arguments that are stored
// as copies
template<class T>
struct bind_traits {
typedef const T type;
};
template<class T>
struct bind_traits<T&> {
typedef T& type;
};
// null_types are an exception, we always want to store them as non const
// so that other templates can assume that null_type is always without const
template<>
struct bind_traits<null_type> {
typedef null_type type;
};
// the bind_tuple_mapper, bind_type_generators may
// introduce const to null_type
template<>
struct bind_traits<const null_type> {
typedef null_type type;
};
// Arrays can't be stored as plain types; convert them to references.
// All arrays are converted to const. This is because bind takes its
// parameters as const T& and thus the knowledge of the potential
// non-constness of actual argument is lost.
template<class T, int n> struct bind_traits <T[n]> {
typedef const T (&type)[n];
};
template<class T, int n>
struct bind_traits<const T[n]> {
typedef const T (&type)[n];
};
template<class T, int n> struct bind_traits<volatile T[n]> {
typedef const volatile T (&type)[n];
};
template<class T, int n>
struct bind_traits<const volatile T[n]> {
typedef const volatile T (&type)[n];
};
template<class R>
struct bind_traits<R()> {
typedef R(&type)();
};
template<class R, class Arg1>
struct bind_traits<R(Arg1)> {
typedef R(&type)(Arg1);
};
template<class R, class Arg1, class Arg2>
struct bind_traits<R(Arg1, Arg2)> {
typedef R(&type)(Arg1, Arg2);
};
template<class R, class Arg1, class Arg2, class Arg3>
struct bind_traits<R(Arg1, Arg2, Arg3)> {
typedef R(&type)(Arg1, Arg2, Arg3);
};
template<class R, class Arg1, class Arg2, class Arg3, class Arg4>
struct bind_traits<R(Arg1, Arg2, Arg3, Arg4)> {
typedef R(&type)(Arg1, Arg2, Arg3, Arg4);
};
template<class R, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5>
struct bind_traits<R(Arg1, Arg2, Arg3, Arg4, Arg5)> {
typedef R(&type)(Arg1, Arg2, Arg3, Arg4, Arg5);
};
template<class R, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6>
struct bind_traits<R(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6)> {
typedef R(&type)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6);
};
template<class R, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7>
struct bind_traits<R(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7)> {
typedef R(&type)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7);
};
template<class R, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7, class Arg8>
struct bind_traits<R(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8)> {
typedef R(&type)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8);
};
template<class R, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5, class Arg6, class Arg7, class Arg8, class Arg9>
struct bind_traits<R(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9)> {
typedef R(&type)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9);
};
template<class T>
struct bind_traits<reference_wrapper<T> >{
typedef T& type;
};
template<class T>
struct bind_traits<const reference_wrapper<T> >{
typedef T& type;
};
template<>
struct bind_traits<void> {
typedef void type;
};
template <
class T0 = null_type, class T1 = null_type, class T2 = null_type,
class T3 = null_type, class T4 = null_type, class T5 = null_type,
class T6 = null_type, class T7 = null_type, class T8 = null_type,
class T9 = null_type
>
struct bind_tuple_mapper {
typedef
tuple<typename bind_traits<T0>::type,
typename bind_traits<T1>::type,
typename bind_traits<T2>::type,
typename bind_traits<T3>::type,
typename bind_traits<T4>::type,
typename bind_traits<T5>::type,
typename bind_traits<T6>::type,
typename bind_traits<T7>::type,
typename bind_traits<T8>::type,
typename bind_traits<T9>::type> type;
};
// bind_traits, except map const T& -> const T
// this is needed e.g. in currying. Const reference arguments can
// refer to temporaries, so it is not safe to store them as references.
template <class T> struct remove_const_reference {
typedef typename bind_traits<T>::type type;
};
template <class T> struct remove_const_reference<const T&> {
typedef const T type;
};
// maps the bind argument types to the resulting lambda functor type
template <
class T0 = null_type, class T1 = null_type, class T2 = null_type,
class T3 = null_type, class T4 = null_type, class T5 = null_type,
class T6 = null_type, class T7 = null_type, class T8 = null_type,
class T9 = null_type
>
class bind_type_generator {
typedef typename
detail::bind_tuple_mapper<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9
>::type args_t;
BOOST_STATIC_CONSTANT(int, nof_elems = boost::tuples::length<args_t>::value);
typedef
action<
nof_elems,
function_action<nof_elems>
> action_type;
public:
typedef
lambda_functor<
lambda_functor_base<
action_type,
args_t
>
> type;
};
} // detail
template <class T> inline const T& make_const(const T& t) { return t; }
} // end of namespace lambda
} // end of namespace boost
#endif // BOOST_LAMBDA_TRAITS_HPP
|
#include "pure_pursuit/subscriber/path_subscriber.hpp"
PathSubscriber::PathSubscriber(ros::NodeHandle& nh, const std::string& topic){
subscriber_ = nh_.subscribe<geometry_msgs::PoseArray>(topic.c_str(), 1, &PathSubscriber::PathCallback, this);
}
bool PathSubscriber::GetPath(std::vector<Eigen::Vector3f>& path){
if(get_trajectory_flag_)
path = trajectory_;
auto flag = get_trajectory_flag_;
get_trajectory_flag_ = false;
return flag;
}
void PathSubscriber::PathCallback(const geometry_msgs::PoseArray::ConstPtr& msg_ptr){
global_mtx_.lock();
trajectory_.clear();
for(int i = 0; i < msg_ptr->poses.size(); i++){
trajectory_.push_back(Eigen::Vector3f(msg_ptr->poses[i].position.x,
msg_ptr->poses[i].position.y,
tf::getYaw(msg_ptr->poses[i].orientation)));
}
get_trajectory_flag_ = true;
std::cout << "get trajectory : " << get_trajectory_flag_ << std::endl;
global_mtx_.unlock();
}
|
/*
* Copyright 2017 Facebook, 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 <folly/dynamic.h>
#include <folly/portability/GTest.h>
#include <boost/next_prior.hpp>
using folly::dynamic;
// This test runs without any external dependencies, including json.
// This means that if there's a test failure, there's no way to print
// a useful runtime representation of the folly::dynamic. We will
// live with this in order to test dependencies. This method is
// normally provided by json.cpp.
void dynamic::print_as_pseudo_json(std::ostream& out) const {
out << "<folly::dynamic object of type " << type_ << ">";
}
TEST(Dynamic, Default) {
dynamic obj;
EXPECT_TRUE(obj.isNull());
}
TEST(Dynamic, ObjectBasics) {
dynamic obj = dynamic::object("a", false);
EXPECT_EQ(obj.at("a"), false);
EXPECT_EQ(obj.size(), 1);
obj.insert("a", true);
EXPECT_EQ(obj.size(), 1);
EXPECT_EQ(obj.at("a"), true);
obj.at("a") = nullptr;
EXPECT_EQ(obj.size(), 1);
EXPECT_TRUE(obj.at("a") == nullptr);
dynamic newObject = dynamic::object;
newObject["z"] = 12;
EXPECT_EQ(newObject.size(), 1);
newObject["a"] = true;
EXPECT_EQ(newObject.size(), 2);
EXPECT_EQ(*newObject.keys().begin(), newObject.items().begin()->first);
EXPECT_EQ(*newObject.values().begin(), newObject.items().begin()->second);
std::vector<std::pair<std::string, dynamic>> found;
found.emplace_back(newObject.keys().begin()->asString(),
*newObject.values().begin());
EXPECT_EQ(*boost::next(newObject.keys().begin()),
boost::next(newObject.items().begin())->first);
EXPECT_EQ(*boost::next(newObject.values().begin()),
boost::next(newObject.items().begin())->second);
found.emplace_back(boost::next(newObject.keys().begin())->asString(),
*boost::next(newObject.values().begin()));
std::sort(found.begin(), found.end());
EXPECT_EQ("a", found[0].first);
EXPECT_TRUE(found[0].second.asBool());
EXPECT_EQ("z", found[1].first);
EXPECT_EQ(12, found[1].second.asInt());
dynamic obj2 = dynamic::object;
EXPECT_TRUE(obj2.isObject());
dynamic d3 = nullptr;
EXPECT_TRUE(d3 == nullptr);
d3 = dynamic::object;
EXPECT_TRUE(d3.isObject());
d3["foo"] = dynamic::array(1, 2, 3);
EXPECT_EQ(d3.count("foo"), 1);
d3[123] = 321;
EXPECT_EQ(d3.at(123), 321);
d3["123"] = 42;
EXPECT_EQ(d3.at("123"), 42);
EXPECT_EQ(d3.at(123), 321);
dynamic objInsert = folly::dynamic::object();
dynamic objA = folly::dynamic::object("1", "2");
dynamic objB = folly::dynamic::object("1", "2");
objInsert.insert("1", std::move(objA));
objInsert.insert("1", std::move(objB));
EXPECT_EQ(objInsert.find("1")->second.size(), 1);
// We don't allow objects as keys in objects.
EXPECT_ANY_THROW(newObject[d3] = 12);
// Merge two objects
dynamic origMergeObj1 = folly::dynamic::object();
dynamic mergeObj1 = origMergeObj1 = folly::dynamic::object
("key1", "value1")
("key2", "value2");
dynamic mergeObj2 = folly::dynamic::object
("key2", "value3")
("key3", "value4");
// Merged object where we prefer the values in mergeObj2
dynamic combinedPreferObj2 = folly::dynamic::object
("key1", "value1")
("key2", "value3")
("key3", "value4");
// Merged object where we prefer the values in mergeObj1
dynamic combinedPreferObj1 = folly::dynamic::object
("key1", "value1")
("key2", "value2")
("key3", "value4");
auto newMergeObj = dynamic::merge(mergeObj1, mergeObj2);
EXPECT_EQ(newMergeObj, combinedPreferObj2);
EXPECT_EQ(mergeObj1, origMergeObj1); // mergeObj1 should be unchanged
mergeObj1.update(mergeObj2);
EXPECT_EQ(mergeObj1, combinedPreferObj2);
dynamic arr = dynamic::array(1, 2, 3, 4, 5, 6);
EXPECT_THROW(mergeObj1.update(arr), std::exception);
mergeObj1 = origMergeObj1; // reset it
mergeObj1.update_missing(mergeObj2);
EXPECT_EQ(mergeObj1, combinedPreferObj1);
}
TEST(Dynamic, ObjectErase) {
dynamic obj = dynamic::object("key1", "val")
("key2", "val2");
EXPECT_EQ(obj.count("key1"), 1);
EXPECT_EQ(obj.count("key2"), 1);
EXPECT_EQ(obj.erase("key1"), 1);
EXPECT_EQ(obj.count("key1"), 0);
EXPECT_EQ(obj.count("key2"), 1);
EXPECT_EQ(obj.erase("key1"), 0);
obj["key1"] = 12;
EXPECT_EQ(obj.count("key1"), 1);
EXPECT_EQ(obj.count("key2"), 1);
auto it = obj.find("key2");
obj.erase(it);
EXPECT_EQ(obj.count("key1"), 1);
EXPECT_EQ(obj.count("key2"), 0);
obj["asd"] = 42.0;
obj["foo"] = 42.0;
EXPECT_EQ(obj.size(), 3);
auto ret = obj.erase(boost::next(obj.items().begin()), obj.items().end());
EXPECT_TRUE(ret == obj.items().end());
EXPECT_EQ(obj.size(), 1);
obj.erase(obj.items().begin());
EXPECT_TRUE(obj.empty());
}
TEST(Dynamic, ArrayErase) {
dynamic arr = dynamic::array(1, 2, 3, 4, 5, 6);
EXPECT_THROW(arr.erase(1), std::exception);
EXPECT_EQ(arr.size(), 6);
EXPECT_EQ(arr[0], 1);
arr.erase(arr.begin());
EXPECT_EQ(arr.size(), 5);
arr.erase(boost::next(arr.begin()), boost::prior(arr.end()));
EXPECT_EQ(arr.size(), 2);
EXPECT_EQ(arr[0], 2);
EXPECT_EQ(arr[1], 6);
}
TEST(Dynamic, StringBasics) {
dynamic str = "hello world";
EXPECT_EQ(11, str.size());
EXPECT_FALSE(str.empty());
str = "";
EXPECT_TRUE(str.empty());
}
TEST(Dynamic, ArrayBasics) {
dynamic array = dynamic::array(1, 2, 3);
EXPECT_EQ(array.size(), 3);
EXPECT_EQ(array.at(0), 1);
EXPECT_EQ(array.at(1), 2);
EXPECT_EQ(array.at(2), 3);
EXPECT_ANY_THROW(array.at(-1));
EXPECT_ANY_THROW(array.at(3));
array.push_back("foo");
EXPECT_EQ(array.size(), 4);
array.resize(12, "something");
EXPECT_EQ(array.size(), 12);
EXPECT_EQ(array[11], "something");
}
TEST(Dynamic, DeepCopy) {
dynamic val = dynamic::array("foo", "bar", dynamic::array("foo1", "bar1"));
EXPECT_EQ(val.at(2).at(0), "foo1");
EXPECT_EQ(val.at(2).at(1), "bar1");
dynamic val2 = val;
EXPECT_EQ(val2.at(2).at(0), "foo1");
EXPECT_EQ(val2.at(2).at(1), "bar1");
EXPECT_EQ(val.at(2).at(0), "foo1");
EXPECT_EQ(val.at(2).at(1), "bar1");
val2.at(2).at(0) = "foo3";
val2.at(2).at(1) = "bar3";
EXPECT_EQ(val.at(2).at(0), "foo1");
EXPECT_EQ(val.at(2).at(1), "bar1");
EXPECT_EQ(val2.at(2).at(0), "foo3");
EXPECT_EQ(val2.at(2).at(1), "bar3");
dynamic obj =
dynamic::object("a", "b")
("c", dynamic::array("d", "e", "f"));
EXPECT_EQ(obj.at("a"), "b");
dynamic obj2 = obj;
obj2.at("a") = dynamic::array(1, 2, 3);
EXPECT_EQ(obj.at("a"), "b");
dynamic expected = dynamic::array(1, 2, 3);
EXPECT_EQ(obj2.at("a"), expected);
}
TEST(Dynamic, ArrayReassignment) {
dynamic o = 1;
dynamic d1 = dynamic::array(o);
EXPECT_EQ(dynamic::ARRAY, d1.type());
d1 = dynamic::array(o);
EXPECT_EQ(dynamic::ARRAY, d1.type());
}
TEST(Dynamic, Operator) {
bool caught = false;
try {
dynamic d1 = dynamic::object;
dynamic d2 = dynamic::object;
auto foo = d1 < d2;
LOG(ERROR) << "operator < returned "
<< static_cast<int>(foo)
<< " instead of throwing";
} catch (std::exception const&) {
caught = true;
}
EXPECT_TRUE(caught);
dynamic foo = "asd";
dynamic bar = "bar";
dynamic sum = foo + bar;
EXPECT_EQ(sum, "asdbar");
dynamic some = 12;
dynamic nums = 4;
dynamic math = some / nums;
EXPECT_EQ(math, 3);
}
TEST(Dynamic, Conversions) {
dynamic str = "12.0";
EXPECT_EQ(str.asDouble(), 12.0);
EXPECT_ANY_THROW(str.asInt());
EXPECT_ANY_THROW(str.asBool());
str = "12";
EXPECT_EQ(str.asInt(), 12);
EXPECT_EQ(str.asDouble(), 12.0);
str = "0";
EXPECT_EQ(str.asBool(), false);
EXPECT_EQ(str.asInt(), 0);
EXPECT_EQ(str.asDouble(), 0);
EXPECT_EQ(str.asString(), "0");
dynamic num = 12;
EXPECT_EQ("12", num.asString());
EXPECT_EQ(12.0, num.asDouble());
}
TEST(Dynamic, GetSetDefaultTest) {
dynamic d1 = dynamic::object("foo", "bar");
EXPECT_EQ(d1.getDefault("foo", "baz"), "bar");
EXPECT_EQ(d1.getDefault("quux", "baz"), "baz");
dynamic d2 = dynamic::object("foo", "bar");
EXPECT_EQ(d2.setDefault("foo", "quux"), "bar");
d2.setDefault("bar", dynamic::array).push_back(42);
EXPECT_EQ(d2["bar"][0], 42);
dynamic d3 = dynamic::object, empty = dynamic::object;
EXPECT_EQ(d3.getDefault("foo"), empty);
d3.setDefault("foo")["bar"] = "baz";
EXPECT_EQ(d3["foo"]["bar"], "baz");
// we do not allow getDefault/setDefault on arrays
dynamic d4 = dynamic::array;
EXPECT_ANY_THROW(d4.getDefault("foo", "bar"));
EXPECT_ANY_THROW(d4.setDefault("foo", "bar"));
}
TEST(Dynamic, ObjectForwarding) {
// Make sure dynamic::object can be constructed the same way as any
// dynamic.
dynamic d = dynamic::object("asd", dynamic::array("foo", "bar"));
dynamic d2 = dynamic::object("key2", dynamic::array("value", "words"))
("key", "value1");
}
TEST(Dynamic, GetPtr) {
dynamic array = dynamic::array(1, 2, "three");
EXPECT_TRUE(array.get_ptr(0));
EXPECT_FALSE(array.get_ptr(-1));
EXPECT_FALSE(array.get_ptr(3));
EXPECT_EQ(dynamic("three"), *array.get_ptr(2));
const dynamic& carray = array;
EXPECT_EQ(dynamic("three"), *carray.get_ptr(2));
dynamic object = dynamic::object("one", 1)("two", 2);
EXPECT_TRUE(object.get_ptr("one"));
EXPECT_FALSE(object.get_ptr("three"));
EXPECT_EQ(dynamic(2), *object.get_ptr("two"));
*object.get_ptr("one") = 11;
EXPECT_EQ(dynamic(11), *object.get_ptr("one"));
const dynamic& cobject = object;
EXPECT_EQ(dynamic(2), *cobject.get_ptr("two"));
}
TEST(Dynamic, Assignment) {
const dynamic ds[] = { dynamic::array(1, 2, 3),
dynamic::object("a", true),
24,
26.5,
true,
"hello", };
const dynamic dd[] = { dynamic::array(5, 6),
dynamic::object("t", "T")(1, 7),
9000,
3.14159,
false,
"world", };
for (const auto& source : ds) {
for (const auto& dest : dd) {
dynamic tmp(dest);
EXPECT_EQ(tmp, dest);
tmp = source;
EXPECT_EQ(tmp, source);
}
}
}
std::string make_long_string() {
return std::string(100, 'a');
}
TEST(Dynamic, GetDefault) {
const auto s = make_long_string();
dynamic ds(s);
dynamic tmp(s);
dynamic d1 = dynamic::object("key1", s);
dynamic d2 = dynamic::object("key2", s);
dynamic d3 = dynamic::object("key3", s);
dynamic d4 = dynamic::object("key4", s);
// lvalue - lvalue
dynamic ayy("ayy");
EXPECT_EQ(ds, d1.getDefault("key1", ayy));
EXPECT_EQ(ds, d1.getDefault("key1", ayy));
EXPECT_EQ(ds, d1.getDefault("not-a-key", tmp));
EXPECT_EQ(ds, tmp);
// lvalue - rvalue
EXPECT_EQ(ds, d1.getDefault("key1", "ayy"));
EXPECT_EQ(ds, d1.getDefault("key1", "ayy"));
EXPECT_EQ(ds, d1.getDefault("not-a-key", std::move(tmp)));
EXPECT_NE(ds, tmp);
// rvalue - lvalue
tmp = s;
EXPECT_EQ(ds, std::move(d1).getDefault("key1", ayy));
EXPECT_NE(ds, d1["key1"]);
EXPECT_EQ(ds, std::move(d2).getDefault("not-a-key", tmp));
EXPECT_EQ(dynamic(dynamic::object("key2", s)), d2);
EXPECT_EQ(ds, tmp);
// rvalue - rvalue
EXPECT_EQ(ds, std::move(d3).getDefault("key3", std::move(tmp)));
EXPECT_NE(ds, d3["key3"]);
EXPECT_EQ(ds, tmp);
EXPECT_EQ(ds, std::move(d4).getDefault("not-a-key", std::move(tmp)));
EXPECT_EQ(dynamic(dynamic::object("key4", s)), d4);
EXPECT_NE(ds, tmp);
}
TEST(Dynamic, GetString) {
const dynamic c(make_long_string());
dynamic d(make_long_string());
dynamic m(make_long_string());
auto s = make_long_string();
EXPECT_EQ(s, c.getString());
EXPECT_EQ(s, c.getString());
d.getString() += " hello";
EXPECT_EQ(s + " hello", d.getString());
EXPECT_EQ(s + " hello", d.getString());
EXPECT_EQ(s, std::move(m).getString());
EXPECT_EQ(s, m.getString());
auto moved = std::move(m).getString();
EXPECT_EQ(s, moved);
EXPECT_NE(dynamic(s), m);
}
TEST(Dynamic, GetSmallThings) {
const dynamic cint(5);
const dynamic cdouble(5.0);
const dynamic cbool(true);
dynamic dint(5);
dynamic ddouble(5.0);
dynamic dbool(true);
dynamic mint(5);
dynamic mdouble(5.0);
dynamic mbool(true);
EXPECT_EQ(5, cint.getInt());
dint.getInt() = 6;
EXPECT_EQ(6, dint.getInt());
EXPECT_EQ(5, std::move(mint).getInt());
EXPECT_EQ(5.0, cdouble.getDouble());
ddouble.getDouble() = 6.0;
EXPECT_EQ(6.0, ddouble.getDouble());
EXPECT_EQ(5.0, std::move(mdouble).getDouble());
EXPECT_EQ(true, cbool.getBool());
dbool.getBool() = false;
EXPECT_FALSE(dbool.getBool());
EXPECT_EQ(true, std::move(mbool).getBool());
}
TEST(Dynamic, At) {
const dynamic cd = dynamic::object("key1", make_long_string());
dynamic dd = dynamic::object("key1", make_long_string());
dynamic md = dynamic::object("key1", make_long_string());
dynamic ds(make_long_string());
EXPECT_EQ(ds, cd.at("key1"));
EXPECT_EQ(ds, cd.at("key1"));
dd.at("key1").getString() += " hello";
EXPECT_EQ(dynamic(make_long_string() + " hello"), dd.at("key1"));
EXPECT_EQ(dynamic(make_long_string() + " hello"), dd.at("key1"));
EXPECT_EQ(ds, std::move(md).at("key1")); // move available, but not performed
EXPECT_EQ(ds, md.at("key1"));
dynamic moved = std::move(md).at("key1"); // move performed
EXPECT_EQ(ds, moved);
EXPECT_NE(ds, md.at("key1"));
}
TEST(Dynamic, Brackets) {
const dynamic cd = dynamic::object("key1", make_long_string());
dynamic dd = dynamic::object("key1", make_long_string());
dynamic md = dynamic::object("key1", make_long_string());
dynamic ds(make_long_string());
EXPECT_EQ(ds, cd["key1"]);
EXPECT_EQ(ds, cd["key1"]);
dd["key1"].getString() += " hello";
EXPECT_EQ(dynamic(make_long_string() + " hello"), dd["key1"]);
EXPECT_EQ(dynamic(make_long_string() + " hello"), dd["key1"]);
EXPECT_EQ(ds, std::move(md)["key1"]); // move available, but not performed
EXPECT_EQ(ds, md["key1"]);
dynamic moved = std::move(md)["key1"]; // move performed
EXPECT_EQ(ds, moved);
EXPECT_NE(ds, md["key1"]);
}
TEST(Dynamic, PrintNull) {
std::stringstream ss;
ss << folly::dynamic(nullptr);
EXPECT_EQ("null", ss.str());
}
TEST(Dynamic, WriteThroughArrayIterators) {
dynamic const cint(0);
dynamic d = dynamic::array(cint, cint, cint);
size_t size = d.size();
for (auto& val : d) {
EXPECT_EQ(val, cint);
}
EXPECT_EQ(d.size(), size);
dynamic ds(make_long_string());
for (auto& val : d) {
val = ds; // assign through reference
}
ds = "short string";
dynamic ds2(make_long_string());
for (auto& val : d) {
EXPECT_EQ(val, ds2);
}
EXPECT_EQ(d.size(), size);
}
TEST(Dynamic, MoveOutOfArrayIterators) {
dynamic ds(make_long_string());
dynamic d = dynamic::array(ds, ds, ds);
size_t size = d.size();
for (auto& val : d) {
EXPECT_EQ(val, ds);
}
EXPECT_EQ(d.size(), size);
for (auto& val : d) {
dynamic waste = std::move(val); // force moving out
EXPECT_EQ(waste, ds);
}
for (auto& val : d) {
EXPECT_NE(val, ds);
}
EXPECT_EQ(d.size(), size);
}
TEST(Dynamic, WriteThroughObjectIterators) {
dynamic const cint(0);
dynamic d = dynamic::object("key1", cint)("key2", cint);
size_t size = d.size();
for (auto& val : d.items()) {
EXPECT_EQ(val.second, cint);
}
EXPECT_EQ(d.size(), size);
dynamic ds(make_long_string());
for (auto& val : d.items()) {
val.second = ds; // assign through reference
}
ds = "short string";
dynamic ds2(make_long_string());
for (auto& val : d.items()) {
EXPECT_EQ(val.second, ds2);
}
EXPECT_EQ(d.size(), size);
}
TEST(Dynamic, MoveOutOfObjectIterators) {
dynamic ds(make_long_string());
dynamic d = dynamic::object("key1", ds)("key2", ds);
size_t size = d.size();
for (auto& val : d.items()) {
EXPECT_EQ(val.second, ds);
}
EXPECT_EQ(d.size(), size);
for (auto& val : d.items()) {
dynamic waste = std::move(val.second); // force moving out
EXPECT_EQ(waste, ds);
}
for (auto& val : d.items()) {
EXPECT_NE(val.second, ds);
}
EXPECT_EQ(d.size(), size);
}
TEST(Dynamic, ArrayIteratorInterop) {
dynamic d = dynamic::array(0, 1, 2);
dynamic const& cdref = d;
auto it = d.begin();
auto cit = cdref.begin();
EXPECT_EQ(it, cit);
EXPECT_EQ(cit, d.begin());
EXPECT_EQ(it, cdref.begin());
// Erase using non-const iterator
it = d.erase(it);
cit = cdref.begin();
EXPECT_EQ(*it, 1);
EXPECT_EQ(cit, it);
// Assign from non-const to const, preserve equality
decltype(cit) cit2 = it;
EXPECT_EQ(cit, cit2);
}
TEST(Dynamic, ObjectIteratorInterop) {
dynamic ds = make_long_string();
dynamic d = dynamic::object(0, ds)(1, ds)(2, ds);
dynamic const& cdref = d;
auto it = d.find(0);
auto cit = cdref.find(0);
EXPECT_NE(it, cdref.items().end());
EXPECT_NE(cit, cdref.items().end());
EXPECT_EQ(it, cit);
++cit;
// Erase using non-const iterator
auto it2 = d.erase(it);
EXPECT_EQ(cit, it2);
// Assign from non-const to const, preserve equality
decltype(cit) cit2 = it2;
EXPECT_EQ(cit, cit2);
}
|
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_drawinglayer.hxx"
#include <drawinglayer/attribute/sdrallattribute3d.hxx>
//////////////////////////////////////////////////////////////////////////////
namespace drawinglayer
{
namespace attribute
{
SdrLineFillShadowAttribute3D::SdrLineFillShadowAttribute3D(
const SdrLineAttribute& rLine,
const SdrFillAttribute& rFill,
const SdrLineStartEndAttribute& rLineStartEnd,
const SdrShadowAttribute& rShadow,
const FillGradientAttribute& rFillFloatTransGradient)
: maLine(rLine),
maFill(rFill),
maLineStartEnd(rLineStartEnd),
maShadow(rShadow),
maFillFloatTransGradient(rFillFloatTransGradient)
{
}
SdrLineFillShadowAttribute3D::SdrLineFillShadowAttribute3D()
: maLine(),
maFill(),
maLineStartEnd(),
maShadow(),
maFillFloatTransGradient()
{
}
bool SdrLineFillShadowAttribute3D::isDefault() const
{
return(getLine().isDefault()
&& getFill().isDefault()
&& getLineStartEnd().isDefault()
&& getShadow().isDefault()
&& getFillFloatTransGradient().isDefault());
}
bool SdrLineFillShadowAttribute3D::operator==(const SdrLineFillShadowAttribute3D& rCandidate) const
{
return(getLine() == rCandidate.getLine()
&& getFill() == rCandidate.getFill()
&& getLineStartEnd() == rCandidate.getLineStartEnd()
&& getShadow() == rCandidate.getShadow()
&& getFillFloatTransGradient() == rCandidate.getFillFloatTransGradient());
}
} // end of namespace overlay
} // end of namespace drawinglayer
//////////////////////////////////////////////////////////////////////////////
// eof
|
/*
Copyright (c) 2018 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ 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 3 of the License, or
(at your option) any later version.
0MQ 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, see <http://www.gnu.org/licenses/>.
*/
#include "../tests/testutil.hpp"
#include <poller.hpp>
#include <i_poll_events.hpp>
#include <ip.hpp>
#include <unity.h>
#ifndef _WIN32
#define closesocket close
#endif
void setUp ()
{
}
void tearDown ()
{
}
void test_create ()
{
zmq::thread_ctx_t thread_ctx;
zmq::poller_t poller (thread_ctx);
}
#if 0
// TODO this triggers an assertion. should it be a valid use case?
void test_start_empty ()
{
zmq::thread_ctx_t thread_ctx;
zmq::poller_t poller (thread_ctx);
poller.start ();
msleep (SETTLE_TIME);
}
#endif
struct test_events_t : zmq::i_poll_events
{
test_events_t (zmq::fd_t fd_, zmq::poller_t &poller_) :
fd (fd_),
poller (poller_)
{
(void)fd;
}
virtual void in_event ()
{
poller.rm_fd (handle);
handle = (zmq::poller_t::handle_t) NULL;
// this must only be incremented after rm_fd
in_events.add (1);
}
virtual void out_event ()
{
// TODO
}
virtual void timer_event (int id_)
{
LIBZMQ_UNUSED (id_);
poller.rm_fd (handle);
handle = (zmq::poller_t::handle_t) NULL;
// this must only be incremented after rm_fd
timer_events.add (1);
}
void set_handle (zmq::poller_t::handle_t handle_) { handle = handle_; }
zmq::atomic_counter_t in_events, timer_events;
private:
zmq::fd_t fd;
zmq::poller_t &poller;
zmq::poller_t::handle_t handle;
};
void wait_in_events (test_events_t &events)
{
void *watch = zmq_stopwatch_start ();
while (events.in_events.get () < 1) {
#ifdef ZMQ_BUILD_DRAFT
TEST_ASSERT_LESS_OR_EQUAL_MESSAGE (SETTLE_TIME,
zmq_stopwatch_intermediate (watch),
"Timeout waiting for in event");
#endif
}
zmq_stopwatch_stop (watch);
}
void wait_timer_events (test_events_t &events)
{
void *watch = zmq_stopwatch_start ();
while (events.timer_events.get () < 1) {
#ifdef ZMQ_BUILD_DRAFT
TEST_ASSERT_LESS_OR_EQUAL_MESSAGE (SETTLE_TIME,
zmq_stopwatch_intermediate (watch),
"Timeout waiting for timer event");
#endif
}
zmq_stopwatch_stop (watch);
}
void create_nonblocking_fdpair (zmq::fd_t *r, zmq::fd_t *w)
{
int rc = zmq::make_fdpair (r, w);
TEST_ASSERT_EQUAL_INT (0, rc);
TEST_ASSERT_NOT_EQUAL (zmq::retired_fd, *r);
TEST_ASSERT_NOT_EQUAL (zmq::retired_fd, *w);
zmq::unblock_socket (*r);
zmq::unblock_socket (*w);
}
void send_signal (zmq::fd_t w)
{
#if defined ZMQ_HAVE_EVENTFD
const uint64_t inc = 1;
ssize_t sz = write (w, &inc, sizeof (inc));
assert (sz == sizeof (inc));
#else
{
char msg[] = "test";
int rc = send (w, msg, sizeof (msg), 0);
assert (rc == sizeof (msg));
}
#endif
}
void close_fdpair (zmq::fd_t w, zmq::fd_t r)
{
int rc = closesocket (w);
TEST_ASSERT_EQUAL_INT (0, rc);
#if !defined ZMQ_HAVE_EVENTFD
rc = closesocket (r);
TEST_ASSERT_EQUAL_INT (0, rc);
#else
LIBZMQ_UNUSED (r);
#endif
}
void test_add_fd_and_start_and_receive_data ()
{
zmq::thread_ctx_t thread_ctx;
zmq::poller_t poller (thread_ctx);
zmq::fd_t r, w;
create_nonblocking_fdpair (&r, &w);
test_events_t events (r, poller);
zmq::poller_t::handle_t handle = poller.add_fd (r, &events);
events.set_handle (handle);
poller.set_pollin (handle);
poller.start ();
send_signal (w);
wait_in_events (events);
// required cleanup
close_fdpair (w, r);
}
void test_add_fd_and_remove_by_timer ()
{
zmq::fd_t r, w;
create_nonblocking_fdpair (&r, &w);
zmq::thread_ctx_t thread_ctx;
zmq::poller_t poller (thread_ctx);
test_events_t events (r, poller);
zmq::poller_t::handle_t handle = poller.add_fd (r, &events);
events.set_handle (handle);
poller.add_timer (50, &events, 0);
poller.start ();
wait_timer_events (events);
// required cleanup
close_fdpair (w, r);
}
#ifdef _WIN32
void test_add_fd_with_pending_failing_connect ()
{
zmq::thread_ctx_t thread_ctx;
zmq::poller_t poller (thread_ctx);
zmq::fd_t bind_socket = socket (AF_INET, SOCK_STREAM, 0);
sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
addr.sin_port = 0;
TEST_ASSERT_EQUAL_INT (0, bind (bind_socket,
reinterpret_cast<const sockaddr *> (&addr),
sizeof (addr)));
int addr_len = static_cast<int> (sizeof (addr));
TEST_ASSERT_EQUAL_INT (0, getsockname (bind_socket,
reinterpret_cast<sockaddr *> (&addr),
&addr_len));
zmq::fd_t connect_socket = socket (AF_INET, SOCK_STREAM, 0);
zmq::unblock_socket (connect_socket);
TEST_ASSERT_EQUAL_INT (
-1, connect (connect_socket, reinterpret_cast<const sockaddr *> (&addr),
sizeof (addr)));
TEST_ASSERT_EQUAL_INT (WSAEWOULDBLOCK, WSAGetLastError ());
test_events_t events (connect_socket, poller);
zmq::poller_t::handle_t handle = poller.add_fd (connect_socket, &events);
events.set_handle (handle);
poller.set_pollin (handle);
poller.start ();
wait_in_events (events);
int value;
int value_len = sizeof (value);
TEST_ASSERT_EQUAL_INT (0, getsockopt (connect_socket, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char *> (&value),
&value_len));
TEST_ASSERT_EQUAL_INT (WSAECONNREFUSED, value);
// required cleanup
close (connect_socket);
close (bind_socket);
}
#endif
int main (void)
{
UNITY_BEGIN ();
zmq::initialize_network ();
setup_test_environment ();
RUN_TEST (test_create);
RUN_TEST (test_add_fd_and_start_and_receive_data);
RUN_TEST (test_add_fd_and_remove_by_timer);
#if defined _WIN32
RUN_TEST (test_add_fd_with_pending_failing_connect);
#endif
zmq::shutdown_network ();
return UNITY_END ();
}
|
/*
043 - Maze Challenge with Lack of Sleep(★4)
https://atcoder.jp/contests/typical90/tasks/typical90_aq
Author: Keitaro Naruse
Date: 2022-01-13, 2022-01-18
MIT License
*/
// # Solution
// - Introduce 01-bfs by deque for graph searching
// - state ( h, w, q ) and four actions
// - 0 cost for same direction, 1 cost for changing direction
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <deque>
struct state {
int h; // [ 0, H )
int w; // [ 0, W )
int q; // 0(Right: w ++), 1(Up: h --), 2(Left: w --), 3 (Down: h++)
};
// According to the orientaion of q, the increse of the next position is as follows
std::vector< int > dh = { 0, -1, 0, 1 };
std::vector< int > dw = { 1, 0, -1, 0 };
const bool Debug = false;
const int Inf = 1000000007;
int main()
{
// Constants
const int Q = 4;
// Read H and W
int H = 0, W = 0; std::cin >> H >> W;
if( Debug ) {
std::cerr << H << " " << W << std::endl;
}
// Read Rs and Cs
int Rs = 0, Cs = 0; std::cin >> Rs >> Cs;
if( Debug ) {
std::cerr << Rs << " " << Cs << std::endl;
}
Rs --; Cs --;
// Read Rt and Ct
int Rt = 0, Ct = 0; std::cin >> Rt >> Ct;
if( Debug ) {
std::cerr << Rt << " " << Ct << std::endl;
}
Rt --; Ct --;
// Read S
std::vector< std::vector< char > > S( H, std::vector< char >( W, ' ' ) );
for(int h = 0; h < H; h ++ ) {
for( int w = 0; w < W; w ++ ) {
std::cin >> S.at( h ).at( w );
}
}
if( Debug ) {
for(int h = 0; h < H; h ++ ) {
for( int w = 0; w < W; w ++ ) {
std::cerr << S.at( h ).at( w );
}
std::cerr << std::endl;
}
}
// Main
std::deque< state > deq;
std::vector< std::vector< std::vector< int > > > length(
H, std::vector< std::vector< int > > (
W, std::vector< int > ( Q, Inf )
)
);
// Initial value
int h = Rs, w = Cs;
for( int q = 0; q < Q; q ++ ) {
length.at( h ).at( w ).at( q ) = 0;
deq.push_back( { h, w, q } );
}
// Main
while( !deq.empty() ) {
// Take a current state
struct state s = deq.front();
if( Debug ) {
std::cerr << s.h << " " << s.w << " " << s.q << " "
<< length.at( s.h ).at( s.w ).at( s.q ) << std::endl;
}
deq.pop_front();
// Goal check
if( s.h == Rt && s.w == Ct ) {
if( Debug ) {
std::cerr << "Goal" << std::endl;
}
break;
}
// Move to the four directions
// If it moves to a facing direction, cost is the same
// Otherwise, cost = cost + 1
for( int q = 0; q < Q; q ++ ) {
int h = s.h + dh.at( q );
int w = s.w + dw.at( q );
if( 0 <= h && h < H && 0 <= w && w < W ) {
if( S.at( h ).at( w ) == '.' ) {
int cost = length.at( s.h ).at( s.w ).at( s.q )
+ ( q == s.q ? 0 : 1);
if( length.at( h ).at( w ).at( q ) > cost ) {
length.at( h ).at( w ).at( q ) = cost;
if( q == s.q ) {
deq.push_front( { h, w, q } );
}
else {
deq.push_back( { h, w, q } );
}
}
}
}
}
}
// Display result
int result = length.at( Rt ).at( Ct ).at( 0 );
for( int q = 1; q < Q; q ++ ) {
result = std::min( result, length.at( Rt ).at( Ct ).at( q ) );
}
std::cout << result << std::endl;
// Finalize
if( Debug ) {
std::cerr << "Normally terminated." << std::endl;
}
return( 0 );
}
|
/**
* Remplir deuxième tableau avec la somme des colonnes du 1ère tableau
*/
#include <iostream>
/* Procédure */
void remplirTab(float tab[6][6], float tab1[6], int c, int l)
{
int som;
for (int i = 0; i < l; ++i) {
som = 0;
for (int j = 0; j < c; ++j)
som += tab[j][i];
tab1[i] = som;
}
}
/* Utilisation */
int main()
{
int c;
int l;
float tab[6][6] = { {1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{}, {}, {}, {} };
float tab1[6] = {};
c = 2;
l = 5;
remplirTab(tab, tab1, c, l);
return 0;
}
|
#include "ED.hpp"
// Default constructor
ED::ED()
{
}
// Contructor with parameters
ED::ED(std::string string_one, std::string string_two)
{
_string_one = string_one;
_string_two = string_two;
}
// Destructor
ED::~ED()
{
}
// Returns the penalty of the two characters.
int ED::penalty(char a, char b)
{
if(a == b) // Equal characters
{
return 0;
}
else if(a != b)
{ // not equal and no spaces
return 1;
}
// If something fails, return a -1.
// We can check this for errors.
return -1;
}
// Finds the minimum integer
int ED::min(int a, int b, int c)
{
if(a < b && a < c)
{
return a;
}
else if(b < a && b < c)
{
return b;
}
else if(c < a && c < b)
{
return c;
}
// They are all equal if we get here.
// So just return a cause w/e
return a;
}
// Finds the optimal distance between the two strings
int ED::OptDistance()
{
// This is where we should do some sort of loop and populate
// the matrix. We should use the penalty and min methods as well.
int i, j;
int N = _string_one.length();
int M = _string_two.length();
// Create the Matrix
/*
* Quick note - it seems the vector of a vector of ints actually runs
* like this:
* ------------------> this is one vector
* ------------------> another vector
* ------------------> etc
*
* So each column is a vector of ints.
* And the entire vector is a vector of a vector of ints.
* With each vector inside the large vector pointing to vectors,
* which are technically the columns.
*
* This is important for some of the math down below, which follows Princeton's
* site but can get confusing due to how the vectors seem to be making themselves.
*
*/
for(i = 0; i <= M; i++)
{
std::vector<int> tmp;
_matrix.push_back(tmp);
// Now push '0's back into the given vector
for(j = 0; j <= N; j++)
{
_matrix.at(i).push_back(0);
}
}
// Start by filling out the bottom row
for(i = 0; i <= M; i++)
{
// Very bottom row
_matrix[i][N] = 2 * (M - i);
}
// Now fill out the side row.
for(j = 0; j <= N; j++)
{
// Very right most column
_matrix[M][j] = 2 * (N - j);
}
// Now that we have the initial sides, we can go ahead and calculate the rest
// of the sub problems.
for(i = M - 1; i >= 0; i--)
{
for(j = N - 1; j >= 0; j--)
{
// Using Princeton's formula, we can just calculate every single row!
/*
* Note - min of 3 numbers, which we must get from using the penalty method.
*
*/
int opt1 = _matrix[i+1][j+1] + penalty(_string_one[j], _string_two[i]);
int opt2 = _matrix[i+1][j] + 2;
int opt3 = _matrix[i][j+1] + 2;
_matrix[i][j] = min(opt1, opt2, opt3);
}
}
return _matrix[0][0];
}
// This is a test method which will print out the matrix, so we can compare
// against Princeton's site to see if we're doing it right.
void ED::PrintMatrix()
{
std::cout << "\n\nPrinting out the Matrix for debug purposes: \n\n";
// Iterator the large vector
std::vector< std::vector<int> >::iterator a;
// Iterator to each vector of integers.
std::vector<int>::iterator b;
for(a = _matrix.begin(); a != _matrix.end(); a++)
{
for(b = (*a).begin(); b != (*a).end(); b++)
{
// Using std::right and setw(3) to align numbers to the right.
// See the stackoverflow post in the README for an example
std::cout << std::right << std::setw(3) << *b << " ";
}
std::cout << "\n";
}
}
// Returns the alignment
// Here we should trace the matrix and find the string that displays the actual alignment.
std::string ED::Alignment()
{
// Let's declare a stringstream object to hold the string we want to return.
std::ostringstream return_string;
// Get M & N for going through the Matrix
// NOTE: I use standard MxN Matrix notation - that is,
// M is the number of rows, N is the number of columns.
int M = _string_two.length();
int N = _string_one.length();
// I left in some debugging stuff for future reference.
// NOTE: Rows are represented by the first vector "of vectors",
// while columns are the vectors of ints inside the main vector.
// std::cout << "M = " << M << "\n";
// std::cout << "N = " << N << "\n";
//
// std::cout << "Row = " << _matrix.size() << "\n";
// std::cout << "Col = " << _matrix.at(0).size() << "\n";
int i = 0, j = 0;
int pen, opt1, opt2, opt3;
std::string ret_str;
// More debug stuff to check where the code is heading.
// std::cout << "We want: " << _matrix[M-1][N-1] << "\n";
// A while loop will work here since we want to move either diagonally, down or right.
while(i < M || j < N) // Need to run until we hit the far bottom right corner!
{
// More test stuff.
// std::cout << "i = " << i << "\nj = " << j << "\n";
// std::cout << "mat is: " << _matrix[i][j] << "\n";
// Checking vector bounds with try/catch
try{
pen = penalty(_string_one[j], _string_two[i]);
opt1 = _matrix.at(i+1).at(j+1) + pen;
}
catch(const std::out_of_range& error)
{
// out of range
opt1 = -1;
}
try{
opt2 = _matrix.at(i+1).at(j) + 2;
}catch(const std::out_of_range& error)
{
// out of range
opt2 = -1;
}
try{
opt3 = _matrix.at(i).at(j+1) + 2;
}catch(const std::out_of_range& error)
{
// out of range
opt3 = -1;
}
// Move diagonally
if(_matrix[i][j] == opt1)
{
return_string << _string_one[j] << " " << _string_two[i] << " " << pen << "\n";
i++;
j++;
}
// Move down
else if(_matrix[i][j] == opt2)
{
return_string << "- " << _string_two[i] << " 2\n";
i++;
}
// Move right
else if(_matrix[i][j] == opt3)
{
return_string << _string_one[j] << " -" << " 2\n";
j++;
}
}
// Get the string from the ostringstream object & return it.
ret_str = return_string.str();
return ret_str;
}
|
/*
* Copyright (c) 2008-2010
* Nakata, Maho
* All rights reserved.
*
* $Id: Ctgsyl.cpp,v 1.6 2010/08/07 04:48:32 nakatamaho Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
*/
/*
Copyright (c) 1992-2007 The University of Tennessee. All rights reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <mblas.h>
#include <mlapack.h>
void Ctgsyl(const char *trans, INTEGER ijob, INTEGER m, INTEGER n, COMPLEX * A, INTEGER lda, COMPLEX * B, INTEGER ldb,
COMPLEX * c, INTEGER ldc, COMPLEX * d, INTEGER ldd, COMPLEX * e, INTEGER lde, COMPLEX * f, INTEGER ldf, REAL * scale,
REAL * dif, COMPLEX * work, INTEGER lwork, INTEGER * iwork, INTEGER * info)
{
INTEGER i, j, k, p, q, ie, je, mb, nb, is, js, pq;
REAL dsum;
INTEGER ifunc, linfo;
INTEGER lwmin;
REAL scale2 = 0, dscale;
REAL scaloc;
INTEGER iround;
LOGICAL notran;
INTEGER isolve;
LOGICAL lquery;
REAL Zero = 0.0, One = 1.0;
//Decode and test input parameters
*info = 0;
notran = Mlsame(trans, "N");
lquery = lwork == -1;
if (!notran && !Mlsame(trans, "C")) {
*info = -1;
} else if (notran) {
if (ijob < 0 || ijob > 4) {
*info = -2;
}
}
if (*info == 0) {
if (m <= 0) {
*info = -3;
} else if (n <= 0) {
*info = -4;
} else if (lda < max((INTEGER) 1, m)) {
*info = -6;
} else if (ldb < max((INTEGER) 1, n)) {
*info = -8;
} else if (ldc < max((INTEGER) 1, m)) {
*info = -10;
} else if (ldd < max((INTEGER) 1, m)) {
*info = -12;
} else if (lde < max((INTEGER) 1, n)) {
*info = -14;
} else if (ldf < max((INTEGER) 1, m)) {
*info = -16;
}
}
if (*info == 0) {
if (notran) {
if (ijob == 1 || ijob == 2) {
lwmin = max((INTEGER) 1, (m << 1) * n);
} else {
lwmin = 1;
}
} else {
lwmin = 1;
}
work[1] = lwmin;
if (lwork < lwmin && !lquery) {
*info = -20;
}
}
if (*info != 0) {
Mxerbla("Ctgsyl", -(*info));
return;
} else if (lquery) {
return;
}
//Quick return if possible
if (m == 0 || n == 0) {
*scale = One;
if (notran) {
if (ijob != 0) {
*dif = Zero;
}
}
return;
}
//Determine optimal block sizes MB and NB
mb = iMlaenv(2, "ZTGSYL", trans, m, n, -1, -1);
nb = iMlaenv(5, "ZTGSYL", trans, m, n, -1, -1);
isolve = 1;
ifunc = 0;
if (notran) {
if (ijob >= 3) {
ifunc = ijob - 2;
Claset("F", m, n, Zero, Zero, &c[0], ldc);
Claset("F", m, n, Zero, Zero, &f[0], ldf);
} else if (ijob >= 1 && notran) {
isolve = 2;
}
}
if ((mb <= 1 && nb <= 1) || (mb >= m && nb >= n)) {
//Use unblocked Level 2 solver
for (iround = 1; iround <= isolve; iround++) {
*scale = One;
dscale = Zero;
dsum = One;
pq = m * n;
Ctgsy2(trans, ifunc, m, n, &A[0], lda, &B[0], ldb, &c[0], ldc, &d[0], ldd, &e[0], lde, &f[0], ldf, scale, &dsum, &dscale, info);
if (dscale != Zero) {
if (ijob == 1 || ijob == 3) {
// *dif = sqrt((REAL) ((m << 1) * n)) / (dscale * sqrt(dsum));
} else {
// *dif = sqrt((REAL) pq) / (dscale * sqrt(dsum));
}
}
if (isolve == 2 && iround == 1) {
if (notran) {
ifunc = ijob;
}
scale2 = *scale;
Clacpy("F", m, n, &c[0], ldc, &work[0], m);
Clacpy("F", m, n, &f[0], ldf, &work[m * n + 1], m);
Claset("F", m, n, Zero, Zero, &c[0], ldc);
Claset("F", m, n, Zero, Zero, &f[0], ldf);
} else if (isolve == 2 && iround == 2) {
Clacpy("F", m, n, &work[0], m, &c[0], ldc);
Clacpy("F", m, n, &work[m * n + 1], m, &f[0], ldf);
*scale = scale2;
}
}
return;
}
//Determine block structure of A
p = 0;
i = 1;
L40:
if (i > m) {
goto L50;
}
++p;
iwork[p] = i;
i = i + mb;
if (i >= m) {
goto L50;
}
goto L40;
L50:
iwork[p + 1] = m + 1;
if (iwork[p] == iwork[p + 1]) {
--p;
}
//Determine block structure of B
q = p + 1;
j = 0;
L60:
if (j > n) {
goto L70;
}
++q;
iwork[q] = j;
j += nb;
if (j >= n) {
goto L70;
}
goto L60;
L70:
iwork[q + 1] = n + 1;
if (iwork[q] == iwork[q + 1]) {
--q;
}
if (notran) {
for (iround = 1; iround <= isolve; iround++) {
//Solve (I, J) - subsystem
// A(I, I) * R(I, J) - L(I, J) * B(J, J) = C(I, J)
// D(I, I) * R(I, J) - L(I, J) * E(J, J) = F(I, J)
//for I = P, P - 1, ..., 1; J = 1, 2, ..., Q
pq = 0;
*scale = One;
dscale = Zero;
dsum = One;
for (j = p + 2; j <= q; j++) {
js = iwork[j];
je = iwork[j + 1] - 1;
nb = je - js + 1;
for (i = p; i >= 1; i--) {
is = iwork[i];
ie = iwork[i + 1] - 1;
mb = ie - is + 1;
Ctgsy2(trans, ifunc, mb, nb, &A[is + is * lda], lda, &B[js + js * ldb], ldb, &c[is + js * ldc], ldc,
&d[is + is * ldd], ldd, &e[js + js * lde], lde, &f[is + js * ldf], ldf, &scaloc, &dsum, &dscale, &linfo);
if (linfo > 0) {
*info = linfo;
}
pq = pq + mb * nb;
if (scaloc != One) {
for (k = 0; k < js - 1; k++) {
Cscal(m, (COMPLEX) scaloc, &c[k * ldc + 1], 1);
Cscal(m, (COMPLEX) scaloc, &f[k * ldf + 1], 1);
}
for (k = js; k <= je; k++) {
Cscal(is - 1, (COMPLEX) scaloc, &c[k * ldc + 1], 1);
Cscal(is - 1, (COMPLEX) scaloc, &f[k * ldf + 1], 1);
}
for (k = js; k <= je; k++) {
Cscal(m - ie, (COMPLEX) scaloc, &c[ie + 1 + k * ldc], 1);
Cscal(m - ie, (COMPLEX) scaloc, &f[ie + 1 + k * ldf], 1);
}
for (k = je + 1; k <= n; k++) {
Cscal(m, (COMPLEX) scaloc, &c[k * ldc + 1], 1);
Cscal(m, (COMPLEX) scaloc, &f[k * ldf + 1], 1);
}
*scale = *scale * scaloc;
}
//Substitute R(I,J) and L(I,J) into remaining equation.
if (i > 1) {
Cgemm("N", "N", is - 1, nb, mb, (COMPLEX) - One, &A[is * lda], lda, &c[is + js * ldc], ldc, (COMPLEX) One, &c[js * ldc + 1], ldc);
Cgemm("N", "N", is - 1, nb, mb, (COMPLEX) - One, &d[is * ldd + 1], ldd, &c[is + js * ldc], ldc, (COMPLEX) One, &f[js * ldf + 1], ldf);
}
if (j < q) {
Cgemm("N", "N", mb, n - je, nb, (COMPLEX) One, &f[is + js * ldf], ldf, &B[js + (je + 1) * ldb], ldb, (COMPLEX) One, &c[is + (je + 1) * ldc], ldc);
Cgemm("N", "N", mb, n - je, nb, (COMPLEX) One, &f[is + js * ldf], ldf, &e[js + (je + 1) * lde], lde, (COMPLEX) One, &f[is + (je + 1) * ldf], ldf);
}
}
}
if (dscale != Zero) {
if (ijob == 1 || ijob == 3) {
// *dif = sqrt((REAL) ((m << 1) * n)) / (dscale * sqrt(dsum));
} else {
// *dif = sqrt((REAL) pq) / (dscale * sqrt(dsum));
}
}
if (isolve == 2 && iround == 1) {
if (notran) {
ifunc = ijob;
}
scale2 = *scale;
Clacpy("F", m, n, &c[0], ldc, &work[0], m);
Clacpy("F", m, n, &f[0], ldf, &work[m * n + 1], m);
Claset("F", m, n, Zero, Zero, &c[0], ldc);
Claset("F", m, n, Zero, Zero, &f[0], ldf);
} else if (isolve == 2 && iround == 2) {
Clacpy("F", m, n, &work[0], m, &c[0], ldc);
Clacpy("F", m, n, &work[m * n + 1], m, &f[0], ldf);
*scale = scale2;
}
}
} else {
//Solve transposed (I, J)-subsystem
// A(I, I)' * R(I, J) + D(I, I)' * L(I, J) = C(I, J)
// R(I, J) * B(J, J) + L(I, J) * E(J, J) = -F(I, J)
//for I = 1,2,..., P; J = Q, Q-1,..., 1
*scale = One;
for (i = 0; i < p; i++) {
is = iwork[i];
ie = iwork[i + 1] - 1;
mb = ie - is + 1;
for (j = q; j >= p + 2; j--) {
js = iwork[j];
je = iwork[j + 1] - 1;
nb = je - js + 1;
Ctgsy2(trans, ifunc, mb, nb, &A[is + is * lda], lda, &B[js + js * ldb], ldb, &c[is + js * ldc], ldc,
&d[is + is * ldd], ldd, &e[js + js * lde], lde, &f[is + js * ldf], ldf, &scaloc, &dsum, &dscale, &linfo);
if (linfo > 0) {
*info = linfo;
}
if (scaloc != One) {
for (k = 0; k < js - 1; k++) {
Cscal(m, (COMPLEX) scaloc, &c[k * ldc + 1], 1);
Cscal(m, (COMPLEX) scaloc, &f[k * ldf + 1], 1);
}
for (k = js; k <= je; k++) {
Cscal(is - 1, (COMPLEX) scaloc, &c[k * ldc + 1], 1);
Cscal(is - 1, (COMPLEX) scaloc, &f[k * ldf + 1], 1);
}
for (k = js; k <= je; k++) {
Cscal(m - ie, (COMPLEX) scaloc, &c[ie + 1 + k * ldc], 1);
Cscal(m - ie, (COMPLEX) scaloc, &f[ie + 1 + k * ldf], 1);
}
for (k = je + 1; k <= n; k++) {
Cscal(m, (COMPLEX) scaloc, &c[k * ldc + 1], 1);
Cscal(m, (COMPLEX) scaloc, &f[k * ldf + 1], 1);
}
*scale = *scale * scaloc;
}
//Substitute R(I,J) and L(I,J) into remaining equation.
if (j > p + 2) {
Cgemm("N", "C", mb, js - 1, nb, (COMPLEX) One, &c[is + js * ldc], ldc, &B[js * ldb + 1], ldb, (COMPLEX) One, &f[is + ldf], ldf);
Cgemm("N", "C", mb, js - 1, nb, (COMPLEX) One, &f[is + js * ldf], ldf, &e[js * lde + 1], lde, (COMPLEX) One, &f[is + ldf], ldf);
}
if (i < p) {
Cgemm("C", "N", m - ie, nb, mb, (COMPLEX) - One, &A[is + (ie + 1)
* lda], lda, &c[is + js * ldc], ldc, (COMPLEX) One, &c[ie + 1 + js * ldc], ldc);
Cgemm("C", "N", m - ie, nb, mb, (COMPLEX) - One, &d[is + (ie + 1) * ldd], ldd, &f[is + js * ldf], ldf, (COMPLEX) One, &c[ie + 1 + js * ldc], ldc);
}
}
}
}
work[1] = lwmin;
return;
}
|
//
// Copyright (c) 2008-2020 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 "../Graphics/Graphics.h"
#include "../Graphics/GraphicsImpl.h"
#include "../Graphics/ShaderPrecache.h"
#include "../Graphics/ShaderVariation.h"
#include "../IO/File.h"
#include "../IO/FileSystem.h"
#include "../IO/Log.h"
#include "../DebugNew.h"
namespace Urho3D
{
ShaderPrecache::ShaderPrecache(Context* context, const ea::string& fileName) :
Object(context),
fileName_(fileName),
xmlFile_(context)
{
if (GetSubsystem<FileSystem>()->FileExists(fileName))
{
// If file exists, read the already listed combinations
File source(context_, fileName);
xmlFile_.Load(source);
XMLElement shader = xmlFile_.GetRoot().GetChild("shader");
while (shader)
{
ea::string oldCombination = shader.GetAttribute("vs") + " " + shader.GetAttribute("vsdefines") + " " +
shader.GetAttribute("ps") + " " + shader.GetAttribute("psdefines");
usedCombinations_.insert(oldCombination);
shader = shader.GetNext("shader");
}
}
// If no file yet or loading failed, create the root element now
if (!xmlFile_.GetRoot())
xmlFile_.CreateRoot("shaders");
URHO3D_LOGINFO("Begin dumping shaders to " + fileName_);
}
ShaderPrecache::~ShaderPrecache()
{
URHO3D_LOGINFO("End dumping shaders");
if (usedCombinations_.empty())
return;
File dest(context_, fileName_, FILE_WRITE);
xmlFile_.Save(dest);
}
void ShaderPrecache::StoreShaders(ShaderVariation* vs, ShaderVariation* ps)
{
if (!vs || !ps)
return;
// Check for duplicate using pointers first (fast)
ea::pair<ShaderVariation*, ShaderVariation*> shaderPair = ea::make_pair(vs, ps);
if (usedPtrCombinations_.contains(shaderPair))
return;
usedPtrCombinations_.insert(shaderPair);
ea::string vsName = vs->GetName();
ea::string psName = ps->GetName();
const ea::string& vsDefines = vs->GetDefines();
const ea::string& psDefines = ps->GetDefines();
// Check for duplicate using strings (needed for combinations loaded from existing file)
ea::string newCombination = vsName + " " + vsDefines + " " + psName + " " + psDefines;
if (usedCombinations_.contains(newCombination))
return;
usedCombinations_.insert(newCombination);
XMLElement shaderElem = xmlFile_.GetRoot().CreateChild("shader");
shaderElem.SetAttribute("vs", vsName);
shaderElem.SetAttribute("vsdefines", vsDefines);
shaderElem.SetAttribute("ps", psName);
shaderElem.SetAttribute("psdefines", psDefines);
}
void ShaderPrecache::LoadShaders(Graphics* graphics, Deserializer& source)
{
URHO3D_LOGDEBUG("Begin precaching shaders");
XMLFile xmlFile(graphics->GetContext());
xmlFile.Load(source);
XMLElement shader = xmlFile.GetRoot().GetChild("shader");
while (shader)
{
ea::string vsDefines = shader.GetAttribute("vsdefines");
ea::string psDefines = shader.GetAttribute("psdefines");
// Check for illegal variations on OpenGL ES and skip them
#ifdef GL_ES_VERSION_2_0
if (
#ifndef __EMSCRIPTEN__
vsDefines.contains("INSTANCED") ||
#endif
(psDefines.contains("POINTLIGHT") && psDefines.contains("SHADOW")))
{
shader = shader.GetNext("shader");
continue;
}
#endif
ShaderVariation* vs = graphics->GetShader(VS, shader.GetAttribute("vs"), vsDefines);
ShaderVariation* ps = graphics->GetShader(PS, shader.GetAttribute("ps"), psDefines);
// Set the shaders active to actually compile them
graphics->SetShaders(vs, ps);
shader = shader.GetNext("shader");
}
URHO3D_LOGDEBUG("End precaching shaders");
}
}
|
#include <QApplication>
#include <QMainWindow>
#include <QAction>
#include <QVector>
#include <QMessageBox>
#include <QBitmap>
#include <CGAL/boost/graph/helpers.h>
#include <CGAL/boost/graph/Euler_operations.h>
#include <CGAL/Three/Scene_item.h>
#include <CGAL/Three/Viewer_interface.h>
#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>
#include "Scene_polyhedron_item.h"
#include "Scene_surface_mesh_item.h"
#include "Scene_points_with_normal_item.h"
#include "Scene_polylines_item.h"
#include <CGAL/subdivision_method_3.h>
#include <CGAL/Kernel_traits.h>
#include "ui_Basic_generator_widget.h"
class GeneratorWidget :
public QDockWidget,
public Ui::BasicGenerator
{
Q_OBJECT
public:
GeneratorWidget(QString name, QWidget *parent)
:QDockWidget(name,parent)
{
setupUi(this);
}
};
typedef Kernel::Point_3 Point;
namespace euler = CGAL::Euler;
using namespace CGAL::Three;
class Q_DECL_EXPORT Basic_generator_plugin :
public QObject,
public Polyhedron_demo_plugin_helper
{
Q_OBJECT
Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)
Q_PLUGIN_METADATA(IID "com.geometryfactory.PolyhedronDemo.PluginInterface/1.0")
public :
void init(QMainWindow* mainWindow,
CGAL::Three::Scene_interface* scene_interface,
Messages_interface*)
{
this->scene = scene_interface;
this->mw = mainWindow;
for(int i=0; i<POLYLINE; ++i)
nbs[i]=0;
QMenu* menuFile = mw->findChild<QMenu*>("menuFile");
QMenu* menu = new QMenu(tr("Objet Generator Widget"), menuFile);
QAction* actionLoad = mw->findChild<QAction*>("actionLoadPlugin");
menuFile->insertMenu(actionLoad, menu);
QAction* actionPrism = new QAction("Prism", mw);
QAction* actionSphere = new QAction("Sphere", mw);
QAction* actionPyramid = new QAction("Pyramid", mw);
QAction* actionHexahedron = new QAction("Hexahedron", mw);
QAction* actionTetrahedron = new QAction("Tetrahedron", mw);
QAction* actionGrid = new QAction("Grid", mw);
QAction* actionPointSet = new QAction("Point Set", mw);
QAction* actionPolyline = new QAction("Polyline", mw);
connect(actionPrism, SIGNAL(triggered()),
this, SLOT(on_actionPrism_triggered()));
_actions << actionPrism;
connect(actionSphere, SIGNAL(triggered()),
this, SLOT(on_actionSphere_triggered()));
_actions << actionSphere;
connect(actionPyramid, SIGNAL(triggered()),
this, SLOT(on_actionPyramid_triggered()));
_actions << actionPyramid;
connect(actionHexahedron, SIGNAL(triggered()),
this, SLOT(on_actionHexahedron_triggered()));
_actions << actionHexahedron;
connect(actionTetrahedron, SIGNAL(triggered()),
this, SLOT(on_actionTetrahedron_triggered()));
_actions << actionTetrahedron;
connect(actionGrid, SIGNAL(triggered()),
this, SLOT(on_actionGrid_triggered()));
_actions << actionGrid;
connect(actionPointSet, SIGNAL(triggered()),
this, SLOT(on_actionPointSet_triggered()));
_actions << actionPointSet;
connect(actionPolyline, SIGNAL(triggered()),
this, SLOT(on_actionPolyline_triggered()));
_actions << actionPolyline;
menu->clear();
Q_FOREACH(QAction* action, _actions)
{
menu->addAction(action);
}
dock_widget = new GeneratorWidget("Basic Objets", mw);
dock_widget->setVisible(false); // do not show at the beginning
addDockWidget(dock_widget);
connect(dock_widget->generateButton, &QAbstractButton::clicked,
this, &Basic_generator_plugin::on_generate_clicked);
connect(dock_widget->selector_tabWidget, &QTabWidget::currentChanged,
this, &Basic_generator_plugin::on_tab_changed);
connect(dock_widget, &GeneratorWidget::visibilityChanged,
this, &Basic_generator_plugin::on_tab_changed);
connect(dock_widget->prismCheckBox, &QCheckBox::stateChanged,
this, &Basic_generator_plugin::on_tab_changed);
connect(dock_widget->pyramidCheckBox, &QCheckBox::stateChanged,
this, &Basic_generator_plugin::on_tab_changed);
}
bool applicable(QAction*) const
{
//not in the Operations menu
return false;
}
QList<QAction*> actions() const {
return _actions;
}
public Q_SLOTS:
void on_actionPrism_triggered();
void on_actionSphere_triggered();
void on_actionPyramid_triggered();
void on_actionHexahedron_triggered();
void on_actionTetrahedron_triggered();
void on_actionGrid_triggered();
void on_actionPointSet_triggered();
void on_actionPolyline_triggered();
void on_generate_clicked();
void on_tab_changed();
void closure(){ dock_widget->hide(); }
private:
QList<QAction*> _actions;
GeneratorWidget* dock_widget;
enum VolumeTab
{
PRISM=0,
SPHERE,
PYRAMID,
HEXAHEDRON,
TETRAHEDRON,
GRID,
POINT_SET,
POLYLINE
};
int nbs[POLYLINE+1];
template<class Facegraph_item>
void generateCube();
template<class Facegraph_item>
void generatePrism();
template<class Facegraph_item>
void generatePyramid();
template<class Facegraph_item>
void generateSphere();
template<class Facegraph_item>
void generateTetrahedron();
void generatePoints();
void generateLines();
template<class Facegraph_item>
void generateGrid();
}; //end of class Basic_generator_plugin
//show the widget
void Basic_generator_plugin::on_actionPrism_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(PRISM);
}
void Basic_generator_plugin::on_actionSphere_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(SPHERE);
}
void Basic_generator_plugin::on_actionPyramid_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(PYRAMID);
}
void Basic_generator_plugin::on_actionHexahedron_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(HEXAHEDRON);
}
void Basic_generator_plugin::on_actionTetrahedron_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(TETRAHEDRON);
}
void Basic_generator_plugin::on_actionGrid_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(GRID);
}
void Basic_generator_plugin::on_actionPointSet_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(POINT_SET);
}
void Basic_generator_plugin::on_actionPolyline_triggered()
{
dock_widget->show();
dock_widget->selector_tabWidget->tabBar()->setCurrentIndex(POLYLINE);
}
void Basic_generator_plugin::on_tab_changed()
{
QString name;
int nb = 0;
switch(dock_widget->selector_tabWidget->currentIndex())
{
case PRISM:
{
name = QString("Prism");
nb = nbs[PRISM];
QPixmap pic;
if(dock_widget->prismCheckBox->isChecked())
pic = QPixmap(":/cgal/Polyhedron_3/resources/prism.png");
else
pic = QPixmap(":/cgal/Polyhedron_3/resources/prism-open.png");
dock_widget->prism_picLabel->setPixmap(pic);
dock_widget->prism_picLabel->show();
}
break;
case SPHERE:
name = QString("Sphere");
nb = nbs[SPHERE];
break;
case PYRAMID:
{
name = QString("Pyramid");
nb = nbs[PYRAMID];
QPixmap pic;
if(dock_widget->pyramidCheckBox->isChecked())
pic = QPixmap(":/cgal/Polyhedron_3/resources/pyramid.png");
else
pic = QPixmap(":/cgal/Polyhedron_3/resources/pyramid-open.png");
dock_widget->pyramid_picLabel->setPixmap(pic);
dock_widget->pyramid_picLabel->show();
}
break;
case HEXAHEDRON:
name = QString("Hexahedron");
nb = nbs[HEXAHEDRON];
break;
case TETRAHEDRON:
name = QString("Tetrahedron");
nb = nbs[TETRAHEDRON];
break;
case GRID:
name = QString("Grid");
nb = nbs[GRID];
break;
case POINT_SET:
name = QString("Point_set");
nb = nbs[POINT_SET];
break;
case POLYLINE:
name = QString("Polyline");
nb = nbs[POLYLINE];
break;
default:
break;
};
dock_widget->name_lineEdit->setText((nb==0)?name:QString(name).append(QString("%1").arg(nb)));
}
//generate
void Basic_generator_plugin::on_generate_clicked()
{
bool is_polyhedron = mw->property("is_polyhedron_mode").toBool();
switch(dock_widget->selector_tabWidget->currentIndex())
{
case PRISM:
if(is_polyhedron)
generatePrism<Scene_polyhedron_item>();
else
generatePrism<Scene_surface_mesh_item>();
++nbs[PRISM];
break;
case SPHERE:
if(is_polyhedron)
generateSphere<Scene_polyhedron_item>();
else
generateSphere<Scene_surface_mesh_item>();
++nbs[SPHERE];
break;
case PYRAMID:
if(is_polyhedron)
generatePyramid<Scene_polyhedron_item>();
else
generatePyramid<Scene_surface_mesh_item>();
++nbs[PYRAMID];
break;
case HEXAHEDRON:
if(is_polyhedron)
generateCube<Scene_polyhedron_item>();
else
generateCube<Scene_surface_mesh_item>();
++nbs[HEXAHEDRON];
break;
case TETRAHEDRON:
if(is_polyhedron)
generateTetrahedron<Scene_polyhedron_item>();
else
generateTetrahedron<Scene_surface_mesh_item>();
++nbs[TETRAHEDRON];
break;
case GRID:
if(is_polyhedron)
generateGrid<Scene_polyhedron_item>();
else
generateGrid<Scene_surface_mesh_item>();
++nbs[GRID];
break;
case POINT_SET:
generatePoints();
++nbs[POINT_SET];
break;
case POLYLINE:
generateLines();
++nbs[POLYLINE];
break;
default:
break;
};
on_tab_changed();
}
//make a non triangle hexahedron
template<class Facegraph_item>
void Basic_generator_plugin::generateCube()
{
typename Facegraph_item::Face_graph cube;
if(dock_widget->tabWidget_2->currentIndex() == 0)
{
QString point_texts[8];
Point points[8];
point_texts[0] = dock_widget->cubeP0->text(); point_texts[4] = dock_widget->cubeP4->text();
point_texts[1] = dock_widget->cubeP1->text(); point_texts[5] = dock_widget->cubeP5->text();
point_texts[2] = dock_widget->cubeP2->text(); point_texts[6] = dock_widget->cubeP6->text();
point_texts[3] = dock_widget->cubeP3->text(); point_texts[7] = dock_widget->cubeP7->text();
for(int i=0; i<8; ++i)
{
QStringList list = point_texts[i].split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (list.isEmpty()) return;
if (list.size()!=3){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of 3 doubles.");
msgBox->exec();
return;
}
double coords[3];
for(int j=0; j<3; ++j)
{
bool ok;
coords[j] = list.at(j).toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
return;
}
}
points[i] = Point(coords[0], coords[1], coords[2]);
}
CGAL::make_hexahedron(
points[3],
points[2],
points[1],
points[0],
points[5],
points[4],
points[7],
points[6],
cube);
}
else
{
QString text = dock_widget->extremaEdit->text();
QStringList list = text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (list.isEmpty()) return;
if (list.size()!=6){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of 6 doubles.");
msgBox->exec();
return;
}
for(int i=0; i<6; ++i)
{
bool ok;
list.at(i).toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
return;
}
}
CGAL::make_hexahedron(Point(list.at(0).toDouble(),list.at(1).toDouble(),list.at(2).toDouble()),
Point(list.at(3).toDouble(),list.at(1).toDouble(),list.at(2).toDouble()),
Point(list.at(3).toDouble(),list.at(1).toDouble(),list.at(5).toDouble()),
Point(list.at(0).toDouble(),list.at(1).toDouble(),list.at(5).toDouble()),
Point(list.at(0).toDouble(),list.at(4).toDouble(),list.at(5).toDouble()),
Point(list.at(0).toDouble(),list.at(4).toDouble(),list.at(2).toDouble()),
Point(list.at(3).toDouble(),list.at(4).toDouble(),list.at(2).toDouble()),
Point(list.at(3).toDouble(),list.at(4).toDouble(),list.at(5).toDouble()),
cube);
}
Facegraph_item* cube_item = new Facegraph_item(cube);
cube_item->setName(dock_widget->name_lineEdit->text());
Scene_interface::Item_id id = scene->addItem(cube_item);
scene->setSelectedItem(id);
}
//make a prism
template<class Facegraph_item>
void Basic_generator_plugin::generatePrism()
{
//gets the precision parameter
int nb_vertices = dock_widget->prismSpinBox->value();
double height(dock_widget->prismHeightSpinBox->value()),
radius(dock_widget->prismBaseSpinBox->value());
bool is_closed = dock_widget->prismCheckBox->isChecked();
QString text = dock_widget->prism_lineEdit->text();
QStringList list = text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (list.isEmpty()) return;
if (list.size()!=3){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of 3 doubles.");
msgBox->exec();
return;
}
double coords[3];
for(int i=0; i<3; ++i)
{
bool ok;
coords[i] = list.at(i).toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
return;
}
}
typename Facegraph_item::Face_graph prism;
make_regular_prism(nb_vertices,
prism,
Point(coords[0], coords[1], coords[2]),
height,
radius,
is_closed);
Facegraph_item* prism_item = new Facegraph_item(prism);
prism_item->setName(dock_widget->name_lineEdit->text());
Scene_interface::Item_id id = scene->addItem(prism_item);
scene->setSelectedItem(id);
}
//make a pyramid
template<class Facegraph_item>
void Basic_generator_plugin::generatePyramid()
{
int nb_vertices = dock_widget->pyramidSpinBox->value();
double height(dock_widget->pyramidHeightSpinBox->value()),
radius(dock_widget->pyramidBaseSpinBox->value());
bool is_closed = dock_widget->pyramidCheckBox->isChecked();
QString text = dock_widget->pyramid_lineEdit->text();
QStringList list = text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (list.isEmpty()) return;
if (list.size()!=3){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of 3 doubles.");
msgBox->exec();
return;
}
double coords[3];
for(int i=0; i<3; ++i)
{
bool ok;
coords[i] = list.at(i).toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
return;
}
}
typename Facegraph_item::Face_graph pyramid;
make_pyramid(nb_vertices,
pyramid,
Point(coords[0], coords[1], coords[2]),
height,
radius,
is_closed);
Facegraph_item* pyramid_item = new Facegraph_item(pyramid);
pyramid_item->setName(dock_widget->name_lineEdit->text());
Scene_interface::Item_id id = scene->addItem(pyramid_item);
scene->setSelectedItem(id);
}
//make a sphere
template<class Facegraph_item>
void Basic_generator_plugin::generateSphere()
{
int precision = dock_widget->SphereSpinBox->value();
QString text = dock_widget->center_radius_lineEdit->text();
QStringList list = text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (list.isEmpty()) return;
if (list.size()!=4){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of four doubles.");
msgBox->exec();
return;
}
double radius = list.at(3).toDouble();
Point center = Point(list.at(0).toDouble(), list.at(1).toDouble(), list.at(2).toDouble());
typename Facegraph_item::Face_graph sphere;
make_icosahedron(sphere, center, radius);
typedef typename boost::property_map<typename Facegraph_item::Face_graph, CGAL::vertex_point_t>::type VPMap;
if(precision !=0)
CGAL::Subdivision_method_3::Sqrt3_subdivision(sphere,
precision);
VPMap vpmap = get(CGAL::vertex_point, sphere);
//emplace the points back on the sphere
BOOST_FOREACH(typename boost::graph_traits<typename Facegraph_item::Face_graph>::vertex_descriptor vd, vertices(sphere))
{
Kernel::Vector_3 vec(get(vpmap, vd), center);
vec = radius*vec/CGAL::sqrt(vec.squared_length());
put(vpmap, vd, Kernel::Point_3(center.x() + vec.x(),
center.y() + vec.y(),
center.z() + vec.z()));
}
Facegraph_item* sphere_item = new Facegraph_item(sphere);
sphere_item->setName(dock_widget->name_lineEdit->text());
Scene_interface::Item_id id = scene->addItem(sphere_item);
scene->setSelectedItem(id);
}
//make a tetrahedron
template<class Facegraph_item>
void Basic_generator_plugin::generateTetrahedron()
{
typename Facegraph_item::Face_graph tetrahedron;
QString point_texts[4];
Point points[4];
point_texts[0] = dock_widget->tetP0->text();
point_texts[1] = dock_widget->tetP1->text();
point_texts[2] = dock_widget->tetP2->text();
point_texts[3] = dock_widget->tetP3->text();
for(int i=0; i<4; ++i)
{
QStringList list = point_texts[i].split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (list.isEmpty()) return;
if (list.size()!=3){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of 3 doubles.");
msgBox->exec();
return;
}
double coords[3];
for(int j=0; j<3; ++j)
{
bool ok;
coords[j] = list.at(j).toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
return;
}
}
points[i] = Point(coords[0], coords[1], coords[2]);
}
CGAL::make_tetrahedron(points[0],
points[1],
points[2],
points[3],
tetrahedron);
Facegraph_item* tet_item = new Facegraph_item(tetrahedron);
tet_item->setName(dock_widget->name_lineEdit->text());
Scene_interface::Item_id id = scene->addItem(tet_item);
scene->setSelectedItem(id);
}
//make a point set
void Basic_generator_plugin::generatePoints()
{
QString text = dock_widget->point_textEdit->toPlainText();
Scene_points_with_normal_item* item = new Scene_points_with_normal_item();
QStringList list = text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
int counter = 0;
double coord[3];
bool ok = true;
if (list.isEmpty()) return;
if (list.size()%3!=0){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of triplets.");
msgBox->exec();
return;
}
Q_FOREACH(QString s, list)
{
if(!s.isEmpty())
{
double res = s.toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
break;
}
else
{
coord[counter] = res;
counter++;
}
}
if(counter == 3)
{
const Kernel::Point_3 p(coord[0], coord[1], coord[2]);
item->point_set()->insert(p);
counter =0;
}
}
if(ok)
{
dock_widget->point_textEdit->clear();
item->point_set()->unselect_all();
item->setName(dock_widget->name_lineEdit->text());
item->setColor(Qt::black);
item->invalidateOpenGLBuffers();
Scene_interface::Item_id id = scene->addItem(item);
scene->setSelectedItem(id);
}
}
//make a polyline
void Basic_generator_plugin::generateLines()
{
QString text = dock_widget->line_textEdit->toPlainText();
std::list<std::vector<Scene_polylines_item::Point_3> > polylines;
polylines.resize(polylines.size()+1);
std::vector<Scene_polylines_item::Point_3>& polyline = *(polylines.rbegin());
QStringList polylines_metadata;
QStringList list = text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
int counter = 0;
double coord[3];
bool ok = true;
if (list.isEmpty()) return;
if (list.size()%3!=0){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of triplets.");
msgBox->exec();
return;
}
Q_FOREACH(QString s, list)
{
if(!s.isEmpty())
{
double res = s.toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
break;
}
else
{
coord[counter] = res;
counter++;
}
}
if(counter == 3)
{
Scene_polylines_item::Point_3 p(coord[0], coord[1], coord[2]);
polyline.push_back(p);
counter =0;
}
}
if(ok)
{
dock_widget->line_textEdit->clear();
Scene_polylines_item* item = new Scene_polylines_item;
item->polylines = polylines;
item->setName(dock_widget->name_lineEdit->text());
item->setColor(Qt::black);
item->setProperty("polylines metadata", polylines_metadata);
item->invalidateOpenGLBuffers();
Scene_interface::Item_id id = scene->addItem(item);
scene->setSelectedItem(id);
}
}
struct Point_generator
{
std::size_t w,h;
Point bl, ur;
Point_generator(const std::size_t& w,
const std::size_t& h,
const Point& bl,
const Point& ur)
:w(w), h(h), bl(bl), ur(ur)
{}
Point operator()(std::size_t i, std::size_t j, std::size_t k) const
{
return Point(bl.x() + i*(ur.x()-bl.x())/(w-1),
bl.y() + j*(ur.y()-bl.y())/(h-1),
k);
}
};
template<class Facegraph_item>
void Basic_generator_plugin::generateGrid()
{
typedef typename Facegraph_item::Face_graph Face_graph;
Face_graph grid;
QString points_text;
Point extrema[2];
typename boost::graph_traits<Face_graph>::vertices_size_type nb_cells[2];
bool triangulated = dock_widget->grid_checkBox->isChecked();
points_text= dock_widget->grid_lineEdit->text();
QStringList list = points_text.split(QRegExp("\\s+"), QString::SkipEmptyParts);
if (list.isEmpty()) return;
if (list.size()!=6){
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Input should consists of 6 doubles.");
msgBox->exec();
return;
}
double coords[6];
for(int j=0; j<6; ++j)
{
bool ok;
coords[j] = list.at(j).toDouble(&ok);
if(!ok)
{
QMessageBox *msgBox = new QMessageBox;
msgBox->setWindowTitle("Error");
msgBox->setText("ERROR : Coordinates are invalid.");
msgBox->exec();
return;
}
}
extrema[0] = Point(coords[0], coords[1], coords[2]);
extrema[1] = Point(coords[3], coords[4], coords[5]);
nb_cells[0] = static_cast<std::size_t>(dock_widget->gridX_spinBox->value());
nb_cells[1] = static_cast<std::size_t>(dock_widget->gridY_spinBox->value());
//nb_points = nb_cells+1
Point_generator point_gen(nb_cells[0]+1, nb_cells[1]+1, extrema[0], extrema[1]);
CGAL::make_grid(nb_cells[0], nb_cells[1], grid, point_gen, triangulated);
Facegraph_item* grid_item = new Facegraph_item(grid);
grid_item->setName(dock_widget->name_lineEdit->text());
Scene_interface::Item_id id = scene->addItem(grid_item);
scene->setSelectedItem(id);
}
#include "Basic_generator_plugin.moc"
|
#ifndef UMINTL_EVALUATION_POLICY_HPP
#define UMINTL_EVALUATION_POLICY_HPP
#include <cstddef>
#include "umintl/forwards.h"
#include "umintl/optimization_context.hpp"
#include <cmath>
namespace umintl{
/** @brief The model_base class
*
* The optimization model can be either deterministic or stochastic. The latter usually corresponds to expected losses
* evaluated accross a large amount of data points
*/
template<class BackendType>
struct model_base{
virtual ~model_base(){ }
virtual bool update(optimization_context<BackendType> & context) = 0;
virtual value_gradient get_value_gradient_tag() const = 0;
virtual hessian_vector_product get_hv_product_tag() const = 0;
};
/** @brief The deterministic class
*
* Assumes the function evaluation is the same at each call. In the case of expected losses, it means all the data-points
* are always used.
*/
template<class BackendType>
struct deterministic : public model_base<BackendType> {
bool update(optimization_context<BackendType> &){ return false; }
value_gradient get_value_gradient_tag() const { return value_gradient(DETERMINISTIC,0,0); }
hessian_vector_product get_hv_product_tag() const { return hessian_vector_product(DETERMINISTIC,0,0); }
};
template<class BackendType>
struct mini_batch : public model_base<BackendType> {
public:
mini_batch(std::size_t sample_size, std::size_t dataset_size) : sample_size_(std::min(sample_size,dataset_size)), offset_(0), dataset_size_(dataset_size){ }
bool update(optimization_context<BackendType> &){
offset_=(offset_+sample_size_)%dataset_size_;
return false;
}
value_gradient get_value_gradient_tag() const { return value_gradient(STOCHASTIC,dataset_size_,0); }
hessian_vector_product get_hv_product_tag() const { return hessian_vector_product(STOCHASTIC,sample_size_,offset_); }
private:
std::size_t sample_size_;
std::size_t offset_;
std::size_t dataset_size_;
};
/** @brief the dynamically_sampled class
*
* Uses the dynamic sampled procedure from Byrd et al. (2012) :
* "Sample Size Selection in Optimization Methods for Machine Learning"
* Requires that the functor overloads :
* void operator()(VectorType const & X, VectorType & variance, umintl::gradient_variance_tag tag)
*
* The parameter tag contains the information on the current offset and sample size
*/
template<class BackendType>
struct dynamically_sampled : public model_base<BackendType> {
private:
typedef typename BackendType::ScalarType ScalarType;
typedef typename BackendType::VectorType VectorType;
public:
dynamically_sampled(double r, std::size_t S0, std::size_t dataset_size, double theta = 0.5) : r_(r), S(std::min(S0,dataset_size)), offset_(0), H_offset_(0), N(dataset_size), theta_(theta){ }
bool update(optimization_context<BackendType> & c){
// {
// VectorType var = BackendType::create_vector(c.N());
// VectorType tmp = BackendType::create_vector(c.N());
// VectorType Hv = BackendType::create_vector(c.N());
// BackendType::set_to_value(var,0,c.N());
// c.fun().compute_hv_product(c.x(),c.g(),c.g(),Hv,hessian_vector_product(STOCHASTIC,S,offset_));
// for(std::size_t i = 0 ; i < S ; ++i){
// //tmp = (grad(xi) - grad(X)).^2
// //var += tmp
// c.fun().compute_hv_product(c.x(),c.g(),c.g(),tmp,hessian_vector_product(STOCHASTIC,1,offset_+i));
// for(std::size_t i = 0 ; i < c.N() ; ++i)
// var[i]+=std::pow(tmp[i]-Hv[i],2);
// }
// BackendType::scale(c.N(),(ScalarType)1/(S-1),var);
// for(std::size_t i = 0 ; i < c.N() ; ++i)
// std::cout << var[i] << " ";
// std::cout << std::endl;
// c.fun().compute_hv_product_variance(c.x(),c.g(), var, hv_product_variance(STOCHASTIC,S,offset_));
// for(std::size_t i = 0 ; i < c.N() ; ++i)
// std::cout << var[i] << " ";
// std::cout << std::endl;
// BackendType::delete_if_dynamically_allocated(var);
// BackendType::delete_if_dynamically_allocated(tmp);
// BackendType::delete_if_dynamically_allocated(Hv);
// }
if(S==N){
H_offset_=(H_offset_+(int)(r_*S))%(S - (int)(r_*S) + 1);
return false;
}
else{
VectorType var = BackendType::create_vector(c.N());
c.fun().compute_gradient_variance(c.x(),var,gradient_variance(STOCHASTIC,S,offset_));
//is_descent_direction = norm1(var)/S*[(N-S)/(N-1)] <= theta^2*norm2(grad)^2
ScalarType nrm1var = BackendType::asum(c.N(),var);
ScalarType nrm2grad = BackendType::nrm2(c.N(),c.g());
//std::gradient_variance << nrm1var*scal << " " << std::pow(theta_,2)*std::pow(nrm2grad,2) << std::endl;
bool is_descent_direction = (nrm1var/S <= (std::pow(theta_,2)*std::pow(nrm2grad,2)));
//Update parameters
std::size_t old_S = S;
if(is_descent_direction==false){
S = nrm1var/std::pow(theta_*nrm2grad,2);
S = std::min(S,N);
if(S>N/2)
S=N;
std::cout << "Augmenting sample size from " << old_S << " to " << S << std::endl;
}
offset_=(offset_+S)%(N-S+1);
if(is_descent_direction==false)
H_offset_ = 0;
else
H_offset_=(H_offset_+S)%(S - (int)(r_*S) + 1);
BackendType::delete_if_dynamically_allocated(var);
return true;
}
}
value_gradient get_value_gradient_tag() const {
return value_gradient(STOCHASTIC,S,offset_);
}
hessian_vector_product get_hv_product_tag() const {
return hessian_vector_product(STOCHASTIC,r_*S,H_offset_+offset_);
}
private:
double theta_;
double r_;
std::size_t S;
std::size_t offset_;
std::size_t H_offset_;
std::size_t N;
};
}
#endif
|
#include <vcpkg/base/checks.h>
#include <vcpkg/base/chrono.h>
#include <vcpkg/base/system.debug.h>
#include <vcpkg/base/system.h>
#include <vcpkg/base/system.process.h>
#include <vcpkg/base/util.h>
#include <ctime>
#if defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#endif
#if defined(_WIN32)
#pragma comment(lib, "Advapi32")
#endif
using namespace vcpkg::System;
namespace vcpkg
{
#if defined(_WIN32)
namespace
{
struct CtrlCStateMachine
{
CtrlCStateMachine() : m_number_of_external_processes(0), m_global_job(NULL), m_in_interactive(0) { }
void transition_to_spawn_process() noexcept
{
int cur = 0;
while (!m_number_of_external_processes.compare_exchange_strong(cur, cur + 1))
{
if (cur < 0)
{
// Ctrl-C was hit and is asynchronously executing on another thread.
// Some other processes are outstanding.
// Sleep forever -- the other process will complete and exit the program
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(10));
System::print2("Waiting for child processes to exit...\n");
}
}
}
}
void transition_from_spawn_process() noexcept
{
auto previous = m_number_of_external_processes.fetch_add(-1);
if (previous == INT_MIN + 1)
{
// Ctrl-C was hit while blocked on the child process
// This is the last external process to complete
// Therefore, exit
Checks::final_cleanup_and_exit(1);
}
else if (previous < 0)
{
// Ctrl-C was hit while blocked on the child process
// Some other processes are outstanding.
// Sleep forever -- the other process will complete and exit the program
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(10));
System::print2("Waiting for child processes to exit...\n");
}
}
}
void transition_handle_ctrl_c() noexcept
{
int old_value = 0;
while (!m_number_of_external_processes.compare_exchange_strong(old_value, old_value + INT_MIN))
{
if (old_value < 0)
{
// Repeat calls to Ctrl-C -- a previous one succeeded.
return;
}
}
if (old_value == 0)
{
// Not currently blocked on a child process
Checks::final_cleanup_and_exit(1);
}
else
{
// We are currently blocked on a child process.
// If none of the child processes are interactive, use the Job Object to terminate the tree.
if (m_in_interactive.load() == 0)
{
auto job = m_global_job.exchange(NULL);
if (job != NULL)
{
::CloseHandle(job);
}
}
}
}
void initialize_job()
{
m_global_job = CreateJobObjectW(NULL, NULL);
if (m_global_job != NULL)
{
JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = {};
info.BasicLimitInformation.LimitFlags =
JOB_OBJECT_LIMIT_BREAKAWAY_OK | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
::SetInformationJobObject(m_global_job, JobObjectExtendedLimitInformation, &info, sizeof(info));
::AssignProcessToJobObject(m_global_job, ::GetCurrentProcess());
}
}
void enter_interactive() { ++m_in_interactive; }
void exit_interactive() { --m_in_interactive; }
private:
std::atomic<int> m_number_of_external_processes;
std::atomic<HANDLE> m_global_job;
std::atomic<int> m_in_interactive;
};
static CtrlCStateMachine g_ctrl_c_state;
}
void System::initialize_global_job_object() { g_ctrl_c_state.initialize_job(); }
void System::enter_interactive_subprocess() { g_ctrl_c_state.enter_interactive(); }
void System::exit_interactive_subprocess() { g_ctrl_c_state.exit_interactive(); }
#endif
fs::path System::get_exe_path_of_current_process()
{
#if defined(_WIN32)
wchar_t buf[_MAX_PATH];
const int bytes = GetModuleFileNameW(nullptr, buf, _MAX_PATH);
if (bytes == 0) std::abort();
return fs::path(buf, buf + bytes);
#elif defined(__APPLE__)
static constexpr const uint32_t buff_size = 1024 * 32;
uint32_t size = buff_size;
char buf[buff_size] = {};
int result = _NSGetExecutablePath(buf, &size);
Checks::check_exit(VCPKG_LINE_INFO, result != -1, "Could not determine current executable path.");
std::unique_ptr<char> canonicalPath(realpath(buf, NULL));
Checks::check_exit(VCPKG_LINE_INFO, result != -1, "Could not determine current executable path.");
return fs::path(std::string(canonicalPath.get()));
#elif defined(__FreeBSD__)
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
char exePath[2048];
size_t len = sizeof(exePath);
auto rcode = sysctl(mib, 4, exePath, &len, NULL, 0);
Checks::check_exit(VCPKG_LINE_INFO, rcode == 0, "Could not determine current executable path.");
Checks::check_exit(VCPKG_LINE_INFO, len > 0, "Could not determine current executable path.");
return fs::path(exePath, exePath + len - 1);
#elif defined(__OpenBSD__)
const char* progname = getprogname();
char resolved_path[PATH_MAX];
auto ret = realpath(progname, resolved_path);
Checks::check_exit(VCPKG_LINE_INFO, ret != nullptr, "Could not determine current executable path.");
return fs::u8path(resolved_path);
#else /* LINUX */
std::array<char, 1024 * 4> buf;
auto written = readlink("/proc/self/exe", buf.data(), buf.size());
Checks::check_exit(VCPKG_LINE_INFO, written != -1, "Could not determine current executable path.");
return fs::path(buf.data(), buf.data() + written);
#endif
}
System::CMakeVariable::CMakeVariable(const StringView varname, const char* varvalue)
: s(Strings::format("-D%s=%s", varname, varvalue))
{
}
System::CMakeVariable::CMakeVariable(const StringView varname, const std::string& varvalue)
: CMakeVariable(varname, varvalue.c_str())
{
}
System::CMakeVariable::CMakeVariable(const StringView varname, const fs::path& path)
: CMakeVariable(varname, fs::generic_u8string(path))
{
}
System::CMakeVariable::CMakeVariable(std::string var) : s(std::move(var)) { }
std::string System::make_basic_cmake_cmd(const fs::path& cmake_tool_path,
const fs::path& cmake_script,
const std::vector<CMakeVariable>& pass_variables)
{
System::CmdLineBuilder cmd;
cmd.path_arg(cmake_tool_path);
for (auto&& var : pass_variables)
{
cmd.string_arg(var.s);
}
cmd.string_arg("-P").path_arg(cmake_script);
return std::move(cmd).extract();
}
System::CmdLineBuilder& System::CmdLineBuilder::string_arg(StringView s) &
{
if (!buf.empty()) buf.push_back(' ');
if (Strings::find_first_of(s, " \t\n\r\"\\,;&`^|'") != s.end())
{
// TODO: improve this to properly handle all escaping
#if _WIN32
// On Windows, `\`s before a double-quote must be doubled. Inner double-quotes must be escaped.
buf.push_back('"');
size_t n_slashes = 0;
for (auto ch : s)
{
if (ch == '\\')
{
++n_slashes;
}
else if (ch == '"')
{
buf.append(n_slashes + 1, '\\');
n_slashes = 0;
}
else
{
n_slashes = 0;
}
buf.push_back(ch);
}
buf.append(n_slashes, '\\');
buf.push_back('"');
#else
// On non-Windows, `\` is the escape character and always requires doubling. Inner double-quotes must be
// escaped.
buf.push_back('"');
for (auto ch : s)
{
if (ch == '\\' || ch == '"') buf.push_back('\\');
buf.push_back(ch);
}
buf.push_back('"');
#endif
}
else
{
Strings::append(buf, s);
}
return *this;
}
#if defined(_WIN32)
Environment System::get_modified_clean_environment(const std::unordered_map<std::string, std::string>& extra_env,
const std::string& prepend_to_path)
{
static const std::string system_root_env =
get_environment_variable("SystemRoot").value_or_exit(VCPKG_LINE_INFO);
static const std::string system32_env = system_root_env + R"(\system32)";
std::string new_path = Strings::format(R"(Path=%s%s;%s;%s\Wbem;%s\WindowsPowerShell\v1.0\)",
prepend_to_path,
system32_env,
system_root_env,
system32_env,
system32_env);
std::vector<std::wstring> env_wstrings = {
L"ALLUSERSPROFILE",
L"APPDATA",
L"CommonProgramFiles",
L"CommonProgramFiles(x86)",
L"CommonProgramW6432",
L"COMPUTERNAME",
L"ComSpec",
L"HOMEDRIVE",
L"HOMEPATH",
L"LOCALAPPDATA",
L"LOGONSERVER",
L"NUMBER_OF_PROCESSORS",
L"OS",
L"PATHEXT",
L"PROCESSOR_ARCHITECTURE",
L"PROCESSOR_ARCHITEW6432",
L"PROCESSOR_IDENTIFIER",
L"PROCESSOR_LEVEL",
L"PROCESSOR_REVISION",
L"ProgramData",
L"ProgramFiles",
L"ProgramFiles(x86)",
L"ProgramW6432",
L"PROMPT",
L"PSModulePath",
L"PUBLIC",
L"SystemDrive",
L"SystemRoot",
L"TEMP",
L"TMP",
L"USERDNSDOMAIN",
L"USERDOMAIN",
L"USERDOMAIN_ROAMINGPROFILE",
L"USERNAME",
L"USERPROFILE",
L"windir",
// Enables proxy information to be passed to Curl, the underlying download library in cmake.exe
L"http_proxy",
L"https_proxy",
// Environment variables to tell git to use custom SSH executable or command
L"GIT_SSH",
L"GIT_SSH_COMMAND",
// Environment variables needed for ssh-agent based authentication
L"SSH_AUTH_SOCK",
L"SSH_AGENT_PID",
// Enables find_package(CUDA) and enable_language(CUDA) in CMake
L"CUDA_PATH",
L"CUDA_PATH_V9_0",
L"CUDA_PATH_V9_1",
L"CUDA_PATH_V10_0",
L"CUDA_PATH_V10_1",
L"CUDA_PATH_V10_2",
L"CUDA_PATH_V11_0",
L"CUDA_TOOLKIT_ROOT_DIR",
// Environmental variable generated automatically by CUDA after installation
L"NVCUDASAMPLES_ROOT",
L"NVTOOLSEXT_PATH",
// Enables find_package(Vulkan) in CMake. Environmental variable generated by Vulkan SDK installer
L"VULKAN_SDK",
// Enable targeted Android NDK
L"ANDROID_NDK_HOME",
};
const Optional<std::string> keep_vars = System::get_environment_variable("VCPKG_KEEP_ENV_VARS");
const auto k = keep_vars.get();
if (k && !k->empty())
{
auto vars = Strings::split(*k, ';');
for (auto&& var : vars)
{
env_wstrings.push_back(Strings::to_utf16(var));
}
}
std::wstring env_cstr;
for (auto&& env_wstring : env_wstrings)
{
const Optional<std::string> value = System::get_environment_variable(Strings::to_utf8(env_wstring.c_str()));
const auto v = value.get();
if (!v || v->empty()) continue;
env_cstr.append(env_wstring);
env_cstr.push_back(L'=');
env_cstr.append(Strings::to_utf16(*v));
env_cstr.push_back(L'\0');
}
if (extra_env.find("PATH") != extra_env.end())
new_path += Strings::format(";%s", extra_env.find("PATH")->second);
env_cstr.append(Strings::to_utf16(new_path));
env_cstr.push_back(L'\0');
env_cstr.append(L"VSLANG=1033");
env_cstr.push_back(L'\0');
env_cstr.append(L"VSCMD_SKIP_SENDTELEMETRY=1");
env_cstr.push_back(L'\0');
for (const auto& item : extra_env)
{
if (item.first == "PATH") continue;
env_cstr.append(Strings::to_utf16(item.first));
env_cstr.push_back(L'=');
env_cstr.append(Strings::to_utf16(item.second));
env_cstr.push_back(L'\0');
}
return {env_cstr};
}
#else
Environment System::get_modified_clean_environment(const std::unordered_map<std::string, std::string>&,
const std::string&)
{
return {};
}
#endif
const Environment& System::get_clean_environment()
{
static const Environment clean_env = get_modified_clean_environment({});
return clean_env;
}
int System::cmd_execute_clean(StringView cmd_line, InWorkingDirectory wd)
{
return cmd_execute(cmd_line, wd, get_clean_environment());
}
#if defined(_WIN32)
struct ProcessInfo
{
constexpr ProcessInfo() noexcept : proc_info{} { }
ProcessInfo(ProcessInfo&& other) noexcept : proc_info(other.proc_info)
{
other.proc_info.hProcess = nullptr;
other.proc_info.hThread = nullptr;
}
~ProcessInfo()
{
if (proc_info.hThread)
{
CloseHandle(proc_info.hThread);
}
if (proc_info.hProcess)
{
CloseHandle(proc_info.hProcess);
}
}
ProcessInfo& operator=(ProcessInfo&& other) noexcept
{
ProcessInfo{std::move(other)}.swap(*this);
return *this;
}
void swap(ProcessInfo& other) noexcept
{
std::swap(proc_info.hProcess, other.proc_info.hProcess);
std::swap(proc_info.hThread, other.proc_info.hThread);
}
friend void swap(ProcessInfo& lhs, ProcessInfo& rhs) noexcept { lhs.swap(rhs); }
unsigned int wait()
{
const DWORD result = WaitForSingleObject(proc_info.hProcess, INFINITE);
Checks::check_exit(VCPKG_LINE_INFO, result != WAIT_FAILED, "WaitForSingleObject failed");
DWORD exit_code = 0;
GetExitCodeProcess(proc_info.hProcess, &exit_code);
return exit_code;
}
PROCESS_INFORMATION proc_info;
};
/// <param name="maybe_environment">If non-null, an environment block to use for the new process. If null, the
/// new process will inherit the current environment.</param>
static ExpectedT<ProcessInfo, unsigned long> windows_create_process(StringView cmd_line,
InWorkingDirectory wd,
const Environment& env,
DWORD dwCreationFlags,
STARTUPINFOW& startup_info) noexcept
{
ProcessInfo process_info;
Debug::print("CreateProcessW(", cmd_line, ")\n");
// Flush stdout before launching external process
fflush(nullptr);
std::wstring working_directory;
if (!wd.working_directory.empty())
{
// this only fails if we can't get the current working directory of vcpkg, and we assume that we have that,
// so it's fine anyways
working_directory = Files::get_real_filesystem().absolute(VCPKG_LINE_INFO, wd.working_directory).native();
}
VCPKG_MSVC_WARNING(suppress : 6335) // Leaking process information handle 'process_info.proc_info.hProcess'
// /analyze can't tell that we transferred ownership here
bool succeeded =
TRUE == CreateProcessW(nullptr,
Strings::to_utf16(cmd_line).data(),
nullptr,
nullptr,
TRUE,
IDLE_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | dwCreationFlags,
env.m_env_data.empty()
? nullptr
: const_cast<void*>(static_cast<const void*>(env.m_env_data.data())),
working_directory.empty() ? nullptr : working_directory.data(),
&startup_info,
&process_info.proc_info);
if (succeeded)
return process_info;
else
return GetLastError();
}
static ExpectedT<ProcessInfo, unsigned long> windows_create_windowless_process(StringView cmd_line,
InWorkingDirectory wd,
const Environment& env,
DWORD dwCreationFlags) noexcept
{
STARTUPINFOW startup_info;
memset(&startup_info, 0, sizeof(STARTUPINFOW));
startup_info.cb = sizeof(STARTUPINFOW);
startup_info.dwFlags = STARTF_USESHOWWINDOW;
startup_info.wShowWindow = SW_HIDE;
return windows_create_process(cmd_line, wd, env, dwCreationFlags, startup_info);
}
struct ProcessInfoAndPipes
{
ProcessInfo proc_info;
HANDLE child_stdin = 0;
HANDLE child_stdout = 0;
template<class Function>
int wait_and_stream_output(Function&& f)
{
CloseHandle(child_stdin);
unsigned long bytes_read = 0;
static constexpr int buffer_size = 1024 * 32;
auto buf = std::make_unique<char[]>(buffer_size);
while (ReadFile(child_stdout, (void*)buf.get(), buffer_size, &bytes_read, nullptr) && bytes_read > 0)
{
f(StringView{buf.get(), static_cast<size_t>(bytes_read)});
}
CloseHandle(child_stdout);
return proc_info.wait();
}
};
static ExpectedT<ProcessInfoAndPipes, unsigned long> windows_create_process_redirect(StringView cmd_line,
InWorkingDirectory wd,
const Environment& env,
DWORD dwCreationFlags) noexcept
{
ProcessInfoAndPipes ret;
STARTUPINFOW startup_info;
memset(&startup_info, 0, sizeof(STARTUPINFOW));
startup_info.cb = sizeof(STARTUPINFOW);
startup_info.dwFlags |= STARTF_USESTDHANDLES;
SECURITY_ATTRIBUTES saAttr;
memset(&saAttr, 0, sizeof(SECURITY_ATTRIBUTES));
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if (!CreatePipe(&ret.child_stdout, &startup_info.hStdOutput, &saAttr, 0)) Checks::exit_fail(VCPKG_LINE_INFO);
// Ensure the read handle to the pipe for STDOUT is not inherited.
if (!SetHandleInformation(ret.child_stdout, HANDLE_FLAG_INHERIT, 0)) Checks::exit_fail(VCPKG_LINE_INFO);
// Create a pipe for the child process's STDIN.
if (!CreatePipe(&startup_info.hStdInput, &ret.child_stdin, &saAttr, 0)) Checks::exit_fail(VCPKG_LINE_INFO);
// Ensure the write handle to the pipe for STDIN is not inherited.
if (!SetHandleInformation(ret.child_stdin, HANDLE_FLAG_INHERIT, 0)) Checks::exit_fail(VCPKG_LINE_INFO);
startup_info.hStdError = startup_info.hStdOutput;
auto maybe_proc_info = windows_create_process(cmd_line, wd, env, dwCreationFlags, startup_info);
CloseHandle(startup_info.hStdInput);
CloseHandle(startup_info.hStdOutput);
if (auto proc_info = maybe_proc_info.get())
{
ret.proc_info = std::move(*proc_info);
return std::move(ret);
}
else
{
return maybe_proc_info.error();
}
}
#endif
#if defined(_WIN32)
void System::cmd_execute_background(StringView cmd_line)
{
auto timer = Chrono::ElapsedTimer::create_started();
auto process_info =
windows_create_windowless_process(cmd_line,
InWorkingDirectory{fs::path()},
{},
CREATE_NEW_CONSOLE | CREATE_NO_WINDOW | CREATE_BREAKAWAY_FROM_JOB);
if (!process_info.get())
{
Debug::print("cmd_execute_background() failed with error code ", process_info.error(), "\n");
}
Debug::print("cmd_execute_background() took ", static_cast<int>(timer.microseconds()), " us\n");
}
Environment System::cmd_execute_modify_env(StringView cmd_line, const Environment& env)
{
static StringLiteral magic_string = "cdARN4xjKueKScMy9C6H";
auto actual_cmd_line = Strings::concat(cmd_line, " & echo ", magic_string, "& set");
auto rc_output = cmd_execute_and_capture_output(actual_cmd_line, env);
Checks::check_exit(VCPKG_LINE_INFO, rc_output.exit_code == 0);
auto it = Strings::search(rc_output.output, Strings::concat(magic_string, "\r\n"));
const auto e = static_cast<const char*>(rc_output.output.data()) + rc_output.output.size();
Checks::check_exit(VCPKG_LINE_INFO, it != e);
it += magic_string.size() + 2;
std::wstring out_env;
for (;;)
{
auto eq = std::find(it, e, '=');
if (eq == e) break;
StringView varname(it, eq);
auto nl = std::find(eq + 1, e, '\r');
if (nl == e) break;
StringView value(eq + 1, nl);
out_env.append(Strings::to_utf16(Strings::concat(varname, '=', value)));
out_env.push_back(L'\0');
it = nl + 1;
if (it != e && *it == '\n') ++it;
}
return {std::move(out_env)};
}
#endif
int System::cmd_execute(StringView cmd_line, System::InWorkingDirectory wd, const Environment& env)
{
auto timer = Chrono::ElapsedTimer::create_started();
#if defined(_WIN32)
using vcpkg::g_ctrl_c_state;
g_ctrl_c_state.transition_to_spawn_process();
auto proc_info = windows_create_windowless_process(cmd_line, wd, env, 0);
auto long_exit_code = [&]() -> unsigned long {
if (auto p = proc_info.get())
return p->wait();
else
return proc_info.error();
}();
if (long_exit_code > INT_MAX) long_exit_code = INT_MAX;
int exit_code = static_cast<int>(long_exit_code);
g_ctrl_c_state.transition_from_spawn_process();
Debug::print(
"cmd_execute() returned ", exit_code, " after ", static_cast<unsigned int>(timer.microseconds()), " us\n");
#else
(void)env;
std::string real_command_line;
if (wd.working_directory.empty())
{
real_command_line.assign(cmd_line.begin(), cmd_line.end());
}
else
{
real_command_line =
System::CmdLineBuilder("cd").path_arg(wd.working_directory).raw_arg("&&").raw_arg(cmd_line).extract();
}
Debug::print("system(", real_command_line, ")\n");
fflush(nullptr);
int exit_code = system(real_command_line.c_str());
Debug::print(
"system() returned ", exit_code, " after ", static_cast<unsigned int>(timer.microseconds()), " us\n");
#endif
return exit_code;
}
int System::cmd_execute_and_stream_lines(StringView cmd_line,
System::InWorkingDirectory wd,
std::function<void(StringView)> per_line_cb,
const Environment& env)
{
std::string buf;
auto rc = cmd_execute_and_stream_data(
cmd_line,
wd,
[&](StringView sv) {
auto prev_size = buf.size();
Strings::append(buf, sv);
auto it = std::find(buf.begin() + prev_size, buf.end(), '\n');
while (it != buf.end())
{
std::string s(buf.begin(), it);
per_line_cb(s);
buf.erase(buf.begin(), it + 1);
it = std::find(buf.begin(), buf.end(), '\n');
}
},
env);
per_line_cb(buf);
return rc;
}
int System::cmd_execute_and_stream_data(StringView cmd_line,
System::InWorkingDirectory wd,
std::function<void(StringView)> data_cb,
const Environment& env)
{
auto timer = Chrono::ElapsedTimer::create_started();
#if defined(_WIN32)
using vcpkg::g_ctrl_c_state;
g_ctrl_c_state.transition_to_spawn_process();
auto maybe_proc_info = windows_create_process_redirect(cmd_line, wd, env, 0);
auto exit_code = [&]() -> unsigned long {
if (auto p = maybe_proc_info.get())
return p->wait_and_stream_output(data_cb);
else
return maybe_proc_info.error();
}();
g_ctrl_c_state.transition_from_spawn_process();
#else
(void)env;
std::string actual_cmd_line;
if (wd.working_directory.empty())
{
actual_cmd_line = Strings::format(R"(%s 2>&1)", cmd_line);
}
else
{
actual_cmd_line = System::CmdLineBuilder("cd")
.path_arg(wd.working_directory)
.raw_arg("&&")
.raw_arg(cmd_line)
.raw_arg("2>&1")
.extract();
}
Debug::print("popen(", actual_cmd_line, ")\n");
// Flush stdout before launching external process
fflush(stdout);
const auto pipe = popen(actual_cmd_line.c_str(), "r");
if (pipe == nullptr)
{
return 1;
}
char buf[1024];
while (fgets(buf, 1024, pipe))
{
data_cb(StringView{buf, strlen(buf)});
}
if (!feof(pipe))
{
return 1;
}
const auto exit_code = pclose(pipe);
#endif
Debug::print("cmd_execute_and_stream_data() returned ",
exit_code,
" after ",
Strings::format("%8d", static_cast<int>(timer.microseconds())),
" us\n");
return exit_code;
}
ExitCodeAndOutput System::cmd_execute_and_capture_output(StringView cmd_line,
System::InWorkingDirectory wd,
const Environment& env)
{
std::string output;
auto rc = cmd_execute_and_stream_data(
cmd_line, wd, [&](StringView sv) { Strings::append(output, sv); }, env);
return {rc, std::move(output)};
}
#if defined(_WIN32)
static BOOL ctrl_handler(DWORD fdw_ctrl_type)
{
switch (fdw_ctrl_type)
{
case CTRL_C_EVENT: g_ctrl_c_state.transition_handle_ctrl_c(); return TRUE;
default: return FALSE;
}
}
void System::register_console_ctrl_handler()
{
SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(ctrl_handler), TRUE);
}
#else
void System::register_console_ctrl_handler() { }
#endif
}
|
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "csegmentbutton.h"
#include "../cdrawcontext.h"
#include "../cframe.h"
#include "../cgraphicspath.h"
#include "../events.h"
#include <algorithm>
namespace VSTGUI {
//-----------------------------------------------------------------------------
CSegmentButton::CSegmentButton (const CRect& size, IControlListener* listener, int32_t tag)
: CControl (size, listener, tag), font (kNormalFont)
{
setWantsFocus (true);
}
//-----------------------------------------------------------------------------
bool CSegmentButton::canAddOneMoreSegment () const
{
return (getSelectionMode () != SelectionMode::kMultiple || segments.size () < 32);
}
//-----------------------------------------------------------------------------
bool CSegmentButton::addSegment (const Segment& segment, uint32_t index)
{
if (!canAddOneMoreSegment ())
return false;
if (index == kPushBack && segments.size () < kPushBack)
segments.emplace_back (segment);
else if (index < segments.size ())
{
auto it = segments.begin ();
std::advance (it, index);
segments.insert (it, segment);
}
updateSegmentSizes ();
return true;
}
//-----------------------------------------------------------------------------
bool CSegmentButton::addSegment (Segment&& segment, uint32_t index)
{
if (!canAddOneMoreSegment ())
return false;
if (index == kPushBack && segments.size () < kPushBack)
segments.emplace_back (std::move (segment));
else if (index < segments.size ())
{
auto it = segments.begin ();
std::advance (it, index);
segments.insert (it, std::move (segment));
}
updateSegmentSizes ();
return true;
}
//-----------------------------------------------------------------------------
void CSegmentButton::removeSegment (uint32_t index)
{
if (index < segments.size ())
{
auto it = segments.begin ();
std::advance (it, index);
segments.erase (it);
}
updateSegmentSizes ();
}
//-----------------------------------------------------------------------------
void CSegmentButton::removeAllSegments ()
{
segments.clear ();
invalid ();
}
//-----------------------------------------------------------------------------
void CSegmentButton::valueChanged ()
{
switch (getSelectionMode ())
{
case SelectionMode::kSingle:
case SelectionMode::kSingleToggle:
{
auto index = static_cast<int64_t> (getSelectedSegment ());
for (auto& segment : segments)
{
bool state = index == 0;
if (state != segment.selected)
{
segment.selected = state;
invalidRect (segment.rect);
}
--index;
}
break;
}
case SelectionMode::kMultiple:
{
auto bitset = static_cast<uint32_t> (value);
size_t index = 0;
for (auto& segment : segments)
{
bool state = (hasBit (bitset, 1 << index));
if (state != segment.selected)
{
segment.selected = state;
invalidRect (segment.rect);
}
++index;
}
break;
}
}
CControl::valueChanged ();
}
//-----------------------------------------------------------------------------
void CSegmentButton::setSelectedSegment (uint32_t index)
{
if (index >= segments.size ())
return;
beginEdit ();
setValueNormalized (static_cast<float> (index) / static_cast<float> (segments.size () - 1));
valueChanged ();
endEdit ();
}
//-----------------------------------------------------------------------------
uint32_t CSegmentButton::getSelectedSegment () const
{
return getSegmentIndex (getValueNormalized ());
}
//-----------------------------------------------------------------------------
void CSegmentButton::setStyle (Style newStyle)
{
if (style != newStyle)
{
style = newStyle;
updateSegmentSizes ();
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setSelectionMode (SelectionMode mode)
{
if (mode != selectionMode)
{
selectionMode = mode;
if (isAttached ())
{
verifySelections ();
invalid ();
}
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextTruncateMode (CDrawMethods::TextTruncateMode mode)
{
if (textTruncateMode != mode)
{
textTruncateMode = mode;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setGradient (CGradient* newGradient)
{
if (gradient != newGradient)
{
gradient = newGradient;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setGradientHighlighted (CGradient* newGradient)
{
if (gradientHighlighted != newGradient)
{
gradientHighlighted = newGradient;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setRoundRadius (CCoord newRoundRadius)
{
if (roundRadius != newRoundRadius)
{
roundRadius = newRoundRadius;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setFont (CFontRef newFont)
{
if (font != newFont)
{
font = newFont;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextAlignment (CHoriTxtAlign newAlignment)
{
if (textAlignment != newAlignment)
{
textAlignment = newAlignment;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextMargin (CCoord newMargin)
{
if (textMargin != newMargin)
{
textMargin = newMargin;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextColor (CColor newColor)
{
if (textColor != newColor)
{
textColor = newColor;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setTextColorHighlighted (CColor newColor)
{
if (textColorHighlighted != newColor)
{
textColorHighlighted = newColor;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setFrameColor (CColor newColor)
{
if (frameColor != newColor)
{
frameColor = newColor;
invalid ();
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::setFrameWidth (CCoord newWidth)
{
if (frameWidth != newWidth)
{
frameWidth = newWidth;
invalid ();
}
}
//-----------------------------------------------------------------------------
bool CSegmentButton::attached (CView* parent)
{
if (CControl::attached (parent))
{
verifySelections ();
updateSegmentSizes ();
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void CSegmentButton::setViewSize (const CRect& rect, bool invalid)
{
CControl::setViewSize (rect, invalid);
updateSegmentSizes ();
}
//------------------------------------------------------------------------
void CSegmentButton::selectSegment (uint32_t index, bool state)
{
beginEdit ();
auto bitset = static_cast<uint32_t> (value);
setBit (bitset, (1 << index), state);
value = static_cast<float> (bitset);
valueChanged ();
endEdit ();
}
//------------------------------------------------------------------------
bool CSegmentButton::isSegmentSelected (uint32_t index) const
{
return segments[index].selected;
}
//-----------------------------------------------------------------------------
CMouseEventResult CSegmentButton::onMouseDown (CPoint& where, const CButtonState& buttons)
{
if (buttons.isLeftButton ())
{
float newValue = 0;
float valueOffset = 1.f / (segments.size () - 1);
for (auto& segment : segments)
{
if (segment.rect.pointInside (where))
{
uint32_t newIndex = getSegmentIndex (newValue);
switch (selectionMode)
{
case SelectionMode::kSingle:
{
uint32_t currentIndex = getSegmentIndex (getValueNormalized ());
if (newIndex != currentIndex)
setSelectedSegment (newIndex);
break;
}
case SelectionMode::kSingleToggle:
{
uint32_t currentIndex = getSegmentIndex (getValueNormalized ());
if (newIndex != currentIndex)
setSelectedSegment (newIndex);
else
{
++currentIndex;
if (getSegments ().size () - 1 < currentIndex)
currentIndex = 0;
setSelectedSegment (currentIndex);
}
break;
}
case SelectionMode::kMultiple:
{
selectSegment (newIndex, !segment.selected);
break;
}
}
break; // out of for loop
}
newValue += valueOffset;
// Last segment can lead to newValue > 1.0
newValue = std::min(newValue, 1.f);
}
}
return kMouseDownEventHandledButDontNeedMovedOrUpEvents;
}
//-----------------------------------------------------------------------------
void CSegmentButton::onKeyboardEvent (KeyboardEvent& event)
{
if (event.type != EventType::KeyDown || event.modifiers.empty () == false ||
event.character != 0)
return;
if (selectionMode != SelectionMode::kMultiple)
{
uint32_t newIndex = getSegmentIndex (getValueNormalized ());
uint32_t oldIndex = newIndex;
switch (event.virt)
{
case VirtualKey::Left:
{
if (style == Style::kHorizontal && newIndex > 0)
newIndex--;
else if (style == Style::kHorizontalInverse && newIndex < segments.size () - 1)
newIndex++;
event.consumed = true;
break;
}
case VirtualKey::Right:
{
if (style == Style::kHorizontal && newIndex < segments.size () - 1)
newIndex++;
else if (style == Style::kHorizontalInverse && newIndex > 0)
newIndex--;
event.consumed = true;
break;
}
case VirtualKey::Up:
{
if (style == Style::kVertical && newIndex > 0)
newIndex--;
else if (style == Style::kVerticalInverse && newIndex < segments.size () - 1)
newIndex++;
event.consumed = true;
break;
}
case VirtualKey::Down:
{
if (style == Style::kVertical && newIndex < segments.size () - 1)
newIndex++;
else if (style == Style::kVerticalInverse && newIndex > 0)
newIndex--;
event.consumed = true;
break;
}
default: return;
}
if (newIndex != oldIndex)
{
setSelectedSegment (newIndex);
}
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::draw (CDrawContext* pContext)
{
CView::draw (pContext);
}
//-----------------------------------------------------------------------------
void CSegmentButton::drawRect (CDrawContext* pContext, const CRect& dirtyRect)
{
if (getOldValue () != getValue ())
verifySelections ();
bool isHorizontal = isHorizontalStyle (style);
bool drawLines = getFrameWidth () != 0. && getFrameColor ().alpha != 0;
auto lineWidth = getFrameWidth ();
if (lineWidth < 0.)
{
lineWidth = pContext->getHairlineSize ();
}
SharedPointer<CGraphicsPath> path;
if (gradient || gradientHighlighted || drawLines)
{
CRect r (getViewSize ());
r.inset (lineWidth / 2., lineWidth / 2.);
path = owned (pContext->createGraphicsPath ());
if (!path)
return;
path->addRoundRect (r, getRoundRadius ());
}
pContext->setDrawMode (kAntiAliasing);
if (drawLines)
{
pContext->setLineStyle (kLineSolid);
pContext->setLineWidth (lineWidth);
pContext->setFrameColor (getFrameColor ());
}
if (gradient)
{
if (isHorizontal)
{
pContext->fillLinearGradient (path, *gradient, getViewSize ().getTopLeft (),
getViewSize ().getBottomLeft ());
}
else
{
pContext->fillLinearGradient (path, *gradient, getViewSize ().getTopLeft (),
getViewSize ().getTopRight ());
}
}
auto lineIndexStart = 1u;
auto lineIndexEnd = segments.size ();
if (isInverseStyle (style))
{
--lineIndexStart;
--lineIndexEnd;
}
for (uint32_t index = 0u, end = static_cast<uint32_t> (segments.size ()); index < end; ++index)
{
const auto& segment = segments[index];
if (!dirtyRect.rectOverlap (segment.rect))
continue;
drawClipped (pContext, segment.rect, [&] () {
if (segment.selected && gradientHighlighted)
{
if (isHorizontal)
{
pContext->fillLinearGradient (path, *gradientHighlighted,
segment.rect.getTopLeft (),
segment.rect.getBottomLeft ());
}
else
{
pContext->fillLinearGradient (path, *gradientHighlighted,
segment.rect.getTopLeft (),
segment.rect.getTopRight ());
}
}
if (segment.selected && segment.backgroundHighlighted)
{
segment.backgroundHighlighted->draw (pContext, segment.rect);
}
else if (segment.background)
{
segment.background->draw (pContext, segment.rect);
}
CDrawMethods::drawIconAndText (
pContext, segment.selected ? segment.iconHighlighted : segment.icon,
segment.iconPosition, textAlignment, textMargin, segment.rect, segment.name, font,
segment.selected ? textColorHighlighted : textColor, textTruncateMode);
});
if (drawLines && index >= lineIndexStart && index < lineIndexEnd)
{
path->beginSubpath (segment.rect.getTopLeft ());
path->addLine (isHorizontal ? segment.rect.getBottomLeft () :
segment.rect.getTopRight ());
}
}
if (drawLines)
pContext->drawGraphicsPath (path, CDrawContext::kPathStroked);
setDirty (false);
}
//-----------------------------------------------------------------------------
uint32_t CSegmentButton::getSegmentIndex (float value) const
{
if (value < 0.f || value > 1.f)
return kPushBack;
const auto segmentIndex = static_cast<float> (segments.size () - 1) * value;
const auto segmentIndexRounded = static_cast<uint32_t> (segmentIndex + 0.5f);
return segmentIndexRounded;
}
//-----------------------------------------------------------------------------
void CSegmentButton::updateSegmentSizes ()
{
if (isAttached () && !segments.empty ())
{
switch (style)
{
case Style::kHorizontal:
{
CCoord width = getWidth () / segments.size ();
CRect r (getViewSize ());
r.setWidth (width);
for (auto& segment : segments)
{
segment.rect = r;
r.offset (width, 0);
}
break;
}
case Style::kHorizontalInverse:
{
CCoord width = getWidth () / segments.size ();
CRect r (getViewSize ());
r.setWidth (width);
for (auto it = segments.rbegin(); it != segments.rend(); ++it)
{
(*it).rect = r;
r.offset (width, 0);
}
break;
}
case Style::kVertical:
{
CCoord height = getHeight () / segments.size ();
CRect r (getViewSize ());
r.setHeight (height);
for (auto& segment : segments)
{
segment.rect = r;
r.offset (0, height);
}
break;
}
case Style::kVerticalInverse:
{
CCoord height = getHeight () / segments.size ();
CRect r (getViewSize ());
r.setHeight (height);
for (auto it = segments.rbegin(); it != segments.rend(); ++it)
{
(*it).rect = r;
r.offset (0, height);
}
break;
}
}
}
}
//-----------------------------------------------------------------------------
void CSegmentButton::verifySelections ()
{
if (selectionMode == SelectionMode::kMultiple)
{
auto bitset = static_cast<uint32_t> (value);
for (auto index = 0u; index < segments.size (); ++index)
{
segments[index].selected = (bitset & (1 << index)) != 0;
}
}
else
{
auto selectedIndex = getSelectedSegment ();
if (selectedIndex > segments.size ())
selectedIndex = 0;
for (auto& segment : segments)
segment.selected = false;
segments[selectedIndex].selected = true;
}
}
//-----------------------------------------------------------------------------
bool CSegmentButton::drawFocusOnTop ()
{
return false;
}
//-----------------------------------------------------------------------------
bool CSegmentButton::getFocusPath (CGraphicsPath& outPath)
{
auto lineWidth = getFrameWidth ();
if (lineWidth < 0.)
lineWidth = 1.;
CRect r (getViewSize ());
r.inset (lineWidth / 2., lineWidth / 2.);
outPath.addRoundRect (r, getRoundRadius ());
CCoord focusWidth = getFrame ()->getFocusWidth ();
r.extend (focusWidth, focusWidth);
outPath.addRoundRect (r, getRoundRadius ());
return true;
}
} // VSTGUI
|
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: mheule@google.com (Markus Heule)
//
// Google C++ Testing Framework (Google Test)
//
// Sometimes it's desirable to build Google Test by compiling a single file.
// This file serves this purpose.
// This line ensures that gtest.h can be compiled on its own, even
// when it's fused.
#include "gtest/gtest.h"
// The following lines pull in the real gtest *.cc files.
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// The Google C++ Testing Framework (Google Test)
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Utilities for testing Google Test itself and code that uses Google Test
// (e.g. frameworks built on top of Google Test).
#ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_
#define GTEST_INCLUDE_GTEST_GTEST_SPI_H_
namespace testing {
// This helper class can be used to mock out Google Test failure reporting
// so that we can test Google Test or code that builds on Google Test.
//
// An object of this class appends a TestPartResult object to the
// TestPartResultArray object given in the constructor whenever a Google Test
// failure is reported. It can either intercept only failures that are
// generated in the same thread that created this object or it can intercept
// all generated failures. The scope of this mock object can be controlled with
// the second argument to the two arguments constructor.
class GTEST_API_ ScopedFakeTestPartResultReporter
: public TestPartResultReporterInterface {
public:
// The two possible mocking modes of this object.
enum InterceptMode {
INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures.
INTERCEPT_ALL_THREADS // Intercepts all failures.
};
// The c'tor sets this object as the test part result reporter used
// by Google Test. The 'result' parameter specifies where to report the
// results. This reporter will only catch failures generated in the current
// thread. DEPRECATED
explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);
// Same as above, but you can choose the interception scope of this object.
ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,
TestPartResultArray* result);
// The d'tor restores the previous test part result reporter.
virtual ~ScopedFakeTestPartResultReporter();
// Appends the TestPartResult object to the TestPartResultArray
// received in the constructor.
//
// This method is from the TestPartResultReporterInterface
// interface.
virtual void ReportTestPartResult(const TestPartResult& result);
private:
void Init();
const InterceptMode intercept_mode_;
TestPartResultReporterInterface* old_reporter_;
TestPartResultArray* const result_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter);
};
namespace internal {
// A helper class for implementing EXPECT_FATAL_FAILURE() and
// EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given
// TestPartResultArray contains exactly one failure that has the given
// type and contains the given substring. If that's not the case, a
// non-fatal failure will be generated.
class GTEST_API_ SingleFailureChecker {
public:
// The constructor remembers the arguments.
SingleFailureChecker(const TestPartResultArray* results,
TestPartResult::Type type,
const string& substr);
~SingleFailureChecker();
private:
const TestPartResultArray* const results_;
const TestPartResult::Type type_;
const string substr_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker);
};
} // namespace internal
} // namespace testing
// A set of macros for testing Google Test assertions or code that's expected
// to generate Google Test fatal failures. It verifies that the given
// statement will cause exactly one fatal Google Test failure with 'substr'
// being part of the failure message.
//
// There are two different versions of this macro. EXPECT_FATAL_FAILURE only
// affects and considers failures generated in the current thread and
// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
//
// The verification of the assertion is done correctly even when the statement
// throws an exception or aborts the current function.
//
// Known restrictions:
// - 'statement' cannot reference local non-static variables or
// non-static members of the current object.
// - 'statement' cannot return a value.
// - You cannot stream a failure message to this macro.
//
// Note that even though the implementations of the following two
// macros are much alike, we cannot refactor them to use a common
// helper macro, due to some peculiarity in how the preprocessor
// works. The AcceptsMacroThatExpandsToUnprotectedComma test in
// gtest_unittest.cc will fail to compile if we do that.
#define EXPECT_FATAL_FAILURE(statement, substr) \
do { \
class GTestExpectFatalFailureHelper {\
public:\
static void Execute() { statement; }\
};\
::testing::TestPartResultArray gtest_failures;\
::testing::internal::SingleFailureChecker gtest_checker(\
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
{\
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
GTestExpectFatalFailureHelper::Execute();\
}\
} while (::testing::internal::AlwaysFalse())
#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
do { \
class GTestExpectFatalFailureHelper {\
public:\
static void Execute() { statement; }\
};\
::testing::TestPartResultArray gtest_failures;\
::testing::internal::SingleFailureChecker gtest_checker(\
>est_failures, ::testing::TestPartResult::kFatalFailure, (substr));\
{\
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ALL_THREADS, >est_failures);\
GTestExpectFatalFailureHelper::Execute();\
}\
} while (::testing::internal::AlwaysFalse())
// A macro for testing Google Test assertions or code that's expected to
// generate Google Test non-fatal failures. It asserts that the given
// statement will cause exactly one non-fatal Google Test failure with 'substr'
// being part of the failure message.
//
// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only
// affects and considers failures generated in the current thread and
// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.
//
// 'statement' is allowed to reference local variables and members of
// the current object.
//
// The verification of the assertion is done correctly even when the statement
// throws an exception or aborts the current function.
//
// Known restrictions:
// - You cannot stream a failure message to this macro.
//
// Note that even though the implementations of the following two
// macros are much alike, we cannot refactor them to use a common
// helper macro, due to some peculiarity in how the preprocessor
// works. If we do that, the code won't compile when the user gives
// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that
// expands to code containing an unprotected comma. The
// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc
// catches that.
//
// For the same reason, we have to write
// if (::testing::internal::AlwaysTrue()) { statement; }
// instead of
// GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)
// to avoid an MSVC warning on unreachable code.
#define EXPECT_NONFATAL_FAILURE(statement, substr) \
do {\
::testing::TestPartResultArray gtest_failures;\
::testing::internal::SingleFailureChecker gtest_checker(\
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
(substr));\
{\
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
::testing::ScopedFakeTestPartResultReporter:: \
INTERCEPT_ONLY_CURRENT_THREAD, >est_failures);\
if (::testing::internal::AlwaysTrue()) { statement; }\
}\
} while (::testing::internal::AlwaysFalse())
#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \
do {\
::testing::TestPartResultArray gtest_failures;\
::testing::internal::SingleFailureChecker gtest_checker(\
>est_failures, ::testing::TestPartResult::kNonFatalFailure, \
(substr));\
{\
::testing::ScopedFakeTestPartResultReporter gtest_reporter(\
::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \
>est_failures);\
if (::testing::internal::AlwaysTrue()) { statement; }\
}\
} while (::testing::internal::AlwaysFalse())
#endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
#include <ctype.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>
#include <algorithm>
#include <iomanip>
#include <limits>
#include <ostream> // NOLINT
#include <sstream>
#include <vector>
#if GTEST_OS_LINUX
// TODO(kenton@google.com): Use autoconf to detect availability of
// gettimeofday().
# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <fcntl.h> // NOLINT
# include <limits.h> // NOLINT
# include <sched.h> // NOLINT
// Declares vsnprintf(). This header is not available on Windows.
# include <strings.h> // NOLINT
# include <sys/mman.h> // NOLINT
# include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT
# include <string>
#elif GTEST_OS_SYMBIAN
# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
#elif GTEST_OS_ZOS
# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
// On z/OS we additionally need strings.h for strcasecmp.
# include <strings.h> // NOLINT
#elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE.
# include <windows.h> // NOLINT
#elif GTEST_OS_WINDOWS // We are on Windows proper.
# include <io.h> // NOLINT
# include <sys/timeb.h> // NOLINT
# include <sys/types.h> // NOLINT
# include <sys/stat.h> // NOLINT
# if GTEST_OS_WINDOWS_MINGW
// MinGW has gettimeofday() but not _ftime64().
// TODO(kenton@google.com): Use autoconf to detect availability of
// gettimeofday().
// TODO(kenton@google.com): There are other ways to get the time on
// Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW
// supports these. consider using them instead.
# define GTEST_HAS_GETTIMEOFDAY_ 1
# include <sys/time.h> // NOLINT
# endif // GTEST_OS_WINDOWS_MINGW
// cpplint thinks that the header is already included, so we want to
// silence it.
# include <windows.h> // NOLINT
#else
// Assume other platforms have gettimeofday().
// TODO(kenton@google.com): Use autoconf to detect availability of
// gettimeofday().
# define GTEST_HAS_GETTIMEOFDAY_ 1
// cpplint thinks that the header is already included, so we want to
// silence it.
# include <sys/time.h> // NOLINT
# include <unistd.h> // NOLINT
#endif // GTEST_OS_LINUX
#if GTEST_HAS_EXCEPTIONS
# include <stdexcept>
#endif
#if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT
#endif
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
#define GTEST_IMPLEMENTATION_ 1
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Utility functions and classes used by the Google C++ testing framework.
//
// Author: wan@google.com (Zhanyong Wan)
//
// This file contains purely Google Test's internal implementation. Please
// DO NOT #INCLUDE IT IN A USER PROGRAM.
#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_
#define GTEST_SRC_GTEST_INTERNAL_INL_H_
// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is
// part of Google Test's implementation; otherwise it's undefined.
#if !GTEST_IMPLEMENTATION_
// A user is trying to include this from his code - just say no.
# error "gtest-internal-inl.h is part of Google Test's internal implementation."
# error "It must not be included except by Google Test itself."
#endif // GTEST_IMPLEMENTATION_
#ifndef _WIN32_WCE
# include <errno.h>
#endif // !_WIN32_WCE
#include <stddef.h>
#include <stdlib.h> // For strtoll/_strtoul64/malloc/free.
#include <string.h> // For memmove.
#include <algorithm>
#include <string>
#include <vector>
#if GTEST_CAN_STREAM_RESULTS_
# include <arpa/inet.h> // NOLINT
# include <netdb.h> // NOLINT
#endif
#if GTEST_OS_WINDOWS
# include <windows.h> // NOLINT
#endif // GTEST_OS_WINDOWS
namespace testing {
// Declares the flags.
//
// We don't want the users to modify this flag in the code, but want
// Google Test's own unit tests to be able to access it. Therefore we
// declare it here as opposed to in gtest.h.
GTEST_DECLARE_bool_(death_test_use_fork);
namespace internal {
// The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId().
GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;
// Names of the flags (needed for parsing Google Test flags).
const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests";
const char kBreakOnFailureFlag[] = "break_on_failure";
const char kCatchExceptionsFlag[] = "catch_exceptions";
const char kColorFlag[] = "color";
const char kFilterFlag[] = "filter";
const char kListTestsFlag[] = "list_tests";
const char kOutputFlag[] = "output";
const char kPrintTimeFlag[] = "print_time";
const char kRandomSeedFlag[] = "random_seed";
const char kRepeatFlag[] = "repeat";
const char kShuffleFlag[] = "shuffle";
const char kStackTraceDepthFlag[] = "stack_trace_depth";
const char kStreamResultToFlag[] = "stream_result_to";
const char kThrowOnFailureFlag[] = "throw_on_failure";
// A valid random seed must be in [1, kMaxRandomSeed].
const int kMaxRandomSeed = 99999;
// g_help_flag is true iff the --help flag or an equivalent form is
// specified on the command line.
GTEST_API_ extern bool g_help_flag;
// Returns the current time in milliseconds.
GTEST_API_ TimeInMillis GetTimeInMillis();
// Returns true iff Google Test should use colors in the output.
GTEST_API_ bool ShouldUseColor(bool stdout_is_tty);
// Formats the given time in milliseconds as seconds.
GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);
// Converts the given time in milliseconds to a date string in the ISO 8601
// format, without the timezone information. N.B.: due to the use the
// non-reentrant localtime() function, this function is not thread safe. Do
// not use it in any code that can be called from multiple threads.
GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);
// Parses a string for an Int32 flag, in the form of "--flag=value".
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
GTEST_API_ bool ParseInt32Flag(
const char* str, const char* flag, Int32* value);
// Returns a random seed in range [1, kMaxRandomSeed] based on the
// given --gtest_random_seed flag value.
inline int GetRandomSeedFromFlag(Int32 random_seed_flag) {
const unsigned int raw_seed = (random_seed_flag == 0) ?
static_cast<unsigned int>(GetTimeInMillis()) :
static_cast<unsigned int>(random_seed_flag);
// Normalizes the actual seed to range [1, kMaxRandomSeed] such that
// it's easy to type.
const int normalized_seed =
static_cast<int>((raw_seed - 1U) %
static_cast<unsigned int>(kMaxRandomSeed)) + 1;
return normalized_seed;
}
// Returns the first valid random seed after 'seed'. The behavior is
// undefined if 'seed' is invalid. The seed after kMaxRandomSeed is
// considered to be 1.
inline int GetNextRandomSeed(int seed) {
GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)
<< "Invalid random seed " << seed << " - must be in [1, "
<< kMaxRandomSeed << "].";
const int next_seed = seed + 1;
return (next_seed > kMaxRandomSeed) ? 1 : next_seed;
}
// This class saves the values of all Google Test flags in its c'tor, and
// restores them in its d'tor.
class GTestFlagSaver {
public:
// The c'tor.
GTestFlagSaver() {
also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);
break_on_failure_ = GTEST_FLAG(break_on_failure);
catch_exceptions_ = GTEST_FLAG(catch_exceptions);
color_ = GTEST_FLAG(color);
death_test_style_ = GTEST_FLAG(death_test_style);
death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);
filter_ = GTEST_FLAG(filter);
internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);
list_tests_ = GTEST_FLAG(list_tests);
output_ = GTEST_FLAG(output);
print_time_ = GTEST_FLAG(print_time);
random_seed_ = GTEST_FLAG(random_seed);
repeat_ = GTEST_FLAG(repeat);
shuffle_ = GTEST_FLAG(shuffle);
stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);
stream_result_to_ = GTEST_FLAG(stream_result_to);
throw_on_failure_ = GTEST_FLAG(throw_on_failure);
}
// The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS.
~GTestFlagSaver() {
GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;
GTEST_FLAG(break_on_failure) = break_on_failure_;
GTEST_FLAG(catch_exceptions) = catch_exceptions_;
GTEST_FLAG(color) = color_;
GTEST_FLAG(death_test_style) = death_test_style_;
GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;
GTEST_FLAG(filter) = filter_;
GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;
GTEST_FLAG(list_tests) = list_tests_;
GTEST_FLAG(output) = output_;
GTEST_FLAG(print_time) = print_time_;
GTEST_FLAG(random_seed) = random_seed_;
GTEST_FLAG(repeat) = repeat_;
GTEST_FLAG(shuffle) = shuffle_;
GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;
GTEST_FLAG(stream_result_to) = stream_result_to_;
GTEST_FLAG(throw_on_failure) = throw_on_failure_;
}
private:
// Fields for saving the original values of flags.
bool also_run_disabled_tests_;
bool break_on_failure_;
bool catch_exceptions_;
std::string color_;
std::string death_test_style_;
bool death_test_use_fork_;
std::string filter_;
std::string internal_run_death_test_;
bool list_tests_;
std::string output_;
bool print_time_;
internal::Int32 random_seed_;
internal::Int32 repeat_;
bool shuffle_;
internal::Int32 stack_trace_depth_;
std::string stream_result_to_;
bool throw_on_failure_;
} GTEST_ATTRIBUTE_UNUSED_;
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be
// wide enough to contain a code point.
// If the code_point is not a valid Unicode code point
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
// to "(Invalid Unicode 0xXXXXXXXX)".
GTEST_API_ std::string CodePointToUtf8(UInt32 code_point);
// Converts a wide string to a narrow string in UTF-8 encoding.
// The wide string is assumed to have the following encoding:
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
// Parameter str points to a null-terminated wide string.
// Parameter num_chars may additionally limit the number
// of wchar_t characters processed. -1 is used when the entire string
// should be processed.
// If the string contains code points that are not valid Unicode code points
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
// and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane.
GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this
// function will write over it. If the variable is present, but the file cannot
// be created, prints an error and exits.
void WriteToShardStatusFileIfNeeded();
// Checks whether sharding is enabled by examining the relevant
// environment variable values. If the variables are present,
// but inconsistent (e.g., shard_index >= total_shards), prints
// an error and exits. If in_subprocess_for_death_test, sharding is
// disabled because it must only be applied to the original test
// process. Otherwise, we could filter out death tests we intended to execute.
GTEST_API_ bool ShouldShard(const char* total_shards_str,
const char* shard_index_str,
bool in_subprocess_for_death_test);
// Parses the environment variable var as an Int32. If it is unset,
// returns default_val. If it is not an Int32, prints an error and
// and aborts.
GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);
// Given the total number of shards, the shard index, and the test id,
// returns true iff the test should be run on this shard. The test id is
// some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards.
GTEST_API_ bool ShouldRunTestOnShard(
int total_shards, int shard_index, int test_id);
// STL container utilities.
// Returns the number of elements in the given container that satisfy
// the given predicate.
template <class Container, typename Predicate>
inline int CountIf(const Container& c, Predicate predicate) {
// Implemented as an explicit loop since std::count_if() in libCstd on
// Solaris has a non-standard signature.
int count = 0;
for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {
if (predicate(*it))
++count;
}
return count;
}
// Applies a function/functor to each element in the container.
template <class Container, typename Functor>
void ForEach(const Container& c, Functor functor) {
std::for_each(c.begin(), c.end(), functor);
}
// Returns the i-th element of the vector, or default_value if i is not
// in range [0, v.size()).
template <typename E>
inline E GetElementOr(const std::vector<E>& v, int i, E default_value) {
return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];
}
// Performs an in-place shuffle of a range of the vector's elements.
// 'begin' and 'end' are element indices as an STL-style range;
// i.e. [begin, end) are shuffled, where 'end' == size() means to
// shuffle to the end of the vector.
template <typename E>
void ShuffleRange(internal::Random* random, int begin, int end,
std::vector<E>* v) {
const int size = static_cast<int>(v->size());
GTEST_CHECK_(0 <= begin && begin <= size)
<< "Invalid shuffle range start " << begin << ": must be in range [0, "
<< size << "].";
GTEST_CHECK_(begin <= end && end <= size)
<< "Invalid shuffle range finish " << end << ": must be in range ["
<< begin << ", " << size << "].";
// Fisher-Yates shuffle, from
// http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
for (int range_width = end - begin; range_width >= 2; range_width--) {
const int last_in_range = begin + range_width - 1;
const int selected = begin + random->Generate(range_width);
std::swap((*v)[selected], (*v)[last_in_range]);
}
}
// Performs an in-place shuffle of the vector's elements.
template <typename E>
inline void Shuffle(internal::Random* random, std::vector<E>* v) {
ShuffleRange(random, 0, static_cast<int>(v->size()), v);
}
// A function for deleting an object. Handy for being used as a
// functor.
template <typename T>
static void Delete(T* x) {
delete x;
}
// A predicate that checks the key of a TestProperty against a known key.
//
// TestPropertyKeyIs is copyable.
class TestPropertyKeyIs {
public:
// Constructor.
//
// TestPropertyKeyIs has NO default constructor.
explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}
// Returns true iff the test name of test property matches on key_.
bool operator()(const TestProperty& test_property) const {
return test_property.key() == key_;
}
private:
std::string key_;
};
// Class UnitTestOptions.
//
// This class contains functions for processing options the user
// specifies when running the tests. It has only static members.
//
// In most cases, the user can specify an option using either an
// environment variable or a command line flag. E.g. you can set the
// test filter using either GTEST_FILTER or --gtest_filter. If both
// the variable and the flag are present, the latter overrides the
// former.
class GTEST_API_ UnitTestOptions {
public:
// Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output.
static std::string GetOutputFormat();
// Returns the absolute path of the requested output file, or the
// default (test_detail.xml in the original working directory) if
// none was explicitly specified.
static std::string GetAbsolutePathToOutputFile();
// Functions for processing the gtest_filter flag.
// Returns true iff the wildcard pattern matches the string. The
// first ':' or '\0' character in pattern marks the end of it.
//
// This recursive algorithm isn't very efficient, but is clear and
// works well enough for matching test names, which are short.
static bool PatternMatchesString(const char *pattern, const char *str);
// Returns true iff the user-specified filter matches the test case
// name and the test name.
static bool FilterMatchesTest(const std::string &test_case_name,
const std::string &test_name);
#if GTEST_OS_WINDOWS
// Function for supporting the gtest_catch_exception flag.
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition.
static int GTestShouldProcessSEH(DWORD exception_code);
#endif // GTEST_OS_WINDOWS
// Returns true if "name" matches the ':' separated list of glob-style
// filters in "filter".
static bool MatchesFilter(const std::string& name, const char* filter);
};
// Returns the current application's name, removing directory path if that
// is present. Used by UnitTestOptions::GetOutputFile.
GTEST_API_ FilePath GetCurrentExecutableName();
// The role interface for getting the OS stack trace as a string.
class OsStackTraceGetterInterface {
public:
OsStackTraceGetterInterface() {}
virtual ~OsStackTraceGetterInterface() {}
// Returns the current OS stack trace as an std::string. Parameters:
//
// max_depth - the maximum number of stack frames to be included
// in the trace.
// skip_count - the number of top frames to be skipped; doesn't count
// against max_depth.
virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;
// UponLeavingGTest() should be called immediately before Google Test calls
// user code. It saves some information about the current stack that
// CurrentStackTrace() will use to find and hide Google Test stack frames.
virtual void UponLeavingGTest() = 0;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);
};
// A working implementation of the OsStackTraceGetterInterface interface.
class OsStackTraceGetter : public OsStackTraceGetterInterface {
public:
OsStackTraceGetter() : caller_frame_(NULL) {}
virtual string CurrentStackTrace(int max_depth, int skip_count)
GTEST_LOCK_EXCLUDED_(mutex_);
virtual void UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_);
// This string is inserted in place of stack frames that are part of
// Google Test's implementation.
static const char* const kElidedFramesMarker;
private:
Mutex mutex_; // protects all internal state
// We save the stack frame below the frame that calls user code.
// We do this because the address of the frame immediately below
// the user code changes between the call to UponLeavingGTest()
// and any calls to CurrentStackTrace() from within the user code.
void* caller_frame_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);
};
// Information about a Google Test trace point.
struct TraceInfo {
const char* file;
int line;
std::string message;
};
// This is the default global test part result reporter used in UnitTestImpl.
// This class should only be used by UnitTestImpl.
class DefaultGlobalTestPartResultReporter
: public TestPartResultReporterInterface {
public:
explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);
// Implements the TestPartResultReporterInterface. Reports the test part
// result in the current test.
virtual void ReportTestPartResult(const TestPartResult& result);
private:
UnitTestImpl* const unit_test_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);
};
// This is the default per thread test part result reporter used in
// UnitTestImpl. This class should only be used by UnitTestImpl.
class DefaultPerThreadTestPartResultReporter
: public TestPartResultReporterInterface {
public:
explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);
// Implements the TestPartResultReporterInterface. The implementation just
// delegates to the current global test part result reporter of *unit_test_.
virtual void ReportTestPartResult(const TestPartResult& result);
private:
UnitTestImpl* const unit_test_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);
};
// The private implementation of the UnitTest class. We don't protect
// the methods under a mutex, as this class is not accessible by a
// user and the UnitTest class that delegates work to this class does
// proper locking.
class GTEST_API_ UnitTestImpl {
public:
explicit UnitTestImpl(UnitTest* parent);
virtual ~UnitTestImpl();
// There are two different ways to register your own TestPartResultReporter.
// You can register your own repoter to listen either only for test results
// from the current thread or for results from all threads.
// By default, each per-thread test result repoter just passes a new
// TestPartResult to the global test result reporter, which registers the
// test part result for the currently running test.
// Returns the global test part result reporter.
TestPartResultReporterInterface* GetGlobalTestPartResultReporter();
// Sets the global test part result reporter.
void SetGlobalTestPartResultReporter(
TestPartResultReporterInterface* reporter);
// Returns the test part result reporter for the current thread.
TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();
// Sets the test part result reporter for the current thread.
void SetTestPartResultReporterForCurrentThread(
TestPartResultReporterInterface* reporter);
// Gets the number of successful test cases.
int successful_test_case_count() const;
// Gets the number of failed test cases.
int failed_test_case_count() const;
// Gets the number of all test cases.
int total_test_case_count() const;
// Gets the number of all test cases that contain at least one test
// that should run.
int test_case_to_run_count() const;
// Gets the number of successful tests.
int successful_test_count() const;
// Gets the number of failed tests.
int failed_test_count() const;
// Gets the number of disabled tests that will be reported in the XML report.
int reportable_disabled_test_count() const;
// Gets the number of disabled tests.
int disabled_test_count() const;
// Gets the number of tests to be printed in the XML report.
int reportable_test_count() const;
// Gets the number of all tests.
int total_test_count() const;
// Gets the number of tests that should run.
int test_to_run_count() const;
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp() const { return start_timestamp_; }
// Gets the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
// Returns true iff the unit test passed (i.e. all test cases passed).
bool Passed() const { return !Failed(); }
// Returns true iff the unit test failed (i.e. some test case failed
// or something outside of all tests failed).
bool Failed() const {
return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();
}
// Gets the i-th test case among all the test cases. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL.
const TestCase* GetTestCase(int i) const {
const int index = GetElementOr(test_case_indices_, i, -1);
return index < 0 ? NULL : test_cases_[i];
}
// Gets the i-th test case among all the test cases. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL.
TestCase* GetMutableTestCase(int i) {
const int index = GetElementOr(test_case_indices_, i, -1);
return index < 0 ? NULL : test_cases_[index];
}
// Provides access to the event listener list.
TestEventListeners* listeners() { return &listeners_; }
// Returns the TestResult for the test that's currently running, or
// the TestResult for the ad hoc test if no test is running.
TestResult* current_test_result();
// Returns the TestResult for the ad hoc test.
const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }
// Sets the OS stack trace getter.
//
// Does nothing if the input and the current OS stack trace getter
// are the same; otherwise, deletes the old getter and makes the
// input the current getter.
void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);
// Returns the current OS stack trace getter if it is not NULL;
// otherwise, creates an OsStackTraceGetter, makes it the current
// getter, and returns it.
OsStackTraceGetterInterface* os_stack_trace_getter();
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter
// specifies the number of top frames to be skipped, which doesn't
// count against the number of frames to be included.
//
// For example, if Foo() calls Bar(), which in turn calls
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;
// Finds and returns a TestCase with the given name. If one doesn't
// exist, creates one and returns it.
//
// Arguments:
//
// test_case_name: name of the test case
// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
TestCase* GetTestCase(const char* test_case_name,
const char* type_param,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc);
// Adds a TestInfo to the unit test.
//
// Arguments:
//
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
// test_info: the TestInfo object
void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc,
TestInfo* test_info) {
// In order to support thread-safe death tests, we need to
// remember the original working directory when the test program
// was first invoked. We cannot do this in RUN_ALL_TESTS(), as
// the user may have changed the current directory before calling
// RUN_ALL_TESTS(). Therefore we capture the current directory in
// AddTestInfo(), which is called to register a TEST or TEST_F
// before main() is reached.
if (original_working_dir_.IsEmpty()) {
original_working_dir_.Set(FilePath::GetCurrentDir());
GTEST_CHECK_(!original_working_dir_.IsEmpty())
<< "Failed to get the current working directory.";
}
GetTestCase(test_info->test_case_name(),
test_info->type_param(),
set_up_tc,
tear_down_tc)->AddTestInfo(test_info);
}
#if GTEST_HAS_PARAM_TEST
// Returns ParameterizedTestCaseRegistry object used to keep track of
// value-parameterized tests and instantiate and register them.
internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {
return parameterized_test_registry_;
}
#endif // GTEST_HAS_PARAM_TEST
// Sets the TestCase object for the test that's currently running.
void set_current_test_case(TestCase* a_current_test_case) {
current_test_case_ = a_current_test_case;
}
// Sets the TestInfo object for the test that's currently running. If
// current_test_info is NULL, the assertion results will be stored in
// ad_hoc_test_result_.
void set_current_test_info(TestInfo* a_current_test_info) {
current_test_info_ = a_current_test_info;
}
// Registers all parameterized tests defined using TEST_P and
// INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter
// combination. This method can be called more then once; it has guards
// protecting from registering the tests more then once. If
// value-parameterized tests are disabled, RegisterParameterizedTests is
// present but does nothing.
void RegisterParameterizedTests();
// Runs all tests in this UnitTest object, prints the result, and
// returns true if all tests are successful. If any exception is
// thrown during a test, this test is considered to be failed, but
// the rest of the tests will still be run.
bool RunAllTests();
// Clears the results of all tests, except the ad hoc tests.
void ClearNonAdHocTestResult() {
ForEach(test_cases_, TestCase::ClearTestCaseResult);
}
// Clears the results of ad-hoc test assertions.
void ClearAdHocTestResult() {
ad_hoc_test_result_.Clear();
}
// Adds a TestProperty to the current TestResult object when invoked in a
// context of a test or a test case, or to the global property set. If the
// result already contains a property with the same key, the value will be
// updated.
void RecordProperty(const TestProperty& test_property);
enum ReactionToSharding {
HONOR_SHARDING_PROTOCOL,
IGNORE_SHARDING_PROTOCOL
};
// Matches the full name of each test against the user-specified
// filter to decide whether the test should run, then records the
// result in each TestCase and TestInfo object.
// If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests
// based on sharding variables in the environment.
// Returns the number of tests that should run.
int FilterTests(ReactionToSharding shard_tests);
// Prints the names of the tests matching the user-specified filter flag.
void ListTestsMatchingFilter();
const TestCase* current_test_case() const { return current_test_case_; }
TestInfo* current_test_info() { return current_test_info_; }
const TestInfo* current_test_info() const { return current_test_info_; }
// Returns the vector of environments that need to be set-up/torn-down
// before/after the tests are run.
std::vector<Environment*>& environments() { return environments_; }
// Getters for the per-thread Google Test trace stack.
std::vector<TraceInfo>& gtest_trace_stack() {
return *(gtest_trace_stack_.pointer());
}
const std::vector<TraceInfo>& gtest_trace_stack() const {
return gtest_trace_stack_.get();
}
#if GTEST_HAS_DEATH_TEST
void InitDeathTestSubprocessControlInfo() {
internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());
}
// Returns a pointer to the parsed --gtest_internal_run_death_test
// flag, or NULL if that flag was not specified.
// This information is useful only in a death test child process.
// Must not be called before a call to InitGoogleTest.
const InternalRunDeathTestFlag* internal_run_death_test_flag() const {
return internal_run_death_test_flag_.get();
}
// Returns a pointer to the current death test factory.
internal::DeathTestFactory* death_test_factory() {
return death_test_factory_.get();
}
void SuppressTestEventsIfInSubprocess();
friend class ReplaceDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
// Initializes the event listener performing XML output as specified by
// UnitTestOptions. Must not be called before InitGoogleTest.
void ConfigureXmlOutput();
#if GTEST_CAN_STREAM_RESULTS_
// Initializes the event listener for streaming test results to a socket.
// Must not be called before InitGoogleTest.
void ConfigureStreamingOutput();
#endif
// Performs initialization dependent upon flag values obtained in
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
// this function is also called from RunAllTests. Since this function can be
// called more than once, it has to be idempotent.
void PostFlagParsingInit();
// Gets the random seed used at the start of the current test iteration.
int random_seed() const { return random_seed_; }
// Gets the random number generator.
internal::Random* random() { return &random_; }
// Shuffles all test cases, and the tests within each test case,
// making sure that death tests are still run first.
void ShuffleTests();
// Restores the test cases and tests to their order before the first shuffle.
void UnshuffleTests();
// Returns the value of GTEST_FLAG(catch_exceptions) at the moment
// UnitTest::Run() starts.
bool catch_exceptions() const { return catch_exceptions_; }
private:
friend class ::testing::UnitTest;
// Used by UnitTest::Run() to capture the state of
// GTEST_FLAG(catch_exceptions) at the moment it starts.
void set_catch_exceptions(bool value) { catch_exceptions_ = value; }
// The UnitTest object that owns this implementation object.
UnitTest* const parent_;
// The working directory when the first TEST() or TEST_F() was
// executed.
internal::FilePath original_working_dir_;
// The default test part result reporters.
DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;
DefaultPerThreadTestPartResultReporter
default_per_thread_test_part_result_reporter_;
// Points to (but doesn't own) the global test part result reporter.
TestPartResultReporterInterface* global_test_part_result_repoter_;
// Protects read and write access to global_test_part_result_reporter_.
internal::Mutex global_test_part_result_reporter_mutex_;
// Points to (but doesn't own) the per-thread test part result reporter.
internal::ThreadLocal<TestPartResultReporterInterface*>
per_thread_test_part_result_reporter_;
// The vector of environments that need to be set-up/torn-down
// before/after the tests are run.
std::vector<Environment*> environments_;
// The vector of TestCases in their original order. It owns the
// elements in the vector.
std::vector<TestCase*> test_cases_;
// Provides a level of indirection for the test case list to allow
// easy shuffling and restoring the test case order. The i-th
// element of this vector is the index of the i-th test case in the
// shuffled order.
std::vector<int> test_case_indices_;
#if GTEST_HAS_PARAM_TEST
// ParameterizedTestRegistry object used to register value-parameterized
// tests.
internal::ParameterizedTestCaseRegistry parameterized_test_registry_;
// Indicates whether RegisterParameterizedTests() has been called already.
bool parameterized_tests_registered_;
#endif // GTEST_HAS_PARAM_TEST
// Index of the last death test case registered. Initially -1.
int last_death_test_case_;
// This points to the TestCase for the currently running test. It
// changes as Google Test goes through one test case after another.
// When no test is running, this is set to NULL and Google Test
// stores assertion results in ad_hoc_test_result_. Initially NULL.
TestCase* current_test_case_;
// This points to the TestInfo for the currently running test. It
// changes as Google Test goes through one test after another. When
// no test is running, this is set to NULL and Google Test stores
// assertion results in ad_hoc_test_result_. Initially NULL.
TestInfo* current_test_info_;
// Normally, a user only writes assertions inside a TEST or TEST_F,
// or inside a function called by a TEST or TEST_F. Since Google
// Test keeps track of which test is current running, it can
// associate such an assertion with the test it belongs to.
//
// If an assertion is encountered when no TEST or TEST_F is running,
// Google Test attributes the assertion result to an imaginary "ad hoc"
// test, and records the result in ad_hoc_test_result_.
TestResult ad_hoc_test_result_;
// The list of event listeners that can be used to track events inside
// Google Test.
TestEventListeners listeners_;
// The OS stack trace getter. Will be deleted when the UnitTest
// object is destructed. By default, an OsStackTraceGetter is used,
// but the user can set this field to use a custom getter if that is
// desired.
OsStackTraceGetterInterface* os_stack_trace_getter_;
// True iff PostFlagParsingInit() has been called.
bool post_flag_parse_init_performed_;
// The random number seed used at the beginning of the test run.
int random_seed_;
// Our random number generator.
internal::Random random_;
// The time of the test program start, in ms from the start of the
// UNIX epoch.
TimeInMillis start_timestamp_;
// How long the test took to run, in milliseconds.
TimeInMillis elapsed_time_;
#if GTEST_HAS_DEATH_TEST
// The decomposed components of the gtest_internal_run_death_test flag,
// parsed when RUN_ALL_TESTS is called.
internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;
internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;
#endif // GTEST_HAS_DEATH_TEST
// A per-thread stack of traces created by the SCOPED_TRACE() macro.
internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;
// The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()
// starts.
bool catch_exceptions_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);
}; // class UnitTestImpl
// Convenience function for accessing the global UnitTest
// implementation object.
inline UnitTestImpl* GetUnitTestImpl() {
return UnitTest::GetInstance()->impl();
}
#if GTEST_USES_SIMPLE_RE
// Internal helper functions for implementing the simple regular
// expression matcher.
GTEST_API_ bool IsInSet(char ch, const char* str);
GTEST_API_ bool IsAsciiDigit(char ch);
GTEST_API_ bool IsAsciiPunct(char ch);
GTEST_API_ bool IsRepeat(char ch);
GTEST_API_ bool IsAsciiWhiteSpace(char ch);
GTEST_API_ bool IsAsciiWordChar(char ch);
GTEST_API_ bool IsValidEscape(char ch);
GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);
GTEST_API_ bool ValidateRegex(const char* regex);
GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);
GTEST_API_ bool MatchRepetitionAndRegexAtHead(
bool escaped, char ch, char repeat, const char* regex, const char* str);
GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);
#endif // GTEST_USES_SIMPLE_RE
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test.
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);
GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);
#if GTEST_HAS_DEATH_TEST
// Returns the message describing the last system error, regardless of the
// platform.
GTEST_API_ std::string GetLastErrnoDescription();
# if GTEST_OS_WINDOWS
// Provides leak-safe Windows kernel handle ownership.
class AutoHandle {
public:
AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}
explicit AutoHandle(HANDLE handle) : handle_(handle) {}
~AutoHandle() { Reset(); }
HANDLE Get() const { return handle_; }
void Reset() { Reset(INVALID_HANDLE_VALUE); }
void Reset(HANDLE handle) {
if (handle != handle_) {
if (handle_ != INVALID_HANDLE_VALUE)
::CloseHandle(handle_);
handle_ = handle;
}
}
private:
HANDLE handle_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle);
};
# endif // GTEST_OS_WINDOWS
// Attempts to parse a string into a positive integer pointed to by the
// number parameter. Returns true if that is possible.
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use
// it here.
template <typename Integer>
bool ParseNaturalNumber(const ::std::string& str, Integer* number) {
// Fail fast if the given string does not begin with a digit;
// this bypasses strtoXXX's "optional leading whitespace and plus
// or minus sign" semantics, which are undesirable here.
if (str.empty() || !IsDigit(str[0])) {
return false;
}
errno = 0;
char* end;
// BiggestConvertible is the largest integer type that system-provided
// string-to-number conversion routines can return.
# if GTEST_OS_WINDOWS && !defined(__GNUC__)
// MSVC and C++ Builder define __int64 instead of the standard long long.
typedef unsigned __int64 BiggestConvertible;
const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);
# else
typedef unsigned long long BiggestConvertible; // NOLINT
const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);
# endif // GTEST_OS_WINDOWS && !defined(__GNUC__)
const bool parse_success = *end == '\0' && errno == 0;
// TODO(vladl@google.com): Convert this to compile time assertion when it is
// available.
GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));
const Integer result = static_cast<Integer>(parsed);
if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {
*number = result;
return true;
}
return false;
}
#endif // GTEST_HAS_DEATH_TEST
// TestResult contains some private methods that should be hidden from
// Google Test user but are required for testing. This class allow our tests
// to access them.
//
// This class is supplied only for the purpose of testing Google Test's own
// constructs. Do not use it in user tests, either directly or indirectly.
class TestResultAccessor {
public:
static void RecordProperty(TestResult* test_result,
const std::string& xml_element,
const TestProperty& property) {
test_result->RecordProperty(xml_element, property);
}
static void ClearTestPartResults(TestResult* test_result) {
test_result->ClearTestPartResults();
}
static const std::vector<testing::TestPartResult>& test_part_results(
const TestResult& test_result) {
return test_result.test_part_results();
}
};
#if GTEST_CAN_STREAM_RESULTS_
// Streams test results to the given port on the given host machine.
class StreamingListener : public EmptyTestEventListener {
public:
// Abstract base class for writing strings to a socket.
class AbstractSocketWriter {
public:
virtual ~AbstractSocketWriter() {}
// Sends a string to the socket.
virtual void Send(const string& message) = 0;
// Closes the socket.
virtual void CloseConnection() {}
// Sends a string and a newline to the socket.
void SendLn(const string& message) {
Send(message + "\n");
}
};
// Concrete class for actually writing strings to a socket.
class SocketWriter : public AbstractSocketWriter {
public:
SocketWriter(const string& host, const string& port)
: sockfd_(-1), host_name_(host), port_num_(port) {
MakeConnection();
}
virtual ~SocketWriter() {
if (sockfd_ != -1)
CloseConnection();
}
// Sends a string to the socket.
virtual void Send(const string& message) {
GTEST_CHECK_(sockfd_ != -1)
<< "Send() can be called only when there is a connection.";
const int len = static_cast<int>(message.length());
if (write(sockfd_, message.c_str(), len) != len) {
GTEST_LOG_(WARNING)
<< "stream_result_to: failed to stream to "
<< host_name_ << ":" << port_num_;
}
}
private:
// Creates a client socket and connects to the server.
void MakeConnection();
// Closes the socket.
void CloseConnection() {
GTEST_CHECK_(sockfd_ != -1)
<< "CloseConnection() can be called only when there is a connection.";
close(sockfd_);
sockfd_ = -1;
}
int sockfd_; // socket file descriptor
const string host_name_;
const string port_num_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);
}; // class SocketWriter
// Escapes '=', '&', '%', and '\n' characters in str as "%xx".
static string UrlEncode(const char* str);
StreamingListener(const string& host, const string& port)
: socket_writer_(new SocketWriter(host, port)) { Start(); }
explicit StreamingListener(AbstractSocketWriter* socket_writer)
: socket_writer_(socket_writer) { Start(); }
void OnTestProgramStart(const UnitTest& /* unit_test */) {
SendLn("event=TestProgramStart");
}
void OnTestProgramEnd(const UnitTest& unit_test) {
// Note that Google Test current only report elapsed time for each
// test iteration, not for the entire test program.
SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed()));
// Notify the streaming server to stop.
socket_writer_->CloseConnection();
}
void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {
SendLn("event=TestIterationStart&iteration=" +
StreamableToString(iteration));
}
void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {
SendLn("event=TestIterationEnd&passed=" +
FormatBool(unit_test.Passed()) + "&elapsed_time=" +
StreamableToString(unit_test.elapsed_time()) + "ms");
}
void OnTestCaseStart(const TestCase& test_case) {
SendLn(std::string("event=TestCaseStart&name=") + test_case.name());
}
void OnTestCaseEnd(const TestCase& test_case) {
SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed())
+ "&elapsed_time=" + StreamableToString(test_case.elapsed_time())
+ "ms");
}
void OnTestStart(const TestInfo& test_info) {
SendLn(std::string("event=TestStart&name=") + test_info.name());
}
void OnTestEnd(const TestInfo& test_info) {
SendLn("event=TestEnd&passed=" +
FormatBool((test_info.result())->Passed()) +
"&elapsed_time=" +
StreamableToString((test_info.result())->elapsed_time()) + "ms");
}
void OnTestPartResult(const TestPartResult& test_part_result) {
const char* file_name = test_part_result.file_name();
if (file_name == NULL)
file_name = "";
SendLn("event=TestPartResult&file=" + UrlEncode(file_name) +
"&line=" + StreamableToString(test_part_result.line_number()) +
"&message=" + UrlEncode(test_part_result.message()));
}
private:
// Sends the given message and a newline to the socket.
void SendLn(const string& message) { socket_writer_->SendLn(message); }
// Called at the start of streaming to notify the receiver what
// protocol we are using.
void Start() { SendLn("gtest_streaming_protocol_version=1.0"); }
string FormatBool(bool value) { return value ? "1" : "0"; }
const scoped_ptr<AbstractSocketWriter> socket_writer_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);
}; // class StreamingListener
#endif // GTEST_CAN_STREAM_RESULTS_
} // namespace internal
} // namespace testing
#endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
#undef GTEST_IMPLEMENTATION_
#if GTEST_OS_WINDOWS
# define vsnprintf _vsnprintf
#endif // GTEST_OS_WINDOWS
namespace testing {
using internal::CountIf;
using internal::ForEach;
using internal::GetElementOr;
using internal::Shuffle;
// Constants.
// A test whose test case name or test name matches this filter is
// disabled and not run.
static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*";
// A test case whose name matches this filter is considered a death
// test case and will be run before test cases whose name doesn't
// match this filter.
static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
// A test filter that matches everything.
static const char kUniversalFilter[] = "*";
// The default output file for XML output.
static const char kDefaultOutputFile[] = "test_detail.xml";
// The environment variable name for the test shard index.
static const char kTestShardIndex[] = "GTEST_SHARD_INDEX";
// The environment variable name for the total number of test shards.
static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS";
// The environment variable name for the test shard status file.
static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE";
namespace internal {
// The text used in failure messages to indicate the start of the
// stack trace.
const char kStackTraceMarker[] = "\nStack trace:\n";
// g_help_flag is true iff the --help flag or an equivalent form is
// specified on the command line.
bool g_help_flag = false;
} // namespace internal
static const char* GetDefaultFilter() {
return kUniversalFilter;
}
GTEST_DEFINE_bool_(
also_run_disabled_tests,
internal::BoolFromGTestEnv("also_run_disabled_tests", false),
"Run disabled tests too, in addition to the tests normally being run.");
GTEST_DEFINE_bool_(
break_on_failure,
internal::BoolFromGTestEnv("break_on_failure", false),
"True iff a failed assertion should be a debugger break-point.");
GTEST_DEFINE_bool_(
catch_exceptions,
internal::BoolFromGTestEnv("catch_exceptions", true),
"True iff " GTEST_NAME_
" should catch exceptions and treat them as test failures.");
GTEST_DEFINE_string_(
color,
internal::StringFromGTestEnv("color", "auto"),
"Whether to use colors in the output. Valid values: yes, no, "
"and auto. 'auto' means to use colors if the output is "
"being sent to a terminal and the TERM environment variable "
"is set to a terminal type that supports colors.");
GTEST_DEFINE_string_(
filter,
internal::StringFromGTestEnv("filter", GetDefaultFilter()),
"A colon-separated list of glob (not regex) patterns "
"for filtering the tests to run, optionally followed by a "
"'-' and a : separated list of negative patterns (tests to "
"exclude). A test is run if it matches one of the positive "
"patterns and does not match any of the negative patterns.");
GTEST_DEFINE_bool_(list_tests, false,
"List all tests without running them.");
GTEST_DEFINE_string_(
output,
internal::StringFromGTestEnv("output", ""),
"A format (currently must be \"xml\"), optionally followed "
"by a colon and an output file name or directory. A directory "
"is indicated by a trailing pathname separator. "
"Examples: \"xml:filename.xml\", \"xml::directoryname/\". "
"If a directory is specified, output files will be created "
"within that directory, with file-names based on the test "
"executable's name and, if necessary, made unique by adding "
"digits.");
GTEST_DEFINE_bool_(
print_time,
internal::BoolFromGTestEnv("print_time", true),
"True iff " GTEST_NAME_
" should display elapsed time in text output.");
GTEST_DEFINE_int32_(
random_seed,
internal::Int32FromGTestEnv("random_seed", 0),
"Random number seed to use when shuffling test orders. Must be in range "
"[1, 99999], or 0 to use a seed based on the current time.");
GTEST_DEFINE_int32_(
repeat,
internal::Int32FromGTestEnv("repeat", 1),
"How many times to repeat each test. Specify a negative number "
"for repeating forever. Useful for shaking out flaky tests.");
GTEST_DEFINE_bool_(
show_internal_stack_frames, false,
"True iff " GTEST_NAME_ " should include internal stack frames when "
"printing test failure stack traces.");
GTEST_DEFINE_bool_(
shuffle,
internal::BoolFromGTestEnv("shuffle", false),
"True iff " GTEST_NAME_
" should randomize tests' order on every run.");
GTEST_DEFINE_int32_(
stack_trace_depth,
internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth),
"The maximum number of stack frames to print when an "
"assertion fails. The valid range is 0 through 100, inclusive.");
GTEST_DEFINE_string_(
stream_result_to,
internal::StringFromGTestEnv("stream_result_to", ""),
"This flag specifies the host name and the port number on which to stream "
"test results. Example: \"localhost:555\". The flag is effective only on "
"Linux.");
GTEST_DEFINE_bool_(
throw_on_failure,
internal::BoolFromGTestEnv("throw_on_failure", false),
"When this flag is specified, a failed assertion will throw an exception "
"if exceptions are enabled or exit the program with a non-zero code "
"otherwise.");
namespace internal {
// Generates a random number from [0, range), using a Linear
// Congruential Generator (LCG). Crashes if 'range' is 0 or greater
// than kMaxRange.
UInt32 Random::Generate(UInt32 range) {
// These constants are the same as are used in glibc's rand(3).
state_ = (1103515245U*state_ + 12345U) % kMaxRange;
GTEST_CHECK_(range > 0)
<< "Cannot generate a number in the range [0, 0).";
GTEST_CHECK_(range <= kMaxRange)
<< "Generation of a number in [0, " << range << ") was requested, "
<< "but this can only generate numbers in [0, " << kMaxRange << ").";
// Converting via modulus introduces a bit of downward bias, but
// it's simple, and a linear congruential generator isn't too good
// to begin with.
return state_ % range;
}
// GTestIsInitialized() returns true iff the user has initialized
// Google Test. Useful for catching the user mistake of not initializing
// Google Test before calling RUN_ALL_TESTS().
//
// A user must call testing::InitGoogleTest() to initialize Google
// Test. g_init_gtest_count is set to the number of times
// InitGoogleTest() has been called. We don't protect this variable
// under a mutex as it is only accessed in the main thread.
GTEST_API_ int g_init_gtest_count = 0;
static bool GTestIsInitialized() { return g_init_gtest_count != 0; }
// Iterates over a vector of TestCases, keeping a running sum of the
// results of calling a given int-returning method on each.
// Returns the sum.
static int SumOverTestCaseList(const std::vector<TestCase*>& case_list,
int (TestCase::*method)() const) {
int sum = 0;
for (size_t i = 0; i < case_list.size(); i++) {
sum += (case_list[i]->*method)();
}
return sum;
}
// Returns true iff the test case passed.
static bool TestCasePassed(const TestCase* test_case) {
return test_case->should_run() && test_case->Passed();
}
// Returns true iff the test case failed.
static bool TestCaseFailed(const TestCase* test_case) {
return test_case->should_run() && test_case->Failed();
}
// Returns true iff test_case contains at least one test that should
// run.
static bool ShouldRunTestCase(const TestCase* test_case) {
return test_case->should_run();
}
// AssertHelper constructor.
AssertHelper::AssertHelper(TestPartResult::Type type,
const char* file,
int line,
const char* message)
: data_(new AssertHelperData(type, file, line, message)) {
}
AssertHelper::~AssertHelper() {
delete data_;
}
// Message assignment, for assertion streaming support.
void AssertHelper::operator=(const Message& message) const {
UnitTest::GetInstance()->
AddTestPartResult(data_->type, data_->file, data_->line,
AppendUserMessage(data_->message, message),
UnitTest::GetInstance()->impl()
->CurrentOsStackTraceExceptTop(1)
// Skips the stack frame for this function itself.
); // NOLINT
}
// Mutex for linked pointers.
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
// Application pathname gotten in InitGoogleTest.
std::string g_executable_path;
// Returns the current application's name, removing directory path if that
// is present.
FilePath GetCurrentExecutableName() {
FilePath result;
#if GTEST_OS_WINDOWS
result.Set(FilePath(g_executable_path).RemoveExtension("exe"));
#else
result.Set(FilePath(g_executable_path));
#endif // GTEST_OS_WINDOWS
return result.RemoveDirectoryName();
}
// Functions for processing the gtest_output flag.
// Returns the output format, or "" for normal printed output.
std::string UnitTestOptions::GetOutputFormat() {
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
if (gtest_output_flag == NULL) return std::string("");
const char* const colon = strchr(gtest_output_flag, ':');
return (colon == NULL) ?
std::string(gtest_output_flag) :
std::string(gtest_output_flag, colon - gtest_output_flag);
}
// Returns the name of the requested output file, or the default if none
// was explicitly specified.
std::string UnitTestOptions::GetAbsolutePathToOutputFile() {
const char* const gtest_output_flag = GTEST_FLAG(output).c_str();
if (gtest_output_flag == NULL)
return "";
const char* const colon = strchr(gtest_output_flag, ':');
if (colon == NULL)
return internal::FilePath::ConcatPaths(
internal::FilePath(
UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(kDefaultOutputFile)).string();
internal::FilePath output_name(colon + 1);
if (!output_name.IsAbsolutePath())
// TODO(wan@google.com): on Windows \some\path is not an absolute
// path (as its meaning depends on the current drive), yet the
// following logic for turning it into an absolute path is wrong.
// Fix it.
output_name = internal::FilePath::ConcatPaths(
internal::FilePath(UnitTest::GetInstance()->original_working_dir()),
internal::FilePath(colon + 1));
if (!output_name.IsDirectory())
return output_name.string();
internal::FilePath result(internal::FilePath::GenerateUniqueFileName(
output_name, internal::GetCurrentExecutableName(),
GetOutputFormat().c_str()));
return result.string();
}
// Returns true iff the wildcard pattern matches the string. The
// first ':' or '\0' character in pattern marks the end of it.
//
// This recursive algorithm isn't very efficient, but is clear and
// works well enough for matching test names, which are short.
bool UnitTestOptions::PatternMatchesString(const char *pattern,
const char *str) {
switch (*pattern) {
case '\0':
case ':': // Either ':' or '\0' marks the end of the pattern.
return *str == '\0';
case '?': // Matches any single character.
return *str != '\0' && PatternMatchesString(pattern + 1, str + 1);
case '*': // Matches any string (possibly empty) of characters.
return (*str != '\0' && PatternMatchesString(pattern, str + 1)) ||
PatternMatchesString(pattern + 1, str);
default: // Non-special character. Matches itself.
return *pattern == *str &&
PatternMatchesString(pattern + 1, str + 1);
}
}
bool UnitTestOptions::MatchesFilter(
const std::string& name, const char* filter) {
const char *cur_pattern = filter;
for (;;) {
if (PatternMatchesString(cur_pattern, name.c_str())) {
return true;
}
// Finds the next pattern in the filter.
cur_pattern = strchr(cur_pattern, ':');
// Returns if no more pattern can be found.
if (cur_pattern == NULL) {
return false;
}
// Skips the pattern separater (the ':' character).
cur_pattern++;
}
}
// Returns true iff the user-specified filter matches the test case
// name and the test name.
bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,
const std::string &test_name) {
const std::string& full_name = test_case_name + "." + test_name.c_str();
// Split --gtest_filter at '-', if there is one, to separate into
// positive filter and negative filter portions
const char* const p = GTEST_FLAG(filter).c_str();
const char* const dash = strchr(p, '-');
std::string positive;
std::string negative;
if (dash == NULL) {
positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter
negative = "";
} else {
positive = std::string(p, dash); // Everything up to the dash
negative = std::string(dash + 1); // Everything after the dash
if (positive.empty()) {
// Treat '-test1' as the same as '*-test1'
positive = kUniversalFilter;
}
}
// A filter is a colon-separated list of patterns. It matches a
// test if any pattern in it matches the test.
return (MatchesFilter(full_name, positive.c_str()) &&
!MatchesFilter(full_name, negative.c_str()));
}
#if GTEST_HAS_SEH
// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the
// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.
// This function is useful as an __except condition.
int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {
// Google Test should handle a SEH exception if:
// 1. the user wants it to, AND
// 2. this is not a breakpoint exception, AND
// 3. this is not a C++ exception (VC++ implements them via SEH,
// apparently).
//
// SEH exception code for C++ exceptions.
// (see http://support.microsoft.com/kb/185294 for more information).
const DWORD kCxxExceptionCode = 0xe06d7363;
bool should_handle = true;
if (!GTEST_FLAG(catch_exceptions))
should_handle = false;
else if (exception_code == EXCEPTION_BREAKPOINT)
should_handle = false;
else if (exception_code == kCxxExceptionCode)
should_handle = false;
return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
}
#endif // GTEST_HAS_SEH
} // namespace internal
// The c'tor sets this object as the test part result reporter used by
// Google Test. The 'result' parameter specifies where to report the
// results. Intercepts only failures from the current thread.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
TestPartResultArray* result)
: intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),
result_(result) {
Init();
}
// The c'tor sets this object as the test part result reporter used by
// Google Test. The 'result' parameter specifies where to report the
// results.
ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(
InterceptMode intercept_mode, TestPartResultArray* result)
: intercept_mode_(intercept_mode),
result_(result) {
Init();
}
void ScopedFakeTestPartResultReporter::Init() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
old_reporter_ = impl->GetGlobalTestPartResultReporter();
impl->SetGlobalTestPartResultReporter(this);
} else {
old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();
impl->SetTestPartResultReporterForCurrentThread(this);
}
}
// The d'tor restores the test part result reporter used by Google Test
// before.
ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
if (intercept_mode_ == INTERCEPT_ALL_THREADS) {
impl->SetGlobalTestPartResultReporter(old_reporter_);
} else {
impl->SetTestPartResultReporterForCurrentThread(old_reporter_);
}
}
// Increments the test part result count and remembers the result.
// This method is from the TestPartResultReporterInterface interface.
void ScopedFakeTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
result_->Append(result);
}
namespace internal {
// Returns the type ID of ::testing::Test. We should always call this
// instead of GetTypeId< ::testing::Test>() to get the type ID of
// testing::Test. This is to work around a suspected linker bug when
// using Google Test as a framework on Mac OS X. The bug causes
// GetTypeId< ::testing::Test>() to return different values depending
// on whether the call is from the Google Test framework itself or
// from user test code. GetTestTypeId() is guaranteed to always
// return the same value, as it always calls GetTypeId<>() from the
// gtest.cc, which is within the Google Test framework.
TypeId GetTestTypeId() {
return GetTypeId<Test>();
}
// The value of GetTestTypeId() as seen from within the Google Test
// library. This is solely for testing GetTestTypeId().
extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();
// This predicate-formatter checks that 'results' contains a test part
// failure of the given type and that the failure message contains the
// given substring.
AssertionResult HasOneFailure(const char* /* results_expr */,
const char* /* type_expr */,
const char* /* substr_expr */,
const TestPartResultArray& results,
TestPartResult::Type type,
const string& substr) {
const std::string expected(type == TestPartResult::kFatalFailure ?
"1 fatal failure" :
"1 non-fatal failure");
Message msg;
if (results.size() != 1) {
msg << "Expected: " << expected << "\n"
<< " Actual: " << results.size() << " failures";
for (int i = 0; i < results.size(); i++) {
msg << "\n" << results.GetTestPartResult(i);
}
return AssertionFailure() << msg;
}
const TestPartResult& r = results.GetTestPartResult(0);
if (r.type() != type) {
return AssertionFailure() << "Expected: " << expected << "\n"
<< " Actual:\n"
<< r;
}
if (strstr(r.message(), substr.c_str()) == NULL) {
return AssertionFailure() << "Expected: " << expected << " containing \""
<< substr << "\"\n"
<< " Actual:\n"
<< r;
}
return AssertionSuccess();
}
// The constructor of SingleFailureChecker remembers where to look up
// test part results, what type of failure we expect, and what
// substring the failure message should contain.
SingleFailureChecker:: SingleFailureChecker(
const TestPartResultArray* results,
TestPartResult::Type type,
const string& substr)
: results_(results),
type_(type),
substr_(substr) {}
// The destructor of SingleFailureChecker verifies that the given
// TestPartResultArray contains exactly one failure that has the given
// type and contains the given substring. If that's not the case, a
// non-fatal failure will be generated.
SingleFailureChecker::~SingleFailureChecker() {
EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);
}
DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
void DefaultGlobalTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
unit_test_->current_test_result()->AddTestPartResult(result);
unit_test_->listeners()->repeater()->OnTestPartResult(result);
}
DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(
UnitTestImpl* unit_test) : unit_test_(unit_test) {}
void DefaultPerThreadTestPartResultReporter::ReportTestPartResult(
const TestPartResult& result) {
unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);
}
// Returns the global test part result reporter.
TestPartResultReporterInterface*
UnitTestImpl::GetGlobalTestPartResultReporter() {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
return global_test_part_result_repoter_;
}
// Sets the global test part result reporter.
void UnitTestImpl::SetGlobalTestPartResultReporter(
TestPartResultReporterInterface* reporter) {
internal::MutexLock lock(&global_test_part_result_reporter_mutex_);
global_test_part_result_repoter_ = reporter;
}
// Returns the test part result reporter for the current thread.
TestPartResultReporterInterface*
UnitTestImpl::GetTestPartResultReporterForCurrentThread() {
return per_thread_test_part_result_reporter_.get();
}
// Sets the test part result reporter for the current thread.
void UnitTestImpl::SetTestPartResultReporterForCurrentThread(
TestPartResultReporterInterface* reporter) {
per_thread_test_part_result_reporter_.set(reporter);
}
// Gets the number of successful test cases.
int UnitTestImpl::successful_test_case_count() const {
return CountIf(test_cases_, TestCasePassed);
}
// Gets the number of failed test cases.
int UnitTestImpl::failed_test_case_count() const {
return CountIf(test_cases_, TestCaseFailed);
}
// Gets the number of all test cases.
int UnitTestImpl::total_test_case_count() const {
return static_cast<int>(test_cases_.size());
}
// Gets the number of all test cases that contain at least one test
// that should run.
int UnitTestImpl::test_case_to_run_count() const {
return CountIf(test_cases_, ShouldRunTestCase);
}
// Gets the number of successful tests.
int UnitTestImpl::successful_test_count() const {
return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);
}
// Gets the number of failed tests.
int UnitTestImpl::failed_test_count() const {
return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);
}
// Gets the number of disabled tests that will be reported in the XML report.
int UnitTestImpl::reportable_disabled_test_count() const {
return SumOverTestCaseList(test_cases_,
&TestCase::reportable_disabled_test_count);
}
// Gets the number of disabled tests.
int UnitTestImpl::disabled_test_count() const {
return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);
}
// Gets the number of tests to be printed in the XML report.
int UnitTestImpl::reportable_test_count() const {
return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);
}
// Gets the number of all tests.
int UnitTestImpl::total_test_count() const {
return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);
}
// Gets the number of tests that should run.
int UnitTestImpl::test_to_run_count() const {
return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);
}
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter
// specifies the number of top frames to be skipped, which doesn't
// count against the number of frames to be included.
//
// For example, if Foo() calls Bar(), which in turn calls
// CurrentOsStackTraceExceptTop(1), Foo() will be included in the
// trace but Bar() and CurrentOsStackTraceExceptTop() won't.
std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {
(void)skip_count;
return "";
}
// Returns the current time in milliseconds.
TimeInMillis GetTimeInMillis() {
#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)
// Difference between 1970-01-01 and 1601-01-01 in milliseconds.
// http://analogous.blogspot.com/2005/04/epoch.html
const TimeInMillis kJavaEpochToWinFileTimeDelta =
static_cast<TimeInMillis>(116444736UL) * 100000UL;
const DWORD kTenthMicrosInMilliSecond = 10000;
SYSTEMTIME now_systime;
FILETIME now_filetime;
ULARGE_INTEGER now_int64;
// TODO(kenton@google.com): Shouldn't this just use
// GetSystemTimeAsFileTime()?
GetSystemTime(&now_systime);
if (SystemTimeToFileTime(&now_systime, &now_filetime)) {
now_int64.LowPart = now_filetime.dwLowDateTime;
now_int64.HighPart = now_filetime.dwHighDateTime;
now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -
kJavaEpochToWinFileTimeDelta;
return now_int64.QuadPart;
}
return 0;
#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_
__timeb64 now;
# ifdef _MSC_VER
// MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996
// (deprecated function) there.
// TODO(kenton@google.com): Use GetTickCount()? Or use
// SystemTimeToFileTime()
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4996) // Temporarily disables warning 4996.
_ftime64(&now);
# pragma warning(pop) // Restores the warning state.
# else
_ftime64(&now);
# endif // _MSC_VER
return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;
#elif GTEST_HAS_GETTIMEOFDAY_
struct timeval now;
gettimeofday(&now, NULL);
return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;
#else
# error "Don't know how to get the current time on your system."
#endif
}
// Utilities
// class String.
#if GTEST_OS_WINDOWS_MOBILE
// Creates a UTF-16 wide string from the given ANSI string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the wide string, or NULL if the
// input is NULL.
LPCWSTR String::AnsiToUtf16(const char* ansi) {
if (!ansi) return NULL;
const int length = strlen(ansi);
const int unicode_length =
MultiByteToWideChar(CP_ACP, 0, ansi, length,
NULL, 0);
WCHAR* unicode = new WCHAR[unicode_length + 1];
MultiByteToWideChar(CP_ACP, 0, ansi, length,
unicode, unicode_length);
unicode[unicode_length] = 0;
return unicode;
}
// Creates an ANSI string from the given wide string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL.
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
if (!utf16_str) return NULL;
const int ansi_length =
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
NULL, 0, NULL, NULL);
char* ansi = new char[ansi_length + 1];
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,
ansi, ansi_length, NULL, NULL);
ansi[ansi_length] = 0;
return ansi;
}
#endif // GTEST_OS_WINDOWS_MOBILE
// Compares two C strings. Returns true iff they have the same content.
//
// Unlike strcmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string,
// including the empty string.
bool String::CStringEquals(const char * lhs, const char * rhs) {
if ( lhs == NULL ) return rhs == NULL;
if ( rhs == NULL ) return false;
return strcmp(lhs, rhs) == 0;
}
#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
// Converts an array of wide chars to a narrow string using the UTF-8
// encoding, and streams the result to the given Message object.
static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,
Message* msg) {
for (size_t i = 0; i != length; ) { // NOLINT
if (wstr[i] != L'\0') {
*msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));
while (i != length && wstr[i] != L'\0')
i++;
} else {
*msg << '\0';
i++;
}
}
}
#endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING
} // namespace internal
// Constructs an empty Message.
// We allocate the stringstream separately because otherwise each use of
// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's
// stack frame leading to huge stack frames in some cases; gcc does not reuse
// the stack space.
Message::Message() : ss_(new ::std::stringstream) {
// By default, we want there to be enough precision when printing
// a double to a Message.
*ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);
}
// These two overloads allow streaming a wide C string to a Message
// using the UTF-8 encoding.
Message& Message::operator <<(const wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
Message& Message::operator <<(wchar_t* wide_c_str) {
return *this << internal::String::ShowWideCString(wide_c_str);
}
#if GTEST_HAS_STD_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
Message& Message::operator <<(const ::std::wstring& wstr) {
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
return *this;
}
#endif // GTEST_HAS_STD_WSTRING
#if GTEST_HAS_GLOBAL_WSTRING
// Converts the given wide string to a narrow string using the UTF-8
// encoding, and streams the result to this Message object.
Message& Message::operator <<(const ::wstring& wstr) {
internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);
return *this;
}
#endif // GTEST_HAS_GLOBAL_WSTRING
// Gets the text streamed to this object so far as an std::string.
// Each '\0' character in the buffer is replaced with "\\0".
std::string Message::GetString() const {
return internal::StringStreamToString(ss_.get());
}
// AssertionResult constructors.
// Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult::AssertionResult(const AssertionResult& other)
: success_(other.success_),
message_(other.message_.get() != NULL ?
new ::std::string(*other.message_) :
static_cast< ::std::string*>(NULL)) {
}
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
AssertionResult AssertionResult::operator!() const {
AssertionResult negation(!success_);
if (message_.get() != NULL)
negation << *message_;
return negation;
}
// Makes a successful assertion result.
AssertionResult AssertionSuccess() {
return AssertionResult(true);
}
// Makes a failed assertion result.
AssertionResult AssertionFailure() {
return AssertionResult(false);
}
// Makes a failed assertion result with the given failure message.
// Deprecated; use AssertionFailure() << message.
AssertionResult AssertionFailure(const Message& message) {
return AssertionFailure() << message;
}
namespace internal {
// Constructs and returns the message for an equality assertion
// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.
//
// The first four parameters are the expressions used in the assertion
// and their values, as strings. For example, for ASSERT_EQ(foo, bar)
// where foo is 5 and bar is 6, we have:
//
// expected_expression: "foo"
// actual_expression: "bar"
// expected_value: "5"
// actual_value: "6"
//
// The ignoring_case parameter is true iff the assertion is a
// *_STRCASEEQ*. When it's true, the string " (ignoring case)" will
// be inserted into the message.
AssertionResult EqFailure(const char* expected_expression,
const char* actual_expression,
const std::string& expected_value,
const std::string& actual_value,
bool ignoring_case) {
Message msg;
msg << "Value of: " << actual_expression;
if (actual_value != actual_expression) {
msg << "\n Actual: " << actual_value;
}
msg << "\nExpected: " << expected_expression;
if (ignoring_case) {
msg << " (ignoring case)";
}
if (expected_value != expected_expression) {
msg << "\nWhich is: " << expected_value;
}
return AssertionFailure() << msg;
}
// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.
std::string GetBoolAssertionFailureMessage(
const AssertionResult& assertion_result,
const char* expression_text,
const char* actual_predicate_value,
const char* expected_predicate_value) {
const char* actual_message = assertion_result.message();
Message msg;
msg << "Value of: " << expression_text
<< "\n Actual: " << actual_predicate_value;
if (actual_message[0] != '\0')
msg << " (" << actual_message << ")";
msg << "\nExpected: " << expected_predicate_value;
return msg.GetString();
}
// Helper function for implementing ASSERT_NEAR.
AssertionResult DoubleNearPredFormat(const char* expr1,
const char* expr2,
const char* abs_error_expr,
double val1,
double val2,
double abs_error) {
const double diff = fabs(val1 - val2);
if (diff <= abs_error) return AssertionSuccess();
// TODO(wan): do not print the value of an expression if it's
// already a literal.
return AssertionFailure()
<< "The difference between " << expr1 << " and " << expr2
<< " is " << diff << ", which exceeds " << abs_error_expr << ", where\n"
<< expr1 << " evaluates to " << val1 << ",\n"
<< expr2 << " evaluates to " << val2 << ", and\n"
<< abs_error_expr << " evaluates to " << abs_error << ".";
}
// Helper template for implementing FloatLE() and DoubleLE().
template <typename RawType>
AssertionResult FloatingPointLE(const char* expr1,
const char* expr2,
RawType val1,
RawType val2) {
// Returns success if val1 is less than val2,
if (val1 < val2) {
return AssertionSuccess();
}
// or if val1 is almost equal to val2.
const FloatingPoint<RawType> lhs(val1), rhs(val2);
if (lhs.AlmostEquals(rhs)) {
return AssertionSuccess();
}
// Note that the above two checks will both fail if either val1 or
// val2 is NaN, as the IEEE floating-point standard requires that
// any predicate involving a NaN must return false.
::std::stringstream val1_ss;
val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< val1;
::std::stringstream val2_ss;
val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< val2;
return AssertionFailure()
<< "Expected: (" << expr1 << ") <= (" << expr2 << ")\n"
<< " Actual: " << StringStreamToString(&val1_ss) << " vs "
<< StringStreamToString(&val2_ss);
}
} // namespace internal
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult FloatLE(const char* expr1, const char* expr2,
float val1, float val2) {
return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);
}
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2) {
return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);
}
namespace internal {
// The helper function for {ASSERT|EXPECT}_EQ with int or enum
// arguments.
AssertionResult CmpHelperEQ(const char* expected_expression,
const char* actual_expression,
BiggestInt expected,
BiggestInt actual) {
if (expected == actual) {
return AssertionSuccess();
}
return EqFailure(expected_expression,
actual_expression,
FormatForComparisonFailureMessage(expected, actual),
FormatForComparisonFailureMessage(actual, expected),
false);
}
// A macro for implementing the helper functions needed to implement
// ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here
// just to avoid copy-and-paste of similar code.
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
BiggestInt val1, BiggestInt val2) {\
if (val1 op val2) {\
return AssertionSuccess();\
} else {\
return AssertionFailure() \
<< "Expected: (" << expr1 << ") " #op " (" << expr2\
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
}\
}
// Implements the helper function for {ASSERT|EXPECT}_NE with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(NE, !=)
// Implements the helper function for {ASSERT|EXPECT}_LE with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(LE, <=)
// Implements the helper function for {ASSERT|EXPECT}_LT with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(LT, < )
// Implements the helper function for {ASSERT|EXPECT}_GE with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(GE, >=)
// Implements the helper function for {ASSERT|EXPECT}_GT with int or
// enum arguments.
GTEST_IMPL_CMP_HELPER_(GT, > )
#undef GTEST_IMPL_CMP_HELPER_
// The helper function for {ASSERT|EXPECT}_STREQ.
AssertionResult CmpHelperSTREQ(const char* expected_expression,
const char* actual_expression,
const char* expected,
const char* actual) {
if (String::CStringEquals(expected, actual)) {
return AssertionSuccess();
}
return EqFailure(expected_expression,
actual_expression,
PrintToString(expected),
PrintToString(actual),
false);
}
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
const char* actual_expression,
const char* expected,
const char* actual) {
if (String::CaseInsensitiveCStringEquals(expected, actual)) {
return AssertionSuccess();
}
return EqFailure(expected_expression,
actual_expression,
PrintToString(expected),
PrintToString(actual),
true);
}
// The helper function for {ASSERT|EXPECT}_STRNE.
AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2) {
if (!String::CStringEquals(s1, s2)) {
return AssertionSuccess();
} else {
return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
<< s2_expression << "), actual: \""
<< s1 << "\" vs \"" << s2 << "\"";
}
}
// The helper function for {ASSERT|EXPECT}_STRCASENE.
AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2) {
if (!String::CaseInsensitiveCStringEquals(s1, s2)) {
return AssertionSuccess();
} else {
return AssertionFailure()
<< "Expected: (" << s1_expression << ") != ("
<< s2_expression << ") (ignoring case), actual: \""
<< s1 << "\" vs \"" << s2 << "\"";
}
}
} // namespace internal
namespace {
// Helper functions for implementing IsSubString() and IsNotSubstring().
// This group of overloaded functions return true iff needle is a
// substring of haystack. NULL is considered a substring of itself
// only.
bool IsSubstringPred(const char* needle, const char* haystack) {
if (needle == NULL || haystack == NULL)
return needle == haystack;
return strstr(haystack, needle) != NULL;
}
bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {
if (needle == NULL || haystack == NULL)
return needle == haystack;
return wcsstr(haystack, needle) != NULL;
}
// StringType here can be either ::std::string or ::std::wstring.
template <typename StringType>
bool IsSubstringPred(const StringType& needle,
const StringType& haystack) {
return haystack.find(needle) != StringType::npos;
}
// This function implements either IsSubstring() or IsNotSubstring(),
// depending on the value of the expected_to_be_substring parameter.
// StringType here can be const char*, const wchar_t*, ::std::string,
// or ::std::wstring.
template <typename StringType>
AssertionResult IsSubstringImpl(
bool expected_to_be_substring,
const char* needle_expr, const char* haystack_expr,
const StringType& needle, const StringType& haystack) {
if (IsSubstringPred(needle, haystack) == expected_to_be_substring)
return AssertionSuccess();
const bool is_wide_string = sizeof(needle[0]) > 1;
const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
return AssertionFailure()
<< "Value of: " << needle_expr << "\n"
<< " Actual: " << begin_string_quote << needle << "\"\n"
<< "Expected: " << (expected_to_be_substring ? "" : "not ")
<< "a substring of " << haystack_expr << "\n"
<< "Which is: " << begin_string_quote << haystack << "\"";
}
} // namespace
// IsSubstring() and IsNotSubstring() check whether needle is a
// substring of haystack (NULL is considered a substring of itself
// only), and return an appropriate error message when they fail.
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
#if GTEST_HAS_STD_WSTRING
AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack) {
return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);
}
AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack) {
return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);
}
#endif // GTEST_HAS_STD_WSTRING
namespace internal {
#if GTEST_OS_WINDOWS
namespace {
// Helper function for IsHRESULT{SuccessFailure} predicates
AssertionResult HRESULTFailureHelper(const char* expr,
const char* expected,
long hr) { // NOLINT
# if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't support FormatMessage.
const char error_text[] = "";
# else
// Looks up the human-readable system message for the HRESULT code
// and since we're not passing any params to FormatMessage, we don't
// want inserts expanded.
const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD kBufSize = 4096;
// Gets the system's human readable message string for this HRESULT.
char error_text[kBufSize] = { '\0' };
DWORD message_length = ::FormatMessageA(kFlags,
0, // no source, we're asking system
hr, // the error
0, // no line width restrictions
error_text, // output buffer
kBufSize, // buf size
NULL); // no arguments for inserts
// Trims tailing white space (FormatMessage leaves a trailing CR-LF)
for (; message_length && IsSpace(error_text[message_length - 1]);
--message_length) {
error_text[message_length - 1] = '\0';
}
# endif // GTEST_OS_WINDOWS_MOBILE
const std::string error_hex("0x" + String::FormatHexInt(hr));
return ::testing::AssertionFailure()
<< "Expected: " << expr << " " << expected << ".\n"
<< " Actual: " << error_hex << " " << error_text << "\n";
}
} // namespace
AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT
if (SUCCEEDED(hr)) {
return AssertionSuccess();
}
return HRESULTFailureHelper(expr, "succeeds", hr);
}
AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT
if (FAILED(hr)) {
return AssertionSuccess();
}
return HRESULTFailureHelper(expr, "fails", hr);
}
#endif // GTEST_OS_WINDOWS
// Utility functions for encoding Unicode text (wide strings) in
// UTF-8.
// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8
// like this:
//
// Code-point length Encoding
// 0 - 7 bits 0xxxxxxx
// 8 - 11 bits 110xxxxx 10xxxxxx
// 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx
// 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// The maximum code-point a one-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1;
// The maximum code-point a two-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;
// The maximum code-point a three-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;
// The maximum code-point a four-byte UTF-8 sequence can represent.
const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;
// Chops off the n lowest bits from a bit pattern. Returns the n
// lowest bits. As a side effect, the original bit pattern will be
// shifted to the right by n bits.
inline UInt32 ChopLowBits(UInt32* bits, int n) {
const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);
*bits >>= n;
return low_bits;
}
// Converts a Unicode code point to a narrow string in UTF-8 encoding.
// code_point parameter is of type UInt32 because wchar_t may not be
// wide enough to contain a code point.
// If the code_point is not a valid Unicode code point
// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted
// to "(Invalid Unicode 0xXXXXXXXX)".
std::string CodePointToUtf8(UInt32 code_point) {
if (code_point > kMaxCodePoint4) {
return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")";
}
char str[5]; // Big enough for the largest valid code point.
if (code_point <= kMaxCodePoint1) {
str[1] = '\0';
str[0] = static_cast<char>(code_point); // 0xxxxxxx
} else if (code_point <= kMaxCodePoint2) {
str[2] = '\0';
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx
} else if (code_point <= kMaxCodePoint3) {
str[3] = '\0';
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx
} else { // code_point <= kMaxCodePoint4
str[4] = '\0';
str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx
str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx
}
return str;
}
// The following two functions only make sense if the the system
// uses UTF-16 for wide string encoding. All supported systems
// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.
// Determines if the arguments constitute UTF-16 surrogate pair
// and thus should be combined into a single Unicode code point
// using CreateCodePointFromUtf16SurrogatePair.
inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {
return sizeof(wchar_t) == 2 &&
(first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;
}
// Creates a Unicode code point from UTF16 surrogate pair.
inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,
wchar_t second) {
const UInt32 mask = (1 << 10) - 1;
return (sizeof(wchar_t) == 2) ?
(((first & mask) << 10) | (second & mask)) + 0x10000 :
// This function should not be called when the condition is
// false, but we provide a sensible default in case it is.
static_cast<UInt32>(first);
}
// Converts a wide string to a narrow string in UTF-8 encoding.
// The wide string is assumed to have the following encoding:
// UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)
// UTF-32 if sizeof(wchar_t) == 4 (on Linux)
// Parameter str points to a null-terminated wide string.
// Parameter num_chars may additionally limit the number
// of wchar_t characters processed. -1 is used when the entire string
// should be processed.
// If the string contains code points that are not valid Unicode code points
// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output
// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding
// and contains invalid UTF-16 surrogate pairs, values in those pairs
// will be encoded as individual Unicode characters from Basic Normal Plane.
std::string WideStringToUtf8(const wchar_t* str, int num_chars) {
if (num_chars == -1)
num_chars = static_cast<int>(wcslen(str));
::std::stringstream stream;
for (int i = 0; i < num_chars; ++i) {
UInt32 unicode_code_point;
if (str[i] == L'\0') {
break;
} else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {
unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],
str[i + 1]);
i++;
} else {
unicode_code_point = static_cast<UInt32>(str[i]);
}
stream << CodePointToUtf8(unicode_code_point);
}
return StringStreamToString(&stream);
}
// Converts a wide C string to an std::string using the UTF-8 encoding.
// NULL will be converted to "(null)".
std::string String::ShowWideCString(const wchar_t * wide_c_str) {
if (wide_c_str == NULL) return "(null)";
return internal::WideStringToUtf8(wide_c_str, -1);
}
// Compares two wide C strings. Returns true iff they have the same
// content.
//
// Unlike wcscmp(), this function can handle NULL argument(s). A NULL
// C string is considered different to any non-NULL C string,
// including the empty string.
bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {
if (lhs == NULL) return rhs == NULL;
if (rhs == NULL) return false;
return wcscmp(lhs, rhs) == 0;
}
// Helper function for *_STREQ on wide strings.
AssertionResult CmpHelperSTREQ(const char* expected_expression,
const char* actual_expression,
const wchar_t* expected,
const wchar_t* actual) {
if (String::WideCStringEquals(expected, actual)) {
return AssertionSuccess();
}
return EqFailure(expected_expression,
actual_expression,
PrintToString(expected),
PrintToString(actual),
false);
}
// Helper function for *_STRNE on wide strings.
AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const wchar_t* s1,
const wchar_t* s2) {
if (!String::WideCStringEquals(s1, s2)) {
return AssertionSuccess();
}
return AssertionFailure() << "Expected: (" << s1_expression << ") != ("
<< s2_expression << "), actual: "
<< PrintToString(s1)
<< " vs " << PrintToString(s2);
}
// Compares two C strings, ignoring case. Returns true iff they have
// the same content.
//
// Unlike strcasecmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string,
// including the empty string.
bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {
if (lhs == NULL)
return rhs == NULL;
if (rhs == NULL)
return false;
return posix::StrCaseCmp(lhs, rhs) == 0;
}
// Compares two wide C strings, ignoring case. Returns true iff they
// have the same content.
//
// Unlike wcscasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL wide C string,
// including the empty string.
// NB: The implementations on different platforms slightly differ.
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
// environment variable. On GNU platform this method uses wcscasecmp
// which compares according to LC_CTYPE category of the current locale.
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
// current locale.
bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
const wchar_t* rhs) {
if (lhs == NULL) return rhs == NULL;
if (rhs == NULL) return false;
#if GTEST_OS_WINDOWS
return _wcsicmp(lhs, rhs) == 0;
#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID
return wcscasecmp(lhs, rhs) == 0;
#else
// Android, Mac OS X and Cygwin don't define wcscasecmp.
// Other unknown OSes may not define it either.
wint_t left, right;
do {
left = towlower(*lhs++);
right = towlower(*rhs++);
} while (left && left == right);
return left == right;
#endif // OS selector
}
// Returns true iff str ends with the given suffix, ignoring case.
// Any string is considered to end with an empty suffix.
bool String::EndsWithCaseInsensitive(
const std::string& str, const std::string& suffix) {
const size_t str_len = str.length();
const size_t suffix_len = suffix.length();
return (str_len >= suffix_len) &&
CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,
suffix.c_str());
}
// Formats an int value as "%02d".
std::string String::FormatIntWidth2(int value) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << value;
return ss.str();
}
// Formats an int value as "%X".
std::string String::FormatHexInt(int value) {
std::stringstream ss;
ss << std::hex << std::uppercase << value;
return ss.str();
}
// Formats a byte as "%02X".
std::string String::FormatByte(unsigned char value) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase
<< static_cast<unsigned int>(value);
return ss.str();
}
// Converts the buffer in a stringstream to an std::string, converting NUL
// bytes to "\\0" along the way.
std::string StringStreamToString(::std::stringstream* ss) {
const ::std::string& str = ss->str();
const char* const start = str.c_str();
const char* const end = start + str.length();
std::string result;
result.reserve(2 * (end - start));
for (const char* ch = start; ch != end; ++ch) {
if (*ch == '\0') {
result += "\\0"; // Replaces NUL with "\\0";
} else {
result += *ch;
}
}
return result;
}
// Appends the user-supplied message to the Google-Test-generated message.
std::string AppendUserMessage(const std::string& gtest_msg,
const Message& user_msg) {
// Appends the user message if it's non-empty.
const std::string user_msg_string = user_msg.GetString();
if (user_msg_string.empty()) {
return gtest_msg;
}
return gtest_msg + "\n" + user_msg_string;
}
} // namespace internal
// class TestResult
// Creates an empty TestResult.
TestResult::TestResult()
: death_test_count_(0),
elapsed_time_(0) {
}
// D'tor.
TestResult::~TestResult() {
}
// Returns the i-th test part result among all the results. i can
// range from 0 to total_part_count() - 1. If i is not in that range,
// aborts the program.
const TestPartResult& TestResult::GetTestPartResult(int i) const {
if (i < 0 || i >= total_part_count())
internal::posix::Abort();
return test_part_results_.at(i);
}
// Returns the i-th test property. i can range from 0 to
// test_property_count() - 1. If i is not in that range, aborts the
// program.
const TestProperty& TestResult::GetTestProperty(int i) const {
if (i < 0 || i >= test_property_count())
internal::posix::Abort();
return test_properties_.at(i);
}
// Clears the test part results.
void TestResult::ClearTestPartResults() {
test_part_results_.clear();
}
// Adds a test part result to the list.
void TestResult::AddTestPartResult(const TestPartResult& test_part_result) {
test_part_results_.push_back(test_part_result);
}
// Adds a test property to the list. If a property with the same key as the
// supplied property is already represented, the value of this test_property
// replaces the old value for that key.
void TestResult::RecordProperty(const std::string& xml_element,
const TestProperty& test_property) {
if (!ValidateTestProperty(xml_element, test_property)) {
return;
}
internal::MutexLock lock(&test_properites_mutex_);
const std::vector<TestProperty>::iterator property_with_matching_key =
std::find_if(test_properties_.begin(), test_properties_.end(),
internal::TestPropertyKeyIs(test_property.key()));
if (property_with_matching_key == test_properties_.end()) {
test_properties_.push_back(test_property);
return;
}
property_with_matching_key->SetValue(test_property.value());
}
// The list of reserved attributes used in the <testsuites> element of XML
// output.
static const char* const kReservedTestSuitesAttributes[] = {
"disabled",
"errors",
"failures",
"name",
"random_seed",
"tests",
"time",
"timestamp"
};
// The list of reserved attributes used in the <testsuite> element of XML
// output.
static const char* const kReservedTestSuiteAttributes[] = {
"disabled",
"errors",
"failures",
"name",
"tests",
"time"
};
// The list of reserved attributes used in the <testcase> element of XML output.
static const char* const kReservedTestCaseAttributes[] = {
"classname",
"name",
"status",
"time",
"type_param",
"value_param"
};
template <int kSize>
std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {
return std::vector<std::string>(array, array + kSize);
}
static std::vector<std::string> GetReservedAttributesForElement(
const std::string& xml_element) {
if (xml_element == "testsuites") {
return ArrayAsVector(kReservedTestSuitesAttributes);
} else if (xml_element == "testsuite") {
return ArrayAsVector(kReservedTestSuiteAttributes);
} else if (xml_element == "testcase") {
return ArrayAsVector(kReservedTestCaseAttributes);
} else {
GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element;
}
// This code is unreachable but some compilers may not realizes that.
return std::vector<std::string>();
}
static std::string FormatWordList(const std::vector<std::string>& words) {
Message word_list;
for (size_t i = 0; i < words.size(); ++i) {
if (i > 0 && words.size() > 2) {
word_list << ", ";
}
if (i == words.size() - 1) {
word_list << "and ";
}
word_list << "'" << words[i] << "'";
}
return word_list.GetString();
}
bool ValidateTestPropertyName(const std::string& property_name,
const std::vector<std::string>& reserved_names) {
if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=
reserved_names.end()) {
ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name
<< " (" << FormatWordList(reserved_names)
<< " are reserved by " << GTEST_NAME_ << ")";
return false;
}
return true;
}
// Adds a failure if the key is a reserved attribute of the element named
// xml_element. Returns true if the property is valid.
bool TestResult::ValidateTestProperty(const std::string& xml_element,
const TestProperty& test_property) {
return ValidateTestPropertyName(test_property.key(),
GetReservedAttributesForElement(xml_element));
}
// Clears the object.
void TestResult::Clear() {
test_part_results_.clear();
test_properties_.clear();
death_test_count_ = 0;
elapsed_time_ = 0;
}
// Returns true iff the test failed.
bool TestResult::Failed() const {
for (int i = 0; i < total_part_count(); ++i) {
if (GetTestPartResult(i).failed())
return true;
}
return false;
}
// Returns true iff the test part fatally failed.
static bool TestPartFatallyFailed(const TestPartResult& result) {
return result.fatally_failed();
}
// Returns true iff the test fatally failed.
bool TestResult::HasFatalFailure() const {
return CountIf(test_part_results_, TestPartFatallyFailed) > 0;
}
// Returns true iff the test part non-fatally failed.
static bool TestPartNonfatallyFailed(const TestPartResult& result) {
return result.nonfatally_failed();
}
// Returns true iff the test has a non-fatal failure.
bool TestResult::HasNonfatalFailure() const {
return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;
}
// Gets the number of all test parts. This is the sum of the number
// of successful test parts and the number of failed test parts.
int TestResult::total_part_count() const {
return static_cast<int>(test_part_results_.size());
}
// Returns the number of the test properties.
int TestResult::test_property_count() const {
return static_cast<int>(test_properties_.size());
}
// class Test
// Creates a Test object.
// The c'tor saves the values of all Google Test flags.
Test::Test()
: gtest_flag_saver_(new internal::GTestFlagSaver) {
}
// The d'tor restores the values of all Google Test flags.
Test::~Test() {
delete gtest_flag_saver_;
}
// Sets up the test fixture.
//
// A sub-class may override this.
void Test::SetUp() {
}
// Tears down the test fixture.
//
// A sub-class may override this.
void Test::TearDown() {
}
// Allows user supplied key value pairs to be recorded for later output.
void Test::RecordProperty(const std::string& key, const std::string& value) {
UnitTest::GetInstance()->RecordProperty(key, value);
}
// Allows user supplied key value pairs to be recorded for later output.
void Test::RecordProperty(const std::string& key, int value) {
Message value_message;
value_message << value;
RecordProperty(key, value_message.GetString().c_str());
}
namespace internal {
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const std::string& message) {
// This function is a friend of UnitTest and as such has access to
// AddTestPartResult.
UnitTest::GetInstance()->AddTestPartResult(
result_type,
NULL, // No info about the source file where the exception occurred.
-1, // We have no info on which line caused the exception.
message,
""); // No stack trace, either.
}
} // namespace internal
// Google Test requires all tests in the same test case to use the same test
// fixture class. This function checks if the current test has the
// same fixture class as the first test in the current test case. If
// yes, it returns true; otherwise it generates a Google Test failure and
// returns false.
bool Test::HasSameFixtureClass() {
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
const TestCase* const test_case = impl->current_test_case();
// Info about the first test in the current test case.
const TestInfo* const first_test_info = test_case->test_info_list()[0];
const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;
const char* const first_test_name = first_test_info->name();
// Info about the current test.
const TestInfo* const this_test_info = impl->current_test_info();
const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;
const char* const this_test_name = this_test_info->name();
if (this_fixture_id != first_fixture_id) {
// Is the first test defined using TEST?
const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();
// Is this test defined using TEST?
const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();
if (first_is_TEST || this_is_TEST) {
// The user mixed TEST and TEST_F in this test case - we'll tell
// him/her how to fix it.
// Gets the name of the TEST and the name of the TEST_F. Note
// that first_is_TEST and this_is_TEST cannot both be true, as
// the fixture IDs are different for the two tests.
const char* const TEST_name =
first_is_TEST ? first_test_name : this_test_name;
const char* const TEST_F_name =
first_is_TEST ? this_test_name : first_test_name;
ADD_FAILURE()
<< "All tests in the same test case must use the same test fixture\n"
<< "class, so mixing TEST_F and TEST in the same test case is\n"
<< "illegal. In test case " << this_test_info->test_case_name()
<< ",\n"
<< "test " << TEST_F_name << " is defined using TEST_F but\n"
<< "test " << TEST_name << " is defined using TEST. You probably\n"
<< "want to change the TEST to TEST_F or move it to another test\n"
<< "case.";
} else {
// The user defined two fixture classes with the same name in
// two namespaces - we'll tell him/her how to fix it.
ADD_FAILURE()
<< "All tests in the same test case must use the same test fixture\n"
<< "class. However, in test case "
<< this_test_info->test_case_name() << ",\n"
<< "you defined test " << first_test_name
<< " and test " << this_test_name << "\n"
<< "using two different test fixture classes. This can happen if\n"
<< "the two classes are from different namespaces or translation\n"
<< "units and have the same name. You should probably rename one\n"
<< "of the classes to put the tests into different test cases.";
}
return false;
}
return true;
}
#if GTEST_HAS_SEH
// Adds an "exception thrown" fatal failure to the current test. This
// function returns its result via an output parameter pointer because VC++
// prohibits creation of objects with destructors on stack in functions
// using __try (see error C2712).
static std::string* FormatSehExceptionMessage(DWORD exception_code,
const char* location) {
Message message;
message << "SEH exception with code 0x" << std::setbase(16) <<
exception_code << std::setbase(10) << " thrown in " << location << ".";
return new std::string(message.GetString());
}
#endif // GTEST_HAS_SEH
namespace internal {
#if GTEST_HAS_EXCEPTIONS
// Adds an "exception thrown" fatal failure to the current test.
static std::string FormatCxxExceptionMessage(const char* description,
const char* location) {
Message message;
if (description != NULL) {
message << "C++ exception with description \"" << description << "\"";
} else {
message << "Unknown C++ exception";
}
message << " thrown in " << location << ".";
return message.GetString();
}
static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result);
GoogleTestFailureException::GoogleTestFailureException(
const TestPartResult& failure)
: ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}
#endif // GTEST_HAS_EXCEPTIONS
// We put these helper functions in the internal namespace as IBM's xlC
// compiler rejects the code if they were declared static.
// Runs the given method and handles SEH exceptions it throws, when
// SEH is supported; returns the 0-value for type Result in case of an
// SEH exception. (Microsoft compilers cannot handle SEH and C++
// exceptions in the same function. Therefore, we provide a separate
// wrapper function for handling SEH exceptions.)
template <class T, typename Result>
Result HandleSehExceptionsInMethodIfSupported(
T* object, Result (T::*method)(), const char* location) {
#if GTEST_HAS_SEH
__try {
return (object->*method)();
} __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT
GetExceptionCode())) {
// We create the exception message on the heap because VC++ prohibits
// creation of objects with destructors on stack in functions using __try
// (see error C2712).
std::string* exception_message = FormatSehExceptionMessage(
GetExceptionCode(), location);
internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,
*exception_message);
delete exception_message;
return static_cast<Result>(0);
}
#else
(void)location;
return (object->*method)();
#endif // GTEST_HAS_SEH
}
// Runs the given method and catches and reports C++ and/or SEH-style
// exceptions, if they are supported; returns the 0-value for type
// Result in case of an SEH exception.
template <class T, typename Result>
Result HandleExceptionsInMethodIfSupported(
T* object, Result (T::*method)(), const char* location) {
// NOTE: The user code can affect the way in which Google Test handles
// exceptions by setting GTEST_FLAG(catch_exceptions), but only before
// RUN_ALL_TESTS() starts. It is technically possible to check the flag
// after the exception is caught and either report or re-throw the
// exception based on the flag's value:
//
// try {
// // Perform the test method.
// } catch (...) {
// if (GTEST_FLAG(catch_exceptions))
// // Report the exception as failure.
// else
// throw; // Re-throws the original exception.
// }
//
// However, the purpose of this flag is to allow the program to drop into
// the debugger when the exception is thrown. On most platforms, once the
// control enters the catch block, the exception origin information is
// lost and the debugger will stop the program at the point of the
// re-throw in this function -- instead of at the point of the original
// throw statement in the code under test. For this reason, we perform
// the check early, sacrificing the ability to affect Google Test's
// exception handling in the method where the exception is thrown.
if (internal::GetUnitTestImpl()->catch_exceptions()) {
#if GTEST_HAS_EXCEPTIONS
try {
return HandleSehExceptionsInMethodIfSupported(object, method, location);
} catch (const internal::GoogleTestFailureException&) { // NOLINT
// This exception type can only be thrown by a failed Google
// Test assertion with the intention of letting another testing
// framework catch it. Therefore we just re-throw it.
throw;
} catch (const std::exception& e) { // NOLINT
internal::ReportFailureInUnknownLocation(
TestPartResult::kFatalFailure,
FormatCxxExceptionMessage(e.what(), location));
} catch (...) { // NOLINT
internal::ReportFailureInUnknownLocation(
TestPartResult::kFatalFailure,
FormatCxxExceptionMessage(NULL, location));
}
return static_cast<Result>(0);
#else
return HandleSehExceptionsInMethodIfSupported(object, method, location);
#endif // GTEST_HAS_EXCEPTIONS
} else {
return (object->*method)();
}
}
} // namespace internal
// Runs the test and updates the test result.
void Test::Run() {
if (!HasSameFixtureClass()) return;
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()");
// We will run the test only if SetUp() was successful.
if (!HasFatalFailure()) {
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &Test::TestBody, "the test body");
}
// However, we want to clean up as much as possible. Hence we will
// always call TearDown(), even if SetUp() or the test body has
// failed.
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &Test::TearDown, "TearDown()");
}
// Returns true iff the current test has a fatal failure.
bool Test::HasFatalFailure() {
return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();
}
// Returns true iff the current test has a non-fatal failure.
bool Test::HasNonfatalFailure() {
return internal::GetUnitTestImpl()->current_test_result()->
HasNonfatalFailure();
}
// class TestInfo
// Constructs a TestInfo object. It assumes ownership of the test factory
// object.
TestInfo::TestInfo(const std::string& a_test_case_name,
const std::string& a_name,
const char* a_type_param,
const char* a_value_param,
internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory)
: test_case_name_(a_test_case_name),
name_(a_name),
type_param_(a_type_param ? new std::string(a_type_param) : NULL),
value_param_(a_value_param ? new std::string(a_value_param) : NULL),
fixture_class_id_(fixture_class_id),
should_run_(false),
is_disabled_(false),
matches_filter_(false),
factory_(factory),
result_() {}
// Destructs a TestInfo object.
TestInfo::~TestInfo() { delete factory_; }
namespace internal {
// Creates a new TestInfo object and registers it with Google Test;
// returns the created object.
//
// Arguments:
//
// test_case_name: name of the test case
// name: name of the test
// type_param: the name of the test's type parameter, or NULL if
// this is not a typed or a type-parameterized test.
// value_param: text representation of the test's value parameter,
// or NULL if this is not a value-parameterized test.
// fixture_class_id: ID of the test fixture class
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
// factory: pointer to the factory that creates a test object.
// The newly created TestInfo instance will assume
// ownership of the factory object.
TestInfo* MakeAndRegisterTestInfo(
const char* test_case_name,
const char* name,
const char* type_param,
const char* value_param,
TypeId fixture_class_id,
SetUpTestCaseFunc set_up_tc,
TearDownTestCaseFunc tear_down_tc,
TestFactoryBase* factory) {
TestInfo* const test_info =
new TestInfo(test_case_name, name, type_param, value_param,
fixture_class_id, factory);
GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);
return test_info;
}
#if GTEST_HAS_PARAM_TEST
void ReportInvalidTestCaseType(const char* test_case_name,
const char* file, int line) {
Message errors;
errors
<< "Attempted redefinition of test case " << test_case_name << ".\n"
<< "All tests in the same test case must use the same test fixture\n"
<< "class. However, in test case " << test_case_name << ", you tried\n"
<< "to define a test using a fixture class different from the one\n"
<< "used earlier. This can happen if the two fixture classes are\n"
<< "from different namespaces and have the same name. You should\n"
<< "probably rename one of the classes to put the tests into different\n"
<< "test cases.";
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
errors.GetString().c_str());
}
#endif // GTEST_HAS_PARAM_TEST
} // namespace internal
namespace {
// A predicate that checks the test name of a TestInfo against a known
// value.
//
// This is used for implementation of the TestCase class only. We put
// it in the anonymous namespace to prevent polluting the outer
// namespace.
//
// TestNameIs is copyable.
class TestNameIs {
public:
// Constructor.
//
// TestNameIs has NO default constructor.
explicit TestNameIs(const char* name)
: name_(name) {}
// Returns true iff the test name of test_info matches name_.
bool operator()(const TestInfo * test_info) const {
return test_info && test_info->name() == name_;
}
private:
std::string name_;
};
} // namespace
namespace internal {
// This method expands all parameterized tests registered with macros TEST_P
// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.
// This will be done just once during the program runtime.
void UnitTestImpl::RegisterParameterizedTests() {
#if GTEST_HAS_PARAM_TEST
if (!parameterized_tests_registered_) {
parameterized_test_registry_.RegisterTests();
parameterized_tests_registered_ = true;
}
#endif
}
} // namespace internal
// Creates the test object, runs it, records its result, and then
// deletes it.
void TestInfo::Run() {
if (!should_run_) return;
// Tells UnitTest where to store test result.
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
impl->set_current_test_info(this);
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
// Notifies the unit test event listeners that a test is about to start.
repeater->OnTestStart(*this);
const TimeInMillis start = internal::GetTimeInMillis();
impl->os_stack_trace_getter()->UponLeavingGTest();
// Creates the test object.
Test* const test = internal::HandleExceptionsInMethodIfSupported(
factory_, &internal::TestFactoryBase::CreateTest,
"the test fixture's constructor");
// Runs the test only if the test object was created and its
// constructor didn't generate a fatal failure.
if ((test != NULL) && !Test::HasFatalFailure()) {
// This doesn't throw as all user code that can throw are wrapped into
// exception handling code.
test->Run();
}
// Deletes the test object.
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
test, &Test::DeleteSelf_, "the test fixture's destructor");
result_.set_elapsed_time(internal::GetTimeInMillis() - start);
// Notifies the unit test event listener that a test has just finished.
repeater->OnTestEnd(*this);
// Tells UnitTest to stop associating assertion results to this
// test.
impl->set_current_test_info(NULL);
}
// class TestCase
// Gets the number of successful tests in this test case.
int TestCase::successful_test_count() const {
return CountIf(test_info_list_, TestPassed);
}
// Gets the number of failed tests in this test case.
int TestCase::failed_test_count() const {
return CountIf(test_info_list_, TestFailed);
}
// Gets the number of disabled tests that will be reported in the XML report.
int TestCase::reportable_disabled_test_count() const {
return CountIf(test_info_list_, TestReportableDisabled);
}
// Gets the number of disabled tests in this test case.
int TestCase::disabled_test_count() const {
return CountIf(test_info_list_, TestDisabled);
}
// Gets the number of tests to be printed in the XML report.
int TestCase::reportable_test_count() const {
return CountIf(test_info_list_, TestReportable);
}
// Get the number of tests in this test case that should run.
int TestCase::test_to_run_count() const {
return CountIf(test_info_list_, ShouldRunTest);
}
// Gets the number of all tests.
int TestCase::total_test_count() const {
return static_cast<int>(test_info_list_.size());
}
// Creates a TestCase with the given name.
//
// Arguments:
//
// name: name of the test case
// a_type_param: the name of the test case's type parameter, or NULL if
// this is not a typed or a type-parameterized test case.
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
TestCase::TestCase(const char* a_name, const char* a_type_param,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc)
: name_(a_name),
type_param_(a_type_param ? new std::string(a_type_param) : NULL),
set_up_tc_(set_up_tc),
tear_down_tc_(tear_down_tc),
should_run_(false),
elapsed_time_(0) {
}
// Destructor of TestCase.
TestCase::~TestCase() {
// Deletes every Test in the collection.
ForEach(test_info_list_, internal::Delete<TestInfo>);
}
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
const TestInfo* TestCase::GetTestInfo(int i) const {
const int index = GetElementOr(test_indices_, i, -1);
return index < 0 ? NULL : test_info_list_[index];
}
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
TestInfo* TestCase::GetMutableTestInfo(int i) {
const int index = GetElementOr(test_indices_, i, -1);
return index < 0 ? NULL : test_info_list_[index];
}
// Adds a test to this test case. Will delete the test upon
// destruction of the TestCase object.
void TestCase::AddTestInfo(TestInfo * test_info) {
test_info_list_.push_back(test_info);
test_indices_.push_back(static_cast<int>(test_indices_.size()));
}
// Runs every test in this TestCase.
void TestCase::Run() {
if (!should_run_) return;
internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();
impl->set_current_test_case(this);
TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();
repeater->OnTestCaseStart(*this);
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &TestCase::RunSetUpTestCase, "SetUpTestCase()");
const internal::TimeInMillis start = internal::GetTimeInMillis();
for (int i = 0; i < total_test_count(); i++) {
GetMutableTestInfo(i)->Run();
}
elapsed_time_ = internal::GetTimeInMillis() - start;
impl->os_stack_trace_getter()->UponLeavingGTest();
internal::HandleExceptionsInMethodIfSupported(
this, &TestCase::RunTearDownTestCase, "TearDownTestCase()");
repeater->OnTestCaseEnd(*this);
impl->set_current_test_case(NULL);
}
// Clears the results of all tests in this test case.
void TestCase::ClearResult() {
ad_hoc_test_result_.Clear();
ForEach(test_info_list_, TestInfo::ClearTestResult);
}
// Shuffles the tests in this test case.
void TestCase::ShuffleTests(internal::Random* random) {
Shuffle(random, &test_indices_);
}
// Restores the test order to before the first shuffle.
void TestCase::UnshuffleTests() {
for (size_t i = 0; i < test_indices_.size(); i++) {
test_indices_[i] = static_cast<int>(i);
}
}
// Formats a countable noun. Depending on its quantity, either the
// singular form or the plural form is used. e.g.
//
// FormatCountableNoun(1, "formula", "formuli") returns "1 formula".
// FormatCountableNoun(5, "book", "books") returns "5 books".
static std::string FormatCountableNoun(int count,
const char * singular_form,
const char * plural_form) {
return internal::StreamableToString(count) + " " +
(count == 1 ? singular_form : plural_form);
}
// Formats the count of tests.
static std::string FormatTestCount(int test_count) {
return FormatCountableNoun(test_count, "test", "tests");
}
// Formats the count of test cases.
static std::string FormatTestCaseCount(int test_case_count) {
return FormatCountableNoun(test_case_count, "test case", "test cases");
}
// Converts a TestPartResult::Type enum to human-friendly string
// representation. Both kNonFatalFailure and kFatalFailure are translated
// to "Failure", as the user usually doesn't care about the difference
// between the two when viewing the test result.
static const char * TestPartResultTypeToString(TestPartResult::Type type) {
switch (type) {
case TestPartResult::kSuccess:
return "Success";
case TestPartResult::kNonFatalFailure:
case TestPartResult::kFatalFailure:
#ifdef _MSC_VER
return "error: ";
#else
return "Failure\n";
#endif
default:
return "Unknown result type";
}
}
namespace internal {
// Prints a TestPartResult to an std::string.
static std::string PrintTestPartResultToString(
const TestPartResult& test_part_result) {
return (Message()
<< internal::FormatFileLocation(test_part_result.file_name(),
test_part_result.line_number())
<< " " << TestPartResultTypeToString(test_part_result.type())
<< test_part_result.message()).GetString();
}
// Prints a TestPartResult.
static void PrintTestPartResult(const TestPartResult& test_part_result) {
const std::string& result =
PrintTestPartResultToString(test_part_result);
printf("%s\n", result.c_str());
fflush(stdout);
// If the test program runs in Visual Studio or a debugger, the
// following statements add the test part result message to the Output
// window such that the user can double-click on it to jump to the
// corresponding source code location; otherwise they do nothing.
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
// We don't call OutputDebugString*() on Windows Mobile, as printing
// to stdout is done by OutputDebugString() there already - we don't
// want the same message printed twice.
::OutputDebugStringA(result.c_str());
::OutputDebugStringA("\n");
#endif
}
// class PrettyUnitTestResultPrinter
enum GTestColor {
COLOR_DEFAULT,
COLOR_RED,
COLOR_GREEN,
COLOR_YELLOW
};
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
// Returns the character attribute for the given color.
WORD GetColorAttribute(GTestColor color) {
switch (color) {
case COLOR_RED: return FOREGROUND_RED;
case COLOR_GREEN: return FOREGROUND_GREEN;
case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;
default: return 0;
}
}
#else
// Returns the ANSI color code for the given color. COLOR_DEFAULT is
// an invalid input.
const char* GetAnsiColorCode(GTestColor color) {
switch (color) {
case COLOR_RED: return "1";
case COLOR_GREEN: return "2";
case COLOR_YELLOW: return "3";
default: return NULL;
};
}
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
// Returns true iff Google Test should use colors in the output.
bool ShouldUseColor(bool stdout_is_tty) {
const char* const gtest_color = GTEST_FLAG(color).c_str();
if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) {
#if GTEST_OS_WINDOWS
// On Windows the TERM variable is usually not set, but the
// console there does support colors.
return stdout_is_tty;
#else
// On non-Windows platforms, we rely on the TERM variable.
const char* const term = posix::GetEnv("TERM");
const bool term_supports_color =
String::CStringEquals(term, "xterm") ||
String::CStringEquals(term, "xterm-color") ||
String::CStringEquals(term, "xterm-256color") ||
String::CStringEquals(term, "screen") ||
String::CStringEquals(term, "screen-256color") ||
String::CStringEquals(term, "linux") ||
String::CStringEquals(term, "cygwin");
return stdout_is_tty && term_supports_color;
#endif // GTEST_OS_WINDOWS
}
return String::CaseInsensitiveCStringEquals(gtest_color, "yes") ||
String::CaseInsensitiveCStringEquals(gtest_color, "true") ||
String::CaseInsensitiveCStringEquals(gtest_color, "t") ||
String::CStringEquals(gtest_color, "1");
// We take "yes", "true", "t", and "1" as meaning "yes". If the
// value is neither one of these nor "auto", we treat it as "no" to
// be conservative.
}
// Helpers for printing colored strings to stdout. Note that on Windows, we
// cannot simply emit special characters and have the terminal change colors.
// This routine must actually emit the characters rather than return a string
// that would be colored when printed, as can be done on Linux.
void ColoredPrintf(GTestColor color, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || GTEST_OS_IOS
const bool use_color = false;
#else
static const bool in_color_mode =
ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);
const bool use_color = in_color_mode && (color != COLOR_DEFAULT);
#endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS
// The '!= 0' comparison is necessary to satisfy MSVC 7.1.
if (!use_color) {
vprintf(fmt, args);
va_end(args);
return;
}
#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
// Gets the current text color.
CONSOLE_SCREEN_BUFFER_INFO buffer_info;
GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);
const WORD old_color_attrs = buffer_info.wAttributes;
// We need to flush the stream buffers into the console before each
// SetConsoleTextAttribute call lest it affect the text that is already
// printed but has not yet reached the console.
fflush(stdout);
SetConsoleTextAttribute(stdout_handle,
GetColorAttribute(color) | FOREGROUND_INTENSITY);
vprintf(fmt, args);
fflush(stdout);
// Restores the text color.
SetConsoleTextAttribute(stdout_handle, old_color_attrs);
#else
printf("\033[0;3%sm", GetAnsiColorCode(color));
vprintf(fmt, args);
printf("\033[m"); // Resets the terminal to default.
#endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE
va_end(args);
}
// Text printed in Google Test's text output and --gunit_list_tests
// output to label the type parameter and value parameter for a test.
static const char kTypeParamLabel[] = "TypeParam";
static const char kValueParamLabel[] = "GetParam()";
void PrintFullTestCommentIfPresent(const TestInfo& test_info) {
const char* const type_param = test_info.type_param();
const char* const value_param = test_info.value_param();
if (type_param != NULL || value_param != NULL) {
printf(", where ");
if (type_param != NULL) {
printf("%s = %s", kTypeParamLabel, type_param);
if (value_param != NULL)
printf(" and ");
}
if (value_param != NULL) {
printf("%s = %s", kValueParamLabel, value_param);
}
}
}
// This class implements the TestEventListener interface.
//
// Class PrettyUnitTestResultPrinter is copyable.
class PrettyUnitTestResultPrinter : public TestEventListener {
public:
PrettyUnitTestResultPrinter() {}
static void PrintTestName(const char * test_case, const char * test) {
printf("%s.%s", test_case, test);
}
// The following methods override what's in the TestEventListener class.
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
virtual void OnTestCaseStart(const TestCase& test_case);
virtual void OnTestStart(const TestInfo& test_info);
virtual void OnTestPartResult(const TestPartResult& result);
virtual void OnTestEnd(const TestInfo& test_info);
virtual void OnTestCaseEnd(const TestCase& test_case);
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
private:
static void PrintFailedTests(const UnitTest& unit_test);
};
// Fired before each iteration of tests starts.
void PrettyUnitTestResultPrinter::OnTestIterationStart(
const UnitTest& unit_test, int iteration) {
if (GTEST_FLAG(repeat) != 1)
printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1);
const char* const filter = GTEST_FLAG(filter).c_str();
// Prints the filter if it's not *. This reminds the user that some
// tests may be skipped.
if (!String::CStringEquals(filter, kUniversalFilter)) {
ColoredPrintf(COLOR_YELLOW,
"Note: %s filter = %s\n", GTEST_NAME_, filter);
}
if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {
const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);
ColoredPrintf(COLOR_YELLOW,
"Note: This is test shard %d of %s.\n",
static_cast<int>(shard_index) + 1,
internal::posix::GetEnv(kTestTotalShards));
}
if (GTEST_FLAG(shuffle)) {
ColoredPrintf(COLOR_YELLOW,
"Note: Randomizing tests' orders with a seed of %d .\n",
unit_test.random_seed());
}
ColoredPrintf(COLOR_GREEN, "[==========] ");
printf("Running %s from %s.\n",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(
const UnitTest& /*unit_test*/) {
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("Global test environment set-up.\n");
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {
const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("%s from %s", counts.c_str(), test_case.name());
if (test_case.type_param() == NULL) {
printf("\n");
} else {
printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param());
}
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {
ColoredPrintf(COLOR_GREEN, "[ RUN ] ");
PrintTestName(test_info.test_case_name(), test_info.name());
printf("\n");
fflush(stdout);
}
// Called after an assertion failure.
void PrettyUnitTestResultPrinter::OnTestPartResult(
const TestPartResult& result) {
// If the test part succeeded, we don't need to do anything.
if (result.type() == TestPartResult::kSuccess)
return;
// Print failure message from the assertion (e.g. expected this and got that).
PrintTestPartResult(result);
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {
if (test_info.result()->Passed()) {
ColoredPrintf(COLOR_GREEN, "[ OK ] ");
} else {
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
}
PrintTestName(test_info.test_case_name(), test_info.name());
if (test_info.result()->Failed())
PrintFullTestCommentIfPresent(test_info);
if (GTEST_FLAG(print_time)) {
printf(" (%s ms)\n", internal::StreamableToString(
test_info.result()->elapsed_time()).c_str());
} else {
printf("\n");
}
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {
if (!GTEST_FLAG(print_time)) return;
const std::string counts =
FormatCountableNoun(test_case.test_to_run_count(), "test", "tests");
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("%s from %s (%s ms total)\n\n",
counts.c_str(), test_case.name(),
internal::StreamableToString(test_case.elapsed_time()).c_str());
fflush(stdout);
}
void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(
const UnitTest& /*unit_test*/) {
ColoredPrintf(COLOR_GREEN, "[----------] ");
printf("Global test environment tear-down\n");
fflush(stdout);
}
// Internal helper for printing the list of failed tests.
void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {
const int failed_test_count = unit_test.failed_test_count();
if (failed_test_count == 0) {
return;
}
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
const TestCase& test_case = *unit_test.GetTestCase(i);
if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {
continue;
}
for (int j = 0; j < test_case.total_test_count(); ++j) {
const TestInfo& test_info = *test_case.GetTestInfo(j);
if (!test_info.should_run() || test_info.result()->Passed()) {
continue;
}
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s.%s", test_case.name(), test_info.name());
PrintFullTestCommentIfPresent(test_info);
printf("\n");
}
}
}
void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
ColoredPrintf(COLOR_GREEN, "[==========] ");
printf("%s from %s ran.",
FormatTestCount(unit_test.test_to_run_count()).c_str(),
FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());
if (GTEST_FLAG(print_time)) {
printf(" (%s ms total)",
internal::StreamableToString(unit_test.elapsed_time()).c_str());
}
printf("\n");
ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str());
int num_failures = unit_test.failed_test_count();
if (!unit_test.Passed()) {
const int failed_test_count = unit_test.failed_test_count();
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str());
PrintFailedTests(unit_test);
printf("\n%2d FAILED %s\n", num_failures,
num_failures == 1 ? "TEST" : "TESTS");
}
int num_disabled = unit_test.reportable_disabled_test_count();
if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {
if (!num_failures) {
printf("\n"); // Add a spacer if no FAILURE banner is displayed.
}
ColoredPrintf(COLOR_YELLOW,
" YOU HAVE %d DISABLED %s\n\n",
num_disabled,
num_disabled == 1 ? "TEST" : "TESTS");
}
// Ensure that Google Test output is printed before, e.g., heapchecker output.
fflush(stdout);
}
// End PrettyUnitTestResultPrinter
// class TestEventRepeater
//
// This class forwards events to other event listeners.
class TestEventRepeater : public TestEventListener {
public:
TestEventRepeater() : forwarding_enabled_(true) {}
virtual ~TestEventRepeater();
void Append(TestEventListener *listener);
TestEventListener* Release(TestEventListener* listener);
// Controls whether events will be forwarded to listeners_. Set to false
// in death test child processes.
bool forwarding_enabled() const { return forwarding_enabled_; }
void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }
virtual void OnTestProgramStart(const UnitTest& unit_test);
virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);
virtual void OnTestCaseStart(const TestCase& test_case);
virtual void OnTestStart(const TestInfo& test_info);
virtual void OnTestPartResult(const TestPartResult& result);
virtual void OnTestEnd(const TestInfo& test_info);
virtual void OnTestCaseEnd(const TestCase& test_case);
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
virtual void OnTestProgramEnd(const UnitTest& unit_test);
private:
// Controls whether events will be forwarded to listeners_. Set to false
// in death test child processes.
bool forwarding_enabled_;
// The list of listeners that receive events.
std::vector<TestEventListener*> listeners_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);
};
TestEventRepeater::~TestEventRepeater() {
ForEach(listeners_, Delete<TestEventListener>);
}
void TestEventRepeater::Append(TestEventListener *listener) {
listeners_.push_back(listener);
}
// TODO(vladl@google.com): Factor the search functionality into Vector::Find.
TestEventListener* TestEventRepeater::Release(TestEventListener *listener) {
for (size_t i = 0; i < listeners_.size(); ++i) {
if (listeners_[i] == listener) {
listeners_.erase(listeners_.begin() + i);
return listener;
}
}
return NULL;
}
// Since most methods are very similar, use macros to reduce boilerplate.
// This defines a member that forwards the call to all listeners.
#define GTEST_REPEATER_METHOD_(Name, Type) \
void TestEventRepeater::Name(const Type& parameter) { \
if (forwarding_enabled_) { \
for (size_t i = 0; i < listeners_.size(); i++) { \
listeners_[i]->Name(parameter); \
} \
} \
}
// This defines a member that forwards the call to all listeners in reverse
// order.
#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \
void TestEventRepeater::Name(const Type& parameter) { \
if (forwarding_enabled_) { \
for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \
listeners_[i]->Name(parameter); \
} \
} \
}
GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)
GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)
GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)
GTEST_REPEATER_METHOD_(OnTestStart, TestInfo)
GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)
GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)
GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)
GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)
GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)
GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)
#undef GTEST_REPEATER_METHOD_
#undef GTEST_REVERSE_REPEATER_METHOD_
void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,
int iteration) {
if (forwarding_enabled_) {
for (size_t i = 0; i < listeners_.size(); i++) {
listeners_[i]->OnTestIterationStart(unit_test, iteration);
}
}
}
void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,
int iteration) {
if (forwarding_enabled_) {
for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {
listeners_[i]->OnTestIterationEnd(unit_test, iteration);
}
}
}
// End TestEventRepeater
// This class generates an XML output file.
class XmlUnitTestResultPrinter : public EmptyTestEventListener {
public:
explicit XmlUnitTestResultPrinter(const char* output_file);
virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);
private:
// Is c a whitespace character that is normalized to a space character
// when it appears in an XML attribute value?
static bool IsNormalizableWhitespace(char c) {
return c == 0x9 || c == 0xA || c == 0xD;
}
// May c appear in a well-formed XML document?
static bool IsValidXmlCharacter(char c) {
return IsNormalizableWhitespace(c) || c >= 0x20;
}
// Returns an XML-escaped copy of the input string str. If
// is_attribute is true, the text is meant to appear as an attribute
// value, and normalizable whitespace is preserved by replacing it
// with character references.
static std::string EscapeXml(const std::string& str, bool is_attribute);
// Returns the given string with all characters invalid in XML removed.
static std::string RemoveInvalidXmlCharacters(const std::string& str);
// Convenience wrapper around EscapeXml when str is an attribute value.
static std::string EscapeXmlAttribute(const std::string& str) {
return EscapeXml(str, true);
}
// Convenience wrapper around EscapeXml when str is not an attribute value.
static std::string EscapeXmlText(const char* str) {
return EscapeXml(str, false);
}
// Verifies that the given attribute belongs to the given element and
// streams the attribute as XML.
static void OutputXmlAttribute(std::ostream* stream,
const std::string& element_name,
const std::string& name,
const std::string& value);
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
static void OutputXmlCDataSection(::std::ostream* stream, const char* data);
// Streams an XML representation of a TestInfo object.
static void OutputXmlTestInfo(::std::ostream* stream,
const char* test_case_name,
const TestInfo& test_info);
// Prints an XML representation of a TestCase object
static void PrintXmlTestCase(::std::ostream* stream,
const TestCase& test_case);
// Prints an XML summary of unit_test to output stream out.
static void PrintXmlUnitTest(::std::ostream* stream,
const UnitTest& unit_test);
// Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs.
// When the std::string is not empty, it includes a space at the beginning,
// to delimit this attribute from prior attributes.
static std::string TestPropertiesAsXmlAttributes(const TestResult& result);
// The output file.
const std::string output_file_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);
};
// Creates a new XmlUnitTestResultPrinter.
XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)
: output_file_(output_file) {
if (output_file_.c_str() == NULL || output_file_.empty()) {
fprintf(stderr, "XML output file may not be null\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
}
// Called after the unit test ends.
void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,
int /*iteration*/) {
FILE* xmlout = NULL;
FilePath output_file(output_file_);
FilePath output_dir(output_file.RemoveFileName());
if (output_dir.CreateDirectoriesRecursively()) {
xmlout = posix::FOpen(output_file_.c_str(), "w");
}
if (xmlout == NULL) {
// TODO(wan): report the reason of the failure.
//
// We don't do it for now as:
//
// 1. There is no urgent need for it.
// 2. It's a bit involved to make the errno variable thread-safe on
// all three operating systems (Linux, Windows, and Mac OS).
// 3. To interpret the meaning of errno in a thread-safe way,
// we need the strerror_r() function, which is not available on
// Windows.
fprintf(stderr,
"Unable to open file \"%s\"\n",
output_file_.c_str());
fflush(stderr);
exit(EXIT_FAILURE);
}
std::stringstream stream;
PrintXmlUnitTest(&stream, unit_test);
fprintf(xmlout, "%s", StringStreamToString(&stream).c_str());
fclose(xmlout);
}
// Returns an XML-escaped copy of the input string str. If is_attribute
// is true, the text is meant to appear as an attribute value, and
// normalizable whitespace is preserved by replacing it with character
// references.
//
// Invalid XML characters in str, if any, are stripped from the output.
// It is expected that most, if not all, of the text processed by this
// module will consist of ordinary English text.
// If this module is ever modified to produce version 1.1 XML output,
// most invalid characters can be retained using character references.
// TODO(wan): It might be nice to have a minimally invasive, human-readable
// escaping scheme for invalid characters, rather than dropping them.
std::string XmlUnitTestResultPrinter::EscapeXml(
const std::string& str, bool is_attribute) {
Message m;
for (size_t i = 0; i < str.size(); ++i) {
const char ch = str[i];
switch (ch) {
case '<':
m << "<";
break;
case '>':
m << ">";
break;
case '&':
m << "&";
break;
case '\'':
if (is_attribute)
m << "'";
else
m << '\'';
break;
case '"':
if (is_attribute)
m << """;
else
m << '"';
break;
default:
if (IsValidXmlCharacter(ch)) {
if (is_attribute && IsNormalizableWhitespace(ch))
m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch))
<< ";";
else
m << ch;
}
break;
}
}
return m.GetString();
}
// Returns the given string with all characters invalid in XML removed.
// Currently invalid characters are dropped from the string. An
// alternative is to replace them with certain characters such as . or ?.
std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(
const std::string& str) {
std::string output;
output.reserve(str.size());
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
if (IsValidXmlCharacter(*it))
output.push_back(*it);
return output;
}
// The following routines generate an XML representation of a UnitTest
// object.
//
// This is how Google Test concepts map to the DTD:
//
// <testsuites name="AllTests"> <-- corresponds to a UnitTest object
// <testsuite name="testcase-name"> <-- corresponds to a TestCase object
// <testcase name="test-name"> <-- corresponds to a TestInfo object
// <failure message="...">...</failure>
// <failure message="...">...</failure>
// <failure message="...">...</failure>
// <-- individual assertion failures
// </testcase>
// </testsuite>
// </testsuites>
// Formats the given time in milliseconds as seconds.
std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {
::std::stringstream ss;
ss << ms/1000.0;
return ss.str();
}
// Converts the given epoch time in milliseconds to a date string in the ISO
// 8601 format, without the timezone information.
std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {
// Using non-reentrant version as localtime_r is not portable.
time_t seconds = static_cast<time_t>(ms / 1000);
#ifdef _MSC_VER
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4996) // Temporarily disables warning 4996
// (function or variable may be unsafe).
const struct tm* const time_struct = localtime(&seconds); // NOLINT
# pragma warning(pop) // Restores the warning state again.
#else
const struct tm* const time_struct = localtime(&seconds); // NOLINT
#endif
if (time_struct == NULL)
return ""; // Invalid ms value
// YYYY-MM-DDThh:mm:ss
return StreamableToString(time_struct->tm_year + 1900) + "-" +
String::FormatIntWidth2(time_struct->tm_mon + 1) + "-" +
String::FormatIntWidth2(time_struct->tm_mday) + "T" +
String::FormatIntWidth2(time_struct->tm_hour) + ":" +
String::FormatIntWidth2(time_struct->tm_min) + ":" +
String::FormatIntWidth2(time_struct->tm_sec);
}
// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.
void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,
const char* data) {
const char* segment = data;
*stream << "<![CDATA[";
for (;;) {
const char* const next_segment = strstr(segment, "]]>");
if (next_segment != NULL) {
stream->write(
segment, static_cast<std::streamsize>(next_segment - segment));
*stream << "]]>]]><![CDATA[";
segment = next_segment + strlen("]]>");
} else {
*stream << segment;
break;
}
}
*stream << "]]>";
}
void XmlUnitTestResultPrinter::OutputXmlAttribute(
std::ostream* stream,
const std::string& element_name,
const std::string& name,
const std::string& value) {
const std::vector<std::string>& allowed_names =
GetReservedAttributesForElement(element_name);
GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=
allowed_names.end())
<< "Attribute " << name << " is not allowed for element <" << element_name
<< ">.";
*stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\"";
}
// Prints an XML representation of a TestInfo object.
// TODO(wan): There is also value in printing properties with the plain printer.
void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,
const char* test_case_name,
const TestInfo& test_info) {
const TestResult& result = *test_info.result();
const std::string kTestcase = "testcase";
*stream << " <testcase";
OutputXmlAttribute(stream, kTestcase, "name", test_info.name());
if (test_info.value_param() != NULL) {
OutputXmlAttribute(stream, kTestcase, "value_param",
test_info.value_param());
}
if (test_info.type_param() != NULL) {
OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param());
}
OutputXmlAttribute(stream, kTestcase, "status",
test_info.should_run() ? "run" : "notrun");
OutputXmlAttribute(stream, kTestcase, "time",
FormatTimeInMillisAsSeconds(result.elapsed_time()));
OutputXmlAttribute(stream, kTestcase, "classname", test_case_name);
*stream << TestPropertiesAsXmlAttributes(result);
int failures = 0;
for (int i = 0; i < result.total_part_count(); ++i) {
const TestPartResult& part = result.GetTestPartResult(i);
if (part.failed()) {
if (++failures == 1) {
*stream << ">\n";
}
const string location = internal::FormatCompilerIndependentFileLocation(
part.file_name(), part.line_number());
const string summary = location + "\n" + part.summary();
*stream << " <failure message=\""
<< EscapeXmlAttribute(summary.c_str())
<< "\" type=\"\">";
const string detail = location + "\n" + part.message();
OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());
*stream << "</failure>\n";
}
}
if (failures == 0)
*stream << " />\n";
else
*stream << " </testcase>\n";
}
// Prints an XML representation of a TestCase object
void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,
const TestCase& test_case) {
const std::string kTestsuite = "testsuite";
*stream << " <" << kTestsuite;
OutputXmlAttribute(stream, kTestsuite, "name", test_case.name());
OutputXmlAttribute(stream, kTestsuite, "tests",
StreamableToString(test_case.reportable_test_count()));
OutputXmlAttribute(stream, kTestsuite, "failures",
StreamableToString(test_case.failed_test_count()));
OutputXmlAttribute(
stream, kTestsuite, "disabled",
StreamableToString(test_case.reportable_disabled_test_count()));
OutputXmlAttribute(stream, kTestsuite, "errors", "0");
OutputXmlAttribute(stream, kTestsuite, "time",
FormatTimeInMillisAsSeconds(test_case.elapsed_time()));
*stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())
<< ">\n";
for (int i = 0; i < test_case.total_test_count(); ++i) {
if (test_case.GetTestInfo(i)->is_reportable())
OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));
}
*stream << " </" << kTestsuite << ">\n";
}
// Prints an XML summary of unit_test to output stream out.
void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,
const UnitTest& unit_test) {
const std::string kTestsuites = "testsuites";
*stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
*stream << "<" << kTestsuites;
OutputXmlAttribute(stream, kTestsuites, "tests",
StreamableToString(unit_test.reportable_test_count()));
OutputXmlAttribute(stream, kTestsuites, "failures",
StreamableToString(unit_test.failed_test_count()));
OutputXmlAttribute(
stream, kTestsuites, "disabled",
StreamableToString(unit_test.reportable_disabled_test_count()));
OutputXmlAttribute(stream, kTestsuites, "errors", "0");
OutputXmlAttribute(
stream, kTestsuites, "timestamp",
FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));
OutputXmlAttribute(stream, kTestsuites, "time",
FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));
if (GTEST_FLAG(shuffle)) {
OutputXmlAttribute(stream, kTestsuites, "random_seed",
StreamableToString(unit_test.random_seed()));
}
*stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());
OutputXmlAttribute(stream, kTestsuites, "name", "AllTests");
*stream << ">\n";
for (int i = 0; i < unit_test.total_test_case_count(); ++i) {
if (unit_test.GetTestCase(i)->reportable_test_count() > 0)
PrintXmlTestCase(stream, *unit_test.GetTestCase(i));
}
*stream << "</" << kTestsuites << ">\n";
}
// Produces a string representing the test properties in a result as space
// delimited XML attributes based on the property key="value" pairs.
std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(
const TestResult& result) {
Message attributes;
for (int i = 0; i < result.test_property_count(); ++i) {
const TestProperty& property = result.GetTestProperty(i);
attributes << " " << property.key() << "="
<< "\"" << EscapeXmlAttribute(property.value()) << "\"";
}
return attributes.GetString();
}
// End XmlUnitTestResultPrinter
#if GTEST_CAN_STREAM_RESULTS_
// Checks if str contains '=', '&', '%' or '\n' characters. If yes,
// replaces them by "%xx" where xx is their hexadecimal value. For
// example, replaces "=" with "%3D". This algorithm is O(strlen(str))
// in both time and space -- important as the input str may contain an
// arbitrarily long test failure message and stack trace.
string StreamingListener::UrlEncode(const char* str) {
string result;
result.reserve(strlen(str) + 1);
for (char ch = *str; ch != '\0'; ch = *++str) {
switch (ch) {
case '%':
case '=':
case '&':
case '\n':
result.append("%" + String::FormatByte(static_cast<unsigned char>(ch)));
break;
default:
result.push_back(ch);
break;
}
}
return result;
}
void StreamingListener::SocketWriter::MakeConnection() {
GTEST_CHECK_(sockfd_ == -1)
<< "MakeConnection() can't be called when there is already a connection.";
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses.
hints.ai_socktype = SOCK_STREAM;
addrinfo* servinfo = NULL;
// Use the getaddrinfo() to get a linked list of IP addresses for
// the given host name.
const int error_num = getaddrinfo(
host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);
if (error_num != 0) {
GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: "
<< gai_strerror(error_num);
}
// Loop through all the results and connect to the first we can.
for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;
cur_addr = cur_addr->ai_next) {
sockfd_ = socket(
cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);
if (sockfd_ != -1) {
// Connect the client socket to the server socket.
if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {
close(sockfd_);
sockfd_ = -1;
}
}
}
freeaddrinfo(servinfo); // all done with this structure
if (sockfd_ == -1) {
GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to "
<< host_name_ << ":" << port_num_;
}
}
// End of class Streaming Listener
#endif // GTEST_CAN_STREAM_RESULTS__
// Class ScopedTrace
// Pushes the given source file location and message onto a per-thread
// trace stack maintained by Google Test.
ScopedTrace::ScopedTrace(const char* file, int line, const Message& message)
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
TraceInfo trace;
trace.file = file;
trace.line = line;
trace.message = message.GetString();
UnitTest::GetInstance()->PushGTestTrace(trace);
}
// Pops the info pushed by the c'tor.
ScopedTrace::~ScopedTrace()
GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {
UnitTest::GetInstance()->PopGTestTrace();
}
// class OsStackTraceGetter
// Returns the current OS stack trace as an std::string. Parameters:
//
// max_depth - the maximum number of stack frames to be included
// in the trace.
// skip_count - the number of top frames to be skipped; doesn't count
// against max_depth.
//
string OsStackTraceGetter::CurrentStackTrace(int /* max_depth */,
int /* skip_count */)
GTEST_LOCK_EXCLUDED_(mutex_) {
return "";
}
void OsStackTraceGetter::UponLeavingGTest()
GTEST_LOCK_EXCLUDED_(mutex_) {
}
const char* const
OsStackTraceGetter::kElidedFramesMarker =
"... " GTEST_NAME_ " internal frames ...";
} // namespace internal
// class TestEventListeners
TestEventListeners::TestEventListeners()
: repeater_(new internal::TestEventRepeater()),
default_result_printer_(NULL),
default_xml_generator_(NULL) {
}
TestEventListeners::~TestEventListeners() { delete repeater_; }
// Returns the standard listener responsible for the default console
// output. Can be removed from the listeners list to shut down default
// console output. Note that removing this object from the listener list
// with Release transfers its ownership to the user.
void TestEventListeners::Append(TestEventListener* listener) {
repeater_->Append(listener);
}
// Removes the given event listener from the list and returns it. It then
// becomes the caller's responsibility to delete the listener. Returns
// NULL if the listener is not found in the list.
TestEventListener* TestEventListeners::Release(TestEventListener* listener) {
if (listener == default_result_printer_)
default_result_printer_ = NULL;
else if (listener == default_xml_generator_)
default_xml_generator_ = NULL;
return repeater_->Release(listener);
}
// Returns repeater that broadcasts the TestEventListener events to all
// subscribers.
TestEventListener* TestEventListeners::repeater() { return repeater_; }
// Sets the default_result_printer attribute to the provided listener.
// The listener is also added to the listener list and previous
// default_result_printer is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {
if (default_result_printer_ != listener) {
// It is an error to pass this method a listener that is already in the
// list.
delete Release(default_result_printer_);
default_result_printer_ = listener;
if (listener != NULL)
Append(listener);
}
}
// Sets the default_xml_generator attribute to the provided listener. The
// listener is also added to the listener list and previous
// default_xml_generator is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {
if (default_xml_generator_ != listener) {
// It is an error to pass this method a listener that is already in the
// list.
delete Release(default_xml_generator_);
default_xml_generator_ = listener;
if (listener != NULL)
Append(listener);
}
}
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
bool TestEventListeners::EventForwardingEnabled() const {
return repeater_->forwarding_enabled();
}
void TestEventListeners::SuppressEventForwarding() {
repeater_->set_forwarding_enabled(false);
}
// class UnitTest
// Gets the singleton UnitTest object. The first time this method is
// called, a UnitTest object is constructed and returned. Consecutive
// calls will return the same object.
//
// We don't protect this under mutex_ as a user is not supposed to
// call this before main() starts, from which point on the return
// value will never change.
UnitTest* UnitTest::GetInstance() {
// When compiled with MSVC 7.1 in optimized mode, destroying the
// UnitTest object upon exiting the program messes up the exit code,
// causing successful tests to appear failed. We have to use a
// different implementation in this case to bypass the compiler bug.
// This implementation makes the compiler happy, at the cost of
// leaking the UnitTest object.
// CodeGear C++Builder insists on a public destructor for the
// default implementation. Use this implementation to keep good OO
// design with private destructor.
#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
static UnitTest* const instance = new UnitTest;
return instance;
#else
static UnitTest instance;
return &instance;
#endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)
}
// Gets the number of successful test cases.
int UnitTest::successful_test_case_count() const {
return impl()->successful_test_case_count();
}
// Gets the number of failed test cases.
int UnitTest::failed_test_case_count() const {
return impl()->failed_test_case_count();
}
// Gets the number of all test cases.
int UnitTest::total_test_case_count() const {
return impl()->total_test_case_count();
}
// Gets the number of all test cases that contain at least one test
// that should run.
int UnitTest::test_case_to_run_count() const {
return impl()->test_case_to_run_count();
}
// Gets the number of successful tests.
int UnitTest::successful_test_count() const {
return impl()->successful_test_count();
}
// Gets the number of failed tests.
int UnitTest::failed_test_count() const { return impl()->failed_test_count(); }
// Gets the number of disabled tests that will be reported in the XML report.
int UnitTest::reportable_disabled_test_count() const {
return impl()->reportable_disabled_test_count();
}
// Gets the number of disabled tests.
int UnitTest::disabled_test_count() const {
return impl()->disabled_test_count();
}
// Gets the number of tests to be printed in the XML report.
int UnitTest::reportable_test_count() const {
return impl()->reportable_test_count();
}
// Gets the number of all tests.
int UnitTest::total_test_count() const { return impl()->total_test_count(); }
// Gets the number of tests that should run.
int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }
// Gets the time of the test program start, in ms from the start of the
// UNIX epoch.
internal::TimeInMillis UnitTest::start_timestamp() const {
return impl()->start_timestamp();
}
// Gets the elapsed time, in milliseconds.
internal::TimeInMillis UnitTest::elapsed_time() const {
return impl()->elapsed_time();
}
// Returns true iff the unit test passed (i.e. all test cases passed).
bool UnitTest::Passed() const { return impl()->Passed(); }
// Returns true iff the unit test failed (i.e. some test case failed
// or something outside of all tests failed).
bool UnitTest::Failed() const { return impl()->Failed(); }
// Gets the i-th test case among all the test cases. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL.
const TestCase* UnitTest::GetTestCase(int i) const {
return impl()->GetTestCase(i);
}
// Returns the TestResult containing information on test failures and
// properties logged outside of individual test cases.
const TestResult& UnitTest::ad_hoc_test_result() const {
return *impl()->ad_hoc_test_result();
}
// Gets the i-th test case among all the test cases. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL.
TestCase* UnitTest::GetMutableTestCase(int i) {
return impl()->GetMutableTestCase(i);
}
// Returns the list of event listeners that can be used to track events
// inside Google Test.
TestEventListeners& UnitTest::listeners() {
return *impl()->listeners();
}
// Registers and returns a global test environment. When a test
// program is run, all global test environments will be set-up in the
// order they were registered. After all tests in the program have
// finished, all global test environments will be torn-down in the
// *reverse* order they were registered.
//
// The UnitTest object takes ownership of the given environment.
//
// We don't protect this under mutex_, as we only support calling it
// from the main thread.
Environment* UnitTest::AddEnvironment(Environment* env) {
if (env == NULL) {
return NULL;
}
impl_->environments().push_back(env);
return env;
}
// Adds a TestPartResult to the current TestResult object. All Google Test
// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call
// this to report their results. The user code should use the
// assertion macros instead of calling this directly.
void UnitTest::AddTestPartResult(
TestPartResult::Type result_type,
const char* file_name,
int line_number,
const std::string& message,
const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {
Message msg;
msg << message;
internal::MutexLock lock(&mutex_);
if (impl_->gtest_trace_stack().size() > 0) {
msg << "\n" << GTEST_NAME_ << " trace:";
for (int i = static_cast<int>(impl_->gtest_trace_stack().size());
i > 0; --i) {
const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];
msg << "\n" << internal::FormatFileLocation(trace.file, trace.line)
<< " " << trace.message;
}
}
if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {
msg << internal::kStackTraceMarker << os_stack_trace;
}
const TestPartResult result =
TestPartResult(result_type, file_name, line_number,
msg.GetString().c_str());
impl_->GetTestPartResultReporterForCurrentThread()->
ReportTestPartResult(result);
if (result_type != TestPartResult::kSuccess) {
// gtest_break_on_failure takes precedence over
// gtest_throw_on_failure. This allows a user to set the latter
// in the code (perhaps in order to use Google Test assertions
// with another testing framework) and specify the former on the
// command line for debugging.
if (GTEST_FLAG(break_on_failure)) {
#if GTEST_OS_WINDOWS
// Using DebugBreak on Windows allows gtest to still break into a debugger
// when a failure happens and both the --gtest_break_on_failure and
// the --gtest_catch_exceptions flags are specified.
DebugBreak();
#else
// Dereference NULL through a volatile pointer to prevent the compiler
// from removing. We use this rather than abort() or __builtin_trap() for
// portability: Symbian doesn't implement abort() well, and some debuggers
// don't correctly trap abort().
*static_cast<volatile int*>(NULL) = 1;
#endif // GTEST_OS_WINDOWS
} else if (GTEST_FLAG(throw_on_failure)) {
#if GTEST_HAS_EXCEPTIONS
throw internal::GoogleTestFailureException(result);
#else
// We cannot call abort() as it generates a pop-up in debug mode
// that cannot be suppressed in VC 7.1 or below.
exit(1);
#endif
}
}
}
// Adds a TestProperty to the current TestResult object when invoked from
// inside a test, to current TestCase's ad_hoc_test_result_ when invoked
// from SetUpTestCase or TearDownTestCase, or to the global property set
// when invoked elsewhere. If the result already contains a property with
// the same key, the value will be updated.
void UnitTest::RecordProperty(const std::string& key,
const std::string& value) {
impl_->RecordProperty(TestProperty(key, value));
}
// Runs all tests in this UnitTest object and prints the result.
// Returns 0 if successful, or 1 otherwise.
//
// We don't protect this under mutex_, as we only support calling it
// from the main thread.
int UnitTest::Run() {
// Captures the value of GTEST_FLAG(catch_exceptions). This value will be
// used for the duration of the program.
impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));
#if GTEST_HAS_SEH
const bool in_death_test_child_process =
internal::GTEST_FLAG(internal_run_death_test).length() > 0;
// Either the user wants Google Test to catch exceptions thrown by the
// tests or this is executing in the context of death test child
// process. In either case the user does not want to see pop-up dialogs
// about crashes - they are expected.
if (impl()->catch_exceptions() || in_death_test_child_process) {
# if !GTEST_OS_WINDOWS_MOBILE
// SetErrorMode doesn't exist on CE.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
# endif // !GTEST_OS_WINDOWS_MOBILE
# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE
// Death test children can be terminated with _abort(). On Windows,
// _abort() can show a dialog with a warning message. This forces the
// abort message to go to stderr instead.
_set_error_mode(_OUT_TO_STDERR);
# endif
# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE
// In the debug version, Visual Studio pops up a separate dialog
// offering a choice to debug the aborted program. We need to suppress
// this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement
// executed. Google Test will notify the user of any unexpected
// failure via stderr.
//
// VC++ doesn't define _set_abort_behavior() prior to the version 8.0.
// Users of prior VC versions shall suffer the agony and pain of
// clicking through the countless debug dialogs.
// TODO(vladl@google.com): find a way to suppress the abort dialog() in the
// debug mode when compiled with VC 7.1 or lower.
if (!GTEST_FLAG(break_on_failure))
_set_abort_behavior(
0x0, // Clear the following flags:
_WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump.
# endif
}
#endif // GTEST_HAS_SEH
return internal::HandleExceptionsInMethodIfSupported(
impl(),
&internal::UnitTestImpl::RunAllTests,
"auxiliary test code (environments or event listeners)") ? 0 : 1;
}
// Returns the working directory when the first TEST() or TEST_F() was
// executed.
const char* UnitTest::original_working_dir() const {
return impl_->original_working_dir_.c_str();
}
// Returns the TestCase object for the test that's currently running,
// or NULL if no test is running.
const TestCase* UnitTest::current_test_case() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
return impl_->current_test_case();
}
// Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running.
const TestInfo* UnitTest::current_test_info() const
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
return impl_->current_test_info();
}
// Returns the random seed used at the start of the current test run.
int UnitTest::random_seed() const { return impl_->random_seed(); }
#if GTEST_HAS_PARAM_TEST
// Returns ParameterizedTestCaseRegistry object used to keep track of
// value-parameterized tests and instantiate and register them.
internal::ParameterizedTestCaseRegistry&
UnitTest::parameterized_test_registry()
GTEST_LOCK_EXCLUDED_(mutex_) {
return impl_->parameterized_test_registry();
}
#endif // GTEST_HAS_PARAM_TEST
// Creates an empty UnitTest.
UnitTest::UnitTest() {
impl_ = new internal::UnitTestImpl(this);
}
// Destructor of UnitTest.
UnitTest::~UnitTest() {
delete impl_;
}
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack.
void UnitTest::PushGTestTrace(const internal::TraceInfo& trace)
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().push_back(trace);
}
// Pops a trace from the per-thread Google Test trace stack.
void UnitTest::PopGTestTrace()
GTEST_LOCK_EXCLUDED_(mutex_) {
internal::MutexLock lock(&mutex_);
impl_->gtest_trace_stack().pop_back();
}
namespace internal {
UnitTestImpl::UnitTestImpl(UnitTest* parent)
: parent_(parent),
#ifdef _MSC_VER
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4355) // Temporarily disables warning 4355
// (using this in initializer).
default_global_test_part_result_reporter_(this),
default_per_thread_test_part_result_reporter_(this),
# pragma warning(pop) // Restores the warning state again.
#else
default_global_test_part_result_reporter_(this),
default_per_thread_test_part_result_reporter_(this),
#endif // _MSC_VER
global_test_part_result_repoter_(
&default_global_test_part_result_reporter_),
per_thread_test_part_result_reporter_(
&default_per_thread_test_part_result_reporter_),
#if GTEST_HAS_PARAM_TEST
parameterized_test_registry_(),
parameterized_tests_registered_(false),
#endif // GTEST_HAS_PARAM_TEST
last_death_test_case_(-1),
current_test_case_(NULL),
current_test_info_(NULL),
ad_hoc_test_result_(),
os_stack_trace_getter_(NULL),
post_flag_parse_init_performed_(false),
random_seed_(0), // Will be overridden by the flag before first use.
random_(0), // Will be reseeded before first use.
start_timestamp_(0),
elapsed_time_(0),
#if GTEST_HAS_DEATH_TEST
death_test_factory_(new DefaultDeathTestFactory),
#endif
// Will be overridden by the flag before first use.
catch_exceptions_(false) {
listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);
}
UnitTestImpl::~UnitTestImpl() {
// Deletes every TestCase.
ForEach(test_cases_, internal::Delete<TestCase>);
// Deletes every Environment.
ForEach(environments_, internal::Delete<Environment>);
delete os_stack_trace_getter_;
}
// Adds a TestProperty to the current TestResult object when invoked in a
// context of a test, to current test case's ad_hoc_test_result when invoke
// from SetUpTestCase/TearDownTestCase, or to the global property set
// otherwise. If the result already contains a property with the same key,
// the value will be updated.
void UnitTestImpl::RecordProperty(const TestProperty& test_property) {
std::string xml_element;
TestResult* test_result; // TestResult appropriate for property recording.
if (current_test_info_ != NULL) {
xml_element = "testcase";
test_result = &(current_test_info_->result_);
} else if (current_test_case_ != NULL) {
xml_element = "testsuite";
test_result = &(current_test_case_->ad_hoc_test_result_);
} else {
xml_element = "testsuites";
test_result = &ad_hoc_test_result_;
}
test_result->RecordProperty(xml_element, test_property);
}
#if GTEST_HAS_DEATH_TEST
// Disables event forwarding if the control is currently in a death test
// subprocess. Must not be called before InitGoogleTest.
void UnitTestImpl::SuppressTestEventsIfInSubprocess() {
if (internal_run_death_test_flag_.get() != NULL)
listeners()->SuppressEventForwarding();
}
#endif // GTEST_HAS_DEATH_TEST
// Initializes event listeners performing XML output as specified by
// UnitTestOptions. Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureXmlOutput() {
const std::string& output_format = UnitTestOptions::GetOutputFormat();
if (output_format == "xml") {
listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(
UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));
} else if (output_format != "") {
printf("WARNING: unrecognized output format \"%s\" ignored.\n",
output_format.c_str());
fflush(stdout);
}
}
#if GTEST_CAN_STREAM_RESULTS_
// Initializes event listeners for streaming test results in string form.
// Must not be called before InitGoogleTest.
void UnitTestImpl::ConfigureStreamingOutput() {
const std::string& target = GTEST_FLAG(stream_result_to);
if (!target.empty()) {
const size_t pos = target.find(':');
if (pos != std::string::npos) {
listeners()->Append(new StreamingListener(target.substr(0, pos),
target.substr(pos+1)));
} else {
printf("WARNING: unrecognized streaming target \"%s\" ignored.\n",
target.c_str());
fflush(stdout);
}
}
}
#endif // GTEST_CAN_STREAM_RESULTS_
// Performs initialization dependent upon flag values obtained in
// ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to
// ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest
// this function is also called from RunAllTests. Since this function can be
// called more than once, it has to be idempotent.
void UnitTestImpl::PostFlagParsingInit() {
// Ensures that this function does not execute more than once.
if (!post_flag_parse_init_performed_) {
post_flag_parse_init_performed_ = true;
#if GTEST_HAS_DEATH_TEST
InitDeathTestSubprocessControlInfo();
SuppressTestEventsIfInSubprocess();
#endif // GTEST_HAS_DEATH_TEST
// Registers parameterized tests. This makes parameterized tests
// available to the UnitTest reflection API without running
// RUN_ALL_TESTS.
RegisterParameterizedTests();
// Configures listeners for XML output. This makes it possible for users
// to shut down the default XML output before invoking RUN_ALL_TESTS.
ConfigureXmlOutput();
#if GTEST_CAN_STREAM_RESULTS_
// Configures listeners for streaming test results to the specified server.
ConfigureStreamingOutput();
#endif // GTEST_CAN_STREAM_RESULTS_
}
}
// A predicate that checks the name of a TestCase against a known
// value.
//
// This is used for implementation of the UnitTest class only. We put
// it in the anonymous namespace to prevent polluting the outer
// namespace.
//
// TestCaseNameIs is copyable.
class TestCaseNameIs {
public:
// Constructor.
explicit TestCaseNameIs(const std::string& name)
: name_(name) {}
// Returns true iff the name of test_case matches name_.
bool operator()(const TestCase* test_case) const {
return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;
}
private:
std::string name_;
};
// Finds and returns a TestCase with the given name. If one doesn't
// exist, creates one and returns it. It's the CALLER'S
// RESPONSIBILITY to ensure that this function is only called WHEN THE
// TESTS ARE NOT SHUFFLED.
//
// Arguments:
//
// test_case_name: name of the test case
// type_param: the name of the test case's type parameter, or NULL if
// this is not a typed or a type-parameterized test case.
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
TestCase* UnitTestImpl::GetTestCase(const char* test_case_name,
const char* type_param,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc) {
// Can we find a TestCase with the given name?
const std::vector<TestCase*>::const_iterator test_case =
std::find_if(test_cases_.begin(), test_cases_.end(),
TestCaseNameIs(test_case_name));
if (test_case != test_cases_.end())
return *test_case;
// No. Let's create one.
TestCase* const new_test_case =
new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);
// Is this a death test case?
if (internal::UnitTestOptions::MatchesFilter(test_case_name,
kDeathTestCaseFilter)) {
// Yes. Inserts the test case after the last death test case
// defined so far. This only works when the test cases haven't
// been shuffled. Otherwise we may end up running a death test
// after a non-death test.
++last_death_test_case_;
test_cases_.insert(test_cases_.begin() + last_death_test_case_,
new_test_case);
} else {
// No. Appends to the end of the list.
test_cases_.push_back(new_test_case);
}
test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));
return new_test_case;
}
// Helpers for setting up / tearing down the given environment. They
// are for use in the ForEach() function.
static void SetUpEnvironment(Environment* env) { env->SetUp(); }
static void TearDownEnvironment(Environment* env) { env->TearDown(); }
// Runs all tests in this UnitTest object, prints the result, and
// returns true if all tests are successful. If any exception is
// thrown during a test, the test is considered to be failed, but the
// rest of the tests will still be run.
//
// When parameterized tests are enabled, it expands and registers
// parameterized tests first in RegisterParameterizedTests().
// All other functions called from RunAllTests() may safely assume that
// parameterized tests are ready to be counted and run.
bool UnitTestImpl::RunAllTests() {
// Makes sure InitGoogleTest() was called.
if (!GTestIsInitialized()) {
printf("%s",
"\nThis test program did NOT call ::testing::InitGoogleTest "
"before calling RUN_ALL_TESTS(). Please fix it.\n");
return false;
}
// Do not run any test if the --help flag was specified.
if (g_help_flag)
return true;
// Repeats the call to the post-flag parsing initialization in case the
// user didn't call InitGoogleTest.
PostFlagParsingInit();
// Even if sharding is not on, test runners may want to use the
// GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding
// protocol.
internal::WriteToShardStatusFileIfNeeded();
// True iff we are in a subprocess for running a thread-safe-style
// death test.
bool in_subprocess_for_death_test = false;
#if GTEST_HAS_DEATH_TEST
in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);
#endif // GTEST_HAS_DEATH_TEST
const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,
in_subprocess_for_death_test);
// Compares the full test names with the filter to decide which
// tests to run.
const bool has_tests_to_run = FilterTests(should_shard
? HONOR_SHARDING_PROTOCOL
: IGNORE_SHARDING_PROTOCOL) > 0;
// Lists the tests and exits if the --gtest_list_tests flag was specified.
if (GTEST_FLAG(list_tests)) {
// This must be called *after* FilterTests() has been called.
ListTestsMatchingFilter();
return true;
}
random_seed_ = GTEST_FLAG(shuffle) ?
GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;
// True iff at least one test has failed.
bool failed = false;
TestEventListener* repeater = listeners()->repeater();
start_timestamp_ = GetTimeInMillis();
repeater->OnTestProgramStart(*parent_);
// How many times to repeat the tests? We don't want to repeat them
// when we are inside the subprocess of a death test.
const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);
// Repeats forever if the repeat count is negative.
const bool forever = repeat < 0;
for (int i = 0; forever || i != repeat; i++) {
// We want to preserve failures generated by ad-hoc test
// assertions executed before RUN_ALL_TESTS().
ClearNonAdHocTestResult();
const TimeInMillis start = GetTimeInMillis();
// Shuffles test cases and tests if requested.
if (has_tests_to_run && GTEST_FLAG(shuffle)) {
random()->Reseed(random_seed_);
// This should be done before calling OnTestIterationStart(),
// such that a test event listener can see the actual test order
// in the event.
ShuffleTests();
}
// Tells the unit test event listeners that the tests are about to start.
repeater->OnTestIterationStart(*parent_, i);
// Runs each test case if there is at least one test to run.
if (has_tests_to_run) {
// Sets up all environments beforehand.
repeater->OnEnvironmentsSetUpStart(*parent_);
ForEach(environments_, SetUpEnvironment);
repeater->OnEnvironmentsSetUpEnd(*parent_);
// Runs the tests only if there was no fatal failure during global
// set-up.
if (!Test::HasFatalFailure()) {
for (int test_index = 0; test_index < total_test_case_count();
test_index++) {
GetMutableTestCase(test_index)->Run();
}
}
// Tears down all environments in reverse order afterwards.
repeater->OnEnvironmentsTearDownStart(*parent_);
std::for_each(environments_.rbegin(), environments_.rend(),
TearDownEnvironment);
repeater->OnEnvironmentsTearDownEnd(*parent_);
}
elapsed_time_ = GetTimeInMillis() - start;
// Tells the unit test event listener that the tests have just finished.
repeater->OnTestIterationEnd(*parent_, i);
// Gets the result and clears it.
if (!Passed()) {
failed = true;
}
// Restores the original test order after the iteration. This
// allows the user to quickly repro a failure that happens in the
// N-th iteration without repeating the first (N - 1) iterations.
// This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in
// case the user somehow changes the value of the flag somewhere
// (it's always safe to unshuffle the tests).
UnshuffleTests();
if (GTEST_FLAG(shuffle)) {
// Picks a new random seed for each iteration.
random_seed_ = GetNextRandomSeed(random_seed_);
}
}
repeater->OnTestProgramEnd(*parent_);
return !failed;
}
// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file
// if the variable is present. If a file already exists at this location, this
// function will write over it. If the variable is present, but the file cannot
// be created, prints an error and exits.
void WriteToShardStatusFileIfNeeded() {
const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);
if (test_shard_file != NULL) {
FILE* const file = posix::FOpen(test_shard_file, "w");
if (file == NULL) {
ColoredPrintf(COLOR_RED,
"Could not write to the test shard status file \"%s\" "
"specified by the %s environment variable.\n",
test_shard_file, kTestShardStatusFile);
fflush(stdout);
exit(EXIT_FAILURE);
}
fclose(file);
}
}
// Checks whether sharding is enabled by examining the relevant
// environment variable values. If the variables are present,
// but inconsistent (i.e., shard_index >= total_shards), prints
// an error and exits. If in_subprocess_for_death_test, sharding is
// disabled because it must only be applied to the original test
// process. Otherwise, we could filter out death tests we intended to execute.
bool ShouldShard(const char* total_shards_env,
const char* shard_index_env,
bool in_subprocess_for_death_test) {
if (in_subprocess_for_death_test) {
return false;
}
const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);
const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);
if (total_shards == -1 && shard_index == -1) {
return false;
} else if (total_shards == -1 && shard_index != -1) {
const Message msg = Message()
<< "Invalid environment variables: you have "
<< kTestShardIndex << " = " << shard_index
<< ", but have left " << kTestTotalShards << " unset.\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (total_shards != -1 && shard_index == -1) {
const Message msg = Message()
<< "Invalid environment variables: you have "
<< kTestTotalShards << " = " << total_shards
<< ", but have left " << kTestShardIndex << " unset.\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
} else if (shard_index < 0 || shard_index >= total_shards) {
const Message msg = Message()
<< "Invalid environment variables: we require 0 <= "
<< kTestShardIndex << " < " << kTestTotalShards
<< ", but you have " << kTestShardIndex << "=" << shard_index
<< ", " << kTestTotalShards << "=" << total_shards << ".\n";
ColoredPrintf(COLOR_RED, msg.GetString().c_str());
fflush(stdout);
exit(EXIT_FAILURE);
}
return total_shards > 1;
}
// Parses the environment variable var as an Int32. If it is unset,
// returns default_val. If it is not an Int32, prints an error
// and aborts.
Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) {
const char* str_val = posix::GetEnv(var);
if (str_val == NULL) {
return default_val;
}
Int32 result;
if (!ParseInt32(Message() << "The value of environment variable " << var,
str_val, &result)) {
exit(EXIT_FAILURE);
}
return result;
}
// Given the total number of shards, the shard index, and the test id,
// returns true iff the test should be run on this shard. The test id is
// some arbitrary but unique non-negative integer assigned to each test
// method. Assumes that 0 <= shard_index < total_shards.
bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {
return (test_id % total_shards) == shard_index;
}
// Compares the name of each test with the user-specified filter to
// decide whether the test should be run, then records the result in
// each TestCase and TestInfo object.
// If shard_tests == true, further filters tests based on sharding
// variables in the environment - see
// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.
// Returns the number of tests that should run.
int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {
const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?
Int32FromEnvOrDie(kTestTotalShards, -1) : -1;
const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?
Int32FromEnvOrDie(kTestShardIndex, -1) : -1;
// num_runnable_tests are the number of tests that will
// run across all shards (i.e., match filter and are not disabled).
// num_selected_tests are the number of tests to be run on
// this shard.
int num_runnable_tests = 0;
int num_selected_tests = 0;
for (size_t i = 0; i < test_cases_.size(); i++) {
TestCase* const test_case = test_cases_[i];
const std::string &test_case_name = test_case->name();
test_case->set_should_run(false);
for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
TestInfo* const test_info = test_case->test_info_list()[j];
const std::string test_name(test_info->name());
// A test is disabled if test case name or test name matches
// kDisableTestFilter.
const bool is_disabled =
internal::UnitTestOptions::MatchesFilter(test_case_name,
kDisableTestFilter) ||
internal::UnitTestOptions::MatchesFilter(test_name,
kDisableTestFilter);
test_info->is_disabled_ = is_disabled;
const bool matches_filter =
internal::UnitTestOptions::FilterMatchesTest(test_case_name,
test_name);
test_info->matches_filter_ = matches_filter;
const bool is_runnable =
(GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&
matches_filter;
const bool is_selected = is_runnable &&
(shard_tests == IGNORE_SHARDING_PROTOCOL ||
ShouldRunTestOnShard(total_shards, shard_index,
num_runnable_tests));
num_runnable_tests += is_runnable;
num_selected_tests += is_selected;
test_info->should_run_ = is_selected;
test_case->set_should_run(test_case->should_run() || is_selected);
}
}
return num_selected_tests;
}
// Prints the given C-string on a single line by replacing all '\n'
// characters with string "\\n". If the output takes more than
// max_length characters, only prints the first max_length characters
// and "...".
static void PrintOnOneLine(const char* str, int max_length) {
if (str != NULL) {
for (int i = 0; *str != '\0'; ++str) {
if (i >= max_length) {
printf("...");
break;
}
if (*str == '\n') {
printf("\\n");
i += 2;
} else {
printf("%c", *str);
++i;
}
}
}
}
// Prints the names of the tests matching the user-specified filter flag.
void UnitTestImpl::ListTestsMatchingFilter() {
// Print at most this many characters for each type/value parameter.
const int kMaxParamLength = 250;
for (size_t i = 0; i < test_cases_.size(); i++) {
const TestCase* const test_case = test_cases_[i];
bool printed_test_case_name = false;
for (size_t j = 0; j < test_case->test_info_list().size(); j++) {
const TestInfo* const test_info =
test_case->test_info_list()[j];
if (test_info->matches_filter_) {
if (!printed_test_case_name) {
printed_test_case_name = true;
printf("%s.", test_case->name());
if (test_case->type_param() != NULL) {
printf(" # %s = ", kTypeParamLabel);
// We print the type parameter on a single line to make
// the output easy to parse by a program.
PrintOnOneLine(test_case->type_param(), kMaxParamLength);
}
printf("\n");
}
printf(" %s", test_info->name());
if (test_info->value_param() != NULL) {
printf(" # %s = ", kValueParamLabel);
// We print the value parameter on a single line to make the
// output easy to parse by a program.
PrintOnOneLine(test_info->value_param(), kMaxParamLength);
}
printf("\n");
}
}
}
fflush(stdout);
}
// Sets the OS stack trace getter.
//
// Does nothing if the input and the current OS stack trace getter are
// the same; otherwise, deletes the old getter and makes the input the
// current getter.
void UnitTestImpl::set_os_stack_trace_getter(
OsStackTraceGetterInterface* getter) {
if (os_stack_trace_getter_ != getter) {
delete os_stack_trace_getter_;
os_stack_trace_getter_ = getter;
}
}
// Returns the current OS stack trace getter if it is not NULL;
// otherwise, creates an OsStackTraceGetter, makes it the current
// getter, and returns it.
OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {
if (os_stack_trace_getter_ == NULL) {
os_stack_trace_getter_ = new OsStackTraceGetter;
}
return os_stack_trace_getter_;
}
// Returns the TestResult for the test that's currently running, or
// the TestResult for the ad hoc test if no test is running.
TestResult* UnitTestImpl::current_test_result() {
return current_test_info_ ?
&(current_test_info_->result_) : &ad_hoc_test_result_;
}
// Shuffles all test cases, and the tests within each test case,
// making sure that death tests are still run first.
void UnitTestImpl::ShuffleTests() {
// Shuffles the death test cases.
ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);
// Shuffles the non-death test cases.
ShuffleRange(random(), last_death_test_case_ + 1,
static_cast<int>(test_cases_.size()), &test_case_indices_);
// Shuffles the tests inside each test case.
for (size_t i = 0; i < test_cases_.size(); i++) {
test_cases_[i]->ShuffleTests(random());
}
}
// Restores the test cases and tests to their order before the first shuffle.
void UnitTestImpl::UnshuffleTests() {
for (size_t i = 0; i < test_cases_.size(); i++) {
// Unshuffles the tests in each test case.
test_cases_[i]->UnshuffleTests();
// Resets the index of each test case.
test_case_indices_[i] = static_cast<int>(i);
}
}
// Returns the current OS stack trace as an std::string.
//
// The maximum number of stack frames to be included is specified by
// the gtest_stack_trace_depth flag. The skip_count parameter
// specifies the number of top frames to be skipped, which doesn't
// count against the number of frames to be included.
//
// For example, if Foo() calls Bar(), which in turn calls
// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in
// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.
std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,
int skip_count) {
// We pass skip_count + 1 to skip this wrapper function in addition
// to what the user really wants to skip.
return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);
}
// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to
// suppress unreachable code warnings.
namespace {
class ClassUniqueToAlwaysTrue {};
}
bool IsTrue(bool condition) { return condition; }
bool AlwaysTrue() {
#if GTEST_HAS_EXCEPTIONS
// This condition is always false so AlwaysTrue() never actually throws,
// but it makes the compiler think that it may throw.
if (IsTrue(false))
throw ClassUniqueToAlwaysTrue();
#endif // GTEST_HAS_EXCEPTIONS
return true;
}
// If *pstr starts with the given prefix, modifies *pstr to be right
// past the prefix and returns true; otherwise leaves *pstr unchanged
// and returns false. None of pstr, *pstr, and prefix can be NULL.
bool SkipPrefix(const char* prefix, const char** pstr) {
const size_t prefix_len = strlen(prefix);
if (strncmp(*pstr, prefix, prefix_len) == 0) {
*pstr += prefix_len;
return true;
}
return false;
}
// Parses a string as a command line flag. The string should have
// the format "--flag=value". When def_optional is true, the "=value"
// part can be omitted.
//
// Returns the value of the flag, or NULL if the parsing failed.
const char* ParseFlagValue(const char* str,
const char* flag,
bool def_optional) {
// str and flag must not be NULL.
if (str == NULL || flag == NULL) return NULL;
// The flag must start with "--" followed by GTEST_FLAG_PREFIX_.
const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag;
const size_t flag_len = flag_str.length();
if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;
// Skips the flag name.
const char* flag_end = str + flag_len;
// When def_optional is true, it's OK to not have a "=value" part.
if (def_optional && (flag_end[0] == '\0')) {
return flag_end;
}
// If def_optional is true and there are more characters after the
// flag name, or if def_optional is false, there must be a '=' after
// the flag name.
if (flag_end[0] != '=') return NULL;
// Returns the string after "=".
return flag_end + 1;
}
// Parses a string for a bool flag, in the form of either
// "--flag=value" or "--flag".
//
// In the former case, the value is taken as true as long as it does
// not start with '0', 'f', or 'F'.
//
// In the latter case, the value is taken as true.
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
bool ParseBoolFlag(const char* str, const char* flag, bool* value) {
// Gets the value of the flag as a string.
const char* const value_str = ParseFlagValue(str, flag, true);
// Aborts if the parsing failed.
if (value_str == NULL) return false;
// Converts the string value to a bool.
*value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');
return true;
}
// Parses a string for an Int32 flag, in the form of
// "--flag=value".
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
bool ParseInt32Flag(const char* str, const char* flag, Int32* value) {
// Gets the value of the flag as a string.
const char* const value_str = ParseFlagValue(str, flag, false);
// Aborts if the parsing failed.
if (value_str == NULL) return false;
// Sets *value to the value of the flag.
return ParseInt32(Message() << "The value of flag --" << flag,
value_str, value);
}
// Parses a string for a string flag, in the form of
// "--flag=value".
//
// On success, stores the value of the flag in *value, and returns
// true. On failure, returns false without changing *value.
bool ParseStringFlag(const char* str, const char* flag, std::string* value) {
// Gets the value of the flag as a string.
const char* const value_str = ParseFlagValue(str, flag, false);
// Aborts if the parsing failed.
if (value_str == NULL) return false;
// Sets *value to the value of the flag.
*value = value_str;
return true;
}
// Determines whether a string has a prefix that Google Test uses for its
// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.
// If Google Test detects that a command line flag has its prefix but is not
// recognized, it will print its help message. Flags starting with
// GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test
// internal flags and do not trigger the help message.
static bool HasGoogleTestFlagPrefix(const char* str) {
return (SkipPrefix("--", &str) ||
SkipPrefix("-", &str) ||
SkipPrefix("/", &str)) &&
!SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) &&
(SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||
SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));
}
// Prints a string containing code-encoded text. The following escape
// sequences can be used in the string to control the text color:
//
// @@ prints a single '@' character.
// @R changes the color to red.
// @G changes the color to green.
// @Y changes the color to yellow.
// @D changes to the default terminal text color.
//
// TODO(wan@google.com): Write tests for this once we add stdout
// capturing to Google Test.
static void PrintColorEncoded(const char* str) {
GTestColor color = COLOR_DEFAULT; // The current color.
// Conceptually, we split the string into segments divided by escape
// sequences. Then we print one segment at a time. At the end of
// each iteration, the str pointer advances to the beginning of the
// next segment.
for (;;) {
const char* p = strchr(str, '@');
if (p == NULL) {
ColoredPrintf(color, "%s", str);
return;
}
ColoredPrintf(color, "%s", std::string(str, p).c_str());
const char ch = p[1];
str = p + 2;
if (ch == '@') {
ColoredPrintf(color, "@");
} else if (ch == 'D') {
color = COLOR_DEFAULT;
} else if (ch == 'R') {
color = COLOR_RED;
} else if (ch == 'G') {
color = COLOR_GREEN;
} else if (ch == 'Y') {
color = COLOR_YELLOW;
} else {
--str;
}
}
}
static const char kColorEncodedHelpMessage[] =
"This program contains tests written using " GTEST_NAME_ ". You can use the\n"
"following command line flags to control its behavior:\n"
"\n"
"Test Selection:\n"
" @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n"
" List the names of all tests instead of running them. The name of\n"
" TEST(Foo, Bar) is \"Foo.Bar\".\n"
" @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS"
"[@G-@YNEGATIVE_PATTERNS]@D\n"
" Run only the tests whose name matches one of the positive patterns but\n"
" none of the negative patterns. '?' matches any single character; '*'\n"
" matches any substring; ':' separates two patterns.\n"
" @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n"
" Run all disabled tests too.\n"
"\n"
"Test Execution:\n"
" @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n"
" Run the tests repeatedly; use a negative count to repeat forever.\n"
" @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n"
" Randomize tests' orders on every iteration.\n"
" @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n"
" Random number seed to use for shuffling test orders (between 1 and\n"
" 99999, or 0 to use a seed based on the current time).\n"
"\n"
"Test Output:\n"
" @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n"
" Enable/disable colored output. The default is @Gauto@D.\n"
" -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n"
" Don't print the elapsed time of each test.\n"
" @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G"
GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n"
" Generate an XML report in the given directory or with the given file\n"
" name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n"
#if GTEST_CAN_STREAM_RESULTS_
" @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n"
" Stream test results to the given server.\n"
#endif // GTEST_CAN_STREAM_RESULTS_
"\n"
"Assertion Behavior:\n"
#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n"
" Set the default death test style.\n"
#endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS
" @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n"
" Turn assertion failures into debugger break-points.\n"
" @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n"
" Turn assertion failures into C++ exceptions.\n"
" @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n"
" Do not report exceptions as test failures. Instead, allow them\n"
" to crash the program or throw a pop-up (on Windows).\n"
"\n"
"Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set "
"the corresponding\n"
"environment variable of a flag (all letters in upper-case). For example, to\n"
"disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_
"color=no@D or set\n"
"the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n"
"\n"
"For more information, please read the " GTEST_NAME_ " documentation at\n"
"@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n"
"(not one in your own code or tests), please report it to\n"
"@G<" GTEST_DEV_EMAIL_ ">@D.\n";
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test. The type parameter CharType can be
// instantiated to either char or wchar_t.
template <typename CharType>
void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {
for (int i = 1; i < *argc; i++) {
const std::string arg_string = StreamableToString(argv[i]);
const char* const arg = arg_string.c_str();
using internal::ParseBoolFlag;
using internal::ParseInt32Flag;
using internal::ParseStringFlag;
// Do we see a Google Test flag?
if (ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,
>EST_FLAG(also_run_disabled_tests)) ||
ParseBoolFlag(arg, kBreakOnFailureFlag,
>EST_FLAG(break_on_failure)) ||
ParseBoolFlag(arg, kCatchExceptionsFlag,
>EST_FLAG(catch_exceptions)) ||
ParseStringFlag(arg, kColorFlag, >EST_FLAG(color)) ||
ParseStringFlag(arg, kDeathTestStyleFlag,
>EST_FLAG(death_test_style)) ||
ParseBoolFlag(arg, kDeathTestUseFork,
>EST_FLAG(death_test_use_fork)) ||
ParseStringFlag(arg, kFilterFlag, >EST_FLAG(filter)) ||
ParseStringFlag(arg, kInternalRunDeathTestFlag,
>EST_FLAG(internal_run_death_test)) ||
ParseBoolFlag(arg, kListTestsFlag, >EST_FLAG(list_tests)) ||
ParseStringFlag(arg, kOutputFlag, >EST_FLAG(output)) ||
ParseBoolFlag(arg, kPrintTimeFlag, >EST_FLAG(print_time)) ||
ParseInt32Flag(arg, kRandomSeedFlag, >EST_FLAG(random_seed)) ||
ParseInt32Flag(arg, kRepeatFlag, >EST_FLAG(repeat)) ||
ParseBoolFlag(arg, kShuffleFlag, >EST_FLAG(shuffle)) ||
ParseInt32Flag(arg, kStackTraceDepthFlag,
>EST_FLAG(stack_trace_depth)) ||
ParseStringFlag(arg, kStreamResultToFlag,
>EST_FLAG(stream_result_to)) ||
ParseBoolFlag(arg, kThrowOnFailureFlag,
>EST_FLAG(throw_on_failure))
) {
// Yes. Shift the remainder of the argv list left by one. Note
// that argv has (*argc + 1) elements, the last one always being
// NULL. The following loop moves the trailing NULL element as
// well.
for (int j = i; j != *argc; j++) {
argv[j] = argv[j + 1];
}
// Decrements the argument count.
(*argc)--;
// We also need to decrement the iterator as we just removed
// an element.
i--;
} else if (arg_string == "--help" || arg_string == "-h" ||
arg_string == "-?" || arg_string == "/?" ||
HasGoogleTestFlagPrefix(arg)) {
// Both help flag and unrecognized Google Test flags (excluding
// internal ones) trigger help display.
g_help_flag = true;
}
}
if (g_help_flag) {
// We print the help here instead of in RUN_ALL_TESTS(), as the
// latter may not be called at all if the user is using Google
// Test with another testing framework.
PrintColorEncoded(kColorEncodedHelpMessage);
}
}
// Parses the command line for Google Test flags, without initializing
// other parts of Google Test.
void ParseGoogleTestFlagsOnly(int* argc, char** argv) {
ParseGoogleTestFlagsOnlyImpl(argc, argv);
}
void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {
ParseGoogleTestFlagsOnlyImpl(argc, argv);
}
// The internal implementation of InitGoogleTest().
//
// The type parameter CharType can be instantiated to either char or
// wchar_t.
template <typename CharType>
void InitGoogleTestImpl(int* argc, CharType** argv) {
g_init_gtest_count++;
// We don't want to run the initialization code twice.
if (g_init_gtest_count != 1) return;
if (*argc <= 0) return;
internal::g_executable_path = internal::StreamableToString(argv[0]);
#if GTEST_HAS_DEATH_TEST
g_argvs.clear();
for (int i = 0; i != *argc; i++) {
g_argvs.push_back(StreamableToString(argv[i]));
}
#endif // GTEST_HAS_DEATH_TEST
ParseGoogleTestFlagsOnly(argc, argv);
GetUnitTestImpl()->PostFlagParsingInit();
}
} // namespace internal
// Initializes Google Test. This must be called before calling
// RUN_ALL_TESTS(). In particular, it parses a command line for the
// flags that Google Test recognizes. Whenever a Google Test flag is
// seen, it is removed from argv, and *argc is decremented.
//
// No value is returned. Instead, the Google Test flag variables are
// updated.
//
// Calling the function for the second time has no user-visible effect.
void InitGoogleTest(int* argc, char** argv) {
internal::InitGoogleTestImpl(argc, argv);
}
// This overloaded version can be used in Windows programs compiled in
// UNICODE mode.
void InitGoogleTest(int* argc, wchar_t** argv) {
internal::InitGoogleTestImpl(argc, argv);
}
} // namespace testing
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)
//
// This file implements death tests.
#if GTEST_HAS_DEATH_TEST
# if GTEST_OS_MAC
# include <crt_externs.h>
# endif // GTEST_OS_MAC
# include <errno.h>
# include <fcntl.h>
# include <limits.h>
# if GTEST_OS_LINUX
# include <signal.h>
# endif // GTEST_OS_LINUX
# include <stdarg.h>
# if GTEST_OS_WINDOWS
# include <windows.h>
# else
# include <sys/mman.h>
# include <sys/wait.h>
# endif // GTEST_OS_WINDOWS
# if GTEST_OS_QNX
# include <spawn.h>
# endif // GTEST_OS_QNX
#endif // GTEST_HAS_DEATH_TEST
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
#define GTEST_IMPLEMENTATION_ 1
#undef GTEST_IMPLEMENTATION_
namespace testing {
// Constants.
// The default death test style.
static const char kDefaultDeathTestStyle[] = "fast";
GTEST_DEFINE_string_(
death_test_style,
internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle),
"Indicates how to run a death test in a forked child process: "
"\"threadsafe\" (child process re-executes the test binary "
"from the beginning, running only the specific death test) or "
"\"fast\" (child process runs the death test immediately "
"after forking).");
GTEST_DEFINE_bool_(
death_test_use_fork,
internal::BoolFromGTestEnv("death_test_use_fork", false),
"Instructs to use fork()/_exit() instead of clone() in death tests. "
"Ignored and always uses fork() on POSIX systems where clone() is not "
"implemented. Useful when running under valgrind or similar tools if "
"those do not support clone(). Valgrind 3.3.1 will just fail if "
"it sees an unsupported combination of clone() flags. "
"It is not recommended to use this flag w/o valgrind though it will "
"work in 99% of the cases. Once valgrind is fixed, this flag will "
"most likely be removed.");
namespace internal {
GTEST_DEFINE_string_(
internal_run_death_test, "",
"Indicates the file, line number, temporal index of "
"the single death test to run, and a file descriptor to "
"which a success code may be sent, all separated by "
"the '|' characters. This flag is specified if and only if the current "
"process is a sub-process launched for running a thread-safe "
"death test. FOR INTERNAL USE ONLY.");
} // namespace internal
#if GTEST_HAS_DEATH_TEST
namespace internal {
// Valid only for fast death tests. Indicates the code is running in the
// child process of a fast style death test.
static bool g_in_fast_death_test_child = false;
// Returns a Boolean value indicating whether the caller is currently
// executing in the context of the death test child process. Tools such as
// Valgrind heap checkers may need this to modify their behavior in death
// tests. IMPORTANT: This is an internal utility. Using it may break the
// implementation of death tests. User code MUST NOT use it.
bool InDeathTestChild() {
# if GTEST_OS_WINDOWS
// On Windows, death tests are thread-safe regardless of the value of the
// death_test_style flag.
return !GTEST_FLAG(internal_run_death_test).empty();
# else
if (GTEST_FLAG(death_test_style) == "threadsafe")
return !GTEST_FLAG(internal_run_death_test).empty();
else
return g_in_fast_death_test_child;
#endif
}
} // namespace internal
// ExitedWithCode constructor.
ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {
}
// ExitedWithCode function-call operator.
bool ExitedWithCode::operator()(int exit_status) const {
# if GTEST_OS_WINDOWS
return exit_status == exit_code_;
# else
return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;
# endif // GTEST_OS_WINDOWS
}
# if !GTEST_OS_WINDOWS
// KilledBySignal constructor.
KilledBySignal::KilledBySignal(int signum) : signum_(signum) {
}
// KilledBySignal function-call operator.
bool KilledBySignal::operator()(int exit_status) const {
return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;
}
# endif // !GTEST_OS_WINDOWS
namespace internal {
// Utilities needed for death tests.
// Generates a textual description of a given exit code, in the format
// specified by wait(2).
static std::string ExitSummary(int exit_code) {
Message m;
# if GTEST_OS_WINDOWS
m << "Exited with exit status " << exit_code;
# else
if (WIFEXITED(exit_code)) {
m << "Exited with exit status " << WEXITSTATUS(exit_code);
} else if (WIFSIGNALED(exit_code)) {
m << "Terminated by signal " << WTERMSIG(exit_code);
}
# ifdef WCOREDUMP
if (WCOREDUMP(exit_code)) {
m << " (core dumped)";
}
# endif
# endif // GTEST_OS_WINDOWS
return m.GetString();
}
// Returns true if exit_status describes a process that was terminated
// by a signal, or exited normally with a nonzero exit code.
bool ExitedUnsuccessfully(int exit_status) {
return !ExitedWithCode(0)(exit_status);
}
# if !GTEST_OS_WINDOWS
// Generates a textual failure message when a death test finds more than
// one thread running, or cannot determine the number of threads, prior
// to executing the given statement. It is the responsibility of the
// caller not to pass a thread_count of 1.
static std::string DeathTestThreadWarning(size_t thread_count) {
Message msg;
msg << "Death tests use fork(), which is unsafe particularly"
<< " in a threaded context. For this test, " << GTEST_NAME_ << " ";
if (thread_count == 0)
msg << "couldn't detect the number of threads.";
else
msg << "detected " << thread_count << " threads.";
return msg.GetString();
}
# endif // !GTEST_OS_WINDOWS
// Flag characters for reporting a death test that did not die.
static const char kDeathTestLived = 'L';
static const char kDeathTestReturned = 'R';
static const char kDeathTestThrew = 'T';
static const char kDeathTestInternalError = 'I';
// An enumeration describing all of the possible ways that a death test can
// conclude. DIED means that the process died while executing the test
// code; LIVED means that process lived beyond the end of the test code;
// RETURNED means that the test statement attempted to execute a return
// statement, which is not allowed; THREW means that the test statement
// returned control by throwing an exception. IN_PROGRESS means the test
// has not yet concluded.
// TODO(vladl@google.com): Unify names and possibly values for
// AbortReason, DeathTestOutcome, and flag characters above.
enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };
// Routine for aborting the program which is safe to call from an
// exec-style death test child process, in which case the error
// message is propagated back to the parent process. Otherwise, the
// message is simply printed to stderr. In either case, the program
// then exits with status 1.
void DeathTestAbort(const std::string& message) {
// On a POSIX system, this function may be called from a threadsafe-style
// death test child process, which operates on a very small stack. Use
// the heap for any additional non-minuscule memory requirements.
const InternalRunDeathTestFlag* const flag =
GetUnitTestImpl()->internal_run_death_test_flag();
if (flag != NULL) {
FILE* parent = posix::FDOpen(flag->write_fd(), "w");
fputc(kDeathTestInternalError, parent);
fprintf(parent, "%s", message.c_str());
fflush(parent);
_exit(1);
} else {
fprintf(stderr, "%s", message.c_str());
fflush(stderr);
posix::Abort();
}
}
// A replacement for CHECK that calls DeathTestAbort if the assertion
// fails.
# define GTEST_DEATH_TEST_CHECK_(expression) \
do { \
if (!::testing::internal::IsTrue(expression)) { \
DeathTestAbort( \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \
+ #expression); \
} \
} while (::testing::internal::AlwaysFalse())
// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for
// evaluating any system call that fulfills two conditions: it must return
// -1 on failure, and set errno to EINTR when it is interrupted and
// should be tried again. The macro expands to a loop that repeatedly
// evaluates the expression as long as it evaluates to -1 and sets
// errno to EINTR. If the expression evaluates to -1 but errno is
// something other than EINTR, DeathTestAbort is called.
# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \
do { \
int gtest_retval; \
do { \
gtest_retval = (expression); \
} while (gtest_retval == -1 && errno == EINTR); \
if (gtest_retval == -1) { \
DeathTestAbort( \
::std::string("CHECK failed: File ") + __FILE__ + ", line " \
+ ::testing::internal::StreamableToString(__LINE__) + ": " \
+ #expression + " != -1"); \
} \
} while (::testing::internal::AlwaysFalse())
// Returns the message describing the last system error in errno.
std::string GetLastErrnoDescription() {
return errno == 0 ? "" : posix::StrError(errno);
}
// This is called from a death test parent process to read a failure
// message from the death test child process and log it with the FATAL
// severity. On Windows, the message is read from a pipe handle. On other
// platforms, it is read from a file descriptor.
static void FailFromInternalError(int fd) {
Message error;
char buffer[256];
int num_read;
do {
while ((num_read = posix::Read(fd, buffer, 255)) > 0) {
buffer[num_read] = '\0';
error << buffer;
}
} while (num_read == -1 && errno == EINTR);
if (num_read == 0) {
GTEST_LOG_(FATAL) << error.GetString();
} else {
const int last_error = errno;
GTEST_LOG_(FATAL) << "Error while reading death test internal: "
<< GetLastErrnoDescription() << " [" << last_error << "]";
}
}
// Death test constructor. Increments the running death test count
// for the current test.
DeathTest::DeathTest() {
TestInfo* const info = GetUnitTestImpl()->current_test_info();
if (info == NULL) {
DeathTestAbort("Cannot run a death test outside of a TEST or "
"TEST_F construct");
}
}
// Creates and returns a death test by dispatching to the current
// death test factory.
bool DeathTest::Create(const char* statement, const RE* regex,
const char* file, int line, DeathTest** test) {
return GetUnitTestImpl()->death_test_factory()->Create(
statement, regex, file, line, test);
}
const char* DeathTest::LastMessage() {
return last_death_test_message_.c_str();
}
void DeathTest::set_last_death_test_message(const std::string& message) {
last_death_test_message_ = message;
}
std::string DeathTest::last_death_test_message_;
// Provides cross platform implementation for some death functionality.
class DeathTestImpl : public DeathTest {
protected:
DeathTestImpl(const char* a_statement, const RE* a_regex)
: statement_(a_statement),
regex_(a_regex),
spawned_(false),
status_(-1),
outcome_(IN_PROGRESS),
read_fd_(-1),
write_fd_(-1) {}
// read_fd_ is expected to be closed and cleared by a derived class.
~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }
void Abort(AbortReason reason);
virtual bool Passed(bool status_ok);
const char* statement() const { return statement_; }
const RE* regex() const { return regex_; }
bool spawned() const { return spawned_; }
void set_spawned(bool is_spawned) { spawned_ = is_spawned; }
int status() const { return status_; }
void set_status(int a_status) { status_ = a_status; }
DeathTestOutcome outcome() const { return outcome_; }
void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }
int read_fd() const { return read_fd_; }
void set_read_fd(int fd) { read_fd_ = fd; }
int write_fd() const { return write_fd_; }
void set_write_fd(int fd) { write_fd_ = fd; }
// Called in the parent process only. Reads the result code of the death
// test child process via a pipe, interprets it to set the outcome_
// member, and closes read_fd_. Outputs diagnostics and terminates in
// case of unexpected codes.
void ReadAndInterpretStatusByte();
private:
// The textual content of the code this object is testing. This class
// doesn't own this string and should not attempt to delete it.
const char* const statement_;
// The regular expression which test output must match. DeathTestImpl
// doesn't own this object and should not attempt to delete it.
const RE* const regex_;
// True if the death test child process has been successfully spawned.
bool spawned_;
// The exit status of the child process.
int status_;
// How the death test concluded.
DeathTestOutcome outcome_;
// Descriptor to the read end of the pipe to the child process. It is
// always -1 in the child process. The child keeps its write end of the
// pipe in write_fd_.
int read_fd_;
// Descriptor to the child's write end of the pipe to the parent process.
// It is always -1 in the parent process. The parent keeps its end of the
// pipe in read_fd_.
int write_fd_;
};
// Called in the parent process only. Reads the result code of the death
// test child process via a pipe, interprets it to set the outcome_
// member, and closes read_fd_. Outputs diagnostics and terminates in
// case of unexpected codes.
void DeathTestImpl::ReadAndInterpretStatusByte() {
char flag;
int bytes_read;
// The read() here blocks until data is available (signifying the
// failure of the death test) or until the pipe is closed (signifying
// its success), so it's okay to call this in the parent before
// the child process has exited.
do {
bytes_read = posix::Read(read_fd(), &flag, 1);
} while (bytes_read == -1 && errno == EINTR);
if (bytes_read == 0) {
set_outcome(DIED);
} else if (bytes_read == 1) {
switch (flag) {
case kDeathTestReturned:
set_outcome(RETURNED);
break;
case kDeathTestThrew:
set_outcome(THREW);
break;
case kDeathTestLived:
set_outcome(LIVED);
break;
case kDeathTestInternalError:
FailFromInternalError(read_fd()); // Does not return.
break;
default:
GTEST_LOG_(FATAL) << "Death test child process reported "
<< "unexpected status byte ("
<< static_cast<unsigned int>(flag) << ")";
}
} else {
GTEST_LOG_(FATAL) << "Read from death test child process failed: "
<< GetLastErrnoDescription();
}
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));
set_read_fd(-1);
}
// Signals that the death test code which should have exited, didn't.
// Should be called only in a death test child process.
// Writes a status byte to the child's status file descriptor, then
// calls _exit(1).
void DeathTestImpl::Abort(AbortReason reason) {
// The parent process considers the death test to be a failure if
// it finds any data in our pipe. So, here we write a single flag byte
// to the pipe, then exit.
const char status_ch =
reason == TEST_DID_NOT_DIE ? kDeathTestLived :
reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;
GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));
// We are leaking the descriptor here because on some platforms (i.e.,
// when built as Windows DLL), destructors of global objects will still
// run after calling _exit(). On such systems, write_fd_ will be
// indirectly closed from the destructor of UnitTestImpl, causing double
// close if it is also closed here. On debug configurations, double close
// may assert. As there are no in-process buffers to flush here, we are
// relying on the OS to close the descriptor after the process terminates
// when the destructors are not run.
_exit(1); // Exits w/o any normal exit hooks (we were supposed to crash)
}
// Returns an indented copy of stderr output for a death test.
// This makes distinguishing death test output lines from regular log lines
// much easier.
static ::std::string FormatDeathTestOutput(const ::std::string& output) {
::std::string ret;
for (size_t at = 0; ; ) {
const size_t line_end = output.find('\n', at);
ret += "[ DEATH ] ";
if (line_end == ::std::string::npos) {
ret += output.substr(at);
break;
}
ret += output.substr(at, line_end + 1 - at);
at = line_end + 1;
}
return ret;
}
// Assesses the success or failure of a death test, using both private
// members which have previously been set, and one argument:
//
// Private data members:
// outcome: An enumeration describing how the death test
// concluded: DIED, LIVED, THREW, or RETURNED. The death test
// fails in the latter three cases.
// status: The exit status of the child process. On *nix, it is in the
// in the format specified by wait(2). On Windows, this is the
// value supplied to the ExitProcess() API or a numeric code
// of the exception that terminated the program.
// regex: A regular expression object to be applied to
// the test's captured standard error output; the death test
// fails if it does not match.
//
// Argument:
// status_ok: true if exit_status is acceptable in the context of
// this particular death test, which fails if it is false
//
// Returns true iff all of the above conditions are met. Otherwise, the
// first failing condition, in the order given above, is the one that is
// reported. Also sets the last death test message string.
bool DeathTestImpl::Passed(bool status_ok) {
if (!spawned())
return false;
const std::string error_message = GetCapturedStderr();
bool success = false;
Message buffer;
buffer << "Death test: " << statement() << "\n";
switch (outcome()) {
case LIVED:
buffer << " Result: failed to die.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
break;
case THREW:
buffer << " Result: threw an exception.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
break;
case RETURNED:
buffer << " Result: illegal return in test statement.\n"
<< " Error msg:\n" << FormatDeathTestOutput(error_message);
break;
case DIED:
if (status_ok) {
const bool matched = RE::PartialMatch(error_message.c_str(), *regex());
if (matched) {
success = true;
} else {
buffer << " Result: died but not with expected error.\n"
<< " Expected: " << regex()->pattern() << "\n"
<< "Actual msg:\n" << FormatDeathTestOutput(error_message);
}
} else {
buffer << " Result: died but not with expected exit code:\n"
<< " " << ExitSummary(status()) << "\n"
<< "Actual msg:\n" << FormatDeathTestOutput(error_message);
}
break;
case IN_PROGRESS:
default:
GTEST_LOG_(FATAL)
<< "DeathTest::Passed somehow called before conclusion of test";
}
DeathTest::set_last_death_test_message(buffer.GetString());
return success;
}
# if GTEST_OS_WINDOWS
// WindowsDeathTest implements death tests on Windows. Due to the
// specifics of starting new processes on Windows, death tests there are
// always threadsafe, and Google Test considers the
// --gtest_death_test_style=fast setting to be equivalent to
// --gtest_death_test_style=threadsafe there.
//
// A few implementation notes: Like the Linux version, the Windows
// implementation uses pipes for child-to-parent communication. But due to
// the specifics of pipes on Windows, some extra steps are required:
//
// 1. The parent creates a communication pipe and stores handles to both
// ends of it.
// 2. The parent starts the child and provides it with the information
// necessary to acquire the handle to the write end of the pipe.
// 3. The child acquires the write end of the pipe and signals the parent
// using a Windows event.
// 4. Now the parent can release the write end of the pipe on its side. If
// this is done before step 3, the object's reference count goes down to
// 0 and it is destroyed, preventing the child from acquiring it. The
// parent now has to release it, or read operations on the read end of
// the pipe will not return when the child terminates.
// 5. The parent reads child's output through the pipe (outcome code and
// any possible error messages) from the pipe, and its stderr and then
// determines whether to fail the test.
//
// Note: to distinguish Win32 API calls from the local method and function
// calls, the former are explicitly resolved in the global namespace.
//
class WindowsDeathTest : public DeathTestImpl {
public:
WindowsDeathTest(const char* a_statement,
const RE* a_regex,
const char* file,
int line)
: DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}
// All of these virtual functions are inherited from DeathTest.
virtual int Wait();
virtual TestRole AssumeRole();
private:
// The name of the file in which the death test is located.
const char* const file_;
// The line number on which the death test is located.
const int line_;
// Handle to the write end of the pipe to the child process.
AutoHandle write_handle_;
// Child process handle.
AutoHandle child_handle_;
// Event the child process uses to signal the parent that it has
// acquired the handle to the write end of the pipe. After seeing this
// event the parent can release its own handles to make sure its
// ReadFile() calls return when the child terminates.
AutoHandle event_handle_;
};
// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
int WindowsDeathTest::Wait() {
if (!spawned())
return 0;
// Wait until the child either signals that it has acquired the write end
// of the pipe or it dies.
const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };
switch (::WaitForMultipleObjects(2,
wait_handles,
FALSE, // Waits for any of the handles.
INFINITE)) {
case WAIT_OBJECT_0:
case WAIT_OBJECT_0 + 1:
break;
default:
GTEST_DEATH_TEST_CHECK_(false); // Should not get here.
}
// The child has acquired the write end of the pipe or exited.
// We release the handle on our side and continue.
write_handle_.Reset();
event_handle_.Reset();
ReadAndInterpretStatusByte();
// Waits for the child process to exit if it haven't already. This
// returns immediately if the child has already exited, regardless of
// whether previous calls to WaitForMultipleObjects synchronized on this
// handle or not.
GTEST_DEATH_TEST_CHECK_(
WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),
INFINITE));
DWORD status_code;
GTEST_DEATH_TEST_CHECK_(
::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);
child_handle_.Reset();
set_status(static_cast<int>(status_code));
return status();
}
// The AssumeRole process for a Windows death test. It creates a child
// process with the same executable as the current process to run the
// death test. The child process is given the --gtest_filter and
// --gtest_internal_run_death_test flags such that it knows to run the
// current death test only.
DeathTest::TestRole WindowsDeathTest::AssumeRole() {
const UnitTestImpl* const impl = GetUnitTestImpl();
const InternalRunDeathTestFlag* const flag =
impl->internal_run_death_test_flag();
const TestInfo* const info = impl->current_test_info();
const int death_test_index = info->result()->death_test_count();
if (flag != NULL) {
// ParseInternalRunDeathTestFlag() has performed all the necessary
// processing.
set_write_fd(flag->write_fd());
return EXECUTE_TEST;
}
// WindowsDeathTest uses an anonymous pipe to communicate results of
// a death test.
SECURITY_ATTRIBUTES handles_are_inheritable = {
sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
HANDLE read_handle, write_handle;
GTEST_DEATH_TEST_CHECK_(
::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
0) // Default buffer size.
!= FALSE);
set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),
O_RDONLY));
write_handle_.Reset(write_handle);
event_handle_.Reset(::CreateEvent(
&handles_are_inheritable,
TRUE, // The event will automatically reset to non-signaled state.
FALSE, // The initial state is non-signalled.
NULL)); // The even is unnamed.
GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);
const std::string filter_flag =
std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
info->test_case_name() + "." + info->name();
const std::string internal_flag =
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +
"=" + file_ + "|" + StreamableToString(line_) + "|" +
StreamableToString(death_test_index) + "|" +
StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +
// size_t has the same width as pointers on both 32-bit and 64-bit
// Windows platforms.
// See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.
"|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +
"|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
char executable_path[_MAX_PATH + 1]; // NOLINT
GTEST_DEATH_TEST_CHECK_(
_MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
executable_path,
_MAX_PATH));
std::string command_line =
std::string(::GetCommandLineA()) + " " + filter_flag + " \"" +
internal_flag + "\"";
DeathTest::set_last_death_test_message("");
CaptureStderr();
// Flush the log buffers since the log streams are shared with the child.
FlushInfoLog();
// The child process will share the standard handles with the parent.
STARTUPINFOA startup_info;
memset(&startup_info, 0, sizeof(STARTUPINFO));
startup_info.dwFlags = STARTF_USESTDHANDLES;
startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);
startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
PROCESS_INFORMATION process_info;
GTEST_DEATH_TEST_CHECK_(::CreateProcessA(
executable_path,
const_cast<char*>(command_line.c_str()),
NULL, // Retuned process handle is not inheritable.
NULL, // Retuned thread handle is not inheritable.
TRUE, // Child inherits all inheritable handles (for write_handle_).
0x0, // Default creation flags.
NULL, // Inherit the parent's environment.
UnitTest::GetInstance()->original_working_dir(),
&startup_info,
&process_info) != FALSE);
child_handle_.Reset(process_info.hProcess);
::CloseHandle(process_info.hThread);
set_spawned(true);
return OVERSEE_TEST;
}
# else // We are not on Windows.
// ForkingDeathTest provides implementations for most of the abstract
// methods of the DeathTest interface. Only the AssumeRole method is
// left undefined.
class ForkingDeathTest : public DeathTestImpl {
public:
ForkingDeathTest(const char* statement, const RE* regex);
// All of these virtual functions are inherited from DeathTest.
virtual int Wait();
protected:
void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }
private:
// PID of child process during death test; 0 in the child process itself.
pid_t child_pid_;
};
// Constructs a ForkingDeathTest.
ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)
: DeathTestImpl(a_statement, a_regex),
child_pid_(-1) {}
// Waits for the child in a death test to exit, returning its exit
// status, or 0 if no child process exists. As a side effect, sets the
// outcome data member.
int ForkingDeathTest::Wait() {
if (!spawned())
return 0;
ReadAndInterpretStatusByte();
int status_value;
GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));
set_status(status_value);
return status_value;
}
// A concrete death test class that forks, then immediately runs the test
// in the child process.
class NoExecDeathTest : public ForkingDeathTest {
public:
NoExecDeathTest(const char* a_statement, const RE* a_regex) :
ForkingDeathTest(a_statement, a_regex) { }
virtual TestRole AssumeRole();
};
// The AssumeRole process for a fork-and-run death test. It implements a
// straightforward fork, with a simple pipe to transmit the status byte.
DeathTest::TestRole NoExecDeathTest::AssumeRole() {
const size_t thread_count = GetThreadCount();
if (thread_count != 1) {
GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);
}
int pipe_fd[2];
GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
DeathTest::set_last_death_test_message("");
CaptureStderr();
// When we fork the process below, the log file buffers are copied, but the
// file descriptors are shared. We flush all log files here so that closing
// the file descriptors in the child process doesn't throw off the
// synchronization between descriptors and buffers in the parent process.
// This is as close to the fork as possible to avoid a race condition in case
// there are multiple threads running before the death test, and another
// thread writes to the log file.
FlushInfoLog();
const pid_t child_pid = fork();
GTEST_DEATH_TEST_CHECK_(child_pid != -1);
set_child_pid(child_pid);
if (child_pid == 0) {
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));
set_write_fd(pipe_fd[1]);
// Redirects all logging to stderr in the child process to prevent
// concurrent writes to the log files. We capture stderr in the parent
// process and append the child process' output to a log.
LogToStderr();
// Event forwarding to the listeners of event listener API mush be shut
// down in death test subprocesses.
GetUnitTestImpl()->listeners()->SuppressEventForwarding();
g_in_fast_death_test_child = true;
return EXECUTE_TEST;
} else {
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
set_read_fd(pipe_fd[0]);
set_spawned(true);
return OVERSEE_TEST;
}
}
// A concrete death test class that forks and re-executes the main
// program from the beginning, with command-line flags set that cause
// only this specific death test to be run.
class ExecDeathTest : public ForkingDeathTest {
public:
ExecDeathTest(const char* a_statement, const RE* a_regex,
const char* file, int line) :
ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }
virtual TestRole AssumeRole();
private:
static ::std::vector<testing::internal::string>
GetArgvsForDeathTestChildProcess() {
::std::vector<testing::internal::string> args = GetInjectableArgvs();
return args;
}
// The name of the file in which the death test is located.
const char* const file_;
// The line number on which the death test is located.
const int line_;
};
// Utility class for accumulating command-line arguments.
class Arguments {
public:
Arguments() {
args_.push_back(NULL);
}
~Arguments() {
for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
++i) {
free(*i);
}
}
void AddArgument(const char* argument) {
args_.insert(args_.end() - 1, posix::StrDup(argument));
}
template <typename Str>
void AddArguments(const ::std::vector<Str>& arguments) {
for (typename ::std::vector<Str>::const_iterator i = arguments.begin();
i != arguments.end();
++i) {
args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));
}
}
char* const* Argv() {
return &args_[0];
}
private:
std::vector<char*> args_;
};
// A struct that encompasses the arguments to the child process of a
// threadsafe-style death test process.
struct ExecDeathTestArgs {
char* const* argv; // Command-line arguments for the child's call to exec
int close_fd; // File descriptor to close; the read end of a pipe
};
# if GTEST_OS_MAC
inline char** GetEnviron() {
// When Google Test is built as a framework on MacOS X, the environ variable
// is unavailable. Apple's documentation (man environ) recommends using
// _NSGetEnviron() instead.
return *_NSGetEnviron();
}
# else
// Some POSIX platforms expect you to declare environ. extern "C" makes
// it reside in the global namespace.
extern "C" char** environ;
inline char** GetEnviron() { return environ; }
# endif // GTEST_OS_MAC
# if !GTEST_OS_QNX
// The main function for a threadsafe-style death test child process.
// This function is called in a clone()-ed process and thus must avoid
// any potentially unsafe operations like malloc or libc functions.
static int ExecDeathTestChildMain(void* child_arg) {
ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));
// We need to execute the test program in the same environment where
// it was originally invoked. Therefore we change to the original
// working directory first.
const char* const original_dir =
UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
GetLastErrnoDescription());
return EXIT_FAILURE;
}
// We can safely call execve() as it's a direct system call. We
// cannot use execvp() as it's a libc function and thus potentially
// unsafe. Since execve() doesn't search the PATH, the user must
// invoke the test program via a valid path that contains at least
// one path separator.
execve(args->argv[0], args->argv, GetEnviron());
DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " +
original_dir + " failed: " +
GetLastErrnoDescription());
return EXIT_FAILURE;
}
# endif // !GTEST_OS_QNX
// Two utility routines that together determine the direction the stack
// grows.
// This could be accomplished more elegantly by a single recursive
// function, but we want to guard against the unlikely possibility of
// a smart compiler optimizing the recursion away.
//
// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining
// StackLowerThanAddress into StackGrowsDown, which then doesn't give
// correct answer.
void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;
void StackLowerThanAddress(const void* ptr, bool* result) {
int dummy;
*result = (&dummy < ptr);
}
bool StackGrowsDown() {
int dummy;
bool result;
StackLowerThanAddress(&dummy, &result);
return result;
}
// Spawns a child process with the same executable as the current process in
// a thread-safe manner and instructs it to run the death test. The
// implementation uses fork(2) + exec. On systems where clone(2) is
// available, it is used instead, being slightly more thread-safe. On QNX,
// fork supports only single-threaded environments, so this function uses
// spawn(2) there instead. The function dies with an error message if
// anything goes wrong.
static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
ExecDeathTestArgs args = { argv, close_fd };
pid_t child_pid = -1;
# if GTEST_OS_QNX
// Obtains the current directory and sets it to be closed in the child
// process.
const int cwd_fd = open(".", O_RDONLY);
GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));
// We need to execute the test program in the same environment where
// it was originally invoked. Therefore we change to the original
// working directory first.
const char* const original_dir =
UnitTest::GetInstance()->original_working_dir();
// We can safely call chdir() as it's a direct system call.
if (chdir(original_dir) != 0) {
DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " +
GetLastErrnoDescription());
return EXIT_FAILURE;
}
int fd_flags;
// Set close_fd to be closed after spawn.
GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));
GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,
fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0};
// spawn is a system call.
child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());
// Restores the current working directory.
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));
# else // GTEST_OS_QNX
# if GTEST_OS_LINUX
// When a SIGPROF signal is received while fork() or clone() are executing,
// the process may hang. To avoid this, we ignore SIGPROF here and re-enable
// it after the call to fork()/clone() is complete.
struct sigaction saved_sigprof_action;
struct sigaction ignore_sigprof_action;
memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));
sigemptyset(&ignore_sigprof_action.sa_mask);
ignore_sigprof_action.sa_handler = SIG_IGN;
GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(
SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));
# endif // GTEST_OS_LINUX
# if GTEST_HAS_CLONE
const bool use_fork = GTEST_FLAG(death_test_use_fork);
if (!use_fork) {
static const bool stack_grows_down = StackGrowsDown();
const size_t stack_size = getpagesize();
// MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.
void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, -1, 0);
GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);
// Maximum stack alignment in bytes: For a downward-growing stack, this
// amount is subtracted from size of the stack space to get an address
// that is within the stack space and is aligned on all systems we care
// about. As far as I know there is no ABI with stack alignment greater
// than 64. We assume stack and stack_size already have alignment of
// kMaxStackAlignment.
const size_t kMaxStackAlignment = 64;
void* const stack_top =
static_cast<char*>(stack) +
(stack_grows_down ? stack_size - kMaxStackAlignment : 0);
GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&
reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);
child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);
GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);
}
# else
const bool use_fork = true;
# endif // GTEST_HAS_CLONE
if (use_fork && (child_pid = fork()) == 0) {
ExecDeathTestChildMain(&args);
_exit(0);
}
# endif // GTEST_OS_QNX
# if GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_SYSCALL_(
sigaction(SIGPROF, &saved_sigprof_action, NULL));
# endif // GTEST_OS_LINUX
GTEST_DEATH_TEST_CHECK_(child_pid != -1);
return child_pid;
}
// The AssumeRole process for a fork-and-exec death test. It re-executes the
// main program from the beginning, setting the --gtest_filter
// and --gtest_internal_run_death_test flags to cause only the current
// death test to be re-run.
DeathTest::TestRole ExecDeathTest::AssumeRole() {
const UnitTestImpl* const impl = GetUnitTestImpl();
const InternalRunDeathTestFlag* const flag =
impl->internal_run_death_test_flag();
const TestInfo* const info = impl->current_test_info();
const int death_test_index = info->result()->death_test_count();
if (flag != NULL) {
set_write_fd(flag->write_fd());
return EXECUTE_TEST;
}
int pipe_fd[2];
GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);
// Clear the close-on-exec flag on the write end of the pipe, lest
// it be closed when the child process does an exec:
GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);
const std::string filter_flag =
std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "="
+ info->test_case_name() + "." + info->name();
const std::string internal_flag =
std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "="
+ file_ + "|" + StreamableToString(line_) + "|"
+ StreamableToString(death_test_index) + "|"
+ StreamableToString(pipe_fd[1]);
Arguments args;
args.AddArguments(GetArgvsForDeathTestChildProcess());
args.AddArgument(filter_flag.c_str());
args.AddArgument(internal_flag.c_str());
DeathTest::set_last_death_test_message("");
CaptureStderr();
// See the comment in NoExecDeathTest::AssumeRole for why the next line
// is necessary.
FlushInfoLog();
const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));
set_child_pid(child_pid);
set_read_fd(pipe_fd[0]);
set_spawned(true);
return OVERSEE_TEST;
}
# endif // !GTEST_OS_WINDOWS
// Creates a concrete DeathTest-derived class that depends on the
// --gtest_death_test_style flag, and sets the pointer pointed to
// by the "test" argument to its address. If the test should be
// skipped, sets that pointer to NULL. Returns true, unless the
// flag is set to an invalid value.
bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,
const char* file, int line,
DeathTest** test) {
UnitTestImpl* const impl = GetUnitTestImpl();
const InternalRunDeathTestFlag* const flag =
impl->internal_run_death_test_flag();
const int death_test_index = impl->current_test_info()
->increment_death_test_count();
if (flag != NULL) {
if (death_test_index > flag->index()) {
DeathTest::set_last_death_test_message(
"Death test count (" + StreamableToString(death_test_index)
+ ") somehow exceeded expected maximum ("
+ StreamableToString(flag->index()) + ")");
return false;
}
if (!(flag->file() == file && flag->line() == line &&
flag->index() == death_test_index)) {
*test = NULL;
return true;
}
}
# if GTEST_OS_WINDOWS
if (GTEST_FLAG(death_test_style) == "threadsafe" ||
GTEST_FLAG(death_test_style) == "fast") {
*test = new WindowsDeathTest(statement, regex, file, line);
}
# else
if (GTEST_FLAG(death_test_style) == "threadsafe") {
*test = new ExecDeathTest(statement, regex, file, line);
} else if (GTEST_FLAG(death_test_style) == "fast") {
*test = new NoExecDeathTest(statement, regex);
}
# endif // GTEST_OS_WINDOWS
else { // NOLINT - this is more readable than unbalanced brackets inside #if.
DeathTest::set_last_death_test_message(
"Unknown death test style \"" + GTEST_FLAG(death_test_style)
+ "\" encountered");
return false;
}
return true;
}
// Splits a given string on a given delimiter, populating a given
// vector with the fields. GTEST_HAS_DEATH_TEST implies that we have
// ::std::string, so we can use it here.
static void SplitString(const ::std::string& str, char delimiter,
::std::vector< ::std::string>* dest) {
::std::vector< ::std::string> parsed;
::std::string::size_type pos = 0;
while (::testing::internal::AlwaysTrue()) {
const ::std::string::size_type colon = str.find(delimiter, pos);
if (colon == ::std::string::npos) {
parsed.push_back(str.substr(pos));
break;
} else {
parsed.push_back(str.substr(pos, colon - pos));
pos = colon + 1;
}
}
dest->swap(parsed);
}
# if GTEST_OS_WINDOWS
// Recreates the pipe and event handles from the provided parameters,
// signals the event, and returns a file descriptor wrapped around the pipe
// handle. This function is called in the child process only.
int GetStatusFileDescriptor(unsigned int parent_process_id,
size_t write_handle_as_size_t,
size_t event_handle_as_size_t) {
AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,
FALSE, // Non-inheritable.
parent_process_id));
if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {
DeathTestAbort("Unable to open parent process " +
StreamableToString(parent_process_id));
}
// TODO(vladl@google.com): Replace the following check with a
// compile-time assertion when available.
GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));
const HANDLE write_handle =
reinterpret_cast<HANDLE>(write_handle_as_size_t);
HANDLE dup_write_handle;
// The newly initialized handle is accessible only in in the parent
// process. To obtain one accessible within the child, we need to use
// DuplicateHandle.
if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,
::GetCurrentProcess(), &dup_write_handle,
0x0, // Requested privileges ignored since
// DUPLICATE_SAME_ACCESS is used.
FALSE, // Request non-inheritable handler.
DUPLICATE_SAME_ACCESS)) {
DeathTestAbort("Unable to duplicate the pipe handle " +
StreamableToString(write_handle_as_size_t) +
" from the parent process " +
StreamableToString(parent_process_id));
}
const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);
HANDLE dup_event_handle;
if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,
::GetCurrentProcess(), &dup_event_handle,
0x0,
FALSE,
DUPLICATE_SAME_ACCESS)) {
DeathTestAbort("Unable to duplicate the event handle " +
StreamableToString(event_handle_as_size_t) +
" from the parent process " +
StreamableToString(parent_process_id));
}
const int write_fd =
::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);
if (write_fd == -1) {
DeathTestAbort("Unable to convert pipe handle " +
StreamableToString(write_handle_as_size_t) +
" to a file descriptor");
}
// Signals the parent that the write end of the pipe has been acquired
// so the parent can release its own write end.
::SetEvent(dup_event_handle);
return write_fd;
}
# endif // GTEST_OS_WINDOWS
// Returns a newly created InternalRunDeathTestFlag object with fields
// initialized from the GTEST_FLAG(internal_run_death_test) flag if
// the flag is specified; otherwise returns NULL.
InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {
if (GTEST_FLAG(internal_run_death_test) == "") return NULL;
// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we
// can use it here.
int line = -1;
int index = -1;
::std::vector< ::std::string> fields;
SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);
int write_fd = -1;
# if GTEST_OS_WINDOWS
unsigned int parent_process_id = 0;
size_t write_handle_as_size_t = 0;
size_t event_handle_as_size_t = 0;
if (fields.size() != 6
|| !ParseNaturalNumber(fields[1], &line)
|| !ParseNaturalNumber(fields[2], &index)
|| !ParseNaturalNumber(fields[3], &parent_process_id)
|| !ParseNaturalNumber(fields[4], &write_handle_as_size_t)
|| !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: " +
GTEST_FLAG(internal_run_death_test));
}
write_fd = GetStatusFileDescriptor(parent_process_id,
write_handle_as_size_t,
event_handle_as_size_t);
# else
if (fields.size() != 4
|| !ParseNaturalNumber(fields[1], &line)
|| !ParseNaturalNumber(fields[2], &index)
|| !ParseNaturalNumber(fields[3], &write_fd)) {
DeathTestAbort("Bad --gtest_internal_run_death_test flag: "
+ GTEST_FLAG(internal_run_death_test));
}
# endif // GTEST_OS_WINDOWS
return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);
}
} // namespace internal
#endif // GTEST_HAS_DEATH_TEST
} // namespace testing
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: keith.ray@gmail.com (Keith Ray)
#include <stdlib.h>
#if GTEST_OS_WINDOWS_MOBILE
# include <windows.h>
#elif GTEST_OS_WINDOWS
# include <direct.h>
# include <io.h>
#elif GTEST_OS_SYMBIAN
// Symbian OpenC has PATH_MAX in sys/syslimits.h
# include <sys/syslimits.h>
#else
# include <limits.h>
# include <climits> // Some Linux distributions define PATH_MAX here.
#endif // GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_WINDOWS
# define GTEST_PATH_MAX_ _MAX_PATH
#elif defined(PATH_MAX)
# define GTEST_PATH_MAX_ PATH_MAX
#elif defined(_XOPEN_PATH_MAX)
# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX
#else
# define GTEST_PATH_MAX_ _POSIX_PATH_MAX
#endif // GTEST_OS_WINDOWS
namespace testing {
namespace internal {
#if GTEST_OS_WINDOWS
// On Windows, '\\' is the standard path separator, but many tools and the
// Windows API also accept '/' as an alternate path separator. Unless otherwise
// noted, a file path can contain either kind of path separators, or a mixture
// of them.
const char kPathSeparator = '\\';
const char kAlternatePathSeparator = '/';
const char kPathSeparatorString[] = "\\";
const char kAlternatePathSeparatorString[] = "/";
# if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have a current directory. You should not use
// the current directory in tests on Windows CE, but this at least
// provides a reasonable fallback.
const char kCurrentDirectoryString[] = "\\";
// Windows CE doesn't define INVALID_FILE_ATTRIBUTES
const DWORD kInvalidFileAttributes = 0xffffffff;
# else
const char kCurrentDirectoryString[] = ".\\";
# endif // GTEST_OS_WINDOWS_MOBILE
#else
const char kPathSeparator = '/';
const char kPathSeparatorString[] = "/";
const char kCurrentDirectoryString[] = "./";
#endif // GTEST_OS_WINDOWS
// Returns whether the given character is a valid path separator.
static bool IsPathSeparator(char c) {
#if GTEST_HAS_ALT_PATH_SEP_
return (c == kPathSeparator) || (c == kAlternatePathSeparator);
#else
return c == kPathSeparator;
#endif
}
// Returns the current working directory, or "" if unsuccessful.
FilePath FilePath::GetCurrentDir() {
#if GTEST_OS_WINDOWS_MOBILE
// Windows CE doesn't have a current directory, so we just return
// something reasonable.
return FilePath(kCurrentDirectoryString);
#elif GTEST_OS_WINDOWS
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#else
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
return FilePath(getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd);
#endif // GTEST_OS_WINDOWS_MOBILE
}
// Returns a copy of the FilePath with the case-insensitive extension removed.
// Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns
// FilePath("dir/file"). If a case-insensitive extension is not
// found, returns a copy of the original FilePath.
FilePath FilePath::RemoveExtension(const char* extension) const {
const std::string dot_extension = std::string(".") + extension;
if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {
return FilePath(pathname_.substr(
0, pathname_.length() - dot_extension.length()));
}
return *this;
}
// Returns a pointer to the last occurence of a valid path separator in
// the FilePath. On Windows, for example, both '/' and '\' are valid path
// separators. Returns NULL if no path separator was found.
const char* FilePath::FindLastPathSeparator() const {
const char* const last_sep = strrchr(c_str(), kPathSeparator);
#if GTEST_HAS_ALT_PATH_SEP_
const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
// Comparing two pointers of which only one is NULL is undefined.
if (last_alt_sep != NULL &&
(last_sep == NULL || last_alt_sep > last_sep)) {
return last_alt_sep;
}
#endif
return last_sep;
}
// Returns a copy of the FilePath with the directory part removed.
// Example: FilePath("path/to/file").RemoveDirectoryName() returns
// FilePath("file"). If there is no directory part ("just_a_file"), it returns
// the FilePath unmodified. If there is no file part ("just_a_dir/") it
// returns an empty FilePath ("").
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveDirectoryName() const {
const char* const last_sep = FindLastPathSeparator();
return last_sep ? FilePath(last_sep + 1) : *this;
}
// RemoveFileName returns the directory path with the filename removed.
// Example: FilePath("path/to/file").RemoveFileName() returns "path/to/".
// If the FilePath is "a_file" or "/a_file", RemoveFileName returns
// FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does
// not have a file, like "just/a/dir/", it returns the FilePath unmodified.
// On Windows platform, '\' is the path separator, otherwise it is '/'.
FilePath FilePath::RemoveFileName() const {
const char* const last_sep = FindLastPathSeparator();
std::string dir;
if (last_sep) {
dir = std::string(c_str(), last_sep + 1 - c_str());
} else {
dir = kCurrentDirectoryString;
}
return FilePath(dir);
}
// Helper functions for naming files in a directory for xml output.
// Given directory = "dir", base_name = "test", number = 0,
// extension = "xml", returns "dir/test.xml". If number is greater
// than zero (e.g., 12), returns "dir/test_12.xml".
// On Windows platform, uses \ as the separator rather than /.
FilePath FilePath::MakeFileName(const FilePath& directory,
const FilePath& base_name,
int number,
const char* extension) {
std::string file;
if (number == 0) {
file = base_name.string() + "." + extension;
} else {
file = base_name.string() + "_" + StreamableToString(number)
+ "." + extension;
}
return ConcatPaths(directory, FilePath(file));
}
// Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml".
// On Windows, uses \ as the separator rather than /.
FilePath FilePath::ConcatPaths(const FilePath& directory,
const FilePath& relative_path) {
if (directory.IsEmpty())
return relative_path;
const FilePath dir(directory.RemoveTrailingPathSeparator());
return FilePath(dir.string() + kPathSeparator + relative_path.string());
}
// Returns true if pathname describes something findable in the file-system,
// either a file, directory, or whatever.
bool FilePath::FileOrDirectoryExists() const {
#if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
return attributes != kInvalidFileAttributes;
#else
posix::StatStruct file_stat;
return posix::Stat(pathname_.c_str(), &file_stat) == 0;
#endif // GTEST_OS_WINDOWS_MOBILE
}
// Returns true if pathname describes a directory in the file-system
// that exists.
bool FilePath::DirectoryExists() const {
bool result = false;
#if GTEST_OS_WINDOWS
// Don't strip off trailing separator if path is a root directory on
// Windows (like "C:\\").
const FilePath& path(IsRootDirectory() ? *this :
RemoveTrailingPathSeparator());
#else
const FilePath& path(*this);
#endif
#if GTEST_OS_WINDOWS_MOBILE
LPCWSTR unicode = String::AnsiToUtf16(path.c_str());
const DWORD attributes = GetFileAttributes(unicode);
delete [] unicode;
if ((attributes != kInvalidFileAttributes) &&
(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
result = true;
}
#else
posix::StatStruct file_stat;
result = posix::Stat(path.c_str(), &file_stat) == 0 &&
posix::IsDir(file_stat);
#endif // GTEST_OS_WINDOWS_MOBILE
return result;
}
// Returns true if pathname describes a root directory. (Windows has one
// root directory per disk drive.)
bool FilePath::IsRootDirectory() const {
#if GTEST_OS_WINDOWS
// TODO(wan@google.com): on Windows a network share like
// \\server\share can be a root directory, although it cannot be the
// current directory. Handle this properly.
return pathname_.length() == 3 && IsAbsolutePath();
#else
return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);
#endif
}
// Returns true if pathname describes an absolute path.
bool FilePath::IsAbsolutePath() const {
const char* const name = pathname_.c_str();
#if GTEST_OS_WINDOWS
return pathname_.length() >= 3 &&
((name[0] >= 'a' && name[0] <= 'z') ||
(name[0] >= 'A' && name[0] <= 'Z')) &&
name[1] == ':' &&
IsPathSeparator(name[2]);
#else
return IsPathSeparator(name[0]);
#endif
}
// Returns a pathname for a file that does not currently exist. The pathname
// will be directory/base_name.extension or
// directory/base_name_<number>.extension if directory/base_name.extension
// already exists. The number will be incremented until a pathname is found
// that does not already exist.
// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.
// There could be a race condition if two or more processes are calling this
// function at the same time -- they could both pick the same filename.
FilePath FilePath::GenerateUniqueFileName(const FilePath& directory,
const FilePath& base_name,
const char* extension) {
FilePath full_pathname;
int number = 0;
do {
full_pathname.Set(MakeFileName(directory, base_name, number++, extension));
} while (full_pathname.FileOrDirectoryExists());
return full_pathname;
}
// Returns true if FilePath ends with a path separator, which indicates that
// it is intended to represent a directory. Returns false otherwise.
// This does NOT check that a directory (or file) actually exists.
bool FilePath::IsDirectory() const {
return !pathname_.empty() &&
IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);
}
// Create directories so that path exists. Returns true if successful or if
// the directories already exist; returns false if unable to create directories
// for any reason.
bool FilePath::CreateDirectoriesRecursively() const {
if (!this->IsDirectory()) {
return false;
}
if (pathname_.length() == 0 || this->DirectoryExists()) {
return true;
}
const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());
return parent.CreateDirectoriesRecursively() && this->CreateFolder();
}
// Create the directory so that path exists. Returns true if successful or
// if the directory already exists; returns false if unable to create the
// directory for any reason, including if the parent directory does not
// exist. Not named "CreateDirectory" because that's a macro on Windows.
bool FilePath::CreateFolder() const {
#if GTEST_OS_WINDOWS_MOBILE
FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, NULL) ? 0 : -1;
delete [] unicode;
#elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str());
#else
int result = mkdir(pathname_.c_str(), 0777);
#endif // GTEST_OS_WINDOWS_MOBILE
if (result == -1) {
return this->DirectoryExists(); // An error is OK if the directory exists.
}
return true; // No error.
}
// If input name has a trailing separator character, remove it and return the
// name, otherwise return the name string unmodified.
// On Windows platform, uses \ as the separator, other platforms use /.
FilePath FilePath::RemoveTrailingPathSeparator() const {
return IsDirectory()
? FilePath(pathname_.substr(0, pathname_.length() - 1))
: *this;
}
// Removes any redundant separators that might be in the pathname.
// For example, "bar///foo" becomes "bar/foo". Does not eliminate other
// redundancies that might be in a pathname involving "." or "..".
// TODO(wan@google.com): handle Windows network shares (e.g. \\server\share).
void FilePath::Normalize() {
if (pathname_.c_str() == NULL) {
pathname_ = "";
return;
}
const char* src = pathname_.c_str();
char* const dest = new char[pathname_.length() + 1];
char* dest_ptr = dest;
memset(dest_ptr, 0, pathname_.length() + 1);
while (*src != '\0') {
*dest_ptr = *src;
if (!IsPathSeparator(*src)) {
src++;
} else {
#if GTEST_HAS_ALT_PATH_SEP_
if (*dest_ptr == kAlternatePathSeparator) {
*dest_ptr = kPathSeparator;
}
#endif
while (IsPathSeparator(*src))
src++;
}
dest_ptr++;
}
*dest_ptr = '\0';
pathname_ = dest;
delete[] dest;
}
} // namespace internal
} // namespace testing
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if GTEST_OS_WINDOWS_MOBILE
# include <windows.h> // For TerminateProcess()
#elif GTEST_OS_WINDOWS
# include <io.h>
# include <sys/stat.h>
#else
# include <unistd.h>
#endif // GTEST_OS_WINDOWS_MOBILE
#if GTEST_OS_MAC
# include <mach/mach_init.h>
# include <mach/task.h>
# include <mach/vm_map.h>
#endif // GTEST_OS_MAC
#if GTEST_OS_QNX
# include <devctl.h>
# include <sys/procfs.h>
#endif // GTEST_OS_QNX
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
#define GTEST_IMPLEMENTATION_ 1
#undef GTEST_IMPLEMENTATION_
namespace testing {
namespace internal {
#if defined(_MSC_VER) || defined(__BORLANDC__)
// MSVC and C++Builder do not provide a definition of STDERR_FILENO.
const int kStdOutFileno = 1;
const int kStdErrFileno = 2;
#else
const int kStdOutFileno = STDOUT_FILENO;
const int kStdErrFileno = STDERR_FILENO;
#endif // _MSC_VER
#if GTEST_OS_MAC
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
size_t GetThreadCount() {
const task_t task = mach_task_self();
mach_msg_type_number_t thread_count;
thread_act_array_t thread_list;
const kern_return_t status = task_threads(task, &thread_list, &thread_count);
if (status == KERN_SUCCESS) {
// task_threads allocates resources in thread_list and we need to free them
// to avoid leaks.
vm_deallocate(task,
reinterpret_cast<vm_address_t>(thread_list),
sizeof(thread_t) * thread_count);
return static_cast<size_t>(thread_count);
} else {
return 0;
}
}
#elif GTEST_OS_QNX
// Returns the number of threads running in the process, or 0 to indicate that
// we cannot detect it.
size_t GetThreadCount() {
const int fd = open("/proc/self/as", O_RDONLY);
if (fd < 0) {
return 0;
}
procfs_info process_info;
const int status =
devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);
close(fd);
if (status == EOK) {
return static_cast<size_t>(process_info.num_threads);
} else {
return 0;
}
}
#else
size_t GetThreadCount() {
size_t thread_count = 0;
if (DIR* dir = opendir("/proc/self/task")) {
while (dirent* entry = readdir(dir)) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0)
++thread_count;
}
closedir(dir);
}
return thread_count;
}
#endif // GTEST_OS_MAC
#if GTEST_USES_POSIX_RE
// Implements RE. Currently only needed for death tests.
RE::~RE() {
if (is_valid_) {
// regfree'ing an invalid regex might crash because the content
// of the regex is undefined. Since the regex's are essentially
// the same, one cannot be valid (or invalid) without the other
// being so too.
regfree(&partial_regex_);
regfree(&full_regex_);
}
free(const_cast<char*>(pattern_));
}
// Returns true iff regular expression re matches the entire str.
bool RE::FullMatch(const char* str, const RE& re) {
if (!re.is_valid_) return false;
regmatch_t match;
return regexec(&re.full_regex_, str, 1, &match, 0) == 0;
}
// Returns true iff regular expression re matches a substring of str
// (including str itself).
bool RE::PartialMatch(const char* str, const RE& re) {
if (!re.is_valid_) return false;
regmatch_t match;
return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;
}
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
pattern_ = posix::StrDup(regex);
// Reserves enough bytes to hold the regular expression used for a
// full match.
const size_t full_regex_len = strlen(regex) + 10;
char* const full_pattern = new char[full_regex_len];
snprintf(full_pattern, full_regex_len, "^(%s)$", regex);
is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;
// We want to call regcomp(&partial_regex_, ...) even if the
// previous expression returns false. Otherwise partial_regex_ may
// not be properly initialized can may cause trouble when it's
// freed.
//
// Some implementation of POSIX regex (e.g. on at least some
// versions of Cygwin) doesn't accept the empty string as a valid
// regex. We change it to an equivalent form "()" to be safe.
if (is_valid_) {
const char* const partial_regex = (*regex == '\0') ? "()" : regex;
is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;
}
EXPECT_TRUE(is_valid_)
<< "Regular expression \"" << regex
<< "\" is not a valid POSIX Extended regular expression.";
delete[] full_pattern;
}
#elif GTEST_USES_SIMPLE_RE
// Returns true iff ch appears anywhere in str (excluding the
// terminating '\0' character).
bool IsInSet(char ch, const char* str) {
return ch != '\0' && strchr(str, ch) != NULL;
}
// Returns true iff ch belongs to the given classification. Unlike
// similar functions in <ctype.h>, these aren't affected by the
// current locale.
bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }
bool IsAsciiPunct(char ch) {
return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~");
}
bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); }
bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); }
bool IsAsciiWordChar(char ch) {
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||
('0' <= ch && ch <= '9') || ch == '_';
}
// Returns true iff "\\c" is a supported escape sequence.
bool IsValidEscape(char c) {
return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW"));
}
// Returns true iff the given atom (specified by escaped and pattern)
// matches ch. The result is undefined if the atom is invalid.
bool AtomMatchesChar(bool escaped, char pattern_char, char ch) {
if (escaped) { // "\\p" where p is pattern_char.
switch (pattern_char) {
case 'd': return IsAsciiDigit(ch);
case 'D': return !IsAsciiDigit(ch);
case 'f': return ch == '\f';
case 'n': return ch == '\n';
case 'r': return ch == '\r';
case 's': return IsAsciiWhiteSpace(ch);
case 'S': return !IsAsciiWhiteSpace(ch);
case 't': return ch == '\t';
case 'v': return ch == '\v';
case 'w': return IsAsciiWordChar(ch);
case 'W': return !IsAsciiWordChar(ch);
}
return IsAsciiPunct(pattern_char) && pattern_char == ch;
}
return (pattern_char == '.' && ch != '\n') || pattern_char == ch;
}
// Helper function used by ValidateRegex() to format error messages.
std::string FormatRegexSyntaxError(const char* regex, int index) {
return (Message() << "Syntax error at index " << index
<< " in simple regular expression \"" << regex << "\": ").GetString();
}
// Generates non-fatal failures and returns false if regex is invalid;
// otherwise returns true.
bool ValidateRegex(const char* regex) {
if (regex == NULL) {
// TODO(wan@google.com): fix the source file location in the
// assertion failures to match where the regex is used in user
// code.
ADD_FAILURE() << "NULL is not a valid simple regular expression.";
return false;
}
bool is_valid = true;
// True iff ?, *, or + can follow the previous atom.
bool prev_repeatable = false;
for (int i = 0; regex[i]; i++) {
if (regex[i] == '\\') { // An escape sequence
i++;
if (regex[i] == '\0') {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
<< "'\\' cannot appear at the end.";
return false;
}
if (!IsValidEscape(regex[i])) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)
<< "invalid escape sequence \"\\" << regex[i] << "\".";
is_valid = false;
}
prev_repeatable = true;
} else { // Not an escape sequence.
const char ch = regex[i];
if (ch == '^' && i > 0) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
<< "'^' can only appear at the beginning.";
is_valid = false;
} else if (ch == '$' && regex[i + 1] != '\0') {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
<< "'$' can only appear at the end.";
is_valid = false;
} else if (IsInSet(ch, "()[]{}|")) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
<< "'" << ch << "' is unsupported.";
is_valid = false;
} else if (IsRepeat(ch) && !prev_repeatable) {
ADD_FAILURE() << FormatRegexSyntaxError(regex, i)
<< "'" << ch << "' can only follow a repeatable token.";
is_valid = false;
}
prev_repeatable = !IsInSet(ch, "^$?*+");
}
}
return is_valid;
}
// Matches a repeated regex atom followed by a valid simple regular
// expression. The regex atom is defined as c if escaped is false,
// or \c otherwise. repeat is the repetition meta character (?, *,
// or +). The behavior is undefined if str contains too many
// characters to be indexable by size_t, in which case the test will
// probably time out anyway. We are fine with this limitation as
// std::string has it too.
bool MatchRepetitionAndRegexAtHead(
bool escaped, char c, char repeat, const char* regex,
const char* str) {
const size_t min_count = (repeat == '+') ? 1 : 0;
const size_t max_count = (repeat == '?') ? 1 :
static_cast<size_t>(-1) - 1;
// We cannot call numeric_limits::max() as it conflicts with the
// max() macro on Windows.
for (size_t i = 0; i <= max_count; ++i) {
// We know that the atom matches each of the first i characters in str.
if (i >= min_count && MatchRegexAtHead(regex, str + i)) {
// We have enough matches at the head, and the tail matches too.
// Since we only care about *whether* the pattern matches str
// (as opposed to *how* it matches), there is no need to find a
// greedy match.
return true;
}
if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i]))
return false;
}
return false;
}
// Returns true iff regex matches a prefix of str. regex must be a
// valid simple regular expression and not start with "^", or the
// result is undefined.
bool MatchRegexAtHead(const char* regex, const char* str) {
if (*regex == '\0') // An empty regex matches a prefix of anything.
return true;
// "$" only matches the end of a string. Note that regex being
// valid guarantees that there's nothing after "$" in it.
if (*regex == '$')
return *str == '\0';
// Is the first thing in regex an escape sequence?
const bool escaped = *regex == '\\';
if (escaped)
++regex;
if (IsRepeat(regex[1])) {
// MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so
// here's an indirect recursion. It terminates as the regex gets
// shorter in each recursion.
return MatchRepetitionAndRegexAtHead(
escaped, regex[0], regex[1], regex + 2, str);
} else {
// regex isn't empty, isn't "$", and doesn't start with a
// repetition. We match the first atom of regex with the first
// character of str and recurse.
return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) &&
MatchRegexAtHead(regex + 1, str + 1);
}
}
// Returns true iff regex matches any substring of str. regex must be
// a valid simple regular expression, or the result is undefined.
//
// The algorithm is recursive, but the recursion depth doesn't exceed
// the regex length, so we won't need to worry about running out of
// stack space normally. In rare cases the time complexity can be
// exponential with respect to the regex length + the string length,
// but usually it's must faster (often close to linear).
bool MatchRegexAnywhere(const char* regex, const char* str) {
if (regex == NULL || str == NULL)
return false;
if (*regex == '^')
return MatchRegexAtHead(regex + 1, str);
// A successful match can be anywhere in str.
do {
if (MatchRegexAtHead(regex, str))
return true;
} while (*str++ != '\0');
return false;
}
// Implements the RE class.
RE::~RE() {
free(const_cast<char*>(pattern_));
free(const_cast<char*>(full_pattern_));
}
// Returns true iff regular expression re matches the entire str.
bool RE::FullMatch(const char* str, const RE& re) {
return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);
}
// Returns true iff regular expression re matches a substring of str
// (including str itself).
bool RE::PartialMatch(const char* str, const RE& re) {
return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);
}
// Initializes an RE from its string representation.
void RE::Init(const char* regex) {
pattern_ = full_pattern_ = NULL;
if (regex != NULL) {
pattern_ = posix::StrDup(regex);
}
is_valid_ = ValidateRegex(regex);
if (!is_valid_) {
// No need to calculate the full pattern when the regex is invalid.
return;
}
const size_t len = strlen(regex);
// Reserves enough bytes to hold the regular expression used for a
// full match: we need space to prepend a '^', append a '$', and
// terminate the string with '\0'.
char* buffer = static_cast<char*>(malloc(len + 3));
full_pattern_ = buffer;
if (*regex != '^')
*buffer++ = '^'; // Makes sure full_pattern_ starts with '^'.
// We don't use snprintf or strncpy, as they trigger a warning when
// compiled with VC++ 8.0.
memcpy(buffer, regex, len);
buffer += len;
if (len == 0 || regex[len - 1] != '$')
*buffer++ = '$'; // Makes sure full_pattern_ ends with '$'.
*buffer = '\0';
}
#endif // GTEST_USES_POSIX_RE
const char kUnknownFile[] = "unknown file";
// Formats a source file path and a line number as they would appear
// in an error message from the compiler used to compile this code.
GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {
const std::string file_name(file == NULL ? kUnknownFile : file);
if (line < 0) {
return file_name + ":";
}
#ifdef _MSC_VER
return file_name + "(" + StreamableToString(line) + "):";
#else
return file_name + ":" + StreamableToString(line) + ":";
#endif // _MSC_VER
}
// Formats a file location for compiler-independent XML output.
// Although this function is not platform dependent, we put it next to
// FormatFileLocation in order to contrast the two functions.
// Note that FormatCompilerIndependentFileLocation() does NOT append colon
// to the file location it produces, unlike FormatFileLocation().
GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(
const char* file, int line) {
const std::string file_name(file == NULL ? kUnknownFile : file);
if (line < 0)
return file_name;
else
return file_name + ":" + StreamableToString(line);
}
GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)
: severity_(severity) {
const char* const marker =
severity == GTEST_INFO ? "[ INFO ]" :
severity == GTEST_WARNING ? "[WARNING]" :
severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]";
GetStream() << ::std::endl << marker << " "
<< FormatFileLocation(file, line).c_str() << ": ";
}
// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.
GTestLog::~GTestLog() {
GetStream() << ::std::endl;
if (severity_ == GTEST_FATAL) {
fflush(stderr);
posix::Abort();
}
}
// Disable Microsoft deprecation warnings for POSIX functions called from
// this class (creat, dup, dup2, and close)
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4996)
#endif // _MSC_VER
#if GTEST_HAS_STREAM_REDIRECTION
// Object that captures an output stream (stdout/stderr).
class CapturedStream {
public:
// The ctor redirects the stream to a temporary file.
explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {
# if GTEST_OS_WINDOWS
char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT
char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT
::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);
const UINT success = ::GetTempFileNameA(temp_dir_path,
"gtest_redir",
0, // Generate unique file name.
temp_file_path);
GTEST_CHECK_(success != 0)
<< "Unable to create a temporary file in " << temp_dir_path;
const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);
GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
<< temp_file_path;
filename_ = temp_file_path;
# else
// There's no guarantee that a test has write access to the current
// directory, so we create the temporary file in the /tmp directory
// instead. We use /tmp on most systems, and /sdcard on Android.
// That's because Android doesn't have /tmp.
# if GTEST_OS_LINUX_ANDROID
// Note: Android applications are expected to call the framework's
// Context.getExternalStorageDirectory() method through JNI to get
// the location of the world-writable SD Card directory. However,
// this requires a Context handle, which cannot be retrieved
// globally from native code. Doing so also precludes running the
// code as part of a regular standalone executable, which doesn't
// run in a Dalvik process (e.g. when running it through 'adb shell').
//
// The location /sdcard is directly accessible from native code
// and is the only location (unofficially) supported by the Android
// team. It's generally a symlink to the real SD Card mount point
// which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or
// other OEM-customized locations. Never rely on these, and always
// use /sdcard.
char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX";
# else
char name_template[] = "/tmp/captured_stream.XXXXXX";
# endif // GTEST_OS_LINUX_ANDROID
const int captured_fd = mkstemp(name_template);
filename_ = name_template;
# endif // GTEST_OS_WINDOWS
fflush(NULL);
dup2(captured_fd, fd_);
close(captured_fd);
}
~CapturedStream() {
remove(filename_.c_str());
}
std::string GetCapturedString() {
if (uncaptured_fd_ != -1) {
// Restores the original stream.
fflush(NULL);
dup2(uncaptured_fd_, fd_);
close(uncaptured_fd_);
uncaptured_fd_ = -1;
}
FILE* const file = posix::FOpen(filename_.c_str(), "r");
const std::string content = ReadEntireFile(file);
posix::FClose(file);
return content;
}
private:
// Reads the entire content of a file as an std::string.
static std::string ReadEntireFile(FILE* file);
// Returns the size (in bytes) of a file.
static size_t GetFileSize(FILE* file);
const int fd_; // A stream to capture.
int uncaptured_fd_;
// Name of the temporary file holding the stderr output.
::std::string filename_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);
};
// Returns the size (in bytes) of a file.
size_t CapturedStream::GetFileSize(FILE* file) {
fseek(file, 0, SEEK_END);
return static_cast<size_t>(ftell(file));
}
// Reads the entire content of a file as a string.
std::string CapturedStream::ReadEntireFile(FILE* file) {
const size_t file_size = GetFileSize(file);
char* const buffer = new char[file_size];
size_t bytes_last_read = 0; // # of bytes read in the last fread()
size_t bytes_read = 0; // # of bytes read so far
fseek(file, 0, SEEK_SET);
// Keeps reading the file until we cannot read further or the
// pre-determined file size is reached.
do {
bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);
bytes_read += bytes_last_read;
} while (bytes_last_read > 0 && bytes_read < file_size);
const std::string content(buffer, bytes_read);
delete[] buffer;
return content;
}
# ifdef _MSC_VER
# pragma warning(pop)
# endif // _MSC_VER
static CapturedStream* g_captured_stderr = NULL;
static CapturedStream* g_captured_stdout = NULL;
// Starts capturing an output stream (stdout/stderr).
void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {
if (*stream != NULL) {
GTEST_LOG_(FATAL) << "Only one " << stream_name
<< " capturer can exist at a time.";
}
*stream = new CapturedStream(fd);
}
// Stops capturing the output stream and returns the captured string.
std::string GetCapturedStream(CapturedStream** captured_stream) {
const std::string content = (*captured_stream)->GetCapturedString();
delete *captured_stream;
*captured_stream = NULL;
return content;
}
// Starts capturing stdout.
void CaptureStdout() {
CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout);
}
// Starts capturing stderr.
void CaptureStderr() {
CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr);
}
// Stops capturing stdout and returns the captured string.
std::string GetCapturedStdout() {
return GetCapturedStream(&g_captured_stdout);
}
// Stops capturing stderr and returns the captured string.
std::string GetCapturedStderr() {
return GetCapturedStream(&g_captured_stderr);
}
#endif // GTEST_HAS_STREAM_REDIRECTION
#if GTEST_HAS_DEATH_TEST
// A copy of all command line arguments. Set by InitGoogleTest().
::std::vector<testing::internal::string> g_argvs;
static const ::std::vector<testing::internal::string>* g_injected_test_argvs =
NULL; // Owned.
void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {
if (g_injected_test_argvs != argvs)
delete g_injected_test_argvs;
g_injected_test_argvs = argvs;
}
const ::std::vector<testing::internal::string>& GetInjectableArgvs() {
if (g_injected_test_argvs != NULL) {
return *g_injected_test_argvs;
}
return g_argvs;
}
#endif // GTEST_HAS_DEATH_TEST
#if GTEST_OS_WINDOWS_MOBILE
namespace posix {
void Abort() {
DebugBreak();
TerminateProcess(GetCurrentProcess(), 1);
}
} // namespace posix
#endif // GTEST_OS_WINDOWS_MOBILE
// Returns the name of the environment variable corresponding to the
// given flag. For example, FlagToEnvVar("foo") will return
// "GTEST_FOO" in the open-source version.
static std::string FlagToEnvVar(const char* flag) {
const std::string full_flag =
(Message() << GTEST_FLAG_PREFIX_ << flag).GetString();
Message env_var;
for (size_t i = 0; i != full_flag.length(); i++) {
env_var << ToUpper(full_flag.c_str()[i]);
}
return env_var.GetString();
}
// Parses 'str' for a 32-bit signed integer. If successful, writes
// the result to *value and returns true; otherwise leaves *value
// unchanged and returns false.
bool ParseInt32(const Message& src_text, const char* str, Int32* value) {
// Parses the environment variable as a decimal integer.
char* end = NULL;
const long long_value = strtol(str, &end, 10); // NOLINT
// Has strtol() consumed all characters in the string?
if (*end != '\0') {
// No - an invalid character was encountered.
Message msg;
msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually"
<< " has value \"" << str << "\".\n";
printf("%s", msg.GetString().c_str());
fflush(stdout);
return false;
}
// Is the parsed value in the range of an Int32?
const Int32 result = static_cast<Int32>(long_value);
if (long_value == LONG_MAX || long_value == LONG_MIN ||
// The parsed value overflows as a long. (strtol() returns
// LONG_MAX or LONG_MIN when the input overflows.)
result != long_value
// The parsed value overflows as an Int32.
) {
Message msg;
msg << "WARNING: " << src_text
<< " is expected to be a 32-bit integer, but actually"
<< " has value " << str << ", which overflows.\n";
printf("%s", msg.GetString().c_str());
fflush(stdout);
return false;
}
*value = result;
return true;
}
// Reads and returns the Boolean environment variable corresponding to
// the given flag; if it's not set, returns default_value.
//
// The value is considered true iff it's not "0".
bool BoolFromGTestEnv(const char* flag, bool default_value) {
const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str());
return string_value == NULL ?
default_value : strcmp(string_value, "0") != 0;
}
// Reads and returns a 32-bit integer stored in the environment
// variable corresponding to the given flag; if it isn't set or
// doesn't represent a valid 32-bit integer, returns default_value.
Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str());
if (string_value == NULL) {
// The environment variable is not set.
return default_value;
}
Int32 result = default_value;
if (!ParseInt32(Message() << "Environment variable " << env_var,
string_value, &result)) {
printf("The default value %s is used.\n",
(Message() << default_value).GetString().c_str());
fflush(stdout);
return default_value;
}
return result;
}
// Reads and returns the string environment variable corresponding to
// the given flag; if it's not set, returns default_value.
const char* StringFromGTestEnv(const char* flag, const char* default_value) {
const std::string env_var = FlagToEnvVar(flag);
const char* const value = posix::GetEnv(env_var.c_str());
return value == NULL ? default_value : value;
}
} // namespace internal
} // namespace testing
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
//
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise. A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.
#include <ctype.h>
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
namespace testing {
namespace {
using ::std::ostream;
// Prints a segment of bytes in the given object.
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) {
char text[5] = "";
for (size_t i = 0; i != count; i++) {
const size_t j = start + i;
if (i != 0) {
// Organizes the bytes into groups of 2 for easy parsing by
// human.
if ((j % 2) == 0)
*os << ' ';
else
*os << '-';
}
GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text;
}
}
// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
ostream* os) {
// Tells the user how big the object is.
*os << count << "-byte object <";
const size_t kThreshold = 132;
const size_t kChunkSize = 64;
// If the object size is bigger than kThreshold, we'll have to omit
// some details by printing only the first and the last kChunkSize
// bytes.
// TODO(wan): let the user control the threshold using a flag.
if (count < kThreshold) {
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
} else {
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
}
} // namespace
namespace internal2 {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
ostream* os) {
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
} // namespace internal2
namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
inline bool IsPrintableAscii(wchar_t c) {
return 0x20 <= c && c <= 0x7E;
}
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
// The template argument UnsignedChar is the unsigned version of Char,
// which is the type of c.
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
case L'\0':
*os << "\\0";
break;
case L'\'':
*os << "\\'";
break;
case L'\\':
*os << "\\\\";
break;
case L'\a':
*os << "\\a";
break;
case L'\b':
*os << "\\b";
break;
case L'\f':
*os << "\\f";
break;
case L'\n':
*os << "\\n";
break;
case L'\r':
*os << "\\r";
break;
case L'\t':
*os << "\\t";
break;
case L'\v':
*os << "\\v";
break;
default:
if (IsPrintableAscii(c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
*os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
return kHexEscape;
}
}
return kSpecialEscape;
}
// Prints a wchar_t c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
return kAsIs;
case L'"':
*os << "\\\"";
return kSpecialEscape;
default:
return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
return PrintAsStringLiteralTo(
static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
}
// Prints a wide or narrow character c and its code. '\0' is printed
// as "'\\0'", other unprintable characters are also properly escaped
// using the standard C++ escape sequence. The template argument
// UnsignedChar is the unsigned version of Char, which is the type of c.
template <typename UnsignedChar, typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
*os << ((sizeof(c) > 1) ? "L'" : "'");
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
if (c == 0)
return;
*os << " (" << static_cast<int>(c);
// For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing.
} else {
*os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
}
*os << ")";
}
void PrintTo(unsigned char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
void PrintTo(signed char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os);
}
// Prints the given array of characters to the ostream. CharType must be either
// char or wchar_t.
// The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated.
template <typename CharType>
static void PrintCharsAsStringTo(
const CharType* begin, size_t len, ostream* os) {
const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
*os << kQuoteBegin;
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const CharType cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" " << kQuoteBegin;
}
is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints a (const) char/wchar_t array of 'len' elements, starting at address
// 'begin'. CharType must be either char or wchar_t.
template <typename CharType>
static void UniversalPrintCharArray(
const CharType* begin, size_t len, ostream* os) {
// The code
// const char kFoo[] = "foo";
// generates an array of 4, not 3, elements, with the last one being '\0'.
//
// Therefore when printing a char array, we don't print the last element if
// it's '\0', such that the output matches the string literal as it's
// written in the source code.
if (len > 0 && begin[len - 1] == '\0') {
PrintCharsAsStringTo(begin, len - 1, os);
return;
}
// If, however, the last element in the array is not '\0', e.g.
// const char kFoo[] = { 'f', 'o', 'o' };
// we must print the entire array. We also print a message to indicate
// that the array is not NUL-terminated.
PrintCharsAsStringTo(begin, len, os);
*os << " (no terminating NUL)";
}
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
// Prints a (const) wchar_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
UniversalPrintCharArray(begin, len, os);
}
// Prints the given C string to the ostream.
void PrintTo(const char* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, strlen(s), os);
}
}
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
void PrintTo(const wchar_t* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, wcslen(s), os);
}
}
#endif // wchar_t is native
// Prints a ::string object.
#if GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::std::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
// Prints a ::wstring object.
#if GTEST_HAS_GLOBAL_WSTRING
void PrintWideStringTo(const ::wstring& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_STD_WSTRING
} // namespace internal
} // namespace testing
// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: mheule@google.com (Markus Heule)
//
// The Google C++ Testing Framework (Google Test)
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
#define GTEST_IMPLEMENTATION_ 1
#undef GTEST_IMPLEMENTATION_
namespace testing {
using internal::GetUnitTestImpl;
// Gets the summary of the failure message by omitting the stack trace
// in it.
std::string TestPartResult::ExtractSummary(const char* message) {
const char* const stack_trace = strstr(message, internal::kStackTraceMarker);
return stack_trace == NULL ? message :
std::string(message, stack_trace);
}
// Prints a TestPartResult object.
std::ostream& operator<<(std::ostream& os, const TestPartResult& result) {
return os
<< result.file_name() << ":" << result.line_number() << ": "
<< (result.type() == TestPartResult::kSuccess ? "Success" :
result.type() == TestPartResult::kFatalFailure ? "Fatal failure" :
"Non-fatal failure") << ":\n"
<< result.message() << std::endl;
}
// Appends a TestPartResult to the array.
void TestPartResultArray::Append(const TestPartResult& result) {
array_.push_back(result);
}
// Returns the TestPartResult at the given index (0-based).
const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {
if (index < 0 || index >= size()) {
printf("\nInvalid index (%d) into TestPartResultArray.\n", index);
internal::posix::Abort();
}
return array_[index];
}
// Returns the number of TestPartResult objects in the array.
int TestPartResultArray::size() const {
return static_cast<int>(array_.size());
}
namespace internal {
HasNewFatalFailureHelper::HasNewFatalFailureHelper()
: has_new_fatal_failure_(false),
original_reporter_(GetUnitTestImpl()->
GetTestPartResultReporterForCurrentThread()) {
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);
}
HasNewFatalFailureHelper::~HasNewFatalFailureHelper() {
GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(
original_reporter_);
}
void HasNewFatalFailureHelper::ReportTestPartResult(
const TestPartResult& result) {
if (result.fatally_failed())
has_new_fatal_failure_ = true;
original_reporter_->ReportTestPartResult(result);
}
} // namespace internal
} // namespace testing
// Copyright 2008 Google Inc.
// All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
namespace testing {
namespace internal {
#if GTEST_HAS_TYPED_TEST_P
// Skips to the first non-space char in str. Returns an empty string if str
// contains only whitespace characters.
static const char* SkipSpaces(const char* str) {
while (IsSpace(*str))
str++;
return str;
}
// Verifies that registered_tests match the test names in
// defined_test_names_; returns registered_tests if successful, or
// aborts the program otherwise.
const char* TypedTestCasePState::VerifyRegisteredTestNames(
const char* file, int line, const char* registered_tests) {
typedef ::std::set<const char*>::const_iterator DefinedTestIter;
registered_ = true;
// Skip initial whitespace in registered_tests since some
// preprocessors prefix stringizied literals with whitespace.
registered_tests = SkipSpaces(registered_tests);
Message errors;
::std::set<std::string> tests;
for (const char* names = registered_tests; names != NULL;
names = SkipComma(names)) {
const std::string name = GetPrefixUntilComma(names);
if (tests.count(name) != 0) {
errors << "Test " << name << " is listed more than once.\n";
continue;
}
bool found = false;
for (DefinedTestIter it = defined_test_names_.begin();
it != defined_test_names_.end();
++it) {
if (name == *it) {
found = true;
break;
}
}
if (found) {
tests.insert(name);
} else {
errors << "No test named " << name
<< " can be found in this test case.\n";
}
}
for (DefinedTestIter it = defined_test_names_.begin();
it != defined_test_names_.end();
++it) {
if (tests.count(*it) == 0) {
errors << "You forgot to list test " << *it << ".\n";
}
}
const std::string& errors_str = errors.GetString();
if (errors_str != "") {
fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(),
errors_str.c_str());
fflush(stderr);
posix::Abort();
}
return registered_tests;
}
#endif // GTEST_HAS_TYPED_TEST_P
} // namespace internal
} // namespace testing
|
/*
*Copyright (c) 2013-2016, yinqiwen <yinqiwen@gmail.com>
*All rights reserved.
*
*Redistribution and use in source and binary forms, with or without
*modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
*AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
*IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
*ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
*CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
*SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
*INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
*CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
*ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
*THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <limits.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sstream>
#include "db.hpp"
#include "repl/repl.hpp"
#include "statistics.hpp"
#if defined __USE_LMDB__
#include "lmdb/lmdb_engine.hpp"
const char* ardb::g_engine_name = "lmdb";
#elif defined __USE_ROCKSDB__
#include "rocksdb/rocksdb_engine.hpp"
const char* ardb::g_engine_name ="rocksdb";
#elif defined __USE_FORESTDB__
#include "forestdb/forestdb_engine.hpp"
const char* ardb::g_engine_name ="forestdb";
#elif defined __USE_LEVELDB__
#include "leveldb/leveldb_engine.hpp"
const char* ardb::g_engine_name = "leveldb";
#elif defined __USE_WIREDTIGER__
#include "wiredtiger/wiredtiger_engine.hpp"
const char* ardb::g_engine_name ="wiredtiger";
#elif defined __USE_PERCONAFT__
#include "perconaft/perconaft_engine.hpp"
const char* ardb::g_engine_name ="perconaft";
#else
const char* ardb::g_engine_name = "unknown";
#endif
/* Command flags. Please check the command table defined in the redis.c file
* for more information about the meaning of every flag. */
#define ARDB_CMD_WRITE 1 /* "w" flag */
#define ARDB_CMD_READONLY 2 /* "r" flag */
#define ARDB_CMD_DENYOOM 4 /* "m" flag */
#define ARDB_CMD_NOT_USED_1 8 /* no longer used flag */
#define ARDB_CMD_ADMIN 16 /* "a" flag */
#define ARDB_CMD_PUBSUB 32 /* "p" flag */
#define ARDB_CMD_NOSCRIPT 64 /* "s" flag */
#define ARDB_CMD_RANDOM 128 /* "R" flag */
#define ARDB_CMD_SORT_FOR_SCRIPT 256 /* "S" flag */
#define ARDB_CMD_LOADING 512 /* "l" flag */
#define ARDB_CMD_STALE 1024 /* "t" flag */
#define ARDB_CMD_SKIP_MONITOR 2048 /* "M" flag */
#define ARDB_CMD_ASKING 4096 /* "k" flag */
#define ARDB_CMD_FAST 8192 /* "F" flag */
OP_NAMESPACE_BEGIN
Ardb* g_db = NULL;
Engine* g_engine = NULL;
bool Ardb::RedisCommandHandlerSetting::IsAllowedInScript() const
{
return (flags & ARDB_CMD_NOSCRIPT) == 0;
}
bool Ardb::RedisCommandHandlerSetting::IsWriteCommand() const
{
return (flags & ARDB_CMD_WRITE) > 0;
}
size_t Ardb::RedisCommandHash::operator ()(const std::string& t) const
{
unsigned int hash = 5381;
size_t len = t.size();
const char* buf = t.data();
while (len--)
hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */
return hash;
}
bool Ardb::RedisCommandEqual::operator()(const std::string& s1, const std::string& s2) const
{
return strcasecmp(s1.c_str(), s2.c_str()) == 0 ? true : false;
}
Ardb::KeyLockGuard::KeyLockGuard(Context& cctx, const KeyObject& key, bool _lock)
: ctx(cctx), lock(_lock)
{
if (lock)
{
ctx.keyslocked = true;
lk.key = key.GetKey();
lk.ns = key.GetNameSpace();
g_db->LockKey(lk);
}
}
Ardb::KeyLockGuard::~KeyLockGuard()
{
if (lock)
{
g_db->UnlockKey(lk);
ctx.keyslocked = false;
}
}
Ardb::KeysLockGuard::KeysLockGuard(Context& cctx, const KeyObjectArray& keys)
: ctx(cctx)
{
ctx.keyslocked = true;
for (size_t i = 0; i < keys.size(); i++)
{
KeyPrefix lk;
lk.key = keys[i].GetKey();
lk.ns = keys[i].GetNameSpace();
ks.insert(lk);
}
g_db->LockKeys(ks);
}
Ardb::KeysLockGuard::KeysLockGuard(Context& cctx, const KeyObject& key1, const KeyObject& key2)
: ctx(cctx)
{
KeyPrefix lk1, lk2;
lk1.key = key1.GetKey();
lk1.ns = key1.GetNameSpace();
lk2.key = key2.GetKey();
lk2.ns = key2.GetNameSpace();
ks.insert(lk1);
ks.insert(lk2);
g_db->LockKeys(ks);
}
Ardb::KeysLockGuard::~KeysLockGuard()
{
g_db->UnlockKeys(ks);
ctx.keyslocked = false;
}
static CostTrack g_cmd_cost_tracks[REDIS_CMD_MAX];
Ardb::Ardb()
: m_engine(NULL), m_starttime(0), m_loading_data(false), m_compacting_data(false), m_prepare_snapshot_num(
0), m_write_caller_num(0), m_db_caller_num(0), m_redis_cursor_seed(0), m_watched_ctxs(NULL), m_ready_keys(
NULL), m_monitors(
NULL), m_restoring_nss(
NULL), m_min_ttl(-1)
{
g_db = this;
m_settings.set_empty_key("");
m_settings.set_deleted_key("\n");
struct RedisCommandHandlerSetting settingTable[] =
{
{ "ping", REDIS_CMD_PING, &Ardb::Ping, 0, 0, "rtF", 0, 0, 0 },
{ "multi", REDIS_CMD_MULTI, &Ardb::Multi, 0, 0, "rsF", 0, 0, 0 },
{ "discard", REDIS_CMD_DISCARD, &Ardb::Discard, 0, 0, "rsF", 0, 0, 0 },
{ "exec", REDIS_CMD_EXEC, &Ardb::Exec, 0, 0, "sM", 0, 0, 0 },
{ "watch", REDIS_CMD_WATCH, &Ardb::Watch, 0, -1, "rsF", 0, 0, 0 },
{ "unwatch", REDIS_CMD_UNWATCH, &Ardb::UnWatch, 0, 0, "rsF", 0, 0, 0 },
{ "subscribe", REDIS_CMD_SUBSCRIBE, &Ardb::Subscribe, 1, -1, "rpslt", 0, 0, 0 },
{ "psubscribe", REDIS_CMD_PSUBSCRIBE, &Ardb::PSubscribe, 1, -1, "rpslt", 0, 0, 0 },
{ "unsubscribe", REDIS_CMD_UNSUBSCRIBE, &Ardb::UnSubscribe, 0, -1, "rpslt", 0, 0, 0 },
{ "punsubscribe", REDIS_CMD_PUNSUBSCRIBE, &Ardb::PUnSubscribe, 0, -1, "rpslt", 0, 0, 0 },
{ "publish", REDIS_CMD_PUBLISH, &Ardb::Publish, 2, 2, "pltrF", 0, 0, 0 },
{ "pubsub", REDIS_CMD_PUBSUB, &Ardb::Pubsub, 1, -1, "pltrF", 0, 0, 0 },
{ "info", REDIS_CMD_INFO, &Ardb::Info, 0, 1, "rlt", 0, 0, 0 },
{ "save", REDIS_CMD_SAVE, &Ardb::Save, 0, 1, "ars", 0, 0, 0 },
{ "bgsave", REDIS_CMD_BGSAVE, &Ardb::BGSave, 0, 1, "ar", 0, 0, 0 },
{ "import", REDIS_CMD_IMPORT, &Ardb::Import, 1, 1, "aws", 0, 0, 0 },
{ "lastsave", REDIS_CMD_LASTSAVE, &Ardb::LastSave, 0, 0, "r", 0, 0, 0 },
{ "slowlog", REDIS_CMD_SLOWLOG, &Ardb::SlowLog, 1, 2, "r", 0, 0, 0 },
{ "dbsize", REDIS_CMD_DBSIZE, &Ardb::DBSize, 0, 0, "r", 0, 0, 0 },
{ "config", REDIS_CMD_CONFIG, &Ardb::Config, 1, 3, "ar", 0, 0, 0 },
{ "client", REDIS_CMD_CLIENT, &Ardb::Client, 1, -1, "ar", 0, 0, 0 },
{ "flushdb", REDIS_CMD_FLUSHDB, &Ardb::FlushDB, 0, 0, "w", 0, 0, 0 },
{ "flushall", REDIS_CMD_FLUSHALL, &Ardb::FlushAll, 0, 0, "w", 0, 0, 0 },
{ "compactdb", REDIS_CMD_COMPACTDB, &Ardb::CompactDB, 0, 0, "ar", 0, 0, 0 },
{ "compactall", REDIS_CMD_COMPACTALL, &Ardb::CompactAll, 0, 0, "ar", 0, 0, 0 },
{ "time", REDIS_CMD_TIME, &Ardb::Time, 0, 0, "ar", 0, 0, 0 },
{ "echo", REDIS_CMD_ECHO, &Ardb::Echo, 1, 1, "r", 0, 0, 0 },
{ "quit", REDIS_CMD_QUIT, &Ardb::Quit, 0, 0, "rs", 0, 0, 0 },
{ "shutdown", REDIS_CMD_SHUTDOWN, &Ardb::Shutdown, 0, 1, "arlt", 0, 0, 0 },
{ "slaveof", REDIS_CMD_SLAVEOF, &Ardb::Slaveof, 2, -1, "ast", 0, 0, 0 },
{ "replconf", REDIS_CMD_REPLCONF, &Ardb::ReplConf, 0, -1, "arslt", 0, 0, 0 },
{ "sync", REDIS_CMD_SYNC, &Ardb::Sync, 0, 2, "ars", 0, 0, 0 },
{ "psync", REDIS_CMD_PSYNC, &Ardb::PSync, 2, -1, "ars", 0, 0, 0 },
{ "select", REDIS_CMD_SELECT, &Ardb::Select, 1, 1, "r", 0, 0, 0 },
{ "append", REDIS_CMD_APPEND, &Ardb::Append, 2, 2, "w", 0, 0, 0 },
{ "append2", REDIS_CMD_APPEND2, &Ardb::Append, 2, 2, "w", 0, 0, 0 },
{ "get", REDIS_CMD_GET, &Ardb::Get, 1, 1, "rF", 0, 0, 0 },
{ "set", REDIS_CMD_SET, &Ardb::Set, 2, 7, "w", 0, 0, 0 },
{ "set2", REDIS_CMD_SET2, &Ardb::Set, 2, 7, "w", 0, 0, 0 },
{ "del", REDIS_CMD_DEL, &Ardb::Del, 1, -1, "w", 0, 0, 0 },
{ "exists", REDIS_CMD_EXISTS, &Ardb::Exists, 1, 1, "r", 0, 0, 0 },
{ "expire", REDIS_CMD_EXPIRE, &Ardb::Expire, 2, 2, "w", 0, 0, 0 },
{ "pexpire", REDIS_CMD_PEXPIRE, &Ardb::PExpire, 2, 2, "w", 0, 0, 0 },
{ "expireat", REDIS_CMD_EXPIREAT, &Ardb::Expireat, 2, 2, "w", 0, 0, 0 },
{ "pexpireat", REDIS_CMD_PEXPIREAT, &Ardb::PExpireat, 2, 2, "w", 0, 0, 0 },
{ "persist", REDIS_CMD_PERSIST, &Ardb::Persist, 1, 1, "w", 1, 0, 0 },
{ "ttl", REDIS_CMD_TTL, &Ardb::TTL, 1, 1, "r", 0, 0, 0 },
{ "pttl", REDIS_CMD_PTTL, &Ardb::PTTL, 1, 1, "r", 0, 0, 0 },
{ "type", REDIS_CMD_TYPE, &Ardb::Type, 1, 1, "r", 0, 0, 0 },
{ "bitcount", REDIS_CMD_BITCOUNT, &Ardb::Bitcount, 1, 3, "r", 0, 0, 0 },
{ "bitop", REDIS_CMD_BITOP, &Ardb::Bitop, 3, -1, "w", 1, 0, 0 },
{ "bitopcount", REDIS_CMD_BITOPCUNT, &Ardb::BitopCount, 2, -1, "r", 0, 0, 0 },
{ "decr", REDIS_CMD_DECR, &Ardb::Decr, 1, 1, "w", 1, 0, 0 },
{ "decr2", REDIS_CMD_DECR2, &Ardb::Decr, 1, 1, "w", 1, 0, 0 },
{ "decrby", REDIS_CMD_DECRBY, &Ardb::Decrby, 2, 2, "w", 1, 0, 0 },
{ "decrby2", REDIS_CMD_DECRBY2, &Ardb::Decrby, 2, 2, "w", 1, 0, 0 },
{ "getbit", REDIS_CMD_GETBIT, &Ardb::GetBit, 2, 2, "r", 0, 0, 0 },
{ "getrange", REDIS_CMD_GETRANGE, &Ardb::GetRange, 3, 3, "r", 0, 0, 0 },
{ "getset", REDIS_CMD_GETSET, &Ardb::GetSet, 2, 2, "w", 1, 0, 0 },
{ "incr", REDIS_CMD_INCR, &Ardb::Incr, 1, 1, "w", 1, 0, 0 },
{ "incr2", REDIS_CMD_INCR2, &Ardb::Incr, 1, 1, "w", 1, 0, 0 },
{ "incrby", REDIS_CMD_INCRBY, &Ardb::Incrby, 2, 2, "w", 1, 0, 0 },
{ "incrby2", REDIS_CMD_INCRBY2, &Ardb::Incrby, 2, 2, "w", 1, 0, 0 },
{ "incrbyfloat", REDIS_CMD_INCRBYFLOAT, &Ardb::IncrbyFloat, 2, 2, "w", 0, 0, 0 },
{ "incrbyfloat2", REDIS_CMD_INCRBYFLOAT2, &Ardb::IncrbyFloat, 2, 2, "w", 0, 0, 0 },
{ "mget", REDIS_CMD_MGET, &Ardb::MGet, 1, -1, "r", 0, 0, 0 },
{ "mset", REDIS_CMD_MSET, &Ardb::MSet, 2, -1, "w", 0, 0, 0 },
{ "mset2", REDIS_CMD_MSET2, &Ardb::MSet, 2, -1, "w", 0, 0, 0 },
{ "msetnx", REDIS_CMD_MSETNX, &Ardb::MSetNX, 2, -1, "w", 0, 0, 0 },
{ "msetnx2", REDIS_CMD_MSETNX2, &Ardb::MSetNX, 2, -1, "w", 0, 0, 0 },
{ "psetex", REDIS_CMD_PSETEX, &Ardb::PSetEX, 3, 3, "w", 0, 0, 0 },
{ "setbit", REDIS_CMD_SETBIT, &Ardb::SetBit, 3, 3, "w", 0, 0, 0 },
{ "setbit2", REDIS_CMD_SETBIT2, &Ardb::SetBit, 3, 3, "w", 0, 0, 0 },
{ "setex", REDIS_CMD_SETEX, &Ardb::SetEX, 3, 3, "w", 0, 0, 0 },
{ "setnx", REDIS_CMD_SETNX, &Ardb::SetNX, 2, 2, "w", 0, 0, 0 },
{ "setnx2", REDIS_CMD_SETNX2, &Ardb::SetNX, 2, 2, "w", 0, 0, 0 },
{ "setrange", REDIS_CMD_SETRANGE, &Ardb::SetRange, 3, 3, "w", 0, 0, 0 },
{ "setrange2", REDIS_CMD_SETRANGE2, &Ardb::SetRange, 3, 3, "w", 0, 0, 0 },
{ "strlen", REDIS_CMD_STRLEN, &Ardb::Strlen, 1, 1, "r", 0, 0, 0 },
{ "hdel", REDIS_CMD_HDEL, &Ardb::HDel, 2, -1, "w", 0, 0, 0 },
{ "hdel2", REDIS_CMD_HDEL2, &Ardb::HDel, 2, -1, "w", 0, 0, 0 },
{ "hexists", REDIS_CMD_HEXISTS, &Ardb::HExists, 2, 2, "r", 0, 0, 0 },
{ "hget", REDIS_CMD_HGET, &Ardb::HGet, 2, 2, "r", 0, 0, 0 },
{ "hgetall", REDIS_CMD_HGETALL, &Ardb::HGetAll, 1, 1, "r", 0, 0, 0 },
{ "hincrby", REDIS_CMD_HINCR, &Ardb::HIncrby, 3, 3, "w", 0, 0, 0 },
{ "hincrby2", REDIS_CMD_HINCR2, &Ardb::HIncrby, 3, 3, "w", 0, 0, 0 },
{ "hincrbyfloat", REDIS_CMD_HINCRBYFLOAT, &Ardb::HIncrbyFloat, 3, 3, "w", 0, 0, 0 },
{ "hincrbyfloat2", REDIS_CMD_HINCRBYFLOAT2, &Ardb::HIncrbyFloat, 3, 3, "w", 0, 0, 0 },
{ "hkeys", REDIS_CMD_HKEYS, &Ardb::HKeys, 1, 1, "r", 0, 0, 0 },
{ "hlen", REDIS_CMD_HLEN, &Ardb::HLen, 1, 1, "r", 0, 0, 0 },
{ "hvals", REDIS_CMD_HVALS, &Ardb::HVals, 1, 1, "r", 0, 0, 0 },
{ "hmget", REDIS_CMD_HMGET, &Ardb::HMGet, 2, -1, "r", 0, 0, 0 },
{ "hset", REDIS_CMD_HSET, &Ardb::HSet, 3, -1, "w", 0, 0, 0 },
{ "hset2", REDIS_CMD_HSET2, &Ardb::HSet, 3, -1, "w", 0, 0, 0 },
{ "hsetnx", REDIS_CMD_HSETNX, &Ardb::HSetNX, 3, 3, "w", 0, 0, 0 },
{ "hsetnx2", REDIS_CMD_HSETNX2, &Ardb::HSetNX, 3, 3, "w", 0, 0, 0 },
{ "hmset", REDIS_CMD_HMSET, &Ardb::HMSet, 3, -1, "w", 0, 0, 0 },
{ "hmset2", REDIS_CMD_HMSET2, &Ardb::HMSet, 3, -1, "w", 0, 0, 0 },
{ "hscan", REDIS_CMD_HSCAN, &Ardb::HScan, 2, 6, "r", 0, 0, 0 },
{ "scard", REDIS_CMD_SCARD, &Ardb::SCard, 1, 1, "r", 0, 0, 0 },
{ "sadd", REDIS_CMD_SADD, &Ardb::SAdd, 2, -1, "w", 0, 0, 0 },
{ "sadd2", REDIS_CMD_SADD2, &Ardb::SAdd, 2, -1, "w", 0, 0, 0 },
{ "sdiff", REDIS_CMD_SDIFF, &Ardb::SDiff, 2, -1, "r", 0, 0, 0 },
{ "sdiffcount", REDIS_CMD_SDIFFCOUNT, &Ardb::SDiffCount, 2, -1, "r", 0, 0, 0 },
{ "sdiffstore", REDIS_CMD_SDIFFSTORE, &Ardb::SDiffStore, 3, -1, "w", 0, 0, 0 },
{ "sinter", REDIS_CMD_SINTER, &Ardb::SInter, 2, -1, "r", 0, 0, 0 },
{ "sintercount", REDIS_CMD_SINTERCOUNT, &Ardb::SInterCount, 2, -1, "r", 0, 0, 0 },
{ "sinterstore", REDIS_CMD_SINTERSTORE, &Ardb::SInterStore, 3, -1, "w", 0, 0, 0 },
{ "sismember", REDIS_CMD_SISMEMBER, &Ardb::SIsMember, 2, 2, "r", 0, 0, 0 },
{ "smembers", REDIS_CMD_SMEMBERS, &Ardb::SMembers, 1, 1, "r", 0, 0, 0 },
{ "smove", REDIS_CMD_SMOVE, &Ardb::SMove, 3, 3, "w", 0, 0, 0 },
{ "spop", REDIS_CMD_SPOP, &Ardb::SPop, 1, 2, "wR", 0, 0, 0 },
{ "srandmember", REDIS_CMD_SRANMEMEBER, &Ardb::SRandMember, 1, 2, "rR", 0, 0, 0 },
{ "srem", REDIS_CMD_SREM, &Ardb::SRem, 2, -1, "w", 1, 0, 0 },
{ "srem2", REDIS_CMD_SREM2, &Ardb::SRem, 2, -1, "w", 1, 0, 0 },
{ "sunion", REDIS_CMD_SUNION, &Ardb::SUnion, 2, -1, "r", 0, 0, 0 },
{ "sunionstore", REDIS_CMD_SUNIONSTORE, &Ardb::SUnionStore, 3, -1, "w", 0, 0, 0 },
{ "sunioncount", REDIS_CMD_SUNIONCOUNT, &Ardb::SUnionCount, 2, -1, "r", 0, 0, 0 },
{ "sscan", REDIS_CMD_SSCAN, &Ardb::SScan, 2, 6, "r", 0, 0, 0 },
{ "zadd", REDIS_CMD_ZADD, &Ardb::ZAdd, 3, -1, "w", 0, 0, 0 },
{ "zcard", REDIS_CMD_ZCARD, &Ardb::ZCard, 1, 1, "r", 0, 0, 0 },
{ "zcount", REDIS_CMD_ZCOUNT, &Ardb::ZCount, 3, 3, "r", 0, 0, 0 },
{ "zincrby", REDIS_CMD_ZINCRBY, &Ardb::ZIncrby, 3, 3, "w", 0, 0, 0 },
{ "zrange", REDIS_CMD_ZRANGE, &Ardb::ZRange, 3, 4, "r", 0, 0, 0 },
{ "zrangebyscore", REDIS_CMD_ZRANGEBYSCORE, &Ardb::ZRangeByScore, 3, 7, "r", 0, 0, 0 },
{ "zrank", REDIS_CMD_ZRANK, &Ardb::ZRank, 2, 2, "r", 0, 0, 0 },
{ "zrem", REDIS_CMD_ZREM, &Ardb::ZRem, 2, -1, "w", 0, 0, 0 },
{ "zremrangebyrank", REDIS_CMD_ZREMRANGEBYRANK, &Ardb::ZRemRangeByRank, 3, 3, "w", 0, 0, 0 },
{ "zremrangebyscore", REDIS_CMD_ZREMRANGEBYSCORE, &Ardb::ZRemRangeByScore, 3, 3, "w", 0, 0, 0 },
{ "zrevrange", REDIS_CMD_ZREVRANGE, &Ardb::ZRevRange, 3, 4, "r", 0, 0, 0 },
{ "zrevrangebyscore", REDIS_CMD_ZREVRANGEBYSCORE, &Ardb::ZRevRangeByScore, 3, 7, "r", 0, 0, 0 },
{ "zinterstore", REDIS_CMD_ZINTERSTORE, &Ardb::ZInterStore, 3, -1, "w", 0, 0, 0 },
{ "zunionstore", REDIS_CMD_ZUNIONSTORE, &Ardb::ZUnionStore, 3, -1, "w", 0, 0, 0 },
{ "zrevrank", REDIS_CMD_ZREVRANK, &Ardb::ZRevRank, 2, 2, "r", 0, 0, 0 },
{ "zscore", REDIS_CMD_ZSCORE, &Ardb::ZScore, 2, 2, "r", 0, 0, 0 },
{ "zscan", REDIS_CMD_ZSCAN, &Ardb::ZScan, 2, 6, "r", 0, 0, 0 },
{ "zlexcount", REDIS_CMD_ZLEXCOUNT, &Ardb::ZLexCount, 3, 3, "r", 0, 0, 0 },
{ "zrangebylex", REDIS_CMD_ZRANGEBYLEX, &Ardb::ZRangeByLex, 3, 6, "r", 0, 0, 0 },
{ "zrevrangebylex", REDIS_CMD_ZREVRANGEBYLEX, &Ardb::ZRangeByLex, 3, 6, "r", 0, 0, 0 },
{ "zremrangebylex", REDIS_CMD_ZREMRANGEBYLEX, &Ardb::ZRemRangeByLex, 3, 3, "w", 0, 0, 0 },
{ "lindex", REDIS_CMD_LINDEX, &Ardb::LIndex, 2, 2, "r", 0, 0, 0 },
{ "linsert", REDIS_CMD_LINSERT, &Ardb::LInsert, 4, 4, "w", 0, 0, 0 },
{ "llen", REDIS_CMD_LLEN, &Ardb::LLen, 1, 1, "r", 0, 0, 0 },
{ "lpop", REDIS_CMD_LPOP, &Ardb::LPop, 1, 1, "w", 0, 0, 0 },
{ "lpush", REDIS_CMD_LPUSH, &Ardb::LPush, 2, -1, "w", 0, 0, 0 },
{ "lpushx", REDIS_CMD_LPUSHX, &Ardb::LPushx, 2, 2, "w", 0, 0, 0 },
{ "lrange", REDIS_CMD_LRANGE, &Ardb::LRange, 3, 3, "r", 0, 0, 0 },
{ "lrem", REDIS_CMD_LREM, &Ardb::LRem, 3, 3, "w", 0, 0, 0 },
{ "lset", REDIS_CMD_LSET, &Ardb::LSet, 3, 3, "w", 0, 0, 0 },
{ "ltrim", REDIS_CMD_LTRIM, &Ardb::LTrim, 3, 3, "w", 0, 0, 0 },
{ "rpop", REDIS_CMD_RPOP, &Ardb::RPop, 1, 1, "w", 0, 0, 0 },
{ "rpush", REDIS_CMD_RPUSH, &Ardb::RPush, 2, -1, "w", 0, 0, 0 },
{ "rpushx", REDIS_CMD_RPUSHX, &Ardb::RPushx, 2, 2, "w", 0, 0, 0 },
{ "rpoplpush", REDIS_CMD_RPOPLPUSH, &Ardb::RPopLPush, 2, 2, "w", 0, 0, 0 },
{ "blpop", REDIS_CMD_BLPOP, &Ardb::BLPop, 2, -1, "ws", 0, 0, 0 },
{ "brpop", REDIS_CMD_BRPOP, &Ardb::BRPop, 2, -1, "ws", 0, 0, 0 },
{ "brpoplpush", REDIS_CMD_BRPOPLPUSH, &Ardb::BRPopLPush, 3, 3, "ws", 0, 0, 0 },
{ "rpoplpush", REDIS_CMD_RPOPLPUSH, &Ardb::RPopLPush, 2, 2, "w", 0, 0, 0 },
{ "move", REDIS_CMD_MOVE, &Ardb::Move, 2, 2, "w", 0, 0, 0 },
{ "rename", REDIS_CMD_RENAME, &Ardb::Rename, 2, 2, "w", 0, 0, 0 },
{ "renamenx", REDIS_CMD_RENAMENX, &Ardb::RenameNX, 2, 2, "w", 0, 0, 0 },
{ "sort", REDIS_CMD_SORT, &Ardb::Sort, 1, -1, "w", 0, 0, 0 },
{ "keys", REDIS_CMD_KEYS, &Ardb::Keys, 1, 6, "r", 0, 0, 0 },
{ "keyscount", REDIS_CMD_KEYSCOUNT, &Ardb::KeysCount, 1, 6, "r", 0, 0, 0 },
{ "eval", REDIS_CMD_EVAL, &Ardb::Eval, 2, -1, "s", 0, 0, 0 },
{ "evalsha", REDIS_CMD_EVALSHA, &Ardb::EvalSHA, 2, -1, "s", 0, 0, 0 },
{ "script", REDIS_CMD_SCRIPT, &Ardb::Script, 1, -1, "rs", 0, 0, 0 },
{ "randomkey", REDIS_CMD_RANDOMKEY, &Ardb::Randomkey, 0, 0, "r", 0, 0, 0 },
{ "scan", REDIS_CMD_SCAN, &Ardb::Scan, 1, 5, "r", 0, 0, 0 },
{ "geoadd", REDIS_CMD_GEO_ADD, &Ardb::GeoAdd, 4, -1, "w", 0, 0, 0 },
{ "georadius", REDIS_CMD_GEO_RADIUS, &Ardb::GeoRadius, 5, -1, "w", 0, 0, 0 },
{ "georadiusbymember", REDIS_CMD_GEO_RADIUSBYMEMBER, &Ardb::GeoRadiusByMember, 4, 10, "w", 0, 0, 0 },
{ "geohash", REDIS_CMD_GEO_HASH, &Ardb::GeoHash, 2, -1, "r", 0, 0, 0 },
{ "geodist", REDIS_CMD_GEO_DIST, &Ardb::GeoDist, 3, 4, "r", 0, 0, 0 },
{ "geopos", REDIS_CMD_GEO_POS, &Ardb::GeoPos, 2, -1, "r", 0, 0, 0 },
{ "auth", REDIS_CMD_AUTH, &Ardb::Auth, 1, 1, "rsltF", 0, 0, 0 },
{ "pfadd", REDIS_CMD_PFADD, &Ardb::PFAdd, 2, -1, "w", 0, 0, 0 },
{ "pfadd2", REDIS_CMD_PFADD2, &Ardb::PFAdd, 2, -1, "w", 0, 0, 0 },
{ "pfcount", REDIS_CMD_PFCOUNT, &Ardb::PFCount, 1, -1, "r", 0, 0, 0 },
{ "pfmerge", REDIS_CMD_PFMERGE, &Ardb::PFMerge, 2, -1, "w", 0, 0, 0 },
{ "dump", REDIS_CMD_DUMP, &Ardb::Dump, 1, 1, "r", 0, 0, 0 },
{ "restore", REDIS_CMD_RESTORE, &Ardb::Restore, 3, 4, "w", 0, 0, 0 },
{ "migrate", REDIS_CMD_MIGRATE, &Ardb::Migrate, 5, -1, "w", 0, 0, 0 },
{ "migratedb", REDIS_CMD_MIGRATEDB, &Ardb::MigrateDB, 4, 4, "w", 0, 0, 0 },
{ "restorechunk", REDIS_CMD_RESTORECHUNK, &Ardb::RestoreChunk, 1, 1, "wl", 0, 0, 0 },
{ "restoredb", REDIS_CMD_RESTOREDB, &Ardb::RestoreDB, 1, 1, "wl", 0, 0, 0 },
{ "monitor", REDIS_CMD_MONITOR, &Ardb::Monitor, 0, 0, "ars", 0, 0, 0 },
{ "debug", REDIS_CMD_DEBUG, &Ardb::Debug, 2, -1, "ars", 0, 0, 0 },
{ "touch", REDIS_CMD_TOUCH, &Ardb::Touch, 1, -2, "rF", 0, 0, 0 },};
CostRanges cmdstat_ranges;
cmdstat_ranges.push_back(CostRange(0, 1000));
cmdstat_ranges.push_back(CostRange(1000, 5000));
cmdstat_ranges.push_back(CostRange(5000, 10000));
cmdstat_ranges.push_back(CostRange(10000, 20000));
cmdstat_ranges.push_back(CostRange(20000, 50000));
cmdstat_ranges.push_back(CostRange(50000, 100000));
cmdstat_ranges.push_back(CostRange(100000, 200000));
cmdstat_ranges.push_back(CostRange(200000, 500000));
cmdstat_ranges.push_back(CostRange(500000, 1000000));
cmdstat_ranges.push_back(CostRange(1000000, UINT64_MAX));
uint32 arraylen = arraysize(settingTable);
for (uint32 i = 0; i < arraylen; i++)
{
settingTable[i].flags = 0;
const char* f = settingTable[i].sflags;
CostTrack& cost_track = g_cmd_cost_tracks[settingTable[i].type];
cost_track.dump_flags = STAT_DUMP_INFO_CMD | STAT_DUMP_PERIOD | STAT_DUMP_PERIOD_CLEAR;
cost_track.name = settingTable[i].name;
cost_track.SetCostRanges(cmdstat_ranges);
Statistics::GetSingleton().AddTrack(&cost_track);
while (*f != '\0')
{
switch (*f)
{
case 'w':
settingTable[i].flags |= ARDB_CMD_WRITE;
break;
case 'r':
settingTable[i].flags |= ARDB_CMD_READONLY;
break;
case 'a':
settingTable[i].flags |= ARDB_CMD_ADMIN;
break;
case 'p':
settingTable[i].flags |= ARDB_CMD_PUBSUB;
break;
case 's':
settingTable[i].flags |= ARDB_CMD_NOSCRIPT;
break;
case 'R':
settingTable[i].flags |= ARDB_CMD_RANDOM;
break;
case 'S':
settingTable[i].flags |= ARDB_CMD_SORT_FOR_SCRIPT;
break;
case 'l':
settingTable[i].flags |= ARDB_CMD_LOADING;
break;
case 't':
settingTable[i].flags |= ARDB_CMD_STALE;
break;
case 'M':
settingTable[i].flags |= ARDB_CMD_SKIP_MONITOR;
break;
case 'k':
settingTable[i].flags |= ARDB_CMD_ASKING;
break;
case 'F':
settingTable[i].flags |= ARDB_CMD_FAST;
break;
default:
break;
}
f++;
}
m_settings[settingTable[i].name] = settingTable[i];
}
}
Ardb::~Ardb()
{
DELETE(m_engine);
DELETE(m_ready_keys);
DELETE(m_watched_ctxs);
ArdbLogger::DestroyDefaultLogger();
}
static void daemonize(void)
{
int fd;
if (fork() != 0)
{
exit(0); /* parent exits */
}
setsid(); /* create a new session */
if ((fd = open("/dev/null", O_RDWR, 0)) != -1)
{
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO)
{
close(fd);
}
}
}
static int signal_setting()
{
signal(SIGPIPE, SIG_IGN);
return 0;
}
static Engine* create_engine()
{
Engine* engine = NULL;
#if defined __USE_LMDB__
NEW(engine, LMDBEngine);
#elif defined __USE_ROCKSDB__
NEW(engine, RocksDBEngine);
#elif defined __USE_LEVELDB__
NEW(engine, LevelDBEngine);
#elif defined __USE_FORESTDB__
NEW(engine, ForestDBEngine);
#elif defined __USE_WIREDTIGER__
NEW(engine, WiredTigerEngine);
#elif defined __USE_PERCONAFT__
NEW(engine, PerconaFTEngine);
#else
ERROR_LOG("Unsupported storage engine specified at compile time.");
return NULL;
#endif
return engine;
}
uint32 Ardb::MaxOpenFiles()
{
/*
* 1000 is reserved open files in Ardb(pipes/logs/dump/etc.)
*/
uint32 maxfiles = g_db->GetConf().max_clients + 1000;
if (g_engine->MaxOpenFiles() > 0)
{
maxfiles += g_engine->MaxOpenFiles();
}
return maxfiles;
}
int Ardb::Init(const std::string& conf_file)
{
Properties props;
if (!conf_file.empty())
{
if (!parse_conf_file(conf_file, props, " "))
{
printf("Error: Failed to parse conf file:%s\n", conf_file.c_str());
return -1;
}
}
if (!m_conf.Parse(props))
{
printf("Failed to parse config file:%s\n", conf_file.c_str());
return -1;
}
if (m_conf.daemonize && !m_conf.servers.empty())
{
daemonize();
}
signal_setting();
RenameCommand();
/*
* save pid into file
*/
if (!m_conf.pidfile.empty())
{
char tmp[200];
sprintf(tmp, "%d", getpid());
std::string content = tmp;
file_write_content(m_conf.pidfile, content);
}
chdir(GetConf().home.c_str());
ArdbLogger::InitDefaultLogger(m_conf.loglevel, m_conf.logfile);
std::string dbdir = GetConf().data_base_path + "/" + g_engine_name;
make_dir(dbdir);
int err = 0;
m_engine = create_engine();
if (NULL == m_engine)
{
return -1;
}
std::string options_key = g_engine_name;
options_key.append(".options");
std::string options_value;
conf_get_string(props, options_key, options_value);
err = m_engine->Init(dbdir, options_value);
if (0 != err)
{
DELETE(m_engine);
ERROR_LOG("Failed to init database engine:%s.", g_engine_name);
return -1;
}
m_starttime = time(NULL);
g_engine = m_engine;
INFO_LOG("Ardb init engine:%s success.", g_engine_name);
return 0;
}
int Ardb::Repair(const std::string& dir)
{
m_engine = create_engine();
if (NULL == m_engine)
{
return -1;
}
return m_engine->Repair(dir);
}
void Ardb::RenameCommand()
{
StringStringMap::const_iterator it = GetConf().rename_commands.begin();
while (it != GetConf().rename_commands.end())
{
std::string cmd = string_tolower(it->first);
RedisCommandHandlerSettingTable::iterator found = m_settings.find(cmd);
if (found != m_settings.end())
{
RedisCommandHandlerSetting setting = found->second;
m_settings.erase(found);
m_settings[it->second] = setting;
}
it++;
}
}
void Ardb::OpenWriteLatchByWriteCaller()
{
LockGuard<ThreadMutexLock> guard(m_write_latch);
while (m_prepare_snapshot_num > 0)
{
m_write_latch.Wait(1);
}
atomic_add_uint32(&m_write_caller_num, 1);
}
void Ardb::CloseWriteLatchByWriteCaller()
{
atomic_sub_uint32(&m_write_caller_num, 1);
}
void Ardb::OpenWriteLatchAfterSnapshotPrepare()
{
LockGuard<ThreadMutexLock> guard(m_write_latch);
m_prepare_snapshot_num--;
if (m_prepare_snapshot_num == 0)
{
m_write_latch.NotifyAll();
}
INFO_LOG("Open write latch for snapshot save preparing complete.");
}
void Ardb::CloseWriteLatchBeforeSnapshotPrepare()
{
/*
* wait until all writing commands complete & wal log appended
*/
LockGuard<ThreadMutexLock> guard(m_write_latch);
m_prepare_snapshot_num++;
while (m_write_caller_num != 0)
{
m_write_latch.Wait(1);
}
while (g_repl->GetReplLog().WALQueueSize() != 0)
{
m_write_latch.Wait(1);
if (g_repl->GetIOService().IsInLoopThread())
{
g_repl->GetIOService().Continue();
}
}
INFO_LOG("Close write latch for snapshot save preparing start.");
}
int Ardb::SetKeyValue(Context& ctx, const KeyObject& key, const ValueObject& val)
{
int ret = 0;
ret = m_engine->Put(ctx, key, val);
if (0 == ret)
{
TouchWatchKey(ctx, key);
ctx.dirty = 1;
}
return ret;
}
int Ardb::MergeKeyValue(Context& ctx, const KeyObject& key, uint16 op, const DataArray& args)
{
int ret = m_engine->Merge(ctx, key, op, args);
if (0 == ret)
{
TouchWatchKey(ctx, key);
ctx.dirty++;
}
return ret;
}
int Ardb::RemoveKey(Context& ctx, const KeyObject& key)
{
int ret = m_engine->Del(ctx, key);
if (0 == ret)
{
TouchWatchKey(ctx, key);
ctx.dirty++;
}
return ret;
}
int Ardb::IteratorDel(Context& ctx, const KeyObject& key, Iterator* iter)
{
if (NULL != iter)
{
iter->Del();
TouchWatchKey(ctx, key);
ctx.dirty++;
}
return 0;
}
int Ardb::CompactDB(Context& ctx, const Data& ns)
{
if (m_compacting_data)
{
WARN_LOG("Can NOT launch compact task since server is compacting db.");
return -1;
}
KeyObject start, end;
start.SetNameSpace(ctx.ns);
m_compacting_data = true;
m_engine->Compact(ctx, start, end);
m_compacting_data = false;
return 0;
}
int Ardb::CompactAll(Context& ctx)
{
if (m_compacting_data)
{
WARN_LOG("Can NOT launch compact task since server is compacting db.");
return -1;
}
m_compacting_data = true;
m_engine->CompactAll(ctx);
m_compacting_data = false;
return 0;
}
int Ardb::FlushDB(Context& ctx, const Data& ns)
{
m_engine->DropNameSpace(ctx, ns);
ctx.dirty += 1000; //makesure all
TouchWatchedKeysOnFlush(ctx, ns);
return 0;
}
int Ardb::FlushAll(Context& ctx)
{
DataArray nss;
m_engine->ListNameSpaces(ctx, nss);
for (size_t i = 0; i < nss.size(); i++)
{
m_engine->DropNameSpace(ctx, nss[i]);
}
ctx.dirty += 1000;
Data empty_ns; //indicate all namespaces
TouchWatchedKeysOnFlush(ctx, empty_ns);
return 0;
}
bool Ardb::LockKey(const KeyPrefix& lk, int wait_limit)
{
// KeyPrefix lk;
// lk.ns = key.GetNameSpace();
// lk.key = key.GetKey();
int wait_counter = 0;
while (wait_limit <= 0 || wait_counter < wait_limit)
{
ThreadMutexLock* lock = NULL;
{
LockGuard<SpinMutexLock> guard(m_locking_keys_lock);
std::pair<LockTable::iterator, bool> ret = m_locking_keys.insert(LockTable::value_type(lk, NULL));
if (!ret.second && NULL != ret.first->second)
{
/*
* already locked by other thread, wait until unlocked
*/
lock = ret.first->second;
}
else
{
/*
* no other thread lock on the key
*/
if (!m_lock_pool.empty())
{
lock = m_lock_pool.top();
m_lock_pool.pop();
}
else
{
NEW(lock, ThreadMutexLock);
}
ret.first->second = lock;
return true;
}
}
if (NULL != lock)
{
LockGuard<ThreadMutexLock> guard(*lock);
lock->Wait(1, MILLIS);
wait_counter++;
}
}
return false;
}
void Ardb::UnlockKey(const KeyPrefix& lk)
{
// KeyPrefix lk;
// lk.ns = key.GetNameSpace();
// lk.key = key.GetKey();
{
LockGuard<SpinMutexLock> guard(m_locking_keys_lock);
LockTable::iterator ret = m_locking_keys.find(lk);
if (ret != m_locking_keys.end())
{
ThreadMutexLock* lock = ret->second;
m_locking_keys.erase(ret);
if(NULL != lock)
{
m_lock_pool.push(lock);
LockGuard<ThreadMutexLock> guard(*lock);
lock->Notify();
}
}
}
}
void Ardb::LockKeys(const KeyPrefixSet& ks)
{
while(true)
{
std::vector<KeyPrefix> locked_keys;
KeyPrefixSet::const_iterator kit = ks.begin();
while (kit != ks.end())
{
if(!LockKey(*kit, 1))
{
break;
}
locked_keys.push_back(*kit);
kit++;
}
if(locked_keys.size() == ks.size())
{
return;
}
//release locked keys, and try again
for(size_t i = 0; i < locked_keys.size(); i++)
{
UnlockKey(locked_keys[i]);
}
}
// for (size_t i = 0; i < ks.size(); i++)
// {
// LockKey(ks[i]);
// }
}
void Ardb::UnlockKeys(const KeyPrefixSet& ks)
{
KeyPrefixSet::const_iterator kit = ks.begin();
while (kit != ks.end())
{
UnlockKey(*kit);
kit++;
}
}
void Ardb::FeedReplicationDelOperation(Context& ctx, const Data& ns, const std::string& key)
{
if (!g_repl->IsInited())
{
return;
}
/*
* generate 'del' command for master instance
*/
RedisCommandFrame del("del");
del.AddArg(key);
FeedReplicationBacklog(ctx, ns, del);
}
void Ardb::FeedReplicationBacklog(Context& ctx, const Data& ns, RedisCommandFrame& cmd)
{
if (!g_repl->IsInited())
{
return;
}
/*
* Since this method may be invoked by multi threads, there is a potential risk that replication commands may have wrong sequence
* if one thread do db operation first but feed replication log later.
* eg:
* Thread A: lpush mylist a (1) Thread B: lpush mylist b (2)
* | |
* \|/ \|/
* Replication Log Thread
* lpush mylist b
* lpush mylist a
* This risk only has data inconsistent effect when multi-threads operating on same key at the same time which is also a rare condition.
* If multi-threads operating on different keys at the same time,there is no any risk.
*
*
*/
// if (!ctx.keyslocked)
// {
// ERROR_LOG("Can NOT feed replication wal log without key locked");
// return;
// }
g_repl->GetReplLog().WriteWAL(ns, cmd);
}
void Ardb::SaveTTL(Context& ctx, const Data& ns, const std::string& key, int64 old_ttl, int64_t new_ttl)
{
/*
* only works with engine that has no compactfilter support
*/
if (m_engine->GetFeatureSet().support_compactfilter)
{
return;
}
if (new_ttl > 0)
{
if (m_min_ttl <= 0 || m_min_ttl > new_ttl)
{
m_min_ttl = new_ttl;
}
Data tll_ns(TTL_DB_NSMAESPACE, false);
KeyObject new_ttl_key(tll_ns, KEY_TTL_SORT, "");
new_ttl_key.SetTTL(new_ttl);
new_ttl_key.SetTTLKeyNamespace(ns);
new_ttl_key.SetTTLKey(key);
ValueObject v;
v.SetType(KEY_TTL_SORT);
ctx.flags.create_if_notexist = 1;
m_engine->Put(ctx, new_ttl_key, v);
}
if (old_ttl > 0)
{
Data tll_ns(TTL_DB_NSMAESPACE, false);
KeyObject old_ttl_key(tll_ns, KEY_TTL_SORT, "");
old_ttl_key.SetTTL(old_ttl);
old_ttl_key.SetTTLKeyNamespace(ns);
old_ttl_key.SetTTLKey(key);
m_engine->Del(ctx, old_ttl_key);
}
}
void Ardb::ScanTTLDB()
{
/*
* only works with engine that has no compactfilter support
*/
if (m_engine->GetFeatureSet().support_compactfilter || !GetConf().master_host.empty())
{
return;
}
if (0 == m_min_ttl)
{
return;
}
uint32 max_scan_keys_one_iter = 1000;
uint32 scaned_keys = 0;
uint32 total_expired_keys = 0;
Context scan_ctx;
Data tll_ns(TTL_DB_NSMAESPACE, false);
KeyObject scan_key(tll_ns, KEY_TTL_SORT, "");
scan_key.SetTTL(m_min_ttl);
Iterator* iter = m_engine->Find(scan_ctx, scan_key);
if (!iter->Valid())
{
m_min_ttl = 0; //no expire key
}
uint64 start_time = get_current_epoch_millis();
while (iter->Valid() && scaned_keys < max_scan_keys_one_iter)
{
KeyObject& k = iter->Key(false);
m_min_ttl = k.GetTTL();
if (k.GetTTL() > get_current_epoch_millis())
{
break;
}
scaned_keys++;
ValueObject meta;
KeyObject meta_key(k.GetElement(1), KEY_META, k.GetElement(2));
KeyLockGuard guard(scan_ctx, meta_key);
if (0 == m_engine->Get(scan_ctx, meta_key, meta))
{
if (meta.GetTTL() == k.GetTTL())
{
//delete whole key
if (meta.GetType() == KEY_STRING)
{
m_engine->Del(scan_ctx, meta_key);
}
else
{
DelKey(scan_ctx, meta_key);
}
total_expired_keys++;
FeedReplicationDelOperation(scan_ctx, meta_key.GetNameSpace(), meta_key.GetKey().AsString());
}
}
else
{
}
iter->Del();
iter->Next();
}
DELETE(iter);
uint64 end_time = get_current_epoch_millis();
if (total_expired_keys > 0)
{
INFO_LOG("Cost %llums to delete %u keys.", (end_time - start_time), total_expired_keys);
}
}
int64 Ardb::ScanExpiredKeys()
{
/*
* do not do scan expire on slaves
*/
if (!GetConf().master_host.empty())
{
return 0;
}
if (!m_engine->GetFeatureSet().support_compactfilter)
{
ScanTTLDB();
return 0;
}
KeyPrefix scan_key;
Context scan_ctx;
int64 total_expired_keys = 0;
uint64 start_time = get_current_epoch_millis();
while (true)
{
{
LockGuard<SpinMutexLock> guard(m_expires_lock);
if (!m_expires.empty())
{
scan_key = *(m_expires.begin());
m_expires.erase(m_expires.begin());
}
else
{
break;
}
}
if (scan_key.IsNil())
{
break;
}
KeyObject key(scan_key.ns, KEY_META, scan_key.key);
KeyLockGuard keylocker(scan_ctx, key);
ValueObject meta;
bool toremove = false;
int err = m_engine->Get(scan_ctx, key, meta);
if (ERR_ENTRY_NOT_EXIST == err)
{
toremove = true;
}
else if (0 == err)
{
if (0 == m_engine->Get(scan_ctx, key, meta))
{
uint64 ttl = meta.GetTTL();
if (ttl == 0 || ttl > get_current_epoch_millis())
{
continue;
}
toremove = true;
total_expired_keys++;
}
}
else
{
continue;
}
total_expired_keys++;
if (toremove)
{
/*
* generate 'del' command for master instance
*/
FeedReplicationDelOperation(scan_ctx, key.GetNameSpace(), key.GetKey().AsString());
}
if (KEY_STRING == meta.GetType())
{
RemoveKey(scan_ctx, key);
}
else if (meta.GetType() > 0)
{
DelKey(scan_ctx, key);
}
}
uint64 end_time = get_current_epoch_millis();
if (total_expired_keys > 0)
{
INFO_LOG("Cost %llums to delete %lld keys.", (end_time - start_time), total_expired_keys);
}
return 0;
}
void Ardb::AddExpiredKey(const Data& ns, const Data& key)
{
KeyPrefix k;
k.key = key;
k.ns = ns;
k.key.ToMutableStr();
k.ns.ToMutableStr();
LockGuard<SpinMutexLock> guard(m_expires_lock);
m_expires.insert(k);
}
int Ardb::FindElementByRedisCursor(const std::string& cursor, std::string& element)
{
uint64 cursor_int = 0;
element.clear();
if (!string_touint64(cursor, cursor_int))
{
element = cursor;
return -1;
}
if (0 == cursor_int)
{
return 0;
}
LockGuard<SpinMutexLock> guard(m_redis_cursor_lock);
return m_redis_cursor_cache.Get(cursor_int, element) ? 0 : -1;
}
uint64 Ardb::GetNewRedisCursor(const std::string& element)
{
LockGuard<SpinMutexLock> guard(m_redis_cursor_lock);
m_redis_cursor_seed++;
RedisCursorCache::CacheEntry entry;
m_redis_cursor_cache.Insert(m_redis_cursor_seed, element, entry);
return m_redis_cursor_seed;
}
bool Ardb::GetLongFromProtocol(Context& ctx, const std::string& str, int64_t& v)
{
RedisReply& reply = ctx.GetReply();
if (!string_toint64(str, v))
{
reply.SetErrCode(ERR_INVALID_INTEGER_ARGS);
return false;
}
if (v < LONG_MIN || v > LONG_MAX)
{
reply.SetErrCode(ERR_OUTOFRANGE);
return false;
}
return true;
}
bool Ardb::CheckMeta(Context& ctx, const std::string& key, KeyType expected)
{
ValueObject meta_value;
return CheckMeta(ctx, key, expected, meta_value);
}
bool Ardb::CheckMeta(Context& ctx, const std::string& key, KeyType expected, ValueObject& meta_value)
{
KeyObject meta_key(ctx.ns, KEY_META, key);
return CheckMeta(ctx, meta_key, expected, meta_value);
}
bool Ardb::CheckMeta(Context& ctx, const KeyObject& key, KeyType expected, ValueObject& meta, bool fetch)
{
RedisReply& reply = ctx.GetReply();
int err = 0;
if (fetch)
{
err = m_engine->Get(ctx, key, meta);
if (err != 0 && err != ERR_ENTRY_NOT_EXIST)
{
reply.SetErrCode(err);
return false;
}
}
if (meta.GetType() > 0)
{
if (expected > 0 && meta.GetType() != expected)
{
reply.SetErrCode(ERR_WRONG_TYPE);
return false;
}
if (meta.GetTTL() > 0 && meta.GetTTL() < get_current_epoch_millis())
{
if (GetConf().master_host.empty() || !GetConf().slave_readonly)
{
KeyLockGuard keylocker(ctx, key, ctx.keyslocked ? false : true);
int old_dirty = ctx.dirty;
if (meta.GetType() == KEY_STRING)
{
RemoveKey(ctx, key);
}
else
{
DelKey(ctx, key);
}
if (GetConf().master_host.empty())
{
/*
* master generate 'del' command for replication & resume dirty after delete kvs
*/
ctx.dirty = old_dirty;
FeedReplicationDelOperation(ctx, key.GetNameSpace(), key.GetKey().AsString());
}
}
meta.Clear();
return true;
}
}
return true;
}
static void async_write_reply_callback(Channel* ch, void * data)
{
RedisReply* r = (RedisReply*) data;
if (NULL != ch && NULL != r)
{
if (!ch->Write(*r))
{
ch->Close();
}
}
DELETE(r);
}
int Ardb::WriteReply(Context& ctx, RedisReply* r, bool async)
{
if (NULL == ctx.client || NULL == ctx.client->client || NULL == r)
{
if (async)
{
DELETE(r);
}
return -1;
}
Channel* ch = ctx.client->client;
if (!async)
{
ch->Write(*r);
}
else
{
ch->GetService().AsyncIO(ch->GetID(), async_write_reply_callback, r);
}
return 0;
}
void Ardb::FreeClient(Context& ctx)
{
UnwatchKeys(ctx);
UnsubscribeAll(ctx, true, false);
UnsubscribeAll(ctx, false, false);
if (NULL != ctx.client)
{
m_clients.GetValue().erase(ctx.client->clientid);
LockGuard<SpinMutexLock> guard(m_clients_lock);
m_all_clients.erase(&ctx);
}
UnblockKeys(ctx, true);
MarkRestoring(ctx, false);
{
WriteLockGuard<SpinRWLock> guard(m_monitors_lock);
if (NULL != m_monitors)
{
m_monitors->erase(&ctx);
if (m_monitors->empty())
{
DELETE(m_monitors);
}
}
}
}
#define CLIENTS_CRON_MIN_ITERATIONS 5
void Ardb::ScanClients()
{
std::vector<Context*> to_close;
uint64 now = get_current_epoch_micros();
ClientIdSet& local_clients = m_clients.GetValue();
if (local_clients.empty())
{
return;
}
int64 numclients = local_clients.size();
int64 iterations = numclients / GetConf().hz;
/* Process at least a few clients while we are at it, even if we need
* to process less than CLIENTS_CRON_MIN_ITERATIONS to meet our contract
* of processing each client once per second. */
if (iterations < CLIENTS_CRON_MIN_ITERATIONS) iterations =
(numclients < CLIENTS_CRON_MIN_ITERATIONS) ? numclients : CLIENTS_CRON_MIN_ITERATIONS;
ClientId& last_scan_clientid = m_last_scan_clientid.GetValue();
ClientIdSet::iterator it = local_clients.lower_bound(last_scan_clientid);
while (it != local_clients.end() && iterations--)
{
ClientId& clientid = *it;
Context* client = clientid.ctx;
if (GetConf().tcp_keepalive > 0)
{
if (!client->IsBlocking() && !client->IsSubscribed())
{
if (now - client->client->last_interaction_ustime >= GetConf().tcp_keepalive * 1000 * 1000)
{
//timeout;
to_close.push_back(client);
client = NULL;
}
}
}
if (NULL != client && client->IsBlocking())
{
if (client->GetBPop().timeout > 0 && now >= client->GetBPop().timeout)
{
//timeout;
RedisReply empty_bulk;
empty_bulk.ReserveMember(-1);
client->client->client->Write(empty_bulk);
to_close.push_back(client);
}
}
if (NULL != client && NULL != client->client && NULL != client->client->client)
{
if (client->client->resume_ustime > 0 && now <= client->client->resume_ustime)
{
client->client->client->AttachFD();
client->client->resume_ustime = -1;
}
}
it++;
}
for (size_t i = 0; i < to_close.size(); i++)
{
to_close[i]->client->client->Close();
}
if (it == local_clients.end())
{
last_scan_clientid.id = 0;
last_scan_clientid.ctx = NULL;
}
else
{
last_scan_clientid = (*it);
}
}
void Ardb::AddClient(Context& ctx)
{
if (NULL != ctx.client)
{
m_clients.GetValue().insert(ctx.client->clientid);
LockGuard<SpinMutexLock> guard(m_clients_lock);
m_all_clients.insert(&ctx);
}
}
bool Ardb::IsLoadingData()
{
return g_repl->GetSlave().IsLoading() || m_loading_data;
}
int Ardb::DoCall(Context& ctx, RedisCommandHandlerSetting& setting, RedisCommandFrame& args)
{
uint64 start_time = get_current_epoch_micros();
/*
* 1. commands recv from slave replication connection always in incompatible mode
* 2. command type > REDIS_CMD_EXTEND_BEGIN
* 3. configuration 'redis_compatible = no'
*/
if ((args.GetType() < REDIS_CMD_EXTEND_BEGIN && GetConf().redis_compatible) || ctx.flags.slave)
{
ctx.flags.redis_compatible = 1;
}
else
{
ctx.flags.redis_compatible = 0;
}
if (NULL != ctx.client)
{
ctx.client->last_interaction_ustime = start_time;
}
ctx.last_cmdtype = setting.type;
if (NULL != m_monitors && !IsLoadingData() && !(setting.flags & (ARDB_CMD_SKIP_MONITOR | ARDB_CMD_ADMIN)))
{
/*
* feed monitors
*/
FeedMonitors(ctx, ctx.ns, args);
}
if (setting.IsWriteCommand())
{
OpenWriteLatchByWriteCaller();
}
atomic_add_uint32(&m_db_caller_num, 1);
int ret = (this->*(setting.handler))(ctx, args);
atomic_sub_uint32(&m_db_caller_num, 1);
if (!ctx.flags.lua)
{
uint64 stop_time = get_current_epoch_micros();
atomic_add_uint64(&(setting.calls), 1);
atomic_add_uint64(&(setting.microseconds), stop_time - start_time);
g_cmd_cost_tracks[setting.type].AddCost((stop_time - start_time));
TryPushSlowCommand(args, stop_time - start_time);
DEBUG_LOG("Process recved cmd cost %lluus", stop_time - start_time);
}
/*
* Sometimes read only command may modify the key/value pair, do NOT propagate it to replication log
*/
if (!ctx.flags.no_wal && ctx.dirty > 0 && setting.IsWriteCommand())
{
FeedReplicationBacklog(ctx, ctx.ns, args);
}
if (setting.IsWriteCommand())
{
CloseWriteLatchByWriteCaller();
}
return ret;
}
Ardb::RedisCommandHandlerSetting* Ardb::FindRedisCommandHandlerSetting(RedisCommandFrame& args)
{
std::string& cmd = args.GetMutableCommand();
lower_string(cmd);
RedisCommandHandlerSettingTable::iterator found = m_settings.find(cmd);
if (found == m_settings.end())
{
return NULL;
}
args.SetType(found->second.type);
return &(found->second);
}
int Ardb::Call(Context& ctx, RedisCommandFrame& args)
{
RedisReply& reply = ctx.GetReply();
RedisCommandHandlerSetting* found = FindRedisCommandHandlerSetting(args);
if (NULL == found)
{
ctx.AbortTransaction();
reply.SetErrorReason("unknown command:" + args.GetCommand());
return -1;
}
DEBUG_LOG("Process recved cmd:%s", args.ToString().c_str());
RedisCommandHandlerSetting& setting = *found;
bool valid_cmd = true;
if (setting.min_arity > 0)
{
valid_cmd = args.GetArguments().size() >= (uint32) setting.min_arity;
}
if (setting.max_arity >= 0 && valid_cmd)
{
valid_cmd = args.GetArguments().size() <= (uint32) setting.max_arity;
}
if (!valid_cmd)
{
ctx.AbortTransaction();
reply.SetErrorReason("wrong number of arguments for command:" + args.GetCommand());
return 0;
}
// if (err == ERR_OVERLOAD)
// {
// /*
// * block overloaded connection
// */
// if (NULL != ctx.client && !ctx.client->IsDetached())
// {
// ctx.client->DetachFD();
// uint64 now = get_current_epoch_millis();
// uint64 next = 1000 - (now % 1000);
// ChannelService& serv = ctx.client->GetService();
// ctx.client->GetService().GetTimer().ScheduleHeapTask(new ResumeOverloadConnection(serv, ctx.client->GetID()), next == 0 ? 1 : next, -1, MILLIS);
// }
// }
ctx.current_cmd = &args;
int ret = 0;
/*
* Check if the connection is authenticated
*/
if (!ctx.authenticated && setting.type != REDIS_CMD_AUTH && setting.type != REDIS_CMD_QUIT)
{
ctx.AbortTransaction();
reply.SetErrCode(ERR_AUTH_FAILED);
//fill_fix_error_reply(ctx.reply, "NOAUTH Authentication required");
return ret;
}
/* Don't accept write commands if there are not enough good slaves and
* user configured the min-slaves-to-write option. */
if (GetConf().master_host.empty() && GetConf().repl_min_slaves_to_write > 0
&& GetConf().repl_min_slaves_max_lag > 0 && (setting.flags & ARDB_CMD_WRITE) > 0
&& g_repl->GetMaster().GoodSlavesCount() < GetConf().repl_min_slaves_to_write)
{
ctx.AbortTransaction();
reply.SetErrCode(ERR_NOREPLICAS);
return 0;
}
/* Don't accept write commands if this is a read only slave. But
* accept write commands if this is our master. */
if (!GetConf().master_host.empty() && (setting.flags & ARDB_CMD_WRITE) > 0)
{
if (!ctx.flags.slave) // from network
{
if (GetConf().slave_readonly)
{
reply.SetErrCode(ERR_READONLY_SLAVE);
return 0;
}
else
{
ctx.flags.no_wal = 1; //do not feed wal in slave node
}
}
}
if (GetConf().slave_ignore_del && ctx.flags.slave && setting.type == REDIS_CMD_DEL)
{
return 0;
}
/* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
* we are a slave with a broken link with master. */
if (!GetConf().master_host.empty() && !g_repl->GetSlave().IsSynced() && !GetConf().repl_serve_stale_data
&& !(setting.flags & ARDB_CMD_STALE))
{
ctx.AbortTransaction();
reply.SetErrCode(ERR_MASTER_DOWN);
return 0;
}
/* Loading DB? Return an error if the command has not the
* CMD_LOADING flag. */
if ((IsLoadingData() || IsRestoring(ctx, ctx.ns)) && !(setting.flags & ARDB_CMD_LOADING))
{
reply.SetErrCode(ERR_LOADING);
return 0;
}
if (ctx.InTransaction())
{
if (setting.type != REDIS_CMD_MULTI && setting.type != REDIS_CMD_EXEC && setting.type != REDIS_CMD_DISCARD
&& setting.type != REDIS_CMD_QUIT)
{
reply.SetStatusCode(STATUS_QUEUED);
args.ClearRawProtocolData();
ctx.GetTransaction().cached_cmds.push_back(args);
return 0;
}
}
else if (ctx.IsSubscribed())
{
if (setting.type != REDIS_CMD_SUBSCRIBE && setting.type != REDIS_CMD_PSUBSCRIBE
&& setting.type != REDIS_CMD_PUNSUBSCRIBE && setting.type != REDIS_CMD_UNSUBSCRIBE
&& setting.type != REDIS_CMD_QUIT)
{
reply.SetErrorReason("only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
return 0;
}
}
ret = DoCall(ctx, setting, args);
WakeClientsBlockingOnList(ctx);
return ret;
}
OP_NAMESPACE_END
|
#include <iostream>
using namespace std;
class Student {
private:
//attributes
int code;
char name[50];
int * grades;
int noGrades;
char* faculty;
public:
//methods
//constructor
Student() {
cout << endl << "Constructor called";
code = 0;
noGrades = 0;
this->grades = NULL;
strcpy(this->name, "John Doe");
// DON'T this->faculty = "CSIE";
this->faculty = new char[strlen("CSIE") + 1];
strcpy(this->faculty, "CSIE");
}
Student(char* name, int code, char*faculty) {
cout << endl << "Constructor called";
//shadowing
//code = code
this->code = code;
this->noGrades = 0;
this->grades = NULL;
strcpy(this->name, name);
this->faculty =
new char[strlen(faculty) + 1];
strcpy(this->faculty, faculty);
}
~Student() {
cout << endl << "Destructor !!!!!";
if (this->faculty != NULL)
delete [] this->faculty;
if (this->grades != NULL)
delete [] grades;
}
//copy constructor
Student(Student& student) {
cout << endl << "Copy constructor called";
this->code = student.code;
strcpy(this->name, student.name);
this->faculty = new char[strlen(student.faculty) + 1];
strcpy(this->faculty, student.faculty);
//grades
if (student.noGrades != 0) {
this->grades = new int[student.noGrades];
for (int i = 0; i < student.noGrades; i++)
grades[i] = student.grades[i];
this->noGrades = student.noGrades;
}
else
{
this->noGrades = 0;
this->grades = NULL;
}
}
public:
//accessor methods
//for reading
int getCode() {
return this->code;
}
char* getFaculty() {
return this->faculty;
}
char* getName() {
return this->name;
}
//write access
void setFaculty(char* newFaculty) {
//validating the input
if (strlen(newFaculty) >= 2) {
//this->faculty = newFaculty; DON'T
if (this->faculty != NULL)
delete [] this->faculty;
this->faculty = new char[strlen(newFaculty) + 1];
strcpy(this->faculty, newFaculty);
}
else {
throw exception("The name is too short!");
}
}
void operator=(Student s2) {
delete [] this->grades;
delete [] this->faculty;
cout << endl << "Operator = called";
this->code = s2.code;
strcpy(this->name, s2.name);
this->faculty = new char[strlen(s2.faculty) + 1];
strcpy(this->faculty, s2.faculty);
//grades
if (s2.noGrades != 0) {
this->grades = new int[s2.noGrades];
for (int i = 0; i < s2.noGrades; i++)
grades[i] = s2.grades[i];
this->noGrades = s2.noGrades;
}
else
{
this->noGrades = 0;
this->grades = NULL;
}
}
friend Student operator+(Student& s, int value);
};
Student operator+(Student& s, int value) {
Student result = s;
int* newGrades = new int[result.noGrades+1];
for (int i = 0; i < result.noGrades; i++)
newGrades[i] = result.grades[i];
newGrades[result.noGrades] = value;
delete [] result.grades;
result.grades = newGrades;
return result;
}
Student operator+(int value, Student& s) {
return s + value;
}
void displayStudent(Student& s) {
cout << endl << "The student name is "
<< s.getName() << ", the code is "
<< s.getCode() << " and the faculty is "
<< s.getFaculty();
}
//overloading operators
//s1 = s2
//s1 = s2 = s3;
//void operator=(Student s1, Student s2) {
//
//}
void main() {
//Student student1;
Student student2("John", 3, "MAN");
displayStudent(student2);
//displayStudent(student2);
//change faculty
//student2.setFaculty("CSIE");
//displayStudent(student2);
//calling the copy-constructor
cout << endl << "Test copy constructor";
Student student3 = student2;
displayStudent(student3);
Student student4;
student4 = student2;
student4 = student4 + 9;
displayStudent(student3);
}
|
/**
* @file
* database.cc
**/
#include "AppHdr.h"
#include "database.h"
#include <cstdlib>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef TARGET_COMPILER_VC
#include <unistd.h>
#endif
#include "clua.h"
#include "end.h"
#include "files.h"
#include "libutil.h"
#include "options.h"
#include "random.h"
#include "stringutil.h"
#include "syscalls.h"
#include "threads.h"
#include "unicode.h"
// TextDB handles dependency checking the db vs text files, creating the
// db, loading, and destroying the DB.
class TextDB
{
public:
// db_name is the savedir-relative name of the db file,
// minus the "db" extension.
TextDB(const char* db_name, const char* dir, vector<string> files);
TextDB(TextDB *parent);
~TextDB() { shutdown(true); delete translation; }
void init();
void shutdown(bool recursive = false);
DBM* get() { return _db; }
// Make it easier to migrate from raw DBM* to TextDB
operator bool() const { return _db != 0; }
operator DBM*() const { return _db; }
private:
bool _needs_update() const;
void _regenerate_db();
private:
bool open_db();
const char* const _db_name;
string _directory;
vector<string> _input_files;
DBM* _db;
string timestamp;
TextDB *_parent;
const char* lang() { return _parent ? Options.lang_name : 0; }
public:
TextDB *translation;
};
// Convenience functions for (read-only) access to generic
// berkeley DB databases.
static void _store_text_db(const string &in, DBM *db);
static string _query_database(TextDB &db, string key, bool canonicalise_key,
bool run_lua, bool untranslated = false);
static void _add_entry(DBM *db, const string &k, string &v);
static TextDB AllDBs[] =
{
TextDB("descriptions", "descript/",
{ "features.txt",
"items.txt",
"unident.txt",
"unrand.txt",
"monsters.txt",
"spells.txt",
"gods.txt",
"branches.txt",
"skills.txt",
"ability.txt",
"cards.txt",
"commands.txt",
"clouds.txt",
"status.txt" }),
TextDB("gamestart", "descript/",
{ "species.txt",
"backgrounds.txt",
"pledges.txt"}),
TextDB("randart", "database/",
{ "randname.txt",
"rand_wpn.txt", // mostly weapons
"rand_arm.txt", // mostly armour
"rand_all.txt", // jewellery and general
"randbook.txt", // artefact books
// This doesn't really belong here, but they *are* god gifts...
"monname.txt" // orcish names for Beogh to choose from
}),
TextDB("speak", "database/",
{ "monspeak.txt", // monster speech
"monspell.txt", // monster spellcasting speech
"monflee.txt", // monster fleeing speech
"wpnnoise.txt", // noisy weapon speech
"insult.txt", // imp/demon taunts
"godspeak.txt" // god speech
}),
TextDB("shout", "database/",
{ "shout.txt",
"insult.txt" // imp/demon taunts, again
}),
TextDB("misc", "database/",
{ "miscname.txt", // names for miscellaneous things
"godname.txt", // god-related names (mostly His Xomminess)
"montitle.txt", // titles for monsters (i.e. uniques)
}),
TextDB("quotes", "descript/",
{ "quotes.txt" // quotes for items and monsters
}),
TextDB("help", "database/",
{ "help.txt" // database for outsourced help texts
}),
TextDB("FAQ", "database/",
{ "FAQ.txt", // database for Frequently Asked Questions
}),
TextDB("hints", "descript/",
{ "hints.txt", // hints mode
"tutorial.txt", // tutorial mode
}),
};
static TextDB& DescriptionDB = AllDBs[0];
static TextDB& GameStartDB = AllDBs[1];
static TextDB& RandartDB = AllDBs[2];
static TextDB& SpeakDB = AllDBs[3];
static TextDB& ShoutDB = AllDBs[4];
static TextDB& MiscDB = AllDBs[5];
static TextDB& QuotesDB = AllDBs[6];
static TextDB& HelpDB = AllDBs[7];
static TextDB& FAQDB = AllDBs[8];
static TextDB& HintsDB = AllDBs[9];
static string _db_cache_path(string db, const char *lang)
{
if (lang)
db = db + "." + lang;
return savedir_versioned_path("db/" + db);
}
// ----------------------------------------------------------------------
// TextDB
// ----------------------------------------------------------------------
TextDB::TextDB(const char* db_name, const char* dir, vector<string> files)
: _db_name(db_name), _directory(dir), _input_files(files),
_db(nullptr), timestamp(""), _parent(0), translation(0)
{
}
TextDB::TextDB(TextDB *parent)
: _db_name(parent->_db_name),
_directory(parent->_directory + Options.lang_name + "/"),
_input_files(parent->_input_files), // FIXME: pointless copy
_db(nullptr), timestamp(""), _parent(parent), translation(nullptr)
{
}
bool TextDB::open_db()
{
if (_db)
return true;
const string full_db_path = _db_cache_path(_db_name, lang());
_db = dbm_open(full_db_path.c_str(), O_RDONLY, 0660);
if (!_db)
return false;
timestamp = _query_database(*this, "TIMESTAMP", false, false, true);
if (timestamp.empty())
return false;
return true;
}
void TextDB::init()
{
if (Options.lang_name && !_parent)
{
translation = new TextDB(this);
translation->init();
}
open_db();
if (!_needs_update())
return;
_regenerate_db();
if (!open_db())
{
end(1, true, "Failed to open DB: %s",
_db_cache_path(_db_name, lang()).c_str());
}
}
void TextDB::shutdown(bool recursive)
{
if (_db)
{
dbm_close(_db);
_db = nullptr;
}
if (recursive && translation)
translation->shutdown(recursive);
}
bool TextDB::_needs_update() const
{
string ts;
bool no_files = true;
for (const string &file : _input_files)
{
string full_input_path = _directory + file;
full_input_path = datafile_path(full_input_path, !_parent);
time_t mtime = file_modtime(full_input_path);
#ifdef __ANDROID__
if (file_exists(full_input_path))
#else
if (mtime)
#endif
no_files = false;
char buf[20];
snprintf(buf, sizeof(buf), ":%" PRId64, (int64_t)mtime);
ts += buf;
}
if (no_files && timestamp.empty())
{
// No point in empty databases, although for simplicity keep ones
// for disappeared translations for now.
ASSERT(_parent);
TextDB *en = _parent;
delete en->translation; // ie, ourself
en->translation = 0;
return false;
}
return ts != timestamp;
}
void TextDB::_regenerate_db()
{
shutdown();
#ifdef DEBUG_DIAGNOSTICS
if (_parent)
printf("Regenerating db: %s [%s]\n", _db_name, Options.lang_name);
else
printf("Regenerating db: %s\n", _db_name);
#endif
string db_path = _db_cache_path(_db_name, lang());
string full_db_path = db_path + ".db";
{
string output_dir = get_parent_directory(db_path);
if (!check_mkdir("DB directory", &output_dir))
end(1);
}
file_lock lock(db_path + ".lk", "wb");
#ifndef DGL_REWRITE_PROTECT_DB_FILES
unlink_u(full_db_path.c_str());
#endif
string ts;
if (!(_db = dbm_open(db_path.c_str(), O_RDWR | O_CREAT, 0660)))
end(1, true, "Unable to open DB: %s", db_path.c_str());
for (const string &file : _input_files)
{
string full_input_path = _directory + file;
full_input_path = datafile_path(full_input_path, !_parent);
char buf[20];
time_t mtime = file_modtime(full_input_path);
snprintf(buf, sizeof(buf), ":%" PRId64, (int64_t)mtime);
ts += buf;
if (
#ifdef __ANDROID__
file_exists(full_input_path)
#else
mtime
#endif
|| !_parent) // english is mandatory
{
_store_text_db(full_input_path, _db);
}
}
_add_entry(_db, "TIMESTAMP", ts);
dbm_close(_db);
_db = 0;
}
// ----------------------------------------------------------------------
// DB system
// ----------------------------------------------------------------------
#define NUM_DB ARRAYSZ(AllDBs)
void databaseSystemInit()
{
for (unsigned int i = 0; i < NUM_DB; i++)
AllDBs[i].init();
}
void databaseSystemShutdown()
{
for (unsigned int i = 0; i < NUM_DB; i++)
AllDBs[i].shutdown(true);
}
////////////////////////////////////////////////////////////////////////////
// Main DB functions
static datum _database_fetch(DBM *database, const string &key)
{
datum result;
result.dptr = nullptr;
result.dsize = 0;
datum dbKey;
dbKey.dptr = (DPTR_COERCE) key.c_str();
dbKey.dsize = key.length();
// Don't use the database if called from "monster".
if (database)
result = dbm_fetch(database, dbKey);
return result;
}
static vector<string> _database_find_keys(DBM *database,
const string ®ex,
bool ignore_case,
db_find_filter filter = nullptr)
{
text_pattern tpat(regex, ignore_case);
vector<string> matches;
datum dbKey = dbm_firstkey(database);
while (dbKey.dptr != nullptr)
{
string key((const char *)dbKey.dptr, dbKey.dsize);
if (tpat.matches(key)
&& key.find("__") == string::npos
&& (filter == nullptr || !(*filter)(key, "")))
{
matches.push_back(key);
}
dbKey = dbm_nextkey(database);
}
return matches;
}
static vector<string> _database_find_bodies(DBM *database,
const string ®ex,
bool ignore_case,
db_find_filter filter = nullptr)
{
text_pattern tpat(regex, ignore_case);
vector<string> matches;
datum dbKey = dbm_firstkey(database);
while (dbKey.dptr != nullptr)
{
string key((const char *)dbKey.dptr, dbKey.dsize);
datum dbBody = dbm_fetch(database, dbKey);
string body((const char *)dbBody.dptr, dbBody.dsize);
if (tpat.matches(body)
&& key.find("__") == string::npos
&& (filter == nullptr || !(*filter)(key, body)))
{
matches.push_back(key);
}
dbKey = dbm_nextkey(database);
}
return matches;
}
///////////////////////////////////////////////////////////////////////////
// Internal DB utility functions
static void _execute_embedded_lua(string &str)
{
// Execute any lua code found between "{{" and "}}". The lua code
// is expected to return a string, with which the lua code and
// braces will be replaced.
string::size_type pos = str.find("{{");
while (pos != string::npos)
{
string::size_type end = str.find("}}", pos + 2);
if (end == string::npos)
{
mprf(MSGCH_DIAGNOSTICS, "Unbalanced {{, bailing.");
break;
}
string lua_full = str.substr(pos, end - pos + 2);
string lua = str.substr(pos + 2, end - pos - 2);
if (clua.execstring(lua.c_str(), "db_embedded_lua", 1))
{
string err = "{{" + clua.error + "}}";
str.replace(pos, lua_full.length(), err);
return;
}
string result;
clua.fnreturns(">s", &result);
str.replace(pos, lua_full.length(), result);
pos = str.find("{{", pos + result.length());
}
}
static void _trim_leading_newlines(string &s)
{
s.erase(0, s.find_first_not_of("\n"));
}
static void _add_entry(DBM *db, const string &k, string &v)
{
_trim_leading_newlines(v);
datum key, value;
key.dptr = (char *) k.c_str();
key.dsize = k.length();
value.dptr = (char *) v.c_str();
value.dsize = v.length();
if (dbm_store(db, key, value, DBM_REPLACE))
end(1, true, "Error storing %s", k.c_str());
}
static void _parse_text_db(LineInput &inf, DBM *db)
{
string key;
string value;
bool in_entry = false;
while (!inf.eof())
{
string line = inf.get_line();
if (!line.empty() && line[0] == '#')
continue;
if (!line.compare(0, 4, "%%%%"))
{
if (!key.empty())
_add_entry(db, key, value);
key.clear();
value.clear();
in_entry = true;
continue;
}
if (!in_entry)
continue;
if (key.empty())
{
key = line;
trim_string(key);
lowercase(key);
}
else
{
trim_string_right(line);
value += line + "\n";
}
}
if (!key.empty())
_add_entry(db, key, value);
}
static void _store_text_db(const string &in, DBM *db)
{
UTF8FileLineInput inf(in.c_str());
if (inf.error())
end(1, true, "Unable to open input file: %s", in.c_str());
_parse_text_db(inf, db);
}
static string _chooseStrByWeight(string entry, int fixed_weight = -1)
{
vector<string> parts;
vector<int> weights;
vector<string> lines = split_string("\n", entry, false, true);
int total_weight = 0;
for (int i = 0, size = lines.size(); i < size; i++)
{
// Skip over multiple blank lines, and leading and trailing
// blank lines.
while (i < size && lines[i].empty())
i++;
if (i == size)
break;
int weight;
string part = "";
if (sscanf(lines[i].c_str(), "w:%d", &weight))
{
i++;
if (i == size)
return "BUG, WEIGHT AT END OF ENTRY";
}
else
weight = 10;
total_weight += weight;
while (i < size && !lines[i].empty())
{
part += lines[i++];
part += "\n";
}
trim_string(part);
parts.push_back(part);
weights.push_back(total_weight);
}
if (parts.empty())
return "BUG, EMPTY ENTRY";
int choice = 0;
if (fixed_weight != -1)
choice = fixed_weight % total_weight;
else
choice = random2(total_weight);
for (int i = 0, size = parts.size(); i < size; i++)
if (choice < weights[i])
return parts[i];
return "BUG, NO STRING CHOSEN";
}
#define MAX_RECURSION_DEPTH 10
#define MAX_REPLACEMENTS 100
static string _getWeightedString(TextDB &db, const string &key,
const string &suffix, int fixed_weight = -1)
{
// We have to canonicalise the key (in case the user typed it
// in and got the case wrong.)
string canonical_key = key + suffix;
lowercase(canonical_key);
// Query the DB.
datum result;
if (db.translation)
result = _database_fetch(db.translation->get(), canonical_key);
if (result.dsize <= 0)
result = _database_fetch(db.get(), canonical_key);
if (result.dsize <= 0)
{
// Try ignoring the suffix.
canonical_key = key;
lowercase(canonical_key);
// Query the DB.
if (db.translation)
result = _database_fetch(db.translation->get(), canonical_key);
if (result.dsize <= 0)
result = _database_fetch(db.get(), canonical_key);
if (result.dsize <= 0)
return "";
}
// Cons up a (C++) string to return. The caller must release it.
string str = string((const char *)result.dptr, result.dsize);
return _chooseStrByWeight(str, fixed_weight);
}
static void _call_recursive_replacement(string &str, TextDB &db,
const string &suffix,
int &num_replacements,
int recursion_depth = 0);
static string _getRandomisedStr(TextDB &db, const string &key,
const string &suffix,
int &num_replacements,
int recursion_depth = 0)
{
recursion_depth++;
if (recursion_depth > MAX_RECURSION_DEPTH)
{
mprf(MSGCH_DIAGNOSTICS, "Too many nested replacements, bailing.");
return "TOO MUCH RECURSION";
}
string str = _getWeightedString(db, key, suffix);
_call_recursive_replacement(str, db, suffix, num_replacements,
recursion_depth);
return str;
}
// Replace any "@foo@" markers that can be found in this database.
// Those that can't be found are left alone for the caller to deal with.
static void _call_recursive_replacement(string &str, TextDB &db,
const string &suffix,
int &num_replacements,
int recursion_depth)
{
string::size_type pos = str.find("@");
while (pos != string::npos)
{
num_replacements++;
if (num_replacements > MAX_REPLACEMENTS)
{
mprf(MSGCH_DIAGNOSTICS, "Too many string replacements, bailing.");
return;
}
string::size_type end = str.find("@", pos + 1);
if (end == string::npos)
{
mprf(MSGCH_DIAGNOSTICS, "Unbalanced @, bailing.");
break;
}
string marker_full = str.substr(pos, end - pos + 1);
string marker = str.substr(pos + 1, end - pos - 1);
string replacement =
_getRandomisedStr(db, marker, suffix, num_replacements,
recursion_depth);
if (replacement.empty())
{
// Nothing in database, leave it alone and go onto next @foo@
pos = str.find("@", end + 1);
}
else
{
str.replace(pos, marker_full.length(), replacement);
// Start search from pos rather than end + 1, so that if
// the replacement contains its own @foo@, we can replace
// that too.
pos = str.find("@", pos);
}
} // while (pos != string::npos)
}
static string _query_database(TextDB &db, string key, bool canonicalise_key,
bool run_lua, bool untranslated)
{
if (canonicalise_key)
{
// We have to canonicalise the key (in case the user typed it
// in and got the case wrong.)
lowercase(key);
}
// Query the DB.
datum result;
if (db.translation && !untranslated)
result = _database_fetch(db.translation->get(), key);
if (result.dsize <= 0)
result = _database_fetch(db.get(), key);
if (result.dsize <= 0)
return "";
string str((const char *)result.dptr, result.dsize);
// <foo> is an alias to key foo
if (str[0] == '<' && str[str.size() - 2] == '>'
&& str.find('<', 1) == str.npos
&& str.find('\n') == str.size() - 1)
{
return _query_database(db, str.substr(1, str.size() - 3),
canonicalise_key, run_lua, untranslated);
}
if (run_lua)
_execute_embedded_lua(str);
return str;
}
/////////////////////////////////////////////////////////////////////////////
// Quote DB specific functions.
string getQuoteString(const string &key)
{
return unwrap_desc(_query_database(QuotesDB, key, true, true));
}
/////////////////////////////////////////////////////////////////////////////
// Description DB specific functions.
string getLongDescription(const string &key)
{
return unwrap_desc(_query_database(DescriptionDB, key, true, true));
}
vector<string> getLongDescKeysByRegex(const string ®ex,
db_find_filter filter)
{
if (!DescriptionDB.get())
{
vector<string> empty;
return empty;
}
// FIXME: need to match regex against translated keys, which can't
// be done by db only.
return _database_find_keys(DescriptionDB.get(), regex, true, filter);
}
vector<string> getLongDescBodiesByRegex(const string ®ex,
db_find_filter filter)
{
if (!DescriptionDB.get())
{
vector<string> empty;
return empty;
}
// On partial translations, this will match only translated descriptions.
// Not good, but otherwise we'd have to check hundreds of keys, with
// two queries for each.
// SQL can do this in one go, DBM can't.
DBM *database = DescriptionDB.translation ?
DescriptionDB.translation->get() : DescriptionDB.get();
return _database_find_bodies(database, regex, true, filter);
}
/////////////////////////////////////////////////////////////////////////////
// GameStart DB specific functions.
string getGameStartDescription(const string &key)
{
return _query_database(GameStartDB, key, true, true);
}
/////////////////////////////////////////////////////////////////////////////
// Shout DB specific functions.
string getShoutString(const string &monst, const string &suffix)
{
int num_replacements = 0;
return _getRandomisedStr(ShoutDB, monst, suffix, num_replacements);
}
/////////////////////////////////////////////////////////////////////////////
// Speak DB specific functions.
string getSpeakString(const string &key)
{
int num_replacements = 0;
#ifdef DEBUG_MONSPEAK
dprf(DIAG_SPEECH, "monster speech lookup for %s", key.c_str());
#endif
string txt = _getRandomisedStr(SpeakDB, key, "", num_replacements);
_execute_embedded_lua(txt);
return txt;
}
/////////////////////////////////////////////////////////////////////////////
// Randname DB specific functions.
string getRandNameString(const string &itemtype, const string &suffix)
{
int num_replacements = 0;
return _getRandomisedStr(RandartDB, itemtype, suffix, num_replacements);
}
/////////////////////////////////////////////////////////////////////////////
// Help DB specific functions.
string getHelpString(const string &topic)
{
string help = _query_database(HelpDB, topic, false, true);
if (help.empty())
help = "Error! The help for \"" + topic + "\" is missing!";
return help;
}
/////////////////////////////////////////////////////////////////////////////
// FAQ DB specific functions.
vector<string> getAllFAQKeys()
{
if (!FAQDB.get())
{
vector<string> empty;
return empty;
}
return _database_find_keys(FAQDB.get(), "^q.+", false);
}
string getFAQ_Question(const string &key)
{
return _query_database(FAQDB, key, false, true);
}
string getFAQ_Answer(const string &question)
{
string key = "a" + question.substr(1, question.length()-1);
string val = unwrap_desc(_query_database(FAQDB, key, false, true));
// Remove blank lines between items on a bulleted list, for small
// terminals' sake. Far easier to store them as separated paragraphs
// in the source.
// Also, use a nicer bullet as we're already here.
val = replace_all(val, "\n\n*", "\n•");
return val;
}
/////////////////////////////////////////////////////////////////////////////
// Miscellaneous DB specific functions.
string getMiscString(const string &misc, const string &suffix)
{
int num_replacements = 0;
string txt = _getRandomisedStr(MiscDB, misc, suffix, num_replacements);
_execute_embedded_lua(txt);
return txt;
}
/////////////////////////////////////////////////////////////////////////////
// Hints DB specific functions.
string getHintString(const string &key)
{
return unwrap_desc(_query_database(HintsDB, key, true, true));
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.