text
stringlengths 54
60.6k
|
---|
<commit_before>/**
* \file
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/internal/scheduler/getScheduler.hpp"
#include "distortos/internal/scheduler/Scheduler.hpp"
#include "distortos/chip/CMSIS-proxy.h"
namespace distortos
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Wrapper for void* distortos::internal::getScheduler().switchContext(void*)
*
* \param [in] stackPointer is the current value of current thread's stack pointer
*
* \return new thread's stack pointer
*/
void* schedulerSwitchContextWrapper(void* const stackPointer)
{
return internal::getScheduler().switchContext(stackPointer);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* Performs the context switch.
*/
extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
constexpr auto basepriValue = CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI << (8 - __NVIC_PRIO_BITS);
static_assert(basepriValue > 0 && basepriValue <= UINT8_MAX,
"Invalid CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI value!");
asm volatile
(
" mov r0, %[basepriValue] \n"
" msr basepri, r0 \n" // enable interrupt masking
:: [basepriValue] "i" (basepriValue)
);
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
asm volatile
(
" cpsid i \n" // disable interrupts
);
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
asm volatile
(
" mrs r0, PSP \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vstmdbeq r0!, {s16-s31} \n" // save "floating-point" context of current thread
// save "regular" context of current thread (r12 is saved just to keep double-word alignment)
" stmdb r0!, {r4-r12, lr} \n"
#else
" stmdb r0!, {r4-r11} \n" // save context of current thread
" mov r4, lr \n"
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" \n"
" bl %[schedulerSwitchContext] \n" // switch context
" \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" ldmia r0!, {r4-r12, lr} \n" // load "regular" context of new thread
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vldmiaeq r0!, {s16-s31} \n" // load "floating-point" context of new thread
#else
" mov lr, r4 \n"
" ldmia r0!, {r4-r11} \n" // load context of new thread
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" msr PSP, r0 \n"
:: [schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
);
asm volatile
(
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
" mov r0, #0 \n"
" msr basepri, r0 \n" // disable interrupt masking
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" cpsie i \n" // enable interrupts
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" \n"
" bx lr \n" // return to new thread
);
__builtin_unreachable();
}
} // namespace distortos
<commit_msg>Modify ARMv7-M-PendSV_Handler.cpp to work for ARMv6-M too<commit_after>/**
* \file
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/internal/scheduler/getScheduler.hpp"
#include "distortos/internal/scheduler/Scheduler.hpp"
#include "distortos/chip/CMSIS-proxy.h"
namespace distortos
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Wrapper for void* distortos::internal::getScheduler().switchContext(void*)
*
* \param [in] stackPointer is the current value of current thread's stack pointer
*
* \return new thread's stack pointer
*/
void* schedulerSwitchContextWrapper(void* const stackPointer)
{
return internal::getScheduler().switchContext(stackPointer);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* Performs the context switch.
*/
extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
constexpr auto basepriValue = CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI << (8 - __NVIC_PRIO_BITS);
static_assert(basepriValue > 0 && basepriValue <= UINT8_MAX,
"Invalid CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI value!");
asm volatile
(
" mov r0, %[basepriValue] \n"
" msr basepri, r0 \n" // enable interrupt masking
:: [basepriValue] "i" (basepriValue)
);
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
asm volatile
(
" cpsid i \n" // disable interrupts
);
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
#ifdef __ARM_ARCH_6M__
asm volatile
(
" mrs r0, PSP \n"
" sub r0, #0x10 \n"
" stmia r0!, {r4-r7} \n" // save lower half of current thread's context
" mov r4, r8 \n"
" mov r5, r9 \n"
" mov r6, r10 \n"
" mov r7, r11 \n"
" sub r0, #0x20 \n"
" stmia r0!, {r4-r7} \n" // save upper half of current thread's context
" sub r0, #0x10 \n"
" mov r4, lr \n"
" \n"
" ldr r1, =%[schedulerSwitchContext] \n"
" blx r1 \n" // switch context
" \n"
" mov lr, r4 \n"
" ldmia r0!, {r4-r7} \n" // load upper half of new thread's context
" mov r8, r4 \n"
" mov r9, r5 \n"
" mov r10, r6 \n"
" mov r11, r7 \n"
" ldmia r0!, {r4-r7} \n" // load lower half of new thread's context
" msr PSP, r0 \n"
:: [schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
);
#else // !def __ARM_ARCH_6M__
asm volatile
(
" mrs r0, PSP \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vstmdbeq r0!, {s16-s31} \n" // save "floating-point" context of current thread
// save "regular" context of current thread (r12 is saved just to keep double-word alignment)
" stmdb r0!, {r4-r12, lr} \n"
#else
" stmdb r0!, {r4-r11} \n" // save context of current thread
" mov r4, lr \n"
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" \n"
" bl %[schedulerSwitchContext] \n" // switch context
" \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" ldmia r0!, {r4-r12, lr} \n" // load "regular" context of new thread
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vldmiaeq r0!, {s16-s31} \n" // load "floating-point" context of new thread
#else
" mov lr, r4 \n"
" ldmia r0!, {r4-r11} \n" // load context of new thread
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" msr PSP, r0 \n"
:: [schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
);
#endif // !def __ARM_ARCH_6M__
asm volatile
(
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
" mov r0, #0 \n"
" msr basepri, r0 \n" // disable interrupt masking
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" cpsie i \n" // enable interrupts
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" \n"
" bx lr \n" // return to new thread
);
__builtin_unreachable();
}
} // namespace distortos
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "autocalib.hpp"
#include "util.hpp"
using namespace std;
using namespace cv;
void focalsFromHomography(const Mat& H, double &f0, double &f1, bool &f0_ok, bool &f1_ok)
{
CV_Assert(H.type() == CV_64F && H.size() == Size(3, 3));
const double* h = reinterpret_cast<const double*>(H.data);
double d1, d2; // Denominators
double v1, v2; // Focal squares value candidates
f1_ok = true;
d1 = h[6] * h[7];
d2 = (h[7] - h[6]) * (h[7] + h[6]);
v1 = -(h[0] * h[1] + h[3] * h[4]) / d1;
v2 = (h[0] * h[0] + h[3] * h[3] - h[1] * h[1] - h[4] * h[4]) / d2;
if (v1 < v2) swap(v1, v2);
if (v1 > 0 && v2 > 0) f1 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
else if (v1 > 0) f1 = sqrt(v1);
else f1_ok = false;
f0_ok = true;
d1 = h[0] * h[3] + h[1] * h[4];
d2 = h[0] * h[0] + h[1] * h[1] - h[3] * h[3] - h[4] * h[4];
v1 = -h[2] * h[5] / d1;
v2 = (h[5] * h[5] - h[2] * h[2]) / d2;
if (v1 < v2) swap(v1, v2);
if (v1 > 0 && v2 > 0) f0 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
else if (v1 > 0) f0 = sqrt(v1);
else f0_ok = false;
}
void estimateFocal(const vector<ImageFeatures> &features, const vector<MatchesInfo> &pairwise_matches,
vector<double> &focals)
{
const int num_images = static_cast<int>(features.size());
focals.resize(num_images);
vector<double> all_focals;
for (int i = 0; i < num_images; ++i)
{
for (int j = 0; j < num_images; ++j)
{
const MatchesInfo &m = pairwise_matches[i*num_images + j];
if (m.H.empty())
continue;
double f0, f1;
bool f0ok, f1ok;
focalsFromHomography(m.H, f0, f1, f0ok, f1ok);
if (f0ok && f1ok)
all_focals.push_back(sqrt(f0 * f1));
}
}
if (static_cast<int>(all_focals.size()) < num_images - 1)
{
LOGLN("Can't estimate focal length, will use anaive approach");
double focals_sum = 0;
for (int i = 0; i < num_images; ++i)
focals_sum += features[i].img_size.width + features[i].img_size.height;
for (int i = 0; i < num_images; ++i)
focals[i] = focals_sum / num_images;
}
else
{
nth_element(all_focals.begin(), all_focals.begin() + all_focals.size()/2, all_focals.end());
for (int i = 0; i < num_images; ++i)
focals[i] = all_focals[all_focals.size()/2];
}
}
<commit_msg>fixed typo in opencv_stitching <commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "autocalib.hpp"
#include "util.hpp"
using namespace std;
using namespace cv;
void focalsFromHomography(const Mat& H, double &f0, double &f1, bool &f0_ok, bool &f1_ok)
{
CV_Assert(H.type() == CV_64F && H.size() == Size(3, 3));
const double* h = reinterpret_cast<const double*>(H.data);
double d1, d2; // Denominators
double v1, v2; // Focal squares value candidates
f1_ok = true;
d1 = h[6] * h[7];
d2 = (h[7] - h[6]) * (h[7] + h[6]);
v1 = -(h[0] * h[1] + h[3] * h[4]) / d1;
v2 = (h[0] * h[0] + h[3] * h[3] - h[1] * h[1] - h[4] * h[4]) / d2;
if (v1 < v2) swap(v1, v2);
if (v1 > 0 && v2 > 0) f1 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
else if (v1 > 0) f1 = sqrt(v1);
else f1_ok = false;
f0_ok = true;
d1 = h[0] * h[3] + h[1] * h[4];
d2 = h[0] * h[0] + h[1] * h[1] - h[3] * h[3] - h[4] * h[4];
v1 = -h[2] * h[5] / d1;
v2 = (h[5] * h[5] - h[2] * h[2]) / d2;
if (v1 < v2) swap(v1, v2);
if (v1 > 0 && v2 > 0) f0 = sqrt(abs(d1) > abs(d2) ? v1 : v2);
else if (v1 > 0) f0 = sqrt(v1);
else f0_ok = false;
}
void estimateFocal(const vector<ImageFeatures> &features, const vector<MatchesInfo> &pairwise_matches,
vector<double> &focals)
{
const int num_images = static_cast<int>(features.size());
focals.resize(num_images);
vector<double> all_focals;
for (int i = 0; i < num_images; ++i)
{
for (int j = 0; j < num_images; ++j)
{
const MatchesInfo &m = pairwise_matches[i*num_images + j];
if (m.H.empty())
continue;
double f0, f1;
bool f0ok, f1ok;
focalsFromHomography(m.H, f0, f1, f0ok, f1ok);
if (f0ok && f1ok)
all_focals.push_back(sqrt(f0 * f1));
}
}
if (static_cast<int>(all_focals.size()) >= num_images - 1)
{
nth_element(all_focals.begin(), all_focals.begin() + all_focals.size()/2, all_focals.end());
for (int i = 0; i < num_images; ++i)
focals[i] = all_focals[all_focals.size()/2];
}
else
{
LOGLN("Can't estimate focal length, will use naive approach");
double focals_sum = 0;
for (int i = 0; i < num_images; ++i)
focals_sum += features[i].img_size.width + features[i].img_size.height;
for (int i = 0; i < num_images; ++i)
focals[i] = focals_sum / num_images;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Ford Motor Company
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 Ford Motor Company 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 "policy/update_status_manager.h"
#include "policy/policy_listener.h"
#include "utils/logger.h"
namespace policy {
CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
UpdateStatusManager::UpdateStatusManager()
: listener_(NULL)
, exchange_in_progress_(false)
, update_required_(false)
, update_scheduled_(false)
, exchange_pending_(false)
, apps_search_in_progress_(false)
, app_registered_from_non_consented_device_(false)
, last_update_status_(policy::StatusUnknown) {
update_status_thread_delegate_ = new UpdateThreadDelegate(this);
thread_ = threads::CreateThread("UpdateStatusThread",
update_status_thread_delegate_);
thread_->start();
}
UpdateStatusManager::~UpdateStatusManager() {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(update_status_thread_delegate_);
DCHECK(thread_);
thread_->join();
delete update_status_thread_delegate_;
threads::DeleteThread(thread_);
}
void UpdateStatusManager::set_listener(PolicyListener* listener) {
listener_ = listener;
}
void UpdateStatusManager::OnUpdateSentOut(uint32_t update_timeout) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(update_status_thread_delegate_);
const unsigned milliseconds_in_second = 1000;
update_status_thread_delegate_->updateTimeOut(update_timeout *
milliseconds_in_second);
set_exchange_in_progress(true);
set_exchange_pending(true);
set_update_required(false);
}
void UpdateStatusManager::OnUpdateTimeoutOccurs() {
LOG4CXX_AUTO_TRACE(logger_);
set_update_required(true);
set_exchange_in_progress(false);
set_exchange_pending(false);
DCHECK(update_status_thread_delegate_);
update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
}
void UpdateStatusManager::OnValidUpdateReceived() {
LOG4CXX_AUTO_TRACE(logger_);
update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
set_exchange_pending(false);
set_exchange_in_progress(false);
}
void UpdateStatusManager::OnWrongUpdateReceived() {
LOG4CXX_AUTO_TRACE(logger_);
update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
set_update_required(true);
set_exchange_in_progress(false);
set_exchange_pending(false);
}
void UpdateStatusManager::OnResetDefaultPT(bool is_update_required) {
LOG4CXX_AUTO_TRACE(logger_);
exchange_in_progress_ = false;
update_required_ = is_update_required;
exchange_pending_ = false;
last_update_status_ = policy::StatusUnknown;
}
void UpdateStatusManager::OnResetRetrySequence() {
LOG4CXX_AUTO_TRACE(logger_);
if (exchange_in_progress_) {
set_exchange_pending(true);
}
set_update_required(true);
}
void UpdateStatusManager::OnNewApplicationAdded(const DeviceConsent consent) {
LOG4CXX_AUTO_TRACE(logger_);
if (kDeviceAllowed != consent) {
app_registered_from_non_consented_device_ = true;
return;
}
app_registered_from_non_consented_device_ = false;
set_update_required(true);
}
void UpdateStatusManager::OnPolicyInit(bool is_update_required) {
LOG4CXX_AUTO_TRACE(logger_);
update_required_ = is_update_required;
}
void UpdateStatusManager::OnDeviceConsented() {
LOG4CXX_AUTO_TRACE(logger_);
if (app_registered_from_non_consented_device_) {
set_update_required(true);
}
}
PolicyTableStatus UpdateStatusManager::GetUpdateStatus() const {
LOG4CXX_AUTO_TRACE(logger_);
if (!exchange_in_progress_ && !exchange_pending_ && !update_required_) {
return PolicyTableStatus::StatusUpToDate;
}
if (update_required_ && !exchange_in_progress_ && !exchange_pending_) {
return PolicyTableStatus::StatusUpdateRequired;
}
return PolicyTableStatus::StatusUpdatePending;
}
bool UpdateStatusManager::IsUpdateRequired() const {
return update_required_ || update_scheduled_;
}
bool UpdateStatusManager::IsUpdatePending() const {
return exchange_pending_;
}
void UpdateStatusManager::ScheduleUpdate() {
update_scheduled_ = true;
update_required_ = true;
}
void UpdateStatusManager::ResetUpdateSchedule() {
update_scheduled_ = false;
}
std::string UpdateStatusManager::StringifiedUpdateStatus() const {
switch (GetUpdateStatus()) {
case policy::StatusUpdatePending:
return "UPDATING";
case policy::StatusUpdateRequired:
return "UPDATE_NEEDED";
case policy::StatusUpToDate:
return "UP_TO_DATE";
default: { return "UNKNOWN"; }
}
}
void policy::UpdateStatusManager::OnAppsSearchStarted() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
apps_search_in_progress_ = true;
}
void policy::UpdateStatusManager::OnAppsSearchCompleted() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
apps_search_in_progress_ = false;
}
bool policy::UpdateStatusManager::IsAppsSearchInProgress() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
return apps_search_in_progress_;
}
void UpdateStatusManager::CheckUpdateStatus() {
LOG4CXX_AUTO_TRACE(logger_);
policy::PolicyTableStatus status = GetUpdateStatus();
if (listener_ && last_update_status_ != status) {
LOG4CXX_INFO(logger_, "Send OnUpdateStatusChanged");
listener_->OnUpdateStatusChanged(StringifiedUpdateStatus());
}
last_update_status_ = status;
}
void UpdateStatusManager::set_exchange_in_progress(bool value) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(exchange_in_progress_lock_);
LOG4CXX_INFO(logger_,
"Exchange in progress value is:" << std::boolalpha << value);
exchange_in_progress_ = value;
CheckUpdateStatus();
}
void UpdateStatusManager::set_exchange_pending(bool value) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(exchange_pending_lock_);
LOG4CXX_INFO(logger_,
"Exchange pending value is:" << std::boolalpha << value);
exchange_pending_ = value;
CheckUpdateStatus();
}
void UpdateStatusManager::set_update_required(bool value) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(update_required_lock_);
LOG4CXX_INFO(logger_, "Update required value is:" << std::boolalpha << value);
update_required_ = value;
CheckUpdateStatus();
}
UpdateStatusManager::UpdateThreadDelegate::UpdateThreadDelegate(
UpdateStatusManager* update_status_manager)
: timeout_(0)
, stop_flag_(false)
, state_lock_(true)
, update_status_manager_(update_status_manager) {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Create UpdateThreadDelegate");
}
UpdateStatusManager::UpdateThreadDelegate::~UpdateThreadDelegate() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Delete UpdateThreadDelegate");
}
void UpdateStatusManager::UpdateThreadDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "UpdateStatusManager thread started (started normal)");
sync_primitives::AutoLock auto_lock(state_lock_);
while (false == stop_flag_) {
if (timeout_ > 0) {
LOG4CXX_DEBUG(logger_, "Timeout is greater then 0");
sync_primitives::ConditionalVariable::WaitStatus wait_status =
termination_condition_.WaitFor(auto_lock, timeout_);
if (sync_primitives::ConditionalVariable::kTimeout == wait_status) {
if (update_status_manager_) {
update_status_manager_->OnUpdateTimeoutOccurs();
}
}
} else {
// Time is not active, wait until timeout will be set,
// or UpdateStatusManager will be deleted
termination_condition_.Wait(auto_lock);
}
}
}
void UpdateStatusManager::UpdateThreadDelegate::exitThreadMain() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
stop_flag_ = true;
LOG4CXX_DEBUG(logger_, "before notify");
termination_condition_.NotifyOne();
}
void UpdateStatusManager::UpdateThreadDelegate::updateTimeOut(
const uint32_t timeout_ms) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
timeout_ = timeout_ms;
termination_condition_.NotifyOne();
}
} // namespace policy
<commit_msg>Makes default value for app registerd from non-consented device<commit_after>/*
Copyright (c) 2014, Ford Motor Company
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 Ford Motor Company 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 "policy/update_status_manager.h"
#include "policy/policy_listener.h"
#include "utils/logger.h"
namespace policy {
CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
UpdateStatusManager::UpdateStatusManager()
: listener_(NULL)
, exchange_in_progress_(false)
, update_required_(false)
, update_scheduled_(false)
, exchange_pending_(false)
, apps_search_in_progress_(false)
, app_registered_from_non_consented_device_(true)
, last_update_status_(policy::StatusUnknown) {
update_status_thread_delegate_ = new UpdateThreadDelegate(this);
thread_ = threads::CreateThread("UpdateStatusThread",
update_status_thread_delegate_);
thread_->start();
}
UpdateStatusManager::~UpdateStatusManager() {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(update_status_thread_delegate_);
DCHECK(thread_);
thread_->join();
delete update_status_thread_delegate_;
threads::DeleteThread(thread_);
}
void UpdateStatusManager::set_listener(PolicyListener* listener) {
listener_ = listener;
}
void UpdateStatusManager::OnUpdateSentOut(uint32_t update_timeout) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(update_status_thread_delegate_);
const unsigned milliseconds_in_second = 1000;
update_status_thread_delegate_->updateTimeOut(update_timeout *
milliseconds_in_second);
set_exchange_in_progress(true);
set_exchange_pending(true);
set_update_required(false);
}
void UpdateStatusManager::OnUpdateTimeoutOccurs() {
LOG4CXX_AUTO_TRACE(logger_);
set_update_required(true);
set_exchange_in_progress(false);
set_exchange_pending(false);
DCHECK(update_status_thread_delegate_);
update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
}
void UpdateStatusManager::OnValidUpdateReceived() {
LOG4CXX_AUTO_TRACE(logger_);
update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
set_exchange_pending(false);
set_exchange_in_progress(false);
}
void UpdateStatusManager::OnWrongUpdateReceived() {
LOG4CXX_AUTO_TRACE(logger_);
update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
set_update_required(true);
set_exchange_in_progress(false);
set_exchange_pending(false);
}
void UpdateStatusManager::OnResetDefaultPT(bool is_update_required) {
LOG4CXX_AUTO_TRACE(logger_);
exchange_in_progress_ = false;
update_required_ = is_update_required;
exchange_pending_ = false;
last_update_status_ = policy::StatusUnknown;
}
void UpdateStatusManager::OnResetRetrySequence() {
LOG4CXX_AUTO_TRACE(logger_);
if (exchange_in_progress_) {
set_exchange_pending(true);
}
set_update_required(true);
}
void UpdateStatusManager::OnNewApplicationAdded(const DeviceConsent consent) {
LOG4CXX_AUTO_TRACE(logger_);
if (kDeviceAllowed != consent) {
app_registered_from_non_consented_device_ = true;
return;
}
app_registered_from_non_consented_device_ = false;
set_update_required(true);
}
void UpdateStatusManager::OnPolicyInit(bool is_update_required) {
LOG4CXX_AUTO_TRACE(logger_);
update_required_ = is_update_required;
}
void UpdateStatusManager::OnDeviceConsented() {
LOG4CXX_AUTO_TRACE(logger_);
if (app_registered_from_non_consented_device_) {
set_update_required(true);
}
}
PolicyTableStatus UpdateStatusManager::GetUpdateStatus() const {
LOG4CXX_AUTO_TRACE(logger_);
if (!exchange_in_progress_ && !exchange_pending_ && !update_required_) {
return PolicyTableStatus::StatusUpToDate;
}
if (update_required_ && !exchange_in_progress_ && !exchange_pending_) {
return PolicyTableStatus::StatusUpdateRequired;
}
return PolicyTableStatus::StatusUpdatePending;
}
bool UpdateStatusManager::IsUpdateRequired() const {
return update_required_ || update_scheduled_;
}
bool UpdateStatusManager::IsUpdatePending() const {
return exchange_pending_;
}
void UpdateStatusManager::ScheduleUpdate() {
update_scheduled_ = true;
update_required_ = true;
}
void UpdateStatusManager::ResetUpdateSchedule() {
update_scheduled_ = false;
}
std::string UpdateStatusManager::StringifiedUpdateStatus() const {
switch (GetUpdateStatus()) {
case policy::StatusUpdatePending:
return "UPDATING";
case policy::StatusUpdateRequired:
return "UPDATE_NEEDED";
case policy::StatusUpToDate:
return "UP_TO_DATE";
default: { return "UNKNOWN"; }
}
}
void policy::UpdateStatusManager::OnAppsSearchStarted() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
apps_search_in_progress_ = true;
}
void policy::UpdateStatusManager::OnAppsSearchCompleted() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
apps_search_in_progress_ = false;
}
bool policy::UpdateStatusManager::IsAppsSearchInProgress() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
return apps_search_in_progress_;
}
void UpdateStatusManager::CheckUpdateStatus() {
LOG4CXX_AUTO_TRACE(logger_);
policy::PolicyTableStatus status = GetUpdateStatus();
if (listener_ && last_update_status_ != status) {
LOG4CXX_INFO(logger_, "Send OnUpdateStatusChanged");
listener_->OnUpdateStatusChanged(StringifiedUpdateStatus());
}
last_update_status_ = status;
}
void UpdateStatusManager::set_exchange_in_progress(bool value) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(exchange_in_progress_lock_);
LOG4CXX_INFO(logger_,
"Exchange in progress value is:" << std::boolalpha << value);
exchange_in_progress_ = value;
CheckUpdateStatus();
}
void UpdateStatusManager::set_exchange_pending(bool value) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(exchange_pending_lock_);
LOG4CXX_INFO(logger_,
"Exchange pending value is:" << std::boolalpha << value);
exchange_pending_ = value;
CheckUpdateStatus();
}
void UpdateStatusManager::set_update_required(bool value) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(update_required_lock_);
LOG4CXX_INFO(logger_, "Update required value is:" << std::boolalpha << value);
update_required_ = value;
CheckUpdateStatus();
}
UpdateStatusManager::UpdateThreadDelegate::UpdateThreadDelegate(
UpdateStatusManager* update_status_manager)
: timeout_(0)
, stop_flag_(false)
, state_lock_(true)
, update_status_manager_(update_status_manager) {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Create UpdateThreadDelegate");
}
UpdateStatusManager::UpdateThreadDelegate::~UpdateThreadDelegate() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "Delete UpdateThreadDelegate");
}
void UpdateStatusManager::UpdateThreadDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "UpdateStatusManager thread started (started normal)");
sync_primitives::AutoLock auto_lock(state_lock_);
while (false == stop_flag_) {
if (timeout_ > 0) {
LOG4CXX_DEBUG(logger_, "Timeout is greater then 0");
sync_primitives::ConditionalVariable::WaitStatus wait_status =
termination_condition_.WaitFor(auto_lock, timeout_);
if (sync_primitives::ConditionalVariable::kTimeout == wait_status) {
if (update_status_manager_) {
update_status_manager_->OnUpdateTimeoutOccurs();
}
}
} else {
// Time is not active, wait until timeout will be set,
// or UpdateStatusManager will be deleted
termination_condition_.Wait(auto_lock);
}
}
}
void UpdateStatusManager::UpdateThreadDelegate::exitThreadMain() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
stop_flag_ = true;
LOG4CXX_DEBUG(logger_, "before notify");
termination_condition_.NotifyOne();
}
void UpdateStatusManager::UpdateThreadDelegate::updateTimeOut(
const uint32_t timeout_ms) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
timeout_ = timeout_ms;
termination_condition_.NotifyOne();
}
} // namespace policy
<|endoftext|> |
<commit_before>/*
* Copyright © 2013 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file brw_lower_unnormalized_offset.cpp
*
* IR lower pass to convert a texture offset into an adjusted coordinate,
* for use with unnormalized coordinates. At least the gather4* messages
* on Ivybridge and Haswell make a mess with nonzero offsets.
*
* \author Chris Forbes <[email protected]>
*/
#include "glsl/glsl_types.h"
#include "glsl/ir.h"
#include "glsl/ir_builder.h"
using namespace ir_builder;
class brw_lower_unnormalized_offset_visitor : public ir_hierarchical_visitor {
public:
brw_lower_unnormalized_offset_visitor()
{
progress = false;
}
ir_visitor_status visit_leave(ir_texture *ir);
bool progress;
};
ir_visitor_status
brw_lower_unnormalized_offset_visitor::visit_leave(ir_texture *ir)
{
if (!ir->offset)
return visit_continue;
if (ir->op == ir_tg4 || ir->op == ir_tex) {
if (ir->sampler->type->sampler_dimensionality != GLSL_SAMPLER_DIM_RECT)
return visit_continue;
}
else if (ir->op != ir_txf) {
return visit_continue;
}
void *mem_ctx = ralloc_parent(ir);
if (ir->op == ir_txf) {
ir_variable *var = new(mem_ctx) ir_variable(ir->coordinate->type,
"coordinate",
ir_var_temporary);
base_ir->insert_before(var);
base_ir->insert_before(assign(var, ir->coordinate));
base_ir->insert_before(assign(var,
add(swizzle_for_size(var, ir->offset->type->vector_elements), ir->offset),
(1 << ir->offset->type->vector_elements) - 1));
ir->coordinate = new(mem_ctx) ir_dereference_variable(var);
} else {
ir->coordinate = add(ir->coordinate, i2f(ir->offset));
}
ir->offset = NULL;
progress = true;
return visit_continue;
}
extern "C" {
bool
brw_do_lower_unnormalized_offset(exec_list *instructions)
{
brw_lower_unnormalized_offset_visitor v;
visit_list_elements(&v, instructions);
return v.progress;
}
}
<commit_msg>i965: Restore a lost comment about TXF offset bugs.<commit_after>/*
* Copyright © 2013 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/**
* \file brw_lower_unnormalized_offset.cpp
*
* IR lower pass to convert a texture offset into an adjusted coordinate,
* for use with unnormalized coordinates. At least the gather4* messages
* on Ivybridge and Haswell make a mess with nonzero offsets.
*
* \author Chris Forbes <[email protected]>
*/
#include "glsl/glsl_types.h"
#include "glsl/ir.h"
#include "glsl/ir_builder.h"
using namespace ir_builder;
class brw_lower_unnormalized_offset_visitor : public ir_hierarchical_visitor {
public:
brw_lower_unnormalized_offset_visitor()
{
progress = false;
}
ir_visitor_status visit_leave(ir_texture *ir);
bool progress;
};
ir_visitor_status
brw_lower_unnormalized_offset_visitor::visit_leave(ir_texture *ir)
{
if (!ir->offset)
return visit_continue;
if (ir->op == ir_tg4 || ir->op == ir_tex) {
if (ir->sampler->type->sampler_dimensionality != GLSL_SAMPLER_DIM_RECT)
return visit_continue;
}
else if (ir->op != ir_txf) {
return visit_continue;
}
void *mem_ctx = ralloc_parent(ir);
if (ir->op == ir_txf) {
/* It appears that the ld instruction used for txf does its
* address bounds check before adding in the offset. To work
* around this, just add the integer offset to the integer texel
* coordinate, and don't put the offset in the header.
*/
ir_variable *var = new(mem_ctx) ir_variable(ir->coordinate->type,
"coordinate",
ir_var_temporary);
base_ir->insert_before(var);
base_ir->insert_before(assign(var, ir->coordinate));
base_ir->insert_before(assign(var,
add(swizzle_for_size(var, ir->offset->type->vector_elements), ir->offset),
(1 << ir->offset->type->vector_elements) - 1));
ir->coordinate = new(mem_ctx) ir_dereference_variable(var);
} else {
ir->coordinate = add(ir->coordinate, i2f(ir->offset));
}
ir->offset = NULL;
progress = true;
return visit_continue;
}
extern "C" {
bool
brw_do_lower_unnormalized_offset(exec_list *instructions)
{
brw_lower_unnormalized_offset_visitor v;
visit_list_elements(&v, instructions);
return v.progress;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <experimental/source_location>
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/uniqued.hpp>
#include <seastar/core/thread.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include "test/lib/test_services.hh"
#include "test/lib/mutation_source_test.hh"
#include "test/lib/cql_test_env.hh"
#include "test/lib/dummy_sharder.hh"
#include "test/lib/reader_lifecycle_policy.hh"
#include "test/lib/log.hh"
#include "dht/sharder.hh"
#include "mutation_reader.hh"
#include "schema_registry.hh"
#include "service/priority_manager.hh"
// Best run with SMP >= 2
SEASTAR_THREAD_TEST_CASE(test_multishard_combining_reader_as_mutation_source) {
if (smp::count < 2) {
std::cerr << "Cannot run test " << get_name() << " with smp::count < 2" << std::endl;
return;
}
// It has to be a container that does not invalidate pointers
std::list<dummy_sharder> keep_alive_sharder;
do_with_cql_env_thread([&] (cql_test_env& env) -> future<> {
auto make_populate = [&] (bool evict_paused_readers, bool single_fragment_buffer) {
return [&, evict_paused_readers, single_fragment_buffer] (schema_ptr s, const std::vector<mutation>& mutations) mutable {
// We need to group mutations that have the same token so they land on the same shard.
std::map<dht::token, std::vector<frozen_mutation>> mutations_by_token;
for (const auto& mut : mutations) {
mutations_by_token[mut.token()].push_back(freeze(mut));
}
dummy_sharder sharder(s->get_sharder(), mutations_by_token);
auto merged_mutations = boost::copy_range<std::vector<std::vector<frozen_mutation>>>(mutations_by_token | boost::adaptors::map_values);
auto remote_memtables = make_lw_shared<std::vector<foreign_ptr<lw_shared_ptr<memtable>>>>();
for (unsigned shard = 0; shard < sharder.shard_count(); ++shard) {
auto remote_mt = smp::submit_to(shard, [shard, gs = global_schema_ptr(s), &merged_mutations, sharder] {
auto s = gs.get();
auto mt = make_lw_shared<memtable>(s);
for (unsigned i = shard; i < merged_mutations.size(); i += sharder.shard_count()) {
for (auto& mut : merged_mutations[i]) {
mt->apply(mut.unfreeze(s));
}
}
return make_foreign(mt);
}).get0();
remote_memtables->emplace_back(std::move(remote_mt));
}
keep_alive_sharder.push_back(sharder);
return mutation_source([&, remote_memtables, evict_paused_readers, single_fragment_buffer] (schema_ptr s,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
streamed_mutation::forwarding fwd_sm,
mutation_reader::forwarding fwd_mr) mutable {
auto factory = [remote_memtables, single_fragment_buffer] (
schema_ptr s,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
mutation_reader::forwarding fwd_mr) {
auto reader = remote_memtables->at(this_shard_id())->make_flat_reader(s, std::move(permit), range, slice, pc, std::move(trace_state),
streamed_mutation::forwarding::no, fwd_mr);
if (single_fragment_buffer) {
reader.set_max_buffer_size(1);
}
return reader;
};
auto lifecycle_policy = seastar::make_shared<test_reader_lifecycle_policy>(std::move(factory), evict_paused_readers);
auto mr = make_multishard_combining_reader_for_tests(keep_alive_sharder.back(), std::move(lifecycle_policy), s,
std::move(permit), range, slice, pc, trace_state, fwd_mr);
if (fwd_sm == streamed_mutation::forwarding::yes) {
return make_forwardable(std::move(mr));
}
return mr;
});
};
};
testlog.info("run_mutation_source_tests(evict_readers=false, single_fragment_buffer=false)");
run_mutation_source_tests(make_populate(false, false));
testlog.info("run_mutation_source_tests(evict_readers=true, single_fragment_buffer=false)");
run_mutation_source_tests(make_populate(true, false));
testlog.info("run_mutation_source_tests(evict_readers=true, single_fragment_buffer=true)");
run_mutation_source_tests(make_populate(true, true));
return make_ready_future<>();
}).get();
}
<commit_msg>test: Move out internals of test_multishard_combining_reader_as_mutation_source<commit_after>/*
* Copyright (C) 2015-present ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <experimental/source_location>
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/uniqued.hpp>
#include <seastar/core/thread.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include "test/lib/test_services.hh"
#include "test/lib/mutation_source_test.hh"
#include "test/lib/cql_test_env.hh"
#include "test/lib/dummy_sharder.hh"
#include "test/lib/reader_lifecycle_policy.hh"
#include "test/lib/log.hh"
#include "dht/sharder.hh"
#include "mutation_reader.hh"
#include "schema_registry.hh"
#include "service/priority_manager.hh"
// It has to be a container that does not invalidate pointers
static std::list<dummy_sharder> keep_alive_sharder;
static auto make_populate(bool evict_paused_readers, bool single_fragment_buffer) {
return [&, evict_paused_readers, single_fragment_buffer] (schema_ptr s, const std::vector<mutation>& mutations) mutable {
// We need to group mutations that have the same token so they land on the same shard.
std::map<dht::token, std::vector<frozen_mutation>> mutations_by_token;
for (const auto& mut : mutations) {
mutations_by_token[mut.token()].push_back(freeze(mut));
}
dummy_sharder sharder(s->get_sharder(), mutations_by_token);
auto merged_mutations = boost::copy_range<std::vector<std::vector<frozen_mutation>>>(mutations_by_token | boost::adaptors::map_values);
auto remote_memtables = make_lw_shared<std::vector<foreign_ptr<lw_shared_ptr<memtable>>>>();
for (unsigned shard = 0; shard < sharder.shard_count(); ++shard) {
auto remote_mt = smp::submit_to(shard, [shard, gs = global_schema_ptr(s), &merged_mutations, sharder] {
auto s = gs.get();
auto mt = make_lw_shared<memtable>(s);
for (unsigned i = shard; i < merged_mutations.size(); i += sharder.shard_count()) {
for (auto& mut : merged_mutations[i]) {
mt->apply(mut.unfreeze(s));
}
}
return make_foreign(mt);
}).get0();
remote_memtables->emplace_back(std::move(remote_mt));
}
keep_alive_sharder.push_back(sharder);
return mutation_source([&, remote_memtables, evict_paused_readers, single_fragment_buffer] (schema_ptr s,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
streamed_mutation::forwarding fwd_sm,
mutation_reader::forwarding fwd_mr) mutable {
auto factory = [remote_memtables, single_fragment_buffer] (
schema_ptr s,
reader_permit permit,
const dht::partition_range& range,
const query::partition_slice& slice,
const io_priority_class& pc,
tracing::trace_state_ptr trace_state,
mutation_reader::forwarding fwd_mr) {
auto reader = remote_memtables->at(this_shard_id())->make_flat_reader(s, std::move(permit), range, slice, pc, std::move(trace_state),
streamed_mutation::forwarding::no, fwd_mr);
if (single_fragment_buffer) {
reader.set_max_buffer_size(1);
}
return reader;
};
auto lifecycle_policy = seastar::make_shared<test_reader_lifecycle_policy>(std::move(factory), evict_paused_readers);
auto mr = make_multishard_combining_reader_for_tests(keep_alive_sharder.back(), std::move(lifecycle_policy), s,
std::move(permit), range, slice, pc, trace_state, fwd_mr);
if (fwd_sm == streamed_mutation::forwarding::yes) {
return make_forwardable(std::move(mr));
}
return mr;
});
};
}
// Best run with SMP >= 2
SEASTAR_THREAD_TEST_CASE(test_multishard_combining_reader_as_mutation_source) {
if (smp::count < 2) {
std::cerr << "Cannot run test " << get_name() << " with smp::count < 2" << std::endl;
return;
}
do_with_cql_env_thread([&] (cql_test_env& env) -> future<> {
testlog.info("run_mutation_source_tests(evict_readers=false, single_fragment_buffer=false)");
run_mutation_source_tests(make_populate(false, false));
testlog.info("run_mutation_source_tests(evict_readers=true, single_fragment_buffer=false)");
run_mutation_source_tests(make_populate(true, false));
testlog.info("run_mutation_source_tests(evict_readers=true, single_fragment_buffer=true)");
run_mutation_source_tests(make_populate(true, true));
return make_ready_future<>();
}).get();
}
<|endoftext|> |
<commit_before>//===-- AsmPrinterDwarf.cpp - AsmPrinter Dwarf Support --------------------===//
//
// 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 Dwarf emissions parts of AsmPrinter.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Dwarf Emission Helper Routines
//===----------------------------------------------------------------------===//
/// EmitSLEB128 - emit the specified signed leb128 value.
void AsmPrinter::EmitSLEB128(int64_t Value, const char *Desc) const {
if (isVerbose() && Desc)
OutStreamer.AddComment(Desc);
OutStreamer.EmitSLEB128IntValue(Value);
}
/// EmitULEB128 - emit the specified signed leb128 value.
void AsmPrinter::EmitULEB128(uint64_t Value, const char *Desc,
unsigned PadTo) const {
if (isVerbose() && Desc)
OutStreamer.AddComment(Desc);
OutStreamer.EmitULEB128IntValue(Value, PadTo);
}
/// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
void AsmPrinter::EmitCFAByte(unsigned Val) const {
if (isVerbose()) {
if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset + 64)
OutStreamer.AddComment("DW_CFA_offset + Reg (" +
Twine(Val - dwarf::DW_CFA_offset) + ")");
else
OutStreamer.AddComment(dwarf::CallFrameString(Val));
}
OutStreamer.EmitIntValue(Val, 1);
}
static const char *DecodeDWARFEncoding(unsigned Encoding) {
switch (Encoding) {
case dwarf::DW_EH_PE_absptr:
return "absptr";
case dwarf::DW_EH_PE_omit:
return "omit";
case dwarf::DW_EH_PE_pcrel:
return "pcrel";
case dwarf::DW_EH_PE_udata4:
return "udata4";
case dwarf::DW_EH_PE_udata8:
return "udata8";
case dwarf::DW_EH_PE_sdata4:
return "sdata4";
case dwarf::DW_EH_PE_sdata8:
return "sdata8";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
return "pcrel udata4";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
return "pcrel sdata4";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
return "pcrel udata8";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
return "pcrel sdata8";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4
:
return "indirect pcrel udata4";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
:
return "indirect pcrel sdata4";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8
:
return "indirect pcrel udata8";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8
:
return "indirect pcrel sdata8";
}
return "<unknown encoding>";
}
/// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an
/// encoding. If verbose assembly output is enabled, we output comments
/// describing the encoding. Desc is an optional string saying what the
/// encoding is specifying (e.g. "LSDA").
void AsmPrinter::EmitEncodingByte(unsigned Val, const char *Desc) const {
if (isVerbose()) {
if (Desc != 0)
OutStreamer.AddComment(Twine(Desc) + " Encoding = " +
Twine(DecodeDWARFEncoding(Val)));
else
OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val));
}
OutStreamer.EmitIntValue(Val, 1);
}
/// GetSizeOfEncodedValue - Return the size of the encoding in bytes.
unsigned AsmPrinter::GetSizeOfEncodedValue(unsigned Encoding) const {
if (Encoding == dwarf::DW_EH_PE_omit)
return 0;
switch (Encoding & 0x07) {
default:
llvm_unreachable("Invalid encoded value.");
case dwarf::DW_EH_PE_absptr:
return TM.getDataLayout()->getPointerSize();
case dwarf::DW_EH_PE_udata2:
return 2;
case dwarf::DW_EH_PE_udata4:
return 4;
case dwarf::DW_EH_PE_udata8:
return 8;
}
}
void AsmPrinter::EmitTTypeReference(const GlobalValue *GV,
unsigned Encoding) const {
if (GV) {
const TargetLoweringObjectFile &TLOF = getObjFileLowering();
const MCExpr *Exp =
TLOF.getTTypeGlobalReference(GV, Mang, MMI, Encoding, OutStreamer);
OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding));
} else
OutStreamer.EmitIntValue(0, GetSizeOfEncodedValue(Encoding));
}
/// EmitSectionOffset - Emit the 4-byte offset of Label from the start of its
/// section. This can be done with a special directive if the target supports
/// it (e.g. cygwin) or by emitting it as an offset from a label at the start
/// of the section.
///
/// SectionLabel is a temporary label emitted at the start of the section that
/// Label lives in.
void AsmPrinter::EmitSectionOffset(const MCSymbol *Label,
const MCSymbol *SectionLabel) const {
// On COFF targets, we have to emit the special .secrel32 directive.
if (MAI->needsDwarfSectionOffsetDirective()) {
OutStreamer.EmitCOFFSecRel32(Label);
return;
}
// Get the section that we're referring to, based on SectionLabel.
const MCSection &Section = SectionLabel->getSection();
// If Label has already been emitted, verify that it is in the same section as
// section label for sanity.
assert((!Label->isInSection() || &Label->getSection() == &Section) &&
"Section offset using wrong section base for label");
// If the section in question will end up with an address of 0 anyway, we can
// just emit an absolute reference to save a relocation.
if (Section.isBaseAddressKnownZero()) {
OutStreamer.EmitSymbolValue(Label, 4);
return;
}
// Otherwise, emit it as a label difference from the start of the section.
EmitLabelDifference(Label, SectionLabel, 4);
}
//===----------------------------------------------------------------------===//
// Dwarf Lowering Routines
//===----------------------------------------------------------------------===//
void AsmPrinter::emitCFIInstruction(const MCCFIInstruction &Inst) const {
switch (Inst.getOperation()) {
default:
llvm_unreachable("Unexpected instruction");
case MCCFIInstruction::OpDefCfaOffset:
OutStreamer.EmitCFIDefCfaOffset(Inst.getOffset());
break;
case MCCFIInstruction::OpDefCfa:
OutStreamer.EmitCFIDefCfa(Inst.getRegister(), Inst.getOffset());
break;
case MCCFIInstruction::OpDefCfaRegister:
OutStreamer.EmitCFIDefCfaRegister(Inst.getRegister());
break;
case MCCFIInstruction::OpOffset:
OutStreamer.EmitCFIOffset(Inst.getRegister(), Inst.getOffset());
break;
case MCCFIInstruction::OpRegister:
OutStreamer.EmitCFIRegister(Inst.getRegister(), Inst.getRegister2());
break;
case MCCFIInstruction::OpWindowSave:
OutStreamer.EmitCFIWindowSave();
break;
}
}
<commit_msg>Simplify check.<commit_after>//===-- AsmPrinterDwarf.cpp - AsmPrinter Dwarf Support --------------------===//
//
// 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 Dwarf emissions parts of AsmPrinter.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MachineLocation.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// Dwarf Emission Helper Routines
//===----------------------------------------------------------------------===//
/// EmitSLEB128 - emit the specified signed leb128 value.
void AsmPrinter::EmitSLEB128(int64_t Value, const char *Desc) const {
if (isVerbose() && Desc)
OutStreamer.AddComment(Desc);
OutStreamer.EmitSLEB128IntValue(Value);
}
/// EmitULEB128 - emit the specified signed leb128 value.
void AsmPrinter::EmitULEB128(uint64_t Value, const char *Desc,
unsigned PadTo) const {
if (isVerbose() && Desc)
OutStreamer.AddComment(Desc);
OutStreamer.EmitULEB128IntValue(Value, PadTo);
}
/// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value.
void AsmPrinter::EmitCFAByte(unsigned Val) const {
if (isVerbose()) {
if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset + 64)
OutStreamer.AddComment("DW_CFA_offset + Reg (" +
Twine(Val - dwarf::DW_CFA_offset) + ")");
else
OutStreamer.AddComment(dwarf::CallFrameString(Val));
}
OutStreamer.EmitIntValue(Val, 1);
}
static const char *DecodeDWARFEncoding(unsigned Encoding) {
switch (Encoding) {
case dwarf::DW_EH_PE_absptr:
return "absptr";
case dwarf::DW_EH_PE_omit:
return "omit";
case dwarf::DW_EH_PE_pcrel:
return "pcrel";
case dwarf::DW_EH_PE_udata4:
return "udata4";
case dwarf::DW_EH_PE_udata8:
return "udata8";
case dwarf::DW_EH_PE_sdata4:
return "sdata4";
case dwarf::DW_EH_PE_sdata8:
return "sdata8";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4:
return "pcrel udata4";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4:
return "pcrel sdata4";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8:
return "pcrel udata8";
case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8:
return "pcrel sdata8";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4
:
return "indirect pcrel udata4";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
:
return "indirect pcrel sdata4";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8
:
return "indirect pcrel udata8";
case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8
:
return "indirect pcrel sdata8";
}
return "<unknown encoding>";
}
/// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an
/// encoding. If verbose assembly output is enabled, we output comments
/// describing the encoding. Desc is an optional string saying what the
/// encoding is specifying (e.g. "LSDA").
void AsmPrinter::EmitEncodingByte(unsigned Val, const char *Desc) const {
if (isVerbose()) {
if (Desc)
OutStreamer.AddComment(Twine(Desc) + " Encoding = " +
Twine(DecodeDWARFEncoding(Val)));
else
OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val));
}
OutStreamer.EmitIntValue(Val, 1);
}
/// GetSizeOfEncodedValue - Return the size of the encoding in bytes.
unsigned AsmPrinter::GetSizeOfEncodedValue(unsigned Encoding) const {
if (Encoding == dwarf::DW_EH_PE_omit)
return 0;
switch (Encoding & 0x07) {
default:
llvm_unreachable("Invalid encoded value.");
case dwarf::DW_EH_PE_absptr:
return TM.getDataLayout()->getPointerSize();
case dwarf::DW_EH_PE_udata2:
return 2;
case dwarf::DW_EH_PE_udata4:
return 4;
case dwarf::DW_EH_PE_udata8:
return 8;
}
}
void AsmPrinter::EmitTTypeReference(const GlobalValue *GV,
unsigned Encoding) const {
if (GV) {
const TargetLoweringObjectFile &TLOF = getObjFileLowering();
const MCExpr *Exp =
TLOF.getTTypeGlobalReference(GV, Mang, MMI, Encoding, OutStreamer);
OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding));
} else
OutStreamer.EmitIntValue(0, GetSizeOfEncodedValue(Encoding));
}
/// EmitSectionOffset - Emit the 4-byte offset of Label from the start of its
/// section. This can be done with a special directive if the target supports
/// it (e.g. cygwin) or by emitting it as an offset from a label at the start
/// of the section.
///
/// SectionLabel is a temporary label emitted at the start of the section that
/// Label lives in.
void AsmPrinter::EmitSectionOffset(const MCSymbol *Label,
const MCSymbol *SectionLabel) const {
// On COFF targets, we have to emit the special .secrel32 directive.
if (MAI->needsDwarfSectionOffsetDirective()) {
OutStreamer.EmitCOFFSecRel32(Label);
return;
}
// Get the section that we're referring to, based on SectionLabel.
const MCSection &Section = SectionLabel->getSection();
// If Label has already been emitted, verify that it is in the same section as
// section label for sanity.
assert((!Label->isInSection() || &Label->getSection() == &Section) &&
"Section offset using wrong section base for label");
// If the section in question will end up with an address of 0 anyway, we can
// just emit an absolute reference to save a relocation.
if (Section.isBaseAddressKnownZero()) {
OutStreamer.EmitSymbolValue(Label, 4);
return;
}
// Otherwise, emit it as a label difference from the start of the section.
EmitLabelDifference(Label, SectionLabel, 4);
}
//===----------------------------------------------------------------------===//
// Dwarf Lowering Routines
//===----------------------------------------------------------------------===//
void AsmPrinter::emitCFIInstruction(const MCCFIInstruction &Inst) const {
switch (Inst.getOperation()) {
default:
llvm_unreachable("Unexpected instruction");
case MCCFIInstruction::OpDefCfaOffset:
OutStreamer.EmitCFIDefCfaOffset(Inst.getOffset());
break;
case MCCFIInstruction::OpDefCfa:
OutStreamer.EmitCFIDefCfa(Inst.getRegister(), Inst.getOffset());
break;
case MCCFIInstruction::OpDefCfaRegister:
OutStreamer.EmitCFIDefCfaRegister(Inst.getRegister());
break;
case MCCFIInstruction::OpOffset:
OutStreamer.EmitCFIOffset(Inst.getRegister(), Inst.getOffset());
break;
case MCCFIInstruction::OpRegister:
OutStreamer.EmitCFIRegister(Inst.getRegister(), Inst.getRegister2());
break;
case MCCFIInstruction::OpWindowSave:
OutStreamer.EmitCFIWindowSave();
break;
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 noexpandtab: */
/*******************************************************************************
* FShell 2
* Copyright 2009 Michael Tautschnig, [email protected]
*
* 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 fshell2/main/fshell2.t.cpp
* \brief TODO
*
* $Id$
* \author Michael Tautschnig <[email protected]>
* \date Wed Apr 15 11:58:54 CEST 2009
*/
#include <diagnostics/unittest.hpp>
#include <fshell2/config/config.hpp>
#include <fshell2/config/annotations.hpp>
#include <fshell2/main/fshell2.hpp>
#include <cerrno>
#include <fstream>
#include <readline/readline.h>
#include <cbmc/src/util/config.h>
#include <cbmc/src/langapi/language_ui.h>
#include <cbmc/src/langapi/mode.h>
#include <cbmc/src/ansi-c/ansi_c_language.h>
#define TEST_COMPONENT_NAME FShell2
#define TEST_COMPONENT_NAMESPACE fshell2
FSHELL2_NAMESPACE_BEGIN;
/** @cond */
TEST_NAMESPACE_BEGIN;
TEST_COMPONENT_TEST_NAMESPACE_BEGIN;
/** @endcond */
using namespace ::diagnostics::unittest;
////////////////////////////////////////////////////////////////////////////////
/**
* @test A test of FShell2
*
*/
void test_single( Test_Data & data )
{
::register_language(new_ansi_c_language);
::cmdlinet cmdline;
::config.set(cmdline);
::language_uit l(cmdline);
::optionst options;
::goto_functionst cfg;
::std::ostringstream os;
::fshell2::FShell2 fshell(options, cfg);
TEST_ASSERT(fshell.process_line(l, os, "QUIT"));
}
////////////////////////////////////////////////////////////////////////////////
/**
* @test A test of FShell2
*
*/
void test_interactive( Test_Data & data )
{
::register_language(new_ansi_c_language);
::cmdlinet cmdline;
::config.set(cmdline);
::language_uit l(cmdline);
::optionst options;
::goto_functionst cfg;
::std::ostringstream os;
::fshell2::FShell2 fshell(options, cfg);
char * tempname(::strdup("/tmp/queryXXXXXX"));
TEST_CHECK(-1 != ::mkstemp(tempname));
::std::ofstream of(tempname);
TEST_CHECK(of.is_open());
of << "show sourcecode all" << ::std::endl
<< "#define bla blubb" << ::std::endl
<< "quit" << ::std::endl;
of.close();
// open the input file
FILE * in(fopen(tempname, "r"));
TEST_CHECK(0 == errno);
// change the readline input to the file
rl_instream = in;
fshell.interactive(l, os);
// print and check the output
TEST_TRACE(os.str());
::std::string data_name(::diagnostics::internal::to_string(
"interactive_query_out_", sizeof(long) * 8, "bit"));
TEST_ASSERT(data.compare(data_name, os.str()));
// change back to stdin
rl_instream = 0;
fclose(in);
::unlink(tempname);
free(tempname);
}
/** @cond */
TEST_COMPONENT_TEST_NAMESPACE_END;
TEST_NAMESPACE_END;
/** @endcond */
FSHELL2_NAMESPACE_END;
TEST_SUITE_BEGIN;
TEST_NORMAL_CASE( &test_single, LEVEL_PROD );
TEST_NORMAL_CASE( &test_interactive, LEVEL_PROD );
TEST_SUITE_END;
STREAM_TEST_SYSTEM_MAIN;
<commit_msg>Added several queries to have a sensible test case<commit_after>/* -*- Mode: C++; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 noexpandtab: */
/*******************************************************************************
* FShell 2
* Copyright 2009 Michael Tautschnig, [email protected]
*
* 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 fshell2/main/fshell2.t.cpp
* \brief TODO
*
* $Id$
* \author Michael Tautschnig <[email protected]>
* \date Wed Apr 15 11:58:54 CEST 2009
*/
#include <diagnostics/unittest.hpp>
#include <fshell2/config/config.hpp>
#include <fshell2/config/annotations.hpp>
#include <fshell2/main/fshell2.hpp>
#include <cerrno>
#include <fstream>
#include <readline/readline.h>
#include <cbmc/src/util/config.h>
#include <cbmc/src/langapi/language_ui.h>
#include <cbmc/src/langapi/mode.h>
#include <cbmc/src/ansi-c/ansi_c_language.h>
#define TEST_COMPONENT_NAME FShell2
#define TEST_COMPONENT_NAMESPACE fshell2
FSHELL2_NAMESPACE_BEGIN;
/** @cond */
TEST_NAMESPACE_BEGIN;
TEST_COMPONENT_TEST_NAMESPACE_BEGIN;
/** @endcond */
using namespace ::diagnostics::unittest;
////////////////////////////////////////////////////////////////////////////////
/**
* @test A test of FShell2
*
*/
void test_single( Test_Data & data )
{
::register_language(new_ansi_c_language);
::cmdlinet cmdline;
::config.set(cmdline);
::language_uit l(cmdline);
::optionst options;
::goto_functionst cfg;
::std::ostringstream os;
::fshell2::FShell2 fshell(options, cfg);
TEST_ASSERT(fshell.process_line(l, os, "QUIT"));
}
////////////////////////////////////////////////////////////////////////////////
/**
* @test A test of FShell2
*
*/
void test_interactive( Test_Data & data )
{
::register_language(new_ansi_c_language);
::cmdlinet cmdline;
::config.set(cmdline);
::language_uit l(cmdline);
::optionst options;
::goto_functionst cfg;
::std::ostringstream os;
::fshell2::FShell2 fshell(options, cfg);
char * tempname(::strdup("/tmp/queryXXXXXX"));
TEST_CHECK(-1 != ::mkstemp(tempname));
::std::ofstream of(tempname);
TEST_CHECK(of.is_open());
of << "show sourcecode all" << ::std::endl
<< "#define bla blubb" << ::std::endl
<< "quit" << ::std::endl;
of.close();
// open the input file
FILE * in(fopen(tempname, "r"));
TEST_CHECK(0 == errno);
// change the readline input to the file
rl_instream = in;
fshell.interactive(l, os);
// print and check the output
TEST_TRACE(os.str());
::std::string data_name(::diagnostics::internal::to_string(
"interactive_query_out_", sizeof(long) * 8, "bit"));
TEST_ASSERT(data.compare(data_name, os.str()));
// change back to stdin
rl_instream = 0;
fclose(in);
::unlink(tempname);
free(tempname);
}
////////////////////////////////////////////////////////////////////////////////
/**
* @test A test of FShell2
*
*/
void test_single2( Test_Data & data )
{
char * tempname(::strdup("/tmp/srcXXXXXX"));
TEST_CHECK(-1 != ::mkstemp(tempname));
::std::string tempname_str(tempname);
tempname_str += ".c";
::std::ofstream of(tempname_str.c_str());
::unlink(tempname);
::free(tempname);
TEST_CHECK(of.is_open());
of
<< "int main(int argc, char* argv[]) {" << ::std::endl
<< " int x=0;" << ::std::endl
<< " if (argc>2) {" << ::std::endl
<< " if (argc<27)" << ::std::endl
<< "L1: --x;" << ::std::endl
<< " else" << ::std::endl
<< " ++x;" << ::std::endl
<< " }" << ::std::endl
<< "L2:" << ::std::endl
<< " x--;" << ::std::endl
<< " x--;" << ::std::endl
<< " x--;" << ::std::endl
<< " x--;" << ::std::endl
<< " return 0;" << ::std::endl
<< "}" << ::std::endl;
of.close();
::register_language(new_ansi_c_language);
::cmdlinet cmdline;
::config.set(cmdline);
::language_uit l(cmdline);
::optionst options;
::goto_functionst gf;
//::std::ostringstream os;
::fshell2::FShell2 fshell(options, gf);
TEST_ASSERT(!fshell.process_line(l, ::std::cerr, ::diagnostics::internal::to_string(
"add sourcecode \"", tempname_str, "\"").c_str()));
::unlink(tempname_str.c_str());
TEST_ASSERT(!fshell.process_line(l, ::std::cerr, "cover edges(@basicblockentry)"));
TEST_ASSERT(!fshell.process_line(l, ::std::cerr, "cover edges(@basicblockentry) passing @func(main)*.@label(L1)->@label(L2).@func(main)*"));
TEST_ASSERT(!fshell.process_line(l, ::std::cerr, "cover edges(@basicblockentry) passing @func(main)*.@label(L2)->@label(L1).@func(main)*"));
TEST_ASSERT(!fshell.process_line(l, ::std::cerr, "cover edges(@conditionedge)->edges(@conditionedge)"));
TEST_ASSERT(!fshell.process_line(l, ::std::cerr, "cover edges(@basicblockentry)-[ @func(main)* ]>edges(@basicblockentry)"));
TEST_ASSERT(fshell.process_line(l, ::std::cerr, "QUIT"));
}
/** @cond */
TEST_COMPONENT_TEST_NAMESPACE_END;
TEST_NAMESPACE_END;
/** @endcond */
FSHELL2_NAMESPACE_END;
TEST_SUITE_BEGIN;
TEST_NORMAL_CASE( &test_single, LEVEL_PROD );
TEST_NORMAL_CASE( &test_interactive, LEVEL_PROD );
TEST_NORMAL_CASE( &test_single2, LEVEL_PROD );
TEST_SUITE_END;
STREAM_TEST_SYSTEM_MAIN;
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 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 "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/testsupport/gtest_disable.h"
#include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"
namespace {
// TODO(phoglund): These tests are generally broken on mac.
// http://code.google.com/p/webrtc/issues/detail?id=1268
class DISABLED_ON_MAC(ViEApiIntegrationTest) : public LegacyFixture {
};
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsBaseTestWithoutErrors) {
tests_->ViEBaseAPITest();
}
// TODO(phoglund): Crashes on the v4l2loopback camera.
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest),
DISABLED_RunsCaptureTestWithoutErrors) {
tests_->ViECaptureAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsCodecTestWithoutErrors) {
tests_->ViECodecAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest),
RunsEncryptionTestWithoutErrors) {
tests_->ViEEncryptionAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest),
RunsImageProcessTestWithoutErrors) {
tests_->ViEImageProcessAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsRenderTestWithoutErrors) {
tests_->ViERenderAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsRtpRtcpTestWithoutErrors) {
tests_->ViERtpRtcpAPITest();
}
} // namespace
<commit_msg>Disable flaky RunsRtpRtcpTestWithoutErrors.<commit_after>/*
* Copyright (c) 2012 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 "testing/gtest/include/gtest/gtest.h"
#include "webrtc/test/testsupport/gtest_disable.h"
#include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h"
#include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h"
namespace {
// TODO(phoglund): These tests are generally broken on mac.
// http://code.google.com/p/webrtc/issues/detail?id=1268
class DISABLED_ON_MAC(ViEApiIntegrationTest) : public LegacyFixture {
};
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsBaseTestWithoutErrors) {
tests_->ViEBaseAPITest();
}
// TODO(phoglund): Crashes on the v4l2loopback camera.
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest),
DISABLED_RunsCaptureTestWithoutErrors) {
tests_->ViECaptureAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsCodecTestWithoutErrors) {
tests_->ViECodecAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest),
RunsEncryptionTestWithoutErrors) {
tests_->ViEEncryptionAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest),
RunsImageProcessTestWithoutErrors) {
tests_->ViEImageProcessAPITest();
}
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest), RunsRenderTestWithoutErrors) {
tests_->ViERenderAPITest();
}
// See: https://code.google.com/p/webrtc/issues/detail?id=2415
TEST_F(DISABLED_ON_MAC(ViEApiIntegrationTest),
DISABLED_RunsRtpRtcpTestWithoutErrors) {
tests_->ViERtpRtcpAPITest();
}
} // namespace
<|endoftext|> |
<commit_before>//===- SparcV9PreSelection.cpp - Specialize LLVM code for SparcV9 ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PreSelection pass which specializes LLVM code for
// the SparcV9 instruction selector, while remaining in legal portable LLVM
// form and preserving type information and type safety. This is meant to enable
// dataflow optimizations on SparcV9-specific operations such as accesses to
// constants, globals, and array indexing.
//
//===----------------------------------------------------------------------===//
#include "SparcV9Internals.h"
#include "SparcV9InstrSelectionSupport.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Scalar.h"
#include <algorithm>
using namespace llvm;
namespace {
//===--------------------------------------------------------------------===//
// PreSelection Pass - Specialize LLVM code for the SparcV9 instr. selector.
//
class PreSelection : public FunctionPass, public InstVisitor<PreSelection> {
const TargetInstrInfo &instrInfo;
public:
PreSelection(const TargetMachine &T)
: instrInfo(*T.getInstrInfo()) {}
// runOnFunction - apply this pass to each Function
bool runOnFunction(Function &F) {
visit(F);
return true;
}
const char *getPassName() const { return "SparcV9 Instr. Pre-selection"; }
// These methods do the actual work of specializing code
void visitInstruction(Instruction &I); // common work for every instr.
void visitGetElementPtrInst(GetElementPtrInst &I);
void visitCallInst(CallInst &I);
void visitPHINode(PHINode &PN);
// Helper functions for visiting operands of every instruction
//
// visitOperands() works on every operand in [firstOp, lastOp-1].
// If lastOp==0, lastOp defaults to #operands or #incoming Phi values.
//
// visitOneOperand() does all the work for one operand.
//
void visitOperands(Instruction &I, int firstOp=0);
void visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
Instruction& insertBefore);
};
#if 0
// Register the pass...
RegisterPass<PreSelection> X("preselect",
"Specialize LLVM code for a target machine"
createPreselectionPass);
#endif
} // end anonymous namespace
//------------------------------------------------------------------------------
// Helper functions used by methods of class PreSelection
//------------------------------------------------------------------------------
// getGlobalAddr(): Put address of a global into a v. register.
static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore) {
return (isa<GlobalVariable>(ptr))
? new GetElementPtrInst(ptr,
std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)),
"addrOfGlobal:" + ptr->getName(), &insertBefore)
: NULL;
}
// Wrapper on Constant::classof to use in find_if
inline static bool nonConstant(const Use& U) {
return ! isa<Constant>(U);
}
static Instruction* DecomposeConstantExpr(ConstantExpr* CE,
Instruction& insertBefore)
{
Value *getArg1, *getArg2;
switch(CE->getOpcode())
{
case Instruction::Cast:
getArg1 = CE->getOperand(0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
return new CastInst(getArg1, CE->getType(), "constantCast",&insertBefore);
case Instruction::GetElementPtr:
assert(find_if(CE->op_begin()+1, CE->op_end(),nonConstant) == CE->op_end()
&& "All indices in ConstantExpr getelementptr must be constant!");
getArg1 = CE->getOperand(0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
else if (GetElementPtrInst* gep = getGlobalAddr(getArg1, insertBefore))
getArg1 = gep;
return new GetElementPtrInst(getArg1,
std::vector<Value*>(CE->op_begin()+1, CE->op_end()),
"constantGEP:" + getArg1->getName(), &insertBefore);
case Instruction::Select: {
Value *C, *S1, *S2;
C = CE->getOperand (0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (C))
C = DecomposeConstantExpr (CEarg, insertBefore);
S1 = CE->getOperand (1);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S1))
S1 = DecomposeConstantExpr (CEarg, insertBefore);
S2 = CE->getOperand (2);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S2))
S2 = DecomposeConstantExpr (CEarg, insertBefore);
return new SelectInst (C, S1, S2, "constantSelect", &insertBefore);
}
default: // must be a binary operator
assert(CE->getOpcode() >= Instruction::BinaryOpsBegin &&
CE->getOpcode() < Instruction::BinaryOpsEnd &&
"Unhandled opcode in ConstantExpr");
getArg1 = CE->getOperand(0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
getArg2 = CE->getOperand(1);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2))
getArg2 = DecomposeConstantExpr(CEarg, insertBefore);
return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(),
getArg1, getArg2,
"constantBinaryOp", &insertBefore);
}
}
static inline bool ConstantTypeMustBeLoaded(const Type* CVT) {
assert(CVT->isPrimitiveType() || isa<PointerType>(CVT));
return !(CVT->isIntegral() || isa<PointerType>(CVT));
}
//------------------------------------------------------------------------------
// Instruction visitor methods to perform instruction-specific operations
//------------------------------------------------------------------------------
inline void
PreSelection::visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
Instruction& insertBefore)
{
assert(&insertBefore != NULL && "Must have instruction to insert before.");
if (GetElementPtrInst* gep = getGlobalAddr(Op, insertBefore)) {
I.setOperand(opNum, gep); // replace global operand
return; // nothing more to do for this op.
}
Constant* CV = dyn_cast<Constant>(Op);
if (CV == NULL)
return;
if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) {
// load-time constant: factor it out so we optimize as best we can
Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore);
I.setOperand(opNum, computeConst); // replace expr operand with result
} else if (ConstantTypeMustBeLoaded(CV->getType())) {
// load address of constant into a register, then load the constant
// this is now done during instruction selection
// the constant will live in the MachineConstantPool later on
} else if (ConstantMayNotFitInImmedField(CV, &I)) {
// put the constant into a virtual register using a cast
CastInst* castI = new CastInst(CV, CV->getType(), "copyConst",
&insertBefore);
I.setOperand(opNum, castI); // replace operand with copy in v.reg.
}
}
/// visitOperands - transform individual operands of all instructions:
/// -- Load "large" int constants into a virtual register. What is large
/// depends on the type of instruction and on the target architecture.
/// -- For any constants that cannot be put in an immediate field,
/// load address into virtual register first, and then load the constant.
///
/// firstOp and lastOp can be used to skip leading and trailing operands.
/// If lastOp is 0, it defaults to #operands or #incoming Phi values.
///
inline void PreSelection::visitOperands(Instruction &I, int firstOp) {
// For any instruction other than PHI, copies go just before the instr.
for (unsigned i = firstOp, e = I.getNumOperands(); i != e; ++i)
visitOneOperand(I, I.getOperand(i), i, I);
}
void PreSelection::visitPHINode(PHINode &PN) {
// For a PHI, operand copies must be before the terminator of the
// appropriate predecessor basic block. Remaining logic is simple
// so just handle PHIs and other instructions separately.
//
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
visitOneOperand(PN, PN.getIncomingValue(i),
PN.getOperandNumForIncomingValue(i),
*PN.getIncomingBlock(i)->getTerminator());
// do not call visitOperands!
}
// Common work for *all* instructions. This needs to be called explicitly
// by other visit<InstructionType> functions.
inline void PreSelection::visitInstruction(Instruction &I) {
visitOperands(I); // Perform operand transformations
}
// GetElementPtr instructions: check if pointer is a global
void PreSelection::visitGetElementPtrInst(GetElementPtrInst &I) {
Instruction* curI = &I;
// The Sparc backend doesn't handle array indexes that are not long types, so
// insert a cast from whatever it is to long, if the sequential type index is
// not a long already.
unsigned Idx = 1;
for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I); TI != E;
++TI, ++Idx)
if (isa<SequentialType>(*TI) &&
I.getOperand(Idx)->getType() != Type::LongTy) {
Value *Op = I.getOperand(Idx);
if (Op->getType()->isUnsigned()) // Must sign extend!
Op = new CastInst(Op, Op->getType()->getSignedVersion(), "v9", &I);
if (Op->getType() != Type::LongTy)
Op = new CastInst(Op, Type::LongTy, "v9", &I);
I.setOperand(Idx, Op);
}
// Decompose multidimensional array references
if (I.getNumIndices() >= 2) {
// DecomposeArrayRef() replaces I and deletes it, if successful,
// so remember predecessor in order to find the replacement instruction.
// Also remember the basic block in case there is no predecessor.
Instruction* prevI = I.getPrev();
BasicBlock* bb = I.getParent();
if (DecomposeArrayRef(&I))
// first instr. replacing I
curI = cast<GetElementPtrInst>(prevI? prevI->getNext() : &bb->front());
}
// Perform other transformations common to all instructions
visitInstruction(*curI);
}
void PreSelection::visitCallInst(CallInst &I) {
// Tell visitOperands to ignore the function name if this is a direct call.
visitOperands(I, (/*firstOp=*/ I.getCalledFunction()? 1 : 0));
}
/// createPreSelectionPass - Public entry point for the PreSelection pass
///
FunctionPass* llvm::createPreSelectionPass(const TargetMachine &TM) {
return new PreSelection(TM);
}
<commit_msg>Include SparcV9BurgISel.h, because PreSelection uses routines from within the SparcV9 BURG instruction selector. Eww!<commit_after>//===- SparcV9PreSelection.cpp - Specialize LLVM code for SparcV9 ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the PreSelection pass which specializes LLVM code for
// the SparcV9 instruction selector, while remaining in legal portable LLVM
// form and preserving type information and type safety. This is meant to enable
// dataflow optimizations on SparcV9-specific operations such as accesses to
// constants, globals, and array indexing.
//
//===----------------------------------------------------------------------===//
#include "SparcV9Internals.h"
#include "SparcV9BurgISel.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Scalar.h"
#include <algorithm>
using namespace llvm;
namespace {
//===--------------------------------------------------------------------===//
// PreSelection Pass - Specialize LLVM code for the SparcV9 instr. selector.
//
class PreSelection : public FunctionPass, public InstVisitor<PreSelection> {
const TargetInstrInfo &instrInfo;
public:
PreSelection(const TargetMachine &T)
: instrInfo(*T.getInstrInfo()) {}
// runOnFunction - apply this pass to each Function
bool runOnFunction(Function &F) {
visit(F);
return true;
}
const char *getPassName() const { return "SparcV9 Instr. Pre-selection"; }
// These methods do the actual work of specializing code
void visitInstruction(Instruction &I); // common work for every instr.
void visitGetElementPtrInst(GetElementPtrInst &I);
void visitCallInst(CallInst &I);
void visitPHINode(PHINode &PN);
// Helper functions for visiting operands of every instruction
//
// visitOperands() works on every operand in [firstOp, lastOp-1].
// If lastOp==0, lastOp defaults to #operands or #incoming Phi values.
//
// visitOneOperand() does all the work for one operand.
//
void visitOperands(Instruction &I, int firstOp=0);
void visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
Instruction& insertBefore);
};
#if 0
// Register the pass...
RegisterPass<PreSelection> X("preselect",
"Specialize LLVM code for a target machine"
createPreselectionPass);
#endif
} // end anonymous namespace
//------------------------------------------------------------------------------
// Helper functions used by methods of class PreSelection
//------------------------------------------------------------------------------
// getGlobalAddr(): Put address of a global into a v. register.
static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore) {
return (isa<GlobalVariable>(ptr))
? new GetElementPtrInst(ptr,
std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)),
"addrOfGlobal:" + ptr->getName(), &insertBefore)
: NULL;
}
// Wrapper on Constant::classof to use in find_if
inline static bool nonConstant(const Use& U) {
return ! isa<Constant>(U);
}
static Instruction* DecomposeConstantExpr(ConstantExpr* CE,
Instruction& insertBefore)
{
Value *getArg1, *getArg2;
switch(CE->getOpcode())
{
case Instruction::Cast:
getArg1 = CE->getOperand(0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
return new CastInst(getArg1, CE->getType(), "constantCast",&insertBefore);
case Instruction::GetElementPtr:
assert(find_if(CE->op_begin()+1, CE->op_end(),nonConstant) == CE->op_end()
&& "All indices in ConstantExpr getelementptr must be constant!");
getArg1 = CE->getOperand(0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
else if (GetElementPtrInst* gep = getGlobalAddr(getArg1, insertBefore))
getArg1 = gep;
return new GetElementPtrInst(getArg1,
std::vector<Value*>(CE->op_begin()+1, CE->op_end()),
"constantGEP:" + getArg1->getName(), &insertBefore);
case Instruction::Select: {
Value *C, *S1, *S2;
C = CE->getOperand (0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (C))
C = DecomposeConstantExpr (CEarg, insertBefore);
S1 = CE->getOperand (1);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S1))
S1 = DecomposeConstantExpr (CEarg, insertBefore);
S2 = CE->getOperand (2);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S2))
S2 = DecomposeConstantExpr (CEarg, insertBefore);
return new SelectInst (C, S1, S2, "constantSelect", &insertBefore);
}
default: // must be a binary operator
assert(CE->getOpcode() >= Instruction::BinaryOpsBegin &&
CE->getOpcode() < Instruction::BinaryOpsEnd &&
"Unhandled opcode in ConstantExpr");
getArg1 = CE->getOperand(0);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1))
getArg1 = DecomposeConstantExpr(CEarg, insertBefore);
getArg2 = CE->getOperand(1);
if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2))
getArg2 = DecomposeConstantExpr(CEarg, insertBefore);
return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(),
getArg1, getArg2,
"constantBinaryOp", &insertBefore);
}
}
static inline bool ConstantTypeMustBeLoaded(const Type* CVT) {
assert(CVT->isPrimitiveType() || isa<PointerType>(CVT));
return !(CVT->isIntegral() || isa<PointerType>(CVT));
}
//------------------------------------------------------------------------------
// Instruction visitor methods to perform instruction-specific operations
//------------------------------------------------------------------------------
inline void
PreSelection::visitOneOperand(Instruction &I, Value* Op, unsigned opNum,
Instruction& insertBefore)
{
assert(&insertBefore != NULL && "Must have instruction to insert before.");
if (GetElementPtrInst* gep = getGlobalAddr(Op, insertBefore)) {
I.setOperand(opNum, gep); // replace global operand
return; // nothing more to do for this op.
}
Constant* CV = dyn_cast<Constant>(Op);
if (CV == NULL)
return;
if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) {
// load-time constant: factor it out so we optimize as best we can
Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore);
I.setOperand(opNum, computeConst); // replace expr operand with result
} else if (ConstantTypeMustBeLoaded(CV->getType())) {
// load address of constant into a register, then load the constant
// this is now done during instruction selection
// the constant will live in the MachineConstantPool later on
} else if (ConstantMayNotFitInImmedField(CV, &I)) {
// put the constant into a virtual register using a cast
CastInst* castI = new CastInst(CV, CV->getType(), "copyConst",
&insertBefore);
I.setOperand(opNum, castI); // replace operand with copy in v.reg.
}
}
/// visitOperands - transform individual operands of all instructions:
/// -- Load "large" int constants into a virtual register. What is large
/// depends on the type of instruction and on the target architecture.
/// -- For any constants that cannot be put in an immediate field,
/// load address into virtual register first, and then load the constant.
///
/// firstOp and lastOp can be used to skip leading and trailing operands.
/// If lastOp is 0, it defaults to #operands or #incoming Phi values.
///
inline void PreSelection::visitOperands(Instruction &I, int firstOp) {
// For any instruction other than PHI, copies go just before the instr.
for (unsigned i = firstOp, e = I.getNumOperands(); i != e; ++i)
visitOneOperand(I, I.getOperand(i), i, I);
}
void PreSelection::visitPHINode(PHINode &PN) {
// For a PHI, operand copies must be before the terminator of the
// appropriate predecessor basic block. Remaining logic is simple
// so just handle PHIs and other instructions separately.
//
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
visitOneOperand(PN, PN.getIncomingValue(i),
PN.getOperandNumForIncomingValue(i),
*PN.getIncomingBlock(i)->getTerminator());
// do not call visitOperands!
}
// Common work for *all* instructions. This needs to be called explicitly
// by other visit<InstructionType> functions.
inline void PreSelection::visitInstruction(Instruction &I) {
visitOperands(I); // Perform operand transformations
}
// GetElementPtr instructions: check if pointer is a global
void PreSelection::visitGetElementPtrInst(GetElementPtrInst &I) {
Instruction* curI = &I;
// The Sparc backend doesn't handle array indexes that are not long types, so
// insert a cast from whatever it is to long, if the sequential type index is
// not a long already.
unsigned Idx = 1;
for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I); TI != E;
++TI, ++Idx)
if (isa<SequentialType>(*TI) &&
I.getOperand(Idx)->getType() != Type::LongTy) {
Value *Op = I.getOperand(Idx);
if (Op->getType()->isUnsigned()) // Must sign extend!
Op = new CastInst(Op, Op->getType()->getSignedVersion(), "v9", &I);
if (Op->getType() != Type::LongTy)
Op = new CastInst(Op, Type::LongTy, "v9", &I);
I.setOperand(Idx, Op);
}
// Decompose multidimensional array references
if (I.getNumIndices() >= 2) {
// DecomposeArrayRef() replaces I and deletes it, if successful,
// so remember predecessor in order to find the replacement instruction.
// Also remember the basic block in case there is no predecessor.
Instruction* prevI = I.getPrev();
BasicBlock* bb = I.getParent();
if (DecomposeArrayRef(&I))
// first instr. replacing I
curI = cast<GetElementPtrInst>(prevI? prevI->getNext() : &bb->front());
}
// Perform other transformations common to all instructions
visitInstruction(*curI);
}
void PreSelection::visitCallInst(CallInst &I) {
// Tell visitOperands to ignore the function name if this is a direct call.
visitOperands(I, (/*firstOp=*/ I.getCalledFunction()? 1 : 0));
}
/// createPreSelectionPass - Public entry point for the PreSelection pass
///
FunctionPass* llvm::createPreSelectionPass(const TargetMachine &TM) {
return new PreSelection(TM);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include "runtime/parsing_and_serializing/parse_fragment.h"
#include <iostream>
#include "zorbatypes/URI.h"
#include "context/static_context.h"
#include "store/api/store.h"
#include "store/api/item.h"
#include "store/api/item_factory.h"
#include "store/api/load_properties.h"
#include "system/globalenv.h"
#include "types/schema/schema.h"
#include "types/schema/validate.h"
namespace zorba
{
/*******************************************************************************
14.9.1 fn-zorba-xml:parse
********************************************************************************/
store::Item_t getFirstAttribute(store::Item_t node)
{
store::Item_t attr;
store::Iterator_t attributes = node->getAttributes();
attributes->open();
attributes->next(attr);
attributes->close();
return attr;
}
void processOptions(store::Item_t item, store::LoadProperties& props, static_context* theSctx, const QueryLoc& loc)
{
URI lValidatedBaseUri;
store::Item_t child, tempItem;
if (item.getp() == NULL)
return;
#ifndef ZORBA_NO_XMLSCHEMA
if (item->isValidated())
{
if (item->getNodeName() == NULL
||
item->getNodeName()->getNamespace() != static_context::ZORBA_XML_FN_OPTIONS_NS)
{
throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
ERROR_PARAMS(ZED(ParseFragmentInvalidOptions)), ERROR_LOC( loc ));
}
}
else
{
tempItem = NULL; // used as the effectiveValidationValue()'s typeName
Validator::effectiveValidationValue(
item,
item,
tempItem,
theSctx->get_typemanager(),
ParseConstants::val_strict,
theSctx,
loc);
}
#endif
store::Iterator_t children = item->getChildren();
children->open();
while (children->next(child))
{
if (child->getNodeKind() != store::StoreConsts::elementNode)
continue;
if (child->getNodeName()->getLocalName() == "base-uri")
{
store::Item_t attr = getFirstAttribute(child);
try {
lValidatedBaseUri = URI(attr->getStringValue());
} catch (ZorbaException const& /* e */) {
throw XQUERY_EXCEPTION(
err::FODC0007,
ERROR_PARAMS( attr->getStringValue() ),
ERROR_LOC( loc )
);
}
if (!lValidatedBaseUri.is_absolute()) {
throw XQUERY_EXCEPTION(
err::FODC0007,
ERROR_PARAMS( lValidatedBaseUri.toString() ),
ERROR_LOC( loc )
);
}
props.setBaseUri(attr->getStringValue());
}
else if (child->getNodeName()->getLocalName() == "no-error")
props.setNoError(true);
else if (child->getNodeName()->getLocalName() == "strip-boundary-space")
props.setStripWhitespace(true);
else if (child->getNodeName()->getLocalName() == "schema-validate")
{
store::Item_t attr = getFirstAttribute(child);
if (attr->getStringValue() == "strict")
props.setSchemaStrictValidate(true);
else
props.setSchemaLaxValidate(true);
}
else if (child->getNodeName()->getLocalName() == "DTD-validate")
props.setDTDValidate(true);
else if (child->getNodeName()->getLocalName() == "DTD-load")
props.setDTDLoad(true);
else if (child->getNodeName()->getLocalName() == "default-DTD-attributes")
props.setDefaultDTDAttributes(true);
else if (child->getNodeName()->getLocalName() == "parse-external-parsed-entity")
{
props.setParseExternalParsedEntity(true);
store::Item_t attr;
store::Iterator_t attribs = child->getAttributes();
attribs->open();
while (attribs->next(attr))
{
if (attr->getNodeName()->getLocalName() == "skip-root-nodes")
props.setSkipRootNodes(ztd::aton<xs_int>(attr->getStringValue().c_str()));
else if (attr->getNodeName()->getLocalName() == "skip-top-level-text-nodes")
props.setSkipTopLevelTextNodes(true);
}
attribs->close();
}
else if (child->getNodeName()->getLocalName() == "substitute-entities")
props.setSubstituteEntities(true);
else if (child->getNodeName()->getLocalName() == "xinclude-substitutions")
props.setXincludeSubstitutions(true);
else if (child->getNodeName()->getLocalName() == "remove-redundant-ns")
props.setRemoveRedundantNS(true);
else if (child->getNodeName()->getLocalName() == "no-CDATA")
props.setNoCDATA(true);
else if (child->getNodeName()->getLocalName() == "no-xinclude-nodes")
props.setNoXIncludeNodes(true);
}
children->close();
if (props.getSchemaLaxValidate() + props.getSchemaStrictValidate() +
props.getDTDValidate() + props.getParseExternalParsedEntity() > 1)
{
throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
ERROR_PARAMS(ZED(ParseFragmentOptionCombinationNotAllowed)), ERROR_LOC( loc ));
}
}
void FnZorbaParseXmlFragmentIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
theFragmentStream.reset();
theProperties.reset();
theProperties.setStoreDocument(false);
baseUri = "";
docUri = "";
}
bool FnZorbaParseXmlFragmentIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Store& lStore = GENV.getStore();
zstring docString;
store::Item_t tempItem;
bool validated = true;
FnZorbaParseXmlFragmentIteratorState* state;
DEFAULT_STACK_INIT(FnZorbaParseXmlFragmentIteratorState, state, planState);
if (consumeNext(result, theChildren[0].getp(), planState))
{
if (result->isStreamable())
{
state->theFragmentStream.theStream = &result->getStream();
}
else
{
result->getStringValue2(docString);
state->theFragmentStream.theIss = new std::istringstream(docString.c_str());
state->theFragmentStream.theStream = state->theFragmentStream.theIss;
}
// read options
consumeNext(tempItem, theChildren[1].getp(), planState);
state->theProperties.setBaseUri(theSctx->get_base_uri());
state->theProperties.setStoreDocument(false);
processOptions(tempItem, state->theProperties, theSctx, loc);
// baseURI serves both as the base URI used by the XML parser
// to resolve relative entity references within the document,
// and as the base URI of the document node that is returned.
state->baseUri = state->theProperties.getBaseUri();
state->docUri = state->theProperties.getBaseUri();
////////////////////////////////////////////////////////////////////////
// External parsed entity processing
////////////////////////////////////////////////////////////////////////
if (state->theProperties.getParseExternalParsedEntity())
{
state->theFragmentStream.root_elements_to_skip = state->theProperties.getSkipRootNodes();
while ( ! state->theFragmentStream.stream_is_consumed())
{
try {
result = lStore.loadDocument(state->baseUri, state->docUri, state->theFragmentStream, state->theProperties);
} catch (ZorbaException const& e) {
if ( ! state->theProperties.getNoError())
throw XQUERY_EXCEPTION( err::FODC0006, ERROR_PARAMS("parse-xml:parse()", e.what()), ERROR_LOC( loc ));
else
result = NULL;
}
if (result == NULL)
continue;
// Return the children of document node
state->theFragmentStream.children = result->getChildren();
while (state->theFragmentStream.children->next(result) && result != NULL)
{
if (state->theProperties.getSkipTopLevelTextNodes() && result->getNodeKind() == store::StoreConsts::textNode)
continue;
STACK_PUSH(true, state);
}
}
}
////////////////////////////////////////////////////////////////////////
// XML document processing
////////////////////////////////////////////////////////////////////////
else // if (!state->theProperties.getEnableExtParsedEntity())
{
try {
result = lStore.loadDocument(state->baseUri, state->docUri, *state->theFragmentStream.theStream, state->theProperties);
} catch (ZorbaException const& e) {
if ( ! state->theProperties.getNoError())
throw XQUERY_EXCEPTION( err::FODC0006, ERROR_PARAMS("parse-xml:parse()", e.what()), ERROR_LOC( loc ));
else
result = NULL;
}
if (result != NULL)
{
#ifndef ZORBA_NO_XMLSCHEMA
if (state->theProperties.getSchemaLaxValidate() || state->theProperties.getSchemaStrictValidate())
{
try
{
tempItem = NULL; // used as the effectiveValidationValue()'s typeName
validated = Validator::effectiveValidationValue(
result,
result,
tempItem,
theSctx->get_typemanager(),
state->theProperties.getSchemaLaxValidate() ? ParseConstants::val_lax : ParseConstants::val_strict,
theSctx,
this->loc);
}
catch (ZorbaException& /*e*/)
{
if ( ! state->theProperties.getNoError())
throw;
else
{
result = NULL;
validated = false;
}
}
}
#endif
// Ignore the schema validation options if Zorba is built without schema support
STACK_PUSH(validated, state);
} // if (result != NULL)
} // if (state->theProperties.getEnableExtParsedEntity())
} // if (consumeNext(result, theChildren[0].getp(), planState))
STACK_END(state);
}
/*******************************************************************************
14.9.2 fn:parse-xml-fragment
********************************************************************************/
bool FnParseXmlFragmentIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
zstring docString;
FnParseXmlFragmentIteratorState* state;
DEFAULT_STACK_INIT(FnParseXmlFragmentIteratorState, state, planState);
if (consumeNext(result, theChildren[0].getp(), planState))
{
if (result->isStreamable())
{
state->theFragmentStream.theStream = &result->getStream();
}
else
{
result->getStringValue2(docString);
state->theFragmentStream.theIss = new std::istringstream(docString.c_str());
state->theFragmentStream.theStream = state->theFragmentStream.theIss;
}
state->theProperties.setBaseUri(theSctx->get_base_uri());
state->baseUri = state->theProperties.getBaseUri();
state->theProperties.setParseExternalParsedEntity(true);
while ( ! state->theFragmentStream.stream_is_consumed() )
{
try {
state->theProperties.setStoreDocument(false);
result = GENV.getStore().loadDocument(state->baseUri, state->docUri, state->theFragmentStream, state->theProperties);
} catch (ZorbaException const& e) {
if( ! state->theProperties.getNoError())
throw XQUERY_EXCEPTION(err::FODC0006, ERROR_PARAMS("fn:parse-xml-fragment()", e.what() ), ERROR_LOC(loc));
else
result = NULL;
}
if(result ==NULL)
continue;
state->theFragmentStream.children = result->getChildren();
while (state->theFragmentStream.children->next(result) && result != NULL)
{
if (result->getNodeKind() == store::StoreConsts::textNode)
continue;
STACK_PUSH(true, state);
}
}
}
STACK_END(state)
}
void FnParseXmlFragmentIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
theFragmentStream.reset();
theProperties.reset();
theProperties.setStoreDocument(false);
baseUri = "";
docUri = "";
}
} /* namespace zorba */
<commit_msg>The fn:parse-xml-fragment() should return Document nodes now<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "stdafx.h"
#include "runtime/parsing_and_serializing/parse_fragment.h"
#include <iostream>
#include "zorbatypes/URI.h"
#include "context/static_context.h"
#include "store/api/store.h"
#include "store/api/item.h"
#include "store/api/item_factory.h"
#include "store/api/load_properties.h"
#include "system/globalenv.h"
#include "types/schema/schema.h"
#include "types/schema/validate.h"
namespace zorba
{
/*******************************************************************************
14.9.1 fn-zorba-xml:parse
********************************************************************************/
store::Item_t getFirstAttribute(store::Item_t node)
{
store::Item_t attr;
store::Iterator_t attributes = node->getAttributes();
attributes->open();
attributes->next(attr);
attributes->close();
return attr;
}
void processOptions(store::Item_t item, store::LoadProperties& props, static_context* theSctx, const QueryLoc& loc)
{
URI lValidatedBaseUri;
store::Item_t child, tempItem;
if (item.getp() == NULL)
return;
#ifndef ZORBA_NO_XMLSCHEMA
if (item->isValidated())
{
if (item->getNodeName() == NULL
||
item->getNodeName()->getNamespace() != static_context::ZORBA_XML_FN_OPTIONS_NS)
{
throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
ERROR_PARAMS(ZED(ParseFragmentInvalidOptions)), ERROR_LOC( loc ));
}
}
else
{
tempItem = NULL; // used as the effectiveValidationValue()'s typeName
Validator::effectiveValidationValue(
item,
item,
tempItem,
theSctx->get_typemanager(),
ParseConstants::val_strict,
theSctx,
loc);
}
#endif
store::Iterator_t children = item->getChildren();
children->open();
while (children->next(child))
{
if (child->getNodeKind() != store::StoreConsts::elementNode)
continue;
if (child->getNodeName()->getLocalName() == "base-uri")
{
store::Item_t attr = getFirstAttribute(child);
try {
lValidatedBaseUri = URI(attr->getStringValue());
} catch (ZorbaException const& /* e */) {
throw XQUERY_EXCEPTION(
err::FODC0007,
ERROR_PARAMS( attr->getStringValue() ),
ERROR_LOC( loc )
);
}
if (!lValidatedBaseUri.is_absolute()) {
throw XQUERY_EXCEPTION(
err::FODC0007,
ERROR_PARAMS( lValidatedBaseUri.toString() ),
ERROR_LOC( loc )
);
}
props.setBaseUri(attr->getStringValue());
}
else if (child->getNodeName()->getLocalName() == "no-error")
props.setNoError(true);
else if (child->getNodeName()->getLocalName() == "strip-boundary-space")
props.setStripWhitespace(true);
else if (child->getNodeName()->getLocalName() == "schema-validate")
{
store::Item_t attr = getFirstAttribute(child);
if (attr->getStringValue() == "strict")
props.setSchemaStrictValidate(true);
else
props.setSchemaLaxValidate(true);
}
else if (child->getNodeName()->getLocalName() == "DTD-validate")
props.setDTDValidate(true);
else if (child->getNodeName()->getLocalName() == "DTD-load")
props.setDTDLoad(true);
else if (child->getNodeName()->getLocalName() == "default-DTD-attributes")
props.setDefaultDTDAttributes(true);
else if (child->getNodeName()->getLocalName() == "parse-external-parsed-entity")
{
props.setParseExternalParsedEntity(true);
store::Item_t attr;
store::Iterator_t attribs = child->getAttributes();
attribs->open();
while (attribs->next(attr))
{
if (attr->getNodeName()->getLocalName() == "skip-root-nodes")
props.setSkipRootNodes(ztd::aton<xs_int>(attr->getStringValue().c_str()));
else if (attr->getNodeName()->getLocalName() == "skip-top-level-text-nodes")
props.setSkipTopLevelTextNodes(true);
}
attribs->close();
}
else if (child->getNodeName()->getLocalName() == "substitute-entities")
props.setSubstituteEntities(true);
else if (child->getNodeName()->getLocalName() == "xinclude-substitutions")
props.setXincludeSubstitutions(true);
else if (child->getNodeName()->getLocalName() == "remove-redundant-ns")
props.setRemoveRedundantNS(true);
else if (child->getNodeName()->getLocalName() == "no-CDATA")
props.setNoCDATA(true);
else if (child->getNodeName()->getLocalName() == "no-xinclude-nodes")
props.setNoXIncludeNodes(true);
}
children->close();
if (props.getSchemaLaxValidate() + props.getSchemaStrictValidate() +
props.getDTDValidate() + props.getParseExternalParsedEntity() > 1)
{
throw XQUERY_EXCEPTION(zerr::ZXQD0003_INCONSISTENT_PARSE_FRAGMENT_OPTIONS,
ERROR_PARAMS(ZED(ParseFragmentOptionCombinationNotAllowed)), ERROR_LOC( loc ));
}
}
void FnZorbaParseXmlFragmentIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
theFragmentStream.reset();
theProperties.reset();
theProperties.setStoreDocument(false);
baseUri = "";
docUri = "";
}
bool FnZorbaParseXmlFragmentIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Store& lStore = GENV.getStore();
zstring docString;
store::Item_t tempItem;
bool validated = true;
FnZorbaParseXmlFragmentIteratorState* state;
DEFAULT_STACK_INIT(FnZorbaParseXmlFragmentIteratorState, state, planState);
if (consumeNext(result, theChildren[0].getp(), planState))
{
if (result->isStreamable())
{
state->theFragmentStream.theStream = &result->getStream();
}
else
{
result->getStringValue2(docString);
state->theFragmentStream.theIss = new std::istringstream(docString.c_str());
state->theFragmentStream.theStream = state->theFragmentStream.theIss;
}
// read options
consumeNext(tempItem, theChildren[1].getp(), planState);
state->theProperties.setBaseUri(theSctx->get_base_uri());
state->theProperties.setStoreDocument(false);
processOptions(tempItem, state->theProperties, theSctx, loc);
// baseURI serves both as the base URI used by the XML parser
// to resolve relative entity references within the document,
// and as the base URI of the document node that is returned.
state->baseUri = state->theProperties.getBaseUri();
state->docUri = state->theProperties.getBaseUri();
////////////////////////////////////////////////////////////////////////
// External parsed entity processing
////////////////////////////////////////////////////////////////////////
if (state->theProperties.getParseExternalParsedEntity())
{
state->theFragmentStream.root_elements_to_skip = state->theProperties.getSkipRootNodes();
while ( ! state->theFragmentStream.stream_is_consumed())
{
try {
result = lStore.loadDocument(state->baseUri, state->docUri, state->theFragmentStream, state->theProperties);
} catch (ZorbaException const& e) {
if ( ! state->theProperties.getNoError())
throw XQUERY_EXCEPTION( err::FODC0006, ERROR_PARAMS("parse-xml:parse()", e.what()), ERROR_LOC( loc ));
else
result = NULL;
}
if (result == NULL)
continue;
// Return the children of document node
state->theFragmentStream.children = result->getChildren();
while (state->theFragmentStream.children->next(result) && result != NULL)
{
if (state->theProperties.getSkipTopLevelTextNodes() && result->getNodeKind() == store::StoreConsts::textNode)
continue;
STACK_PUSH(true, state);
}
}
}
////////////////////////////////////////////////////////////////////////
// XML document processing
////////////////////////////////////////////////////////////////////////
else // if (!state->theProperties.getEnableExtParsedEntity())
{
try {
result = lStore.loadDocument(state->baseUri, state->docUri, *state->theFragmentStream.theStream, state->theProperties);
} catch (ZorbaException const& e) {
if ( ! state->theProperties.getNoError())
throw XQUERY_EXCEPTION( err::FODC0006, ERROR_PARAMS("parse-xml:parse()", e.what()), ERROR_LOC( loc ));
else
result = NULL;
}
if (result != NULL)
{
#ifndef ZORBA_NO_XMLSCHEMA
if (state->theProperties.getSchemaLaxValidate() || state->theProperties.getSchemaStrictValidate())
{
try
{
tempItem = NULL; // used as the effectiveValidationValue()'s typeName
validated = Validator::effectiveValidationValue(
result,
result,
tempItem,
theSctx->get_typemanager(),
state->theProperties.getSchemaLaxValidate() ? ParseConstants::val_lax : ParseConstants::val_strict,
theSctx,
this->loc);
}
catch (ZorbaException& /*e*/)
{
if ( ! state->theProperties.getNoError())
throw;
else
{
result = NULL;
validated = false;
}
}
}
#endif
// Ignore the schema validation options if Zorba is built without schema support
STACK_PUSH(validated, state);
} // if (result != NULL)
} // if (state->theProperties.getEnableExtParsedEntity())
} // if (consumeNext(result, theChildren[0].getp(), planState))
STACK_END(state);
}
/*******************************************************************************
14.9.2 fn:parse-xml-fragment
********************************************************************************/
bool FnParseXmlFragmentIterator::nextImpl(store::Item_t& result, PlanState& planState) const
{
zstring docString;
FnParseXmlFragmentIteratorState* state;
DEFAULT_STACK_INIT(FnParseXmlFragmentIteratorState, state, planState);
if (consumeNext(result, theChildren[0].getp(), planState))
{
if (result->isStreamable())
{
state->theFragmentStream.theStream = &result->getStream();
}
else
{
result->getStringValue2(docString);
state->theFragmentStream.theIss = new std::istringstream(docString.c_str());
state->theFragmentStream.theStream = state->theFragmentStream.theIss;
}
state->theProperties.setBaseUri(theSctx->get_base_uri());
state->baseUri = state->theProperties.getBaseUri();
state->theProperties.setParseExternalParsedEntity(true);
while ( ! state->theFragmentStream.stream_is_consumed() )
{
try {
state->theProperties.setStoreDocument(false);
result = GENV.getStore().loadDocument(state->baseUri, state->docUri, state->theFragmentStream, state->theProperties);
} catch (ZorbaException const& e) {
if( ! state->theProperties.getNoError())
throw XQUERY_EXCEPTION(err::FODC0006, ERROR_PARAMS("fn:parse-xml-fragment()", e.what() ), ERROR_LOC(loc));
else
result = NULL;
}
if (result == NULL)
continue;
STACK_PUSH(true, state);
} // while
} // if
STACK_END(state)
}
void FnParseXmlFragmentIteratorState::reset(PlanState& planState)
{
PlanIteratorState::reset(planState);
theFragmentStream.reset();
theProperties.reset();
theProperties.setStoreDocument(false);
baseUri = "";
docUri = "";
}
} /* namespace zorba */
<|endoftext|> |
<commit_before>#include <string>
#include <boost/random/additive_combine.hpp>
#include <stan/io/dump.hpp>
#include <test/unit/mcmc/hmc/mock_hmc.hpp>
#include <stan/mcmc/hmc/hamiltonians/dense_e_metric.hpp>
#include <test/test-models/good/mcmc/hmc/hamiltonians/funnel.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>
#include <iostream>
typedef boost::ecuyer1988 rng_t;
TEST(McmcDenseEMetric, sample_p) {
rng_t base_rng(0);
Eigen::Matrix2d m(2,2);
m(0, 0) = 3.0;
m(1, 0) = -2.0;
m(0, 1) = -2.0;
m(1, 1) = 4.0;
Eigen::Matrix2d m_inv = m.inverse();
stan::mcmc::mock_model model(2);
stan::mcmc::dense_e_metric<stan::mcmc::mock_model, rng_t> metric(model);
stan::mcmc::dense_e_point z(2);
z.set_metric(m_inv);
int n_samples = 1000;
Eigen::Matrix2d sample_cov(2,2);
sample_cov(0, 0) = 0.0;
sample_cov(0, 1) = 0.0;
sample_cov(1, 0) = 0.0;
sample_cov(1, 1) = 0.0;
for (int i = 0; i < n_samples; ++i) {
metric.sample_p(z, base_rng);
sample_cov(0, 0) += z.p[0] * z.p[0] / (n_samples + 0.0);
sample_cov(0, 1) += z.p[0] * z.p[1] / (n_samples + 0.0);
sample_cov(1, 0) += z.p[1] * z.p[0] / (n_samples + 0.0);
sample_cov(1, 1) += z.p[1] * z.p[1] / (n_samples + 0.0);
}
Eigen::Matrix2d var(2,2);
var(0, 0) = 2 * m(0, 0);
var(1, 0) = m(1, 0) * m(1, 0) + m(1, 1) * m(0, 0);
var(0, 1) = m(0, 1) * m(0, 1) + m(1, 1) * m(0, 0);
var(1, 1) = 2 * m(1, 1);
// Covariance matrix within 5sigma of expected value (comes from a Wishart distribution)
EXPECT_TRUE(std::fabs(m(0, 0) - sample_cov(0, 0)) < 5.0 * sqrt(var(0, 0) / n_samples));
EXPECT_TRUE(std::fabs(m(1, 0) - sample_cov(1, 0)) < 5.0 * sqrt(var(1, 0) / n_samples));
EXPECT_TRUE(std::fabs(m(0, 1) - sample_cov(0, 1)) < 5.0 * sqrt(var(0, 1) / n_samples));
EXPECT_TRUE(std::fabs(m(1, 1) - sample_cov(1, 1)) < 5.0 * sqrt(var(1, 1) / n_samples));
}
TEST(McmcDenseEMetric, gradients) {
rng_t base_rng(0);
Eigen::VectorXd q = Eigen::VectorXd::Ones(11);
stan::mcmc::dense_e_point z(q.size());
z.q = q;
z.p.setOnes();
std::fstream data_stream(std::string("").c_str(), std::fstream::in);
stan::io::dump data_var_context(data_stream);
data_stream.close();
std::stringstream model_output;
std::stringstream debug, info, warn, error, fatal;
stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);
funnel_model_namespace::funnel_model model(data_var_context, &model_output);
stan::mcmc::dense_e_metric<funnel_model_namespace::funnel_model, rng_t> metric(model);
double epsilon = 1e-6;
metric.init(z, logger);
Eigen::VectorXd g1 = metric.dtau_dq(z, logger);
for (int i = 0; i < z.q.size(); ++i) {
double delta = 0;
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta += metric.tau(z);
z.q(i) -= 2 * epsilon;
metric.update_potential(z, logger);
delta -= metric.tau(z);
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta /= 2 * epsilon;
EXPECT_NEAR(delta, g1(i), epsilon);
}
Eigen::VectorXd g2 = metric.dtau_dp(z);
for (int i = 0; i < z.q.size(); ++i) {
double delta = 0;
z.p(i) += epsilon;
delta += metric.tau(z);
z.p(i) -= 2 * epsilon;
delta -= metric.tau(z);
z.p(i) += epsilon;
delta /= 2 * epsilon;
EXPECT_NEAR(delta, g2(i), epsilon);
}
Eigen::VectorXd g3 = metric.dphi_dq(z, logger);
for (int i = 0; i < z.q.size(); ++i) {
double delta = 0;
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta += metric.phi(z);
z.q(i) -= 2 * epsilon;
metric.update_potential(z, logger);
delta -= metric.phi(z);
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta /= 2 * epsilon;
EXPECT_NEAR(delta, g3(i), epsilon);
}
EXPECT_EQ("", model_output.str());
EXPECT_EQ("", debug.str());
EXPECT_EQ("", info.str());
EXPECT_EQ("", warn.str());
EXPECT_EQ("", error.str());
EXPECT_EQ("", fatal.str());
}
TEST(McmcDenseEMetric, streams) {
stan::test::capture_std_streams();
rng_t base_rng(0);
Eigen::VectorXd q(2);
q(0) = 5;
q(1) = 1;
stan::mcmc::mock_model model(q.size());
// typedef to use within Google Test macros
typedef stan::mcmc::dense_e_metric<stan::mcmc::mock_model, rng_t> dense_e;
EXPECT_NO_THROW(dense_e metric(model));
stan::test::reset_std_streams();
EXPECT_EQ("", stan::test::cout_ss.str());
EXPECT_EQ("", stan::test::cerr_ss.str());
}
<commit_msg>iostream just sneaks in sometimes<commit_after>#include <string>
#include <boost/random/additive_combine.hpp>
#include <stan/io/dump.hpp>
#include <test/unit/mcmc/hmc/mock_hmc.hpp>
#include <stan/mcmc/hmc/hamiltonians/dense_e_metric.hpp>
#include <test/test-models/good/mcmc/hmc/hamiltonians/funnel.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>
typedef boost::ecuyer1988 rng_t;
TEST(McmcDenseEMetric, sample_p) {
rng_t base_rng(0);
Eigen::Matrix2d m(2,2);
m(0, 0) = 3.0;
m(1, 0) = -2.0;
m(0, 1) = -2.0;
m(1, 1) = 4.0;
Eigen::Matrix2d m_inv = m.inverse();
stan::mcmc::mock_model model(2);
stan::mcmc::dense_e_metric<stan::mcmc::mock_model, rng_t> metric(model);
stan::mcmc::dense_e_point z(2);
z.set_metric(m_inv);
int n_samples = 1000;
Eigen::Matrix2d sample_cov(2,2);
sample_cov(0, 0) = 0.0;
sample_cov(0, 1) = 0.0;
sample_cov(1, 0) = 0.0;
sample_cov(1, 1) = 0.0;
for (int i = 0; i < n_samples; ++i) {
metric.sample_p(z, base_rng);
sample_cov(0, 0) += z.p[0] * z.p[0] / (n_samples + 0.0);
sample_cov(0, 1) += z.p[0] * z.p[1] / (n_samples + 0.0);
sample_cov(1, 0) += z.p[1] * z.p[0] / (n_samples + 0.0);
sample_cov(1, 1) += z.p[1] * z.p[1] / (n_samples + 0.0);
}
Eigen::Matrix2d var(2,2);
var(0, 0) = 2 * m(0, 0);
var(1, 0) = m(1, 0) * m(1, 0) + m(1, 1) * m(0, 0);
var(0, 1) = m(0, 1) * m(0, 1) + m(1, 1) * m(0, 0);
var(1, 1) = 2 * m(1, 1);
// Covariance matrix within 5sigma of expected value (comes from a Wishart distribution)
EXPECT_TRUE(std::fabs(m(0, 0) - sample_cov(0, 0)) < 5.0 * sqrt(var(0, 0) / n_samples));
EXPECT_TRUE(std::fabs(m(1, 0) - sample_cov(1, 0)) < 5.0 * sqrt(var(1, 0) / n_samples));
EXPECT_TRUE(std::fabs(m(0, 1) - sample_cov(0, 1)) < 5.0 * sqrt(var(0, 1) / n_samples));
EXPECT_TRUE(std::fabs(m(1, 1) - sample_cov(1, 1)) < 5.0 * sqrt(var(1, 1) / n_samples));
}
TEST(McmcDenseEMetric, gradients) {
rng_t base_rng(0);
Eigen::VectorXd q = Eigen::VectorXd::Ones(11);
stan::mcmc::dense_e_point z(q.size());
z.q = q;
z.p.setOnes();
std::fstream data_stream(std::string("").c_str(), std::fstream::in);
stan::io::dump data_var_context(data_stream);
data_stream.close();
std::stringstream model_output;
std::stringstream debug, info, warn, error, fatal;
stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);
funnel_model_namespace::funnel_model model(data_var_context, &model_output);
stan::mcmc::dense_e_metric<funnel_model_namespace::funnel_model, rng_t> metric(model);
double epsilon = 1e-6;
metric.init(z, logger);
Eigen::VectorXd g1 = metric.dtau_dq(z, logger);
for (int i = 0; i < z.q.size(); ++i) {
double delta = 0;
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta += metric.tau(z);
z.q(i) -= 2 * epsilon;
metric.update_potential(z, logger);
delta -= metric.tau(z);
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta /= 2 * epsilon;
EXPECT_NEAR(delta, g1(i), epsilon);
}
Eigen::VectorXd g2 = metric.dtau_dp(z);
for (int i = 0; i < z.q.size(); ++i) {
double delta = 0;
z.p(i) += epsilon;
delta += metric.tau(z);
z.p(i) -= 2 * epsilon;
delta -= metric.tau(z);
z.p(i) += epsilon;
delta /= 2 * epsilon;
EXPECT_NEAR(delta, g2(i), epsilon);
}
Eigen::VectorXd g3 = metric.dphi_dq(z, logger);
for (int i = 0; i < z.q.size(); ++i) {
double delta = 0;
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta += metric.phi(z);
z.q(i) -= 2 * epsilon;
metric.update_potential(z, logger);
delta -= metric.phi(z);
z.q(i) += epsilon;
metric.update_potential(z, logger);
delta /= 2 * epsilon;
EXPECT_NEAR(delta, g3(i), epsilon);
}
EXPECT_EQ("", model_output.str());
EXPECT_EQ("", debug.str());
EXPECT_EQ("", info.str());
EXPECT_EQ("", warn.str());
EXPECT_EQ("", error.str());
EXPECT_EQ("", fatal.str());
}
TEST(McmcDenseEMetric, streams) {
stan::test::capture_std_streams();
rng_t base_rng(0);
Eigen::VectorXd q(2);
q(0) = 5;
q(1) = 1;
stan::mcmc::mock_model model(q.size());
// typedef to use within Google Test macros
typedef stan::mcmc::dense_e_metric<stan::mcmc::mock_model, rng_t> dense_e;
EXPECT_NO_THROW(dense_e metric(model));
stan::test::reset_std_streams();
EXPECT_EQ("", stan::test::cout_ss.str());
EXPECT_EQ("", stan::test::cerr_ss.str());
}
<|endoftext|> |
<commit_before>//Contains hooks that control attack range and seek range (AKA target acquisition range).
#include "weapon_range.h"
#include "../SCBW/scbwdata.h"
#include "../SCBW/enumerations.h"
#include "../SCBW/api.h"
namespace hooks {
/// Returns the modified seek range (AKA target acquisition range) for the unit.
/// Note: Seek ranges are measured in matrices (1 matrix = 32 pixels).
/// This hook affects the behavior of CUnit::getSeekRange().
u8 getSeekRangeHook(const CUnit *unit) {
using UnitStatus::Cloaked;
using UnitStatus::RequiresDetection;
using scbw::getUpgradeLevel;
const u16 unitId = unit->id;
//Cloaked ghosts do not voluntarily attack enemy units
if ((unitId == UnitId::ghost
|| unitId == UnitId::sarah_kerrigan
|| unitId == UnitId::Hero_AlexeiStukov
|| unitId == UnitId::Hero_SamirDuran
|| unitId == UnitId::Hero_InfestedDuran)
&& unit->status & (Cloaked | RequiresDetection)
&& unit->mainOrderId != OrderId::HoldPosition2)
return 0;
u8 bonusAmount = 0;
switch (unitId) {
case UnitId::marine:
case UNIT_FIEND:
if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells))
bonusAmount = 1;
break;
case UnitId::hydralisk:
if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines))
bonusAmount = 1;
break;
case UnitId::dragoon:
if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge))
bonusAmount = 2;
break;
case UnitId::fenix_dragoon:
if (scbw::isBroodWarMode())
bonusAmount = 2;
break;
case UnitId::goliath:
case UnitId::goliath_turret:
if (getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster))
bonusAmount = 3;
break;
case UnitId::alan_schezar:
case UnitId::alan_schezar_turret:
if (scbw::isBroodWarMode())
bonusAmount = 3;
break;
//Added
case UnitId::spider_mine:
if (getUpgradeLevel(unit->playerId, UPGRADE_THERMAL_SENSORS))
bonusAmount = 1;
break;
}
//Added: Ocular Implants adds a flat +1 seek range
if (unit->isBlind)
bonusAmount += 1;
return Unit::SeekRange[unitId] + bonusAmount;
}
/// Returns the modified max range for the weapon, which is assumed to be
/// attached to the given unit.
/// This hook affects the behavior of CUnit::getMaxWeaponRange().
/// Note: Weapon ranges are measured in pixels.
///
/// @param weapon The weapons.dat ID of the weapon.
/// @param unit The unit that owns the weapon. Use this to check upgrades.
u32 getMaxWeaponRangeHook(const CUnit *unit, u8 weaponId) {
using scbw::getUpgradeLevel;
u32 bonusAmount = 0;
//Give bonus range to units inside Bunkers
if (unit->status & UnitStatus::InBuilding)
bonusAmount = 64;
switch (unit->id) {
case UnitId::marine:
case UNIT_FIEND:
if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells))
bonusAmount += 32;
break;
case UnitId::hydralisk:
if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines))
bonusAmount += 32;
break;
case UnitId::dragoon:
if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge))
bonusAmount += 64;
break;
case UnitId::fenix_dragoon:
if (scbw::isBroodWarMode())
bonusAmount += 64;
break;
case UnitId::goliath:
case UnitId::goliath_turret:
if (weaponId == WeaponId::HellfireMissilePack
&& getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster))
bonusAmount += 96;
break;
case UnitId::alan_schezar:
case UnitId::alan_schezar_turret:
if (weaponId == WeaponId::HellfireMissilePack_AlanSchezar
&& scbw::isBroodWarMode())
bonusAmount += 96;
break;
}
//Added: Ocular Implants adds a flat +32 weapon range (to ranged units only)
if (unit->isBlind && Weapon::MaxRange[weaponId] >= 64)
bonusAmount += 32;
return Weapon::MaxRange[weaponId] + bonusAmount;
}
} //hooks
<commit_msg>SCT Plugin: Fix bug that prevented Ocular Implants from working on Siege Tanks<commit_after>//Contains hooks that control attack range and seek range (AKA target acquisition range).
#include "weapon_range.h"
#include "../SCBW/scbwdata.h"
#include "../SCBW/enumerations.h"
#include "../SCBW/api.h"
namespace hooks {
/// Returns the modified seek range (AKA target acquisition range) for the unit.
/// Note: Seek ranges are measured in matrices (1 matrix = 32 pixels).
/// This hook affects the behavior of CUnit::getSeekRange().
u8 getSeekRangeHook(const CUnit *unit) {
using UnitStatus::Cloaked;
using UnitStatus::RequiresDetection;
using scbw::getUpgradeLevel;
const u16 unitId = unit->id;
//Cloaked ghosts do not voluntarily attack enemy units
if ((unitId == UnitId::ghost
|| unitId == UnitId::sarah_kerrigan
|| unitId == UnitId::Hero_AlexeiStukov
|| unitId == UnitId::Hero_SamirDuran
|| unitId == UnitId::Hero_InfestedDuran)
&& unit->status & (Cloaked | RequiresDetection)
&& unit->mainOrderId != OrderId::HoldPosition2)
return 0;
u8 bonusAmount = 0;
switch (unitId) {
case UnitId::marine:
case UNIT_FIEND:
if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells))
bonusAmount = 1;
break;
case UnitId::hydralisk:
if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines))
bonusAmount = 1;
break;
case UnitId::dragoon:
if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge))
bonusAmount = 2;
break;
case UnitId::fenix_dragoon:
if (scbw::isBroodWarMode())
bonusAmount = 2;
break;
case UnitId::goliath:
case UnitId::goliath_turret:
if (getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster))
bonusAmount = 3;
break;
case UnitId::alan_schezar:
case UnitId::alan_schezar_turret:
if (scbw::isBroodWarMode())
bonusAmount = 3;
break;
//Added
case UnitId::spider_mine:
if (getUpgradeLevel(unit->playerId, UPGRADE_THERMAL_SENSORS))
bonusAmount = 1;
break;
}
//Added: Ocular Implants adds a flat +1 seek range
if (unit->isBlind || unit->subunit && unit->subunit->isBlind)
bonusAmount += 1;
return Unit::SeekRange[unitId] + bonusAmount;
}
/// Returns the modified max range for the weapon, which is assumed to be
/// attached to the given unit.
/// This hook affects the behavior of CUnit::getMaxWeaponRange().
/// Note: Weapon ranges are measured in pixels.
///
/// @param weapon The weapons.dat ID of the weapon.
/// @param unit The unit that owns the weapon. Use this to check upgrades.
u32 getMaxWeaponRangeHook(const CUnit *unit, u8 weaponId) {
using scbw::getUpgradeLevel;
u32 bonusAmount = 0;
//Give bonus range to units inside Bunkers
if (unit->status & UnitStatus::InBuilding)
bonusAmount = 64;
switch (unit->id) {
case UnitId::marine:
case UNIT_FIEND:
if (getUpgradeLevel(unit->playerId, UpgradeId::U_238Shells))
bonusAmount += 32;
break;
case UnitId::hydralisk:
if (getUpgradeLevel(unit->playerId, UpgradeId::GroovedSpines))
bonusAmount += 32;
break;
case UnitId::dragoon:
if (getUpgradeLevel(unit->playerId, UpgradeId::SingularityCharge))
bonusAmount += 64;
break;
case UnitId::fenix_dragoon:
if (scbw::isBroodWarMode())
bonusAmount += 64;
break;
case UnitId::goliath:
case UnitId::goliath_turret:
if (weaponId == WeaponId::HellfireMissilePack
&& getUpgradeLevel(unit->playerId, UpgradeId::CharonBooster))
bonusAmount += 96;
break;
case UnitId::alan_schezar:
case UnitId::alan_schezar_turret:
if (weaponId == WeaponId::HellfireMissilePack_AlanSchezar
&& scbw::isBroodWarMode())
bonusAmount += 96;
break;
}
//Added: Ocular Implants adds a flat +32 weapon range (to ranged units only)
if ((unit->isBlind || unit->subunit && unit->subunit->isBlind)
&& Weapon::MaxRange[weaponId] >= 64)
bonusAmount += 32;
return Weapon::MaxRange[weaponId] + bonusAmount;
}
} //hooks
<|endoftext|> |
<commit_before>#include "vvaabb.h"
#include "vvdebugmsg.h"
#include "vvpthread.h"
#include "vvsoftrayrend.h"
#include "vvtoolshed.h"
#include "vvvoldesc.h"
#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif
#ifdef HAVE_GL
#include <GL/glew.h>
#include "vvgltools.h"
#endif
#include <queue>
struct Ray
{
vvVector3 o;
vvVector3 d;
};
bool intersectBox(const Ray& ray, const vvAABB& aabb,
float* tnear, float* tfar)
{
// compute intersection of ray with all six bbox planes
vvVector3 invR(1.0f / ray.d[0], 1.0f / ray.d[1], 1.0f / ray.d[2]);
float t1 = (aabb.getMin()[0] - ray.o[0]) * invR[0];
float t2 = (aabb.getMax()[0] - ray.o[0]) * invR[0];
float tmin = fminf(t1, t2);
float tmax = fmaxf(t1, t2);
t1 = (aabb.getMin()[1] - ray.o[1]) * invR[1];
t2 = (aabb.getMax()[1] - ray.o[1]) * invR[1];
tmin = fmaxf(fminf(t1, t2), tmin);
tmax = fminf(fmaxf(t1, t2), tmax);
t1 = (aabb.getMin()[2] - ray.o[2]) * invR[2];
t2 = (aabb.getMax()[2] - ray.o[2]) * invR[2];
tmin = fmaxf(fminf(t1, t2), tmin);
tmax = fminf(fmaxf(t1, t2), tmax);
*tnear = tmin;
*tfar = tmax;
return ((tmax >= tmin) && (tmax >= 0.0f));
}
struct vvSoftRayRend::Thread
{
int id;
pthread_t threadHandle;
vvSoftRayRend* renderer;
vvMatrix invViewMatrix;
std::vector<float>* colors;
pthread_barrier_t* barrier;
pthread_mutex_t* mutex;
std::vector<Tile>* tiles;
enum Event
{
VV_RENDER = 0,
VV_EXIT
};
std::queue<Event> events;
};
vvSoftRayRend::vvSoftRayRend(vvVolDesc* vd, vvRenderState renderState)
: vvRenderer(vd, renderState)
, _width(512)
, _height(512)
, _firstThread(NULL)
, _rgbaTF(NULL)
, _earlyRayTermination(true)
, _opacityCorrection(true)
{
vvDebugMsg::msg(1, "vvSoftRayRend::vvSoftRayRend()");
#ifdef HAVE_GL
glewInit();
#endif
updateTransferFunction();
int numThreads = vvToolshed::getNumProcessors();
pthread_barrier_t* barrier = numThreads > 0 ? new pthread_barrier_t : NULL;
pthread_mutex_t* mutex = numThreads > 0 ? new pthread_mutex_t : NULL;
pthread_barrier_init(barrier, NULL, numThreads + 1);
pthread_mutex_init(mutex, NULL);
for (int i = 0; i < numThreads; ++i)
{
Thread* thread = new Thread;
thread->id = i;
thread->renderer = this;
thread->barrier = barrier;
thread->mutex = mutex;
pthread_create(&thread->threadHandle, NULL, renderFunc, thread);
_threads.push_back(thread);
if (i == 0)
{
_firstThread = thread;
}
}
}
vvSoftRayRend::~vvSoftRayRend()
{
vvDebugMsg::msg(1, "vvSoftRayRend::~vvSoftRayRend()");
for (std::vector<Thread*>::const_iterator it = _threads.begin();
it != _threads.end(); ++it)
{
pthread_mutex_lock((*it)->mutex);
(*it)->events.push(Thread::VV_EXIT);
pthread_mutex_unlock((*it)->mutex);
if (pthread_join((*it)->threadHandle, NULL) != 0)
{
vvDebugMsg::msg(0, "vvSoftRayRend::~vvSoftRayRend(): Error joining thread");
}
}
for (std::vector<Thread*>::const_iterator it = _threads.begin();
it != _threads.end(); ++it)
{
if (it == _threads.begin())
{
pthread_barrier_destroy((*it)->barrier);
pthread_mutex_destroy((*it)->mutex);
delete (*it)->barrier;
delete (*it)->mutex;
}
delete *it;
}
}
void vvSoftRayRend::renderVolumeGL()
{
vvDebugMsg::msg(3, "vvSoftRayRend::renderVolumeGL()");
vvMatrix mv;
vvMatrix pr;
#ifdef HAVE_GL
vvGLTools::getModelviewMatrix(&mv);
vvGLTools::getProjectionMatrix(&pr);
const vvGLTools::Viewport viewport = vvGLTools::getViewport();
_width = viewport[2];
_height = viewport[3];
#endif
vvMatrix invViewMatrix = mv;
invViewMatrix.multiplyLeft(pr);
invViewMatrix.invert();
std::vector<Tile> tiles = makeTiles(_width, _height);
std::vector<float> colors;
colors.resize(_width * _height * 4);
for (std::vector<Thread*>::const_iterator it = _threads.begin();
it != _threads.end(); ++it)
{
(*it)->invViewMatrix = invViewMatrix;
(*it)->colors = &colors;
(*it)->tiles = &tiles;
(*it)->events.push(Thread::VV_RENDER);
}
pthread_barrier_wait(_firstThread->barrier);
// threads render
pthread_barrier_wait(_firstThread->barrier);
#ifdef HAVE_GL
glWindowPos2i(0, 0);
glDrawPixels(_width, _height, GL_RGBA, GL_FLOAT, &colors[0]);
#endif
}
void vvSoftRayRend::updateTransferFunction()
{
vvDebugMsg::msg(3, "vvSoftRayRend::updateTransferFunction()");
if (_firstThread != NULL && _firstThread->mutex != NULL)
{
pthread_mutex_lock(_firstThread->mutex);
}
int lutEntries = getLUTSize();
delete[] _rgbaTF;
_rgbaTF = new float[4 * lutEntries];
vd->computeTFTexture(lutEntries, 1, 1, _rgbaTF);
if (_firstThread != NULL && _firstThread->mutex != NULL)
{
pthread_mutex_unlock(_firstThread->mutex);
}
}
int vvSoftRayRend::getLUTSize() const
{
vvDebugMsg::msg(3, "vvSoftRayRend::getLUTSize()");
return (vd->getBPV()==2) ? 4096 : 256;
}
void vvSoftRayRend::setParameter(ParameterType param, const vvParam& newValue)
{
vvDebugMsg::msg(3, "vvSoftRayRend::setParameter()");
switch (param)
{
case vvRenderer::VV_OPCORR:
_opacityCorrection = newValue;
break;
case vvRenderer::VV_TERMINATEEARLY:
_earlyRayTermination = newValue;
break;
default:
vvRenderer::setParameter(param, newValue);
break;
}
}
vvParam vvSoftRayRend::getParameter(ParameterType param) const
{
vvDebugMsg::msg(3, "vvSoftRayRend::getParameter()");
switch (param)
{
case vvRenderer::VV_OPCORR:
return _opacityCorrection;
case vvRenderer::VV_TERMINATEEARLY:
return _earlyRayTermination;
default:
return vvRenderer::getParameter(param);
}
}
std::vector<vvSoftRayRend::Tile> vvSoftRayRend::makeTiles(const int w, const int h)
{
vvDebugMsg::msg(3, "vvSoftRayRend::makeTiles()");
const int tilew = 16;
const int tileh = 16;
int numtilesx = vvToolshed::iDivUp(w, tilew);
int numtilesy = vvToolshed::iDivUp(h, tileh);
std::vector<Tile> result;
for (int y = 0; y < numtilesy; ++y)
{
for (int x = 0; x < numtilesx; ++x)
{
Tile t;
t.left = tilew * x;
t.bottom = tileh * y;
t.right = t.left + tilew;
t.top = t.bottom + tileh;
result.push_back(t);
}
}
return result;
}
void vvSoftRayRend::renderTile(const vvSoftRayRend::Tile& tile, const vvMatrix& invViewMatrix, std::vector<float>* colors)
{
vvDebugMsg::msg(3, "vvSoftRayRend::renderTile()");
const float opacityThreshold = 0.95f;
vvVector3i minVox = _visibleRegion.getMin();
vvVector3i maxVox = _visibleRegion.getMax();
for (int i = 0; i < 3; ++i)
{
minVox[i] = std::max(minVox[i], 0);
maxVox[i] = std::min(maxVox[i], vd->vox[i]);
}
const vvVector3 minCorner = vd->objectCoords(minVox);
const vvVector3 maxCorner = vd->objectCoords(maxVox);
const vvAABB aabb = vvAABB(minCorner, maxCorner);
vvVector3 size2 = vd->getSize() * 0.5f;
const float diagonalVoxels = sqrtf(float(vd->vox[0] * vd->vox[0] +
vd->vox[1] * vd->vox[1] +
vd->vox[2] * vd->vox[2]));
int numSlices = std::max(1, static_cast<int>(_quality * diagonalVoxels));
uchar* raw = vd->getRaw(vd->getCurrentFrame());
for (int y = tile.bottom; y < tile.top; ++y)
{
for (int x = tile.left; x < tile.right; ++x)
{
const float u = (x / static_cast<float>(_width)) * 2.0f - 1.0f;
const float v = (y / static_cast<float>(_height)) * 2.0f - 1.0f;
vvVector4 o(u, v, -1.0f, 1.0f);
o.multiply(invViewMatrix);
vvVector4 d(u, v, 1.0f, 1.0f);
d.multiply(invViewMatrix);
Ray ray;
ray.o = vvVector3(o[0] / o[3], o[1] / o[3], o[2] / o[3]);
ray.d = vvVector3(d[0] / d[3], d[1] / d[3], d[2] / d[3]);
ray.d = ray.d - ray.o;
ray.d.normalize();
float tbnear = 0.0f;
float tbfar = 0.0f;
const bool hit = intersectBox(ray, aabb, &tbnear, &tbfar);
if (hit)
{
float dist = diagonalVoxels / float(numSlices);
float t = tbnear;
vvVector3 pos = ray.o + ray.d * tbnear;
const vvVector3 step = ray.d * dist;
vvVector4 dst(0.0f);
while (true)
{
vvVector3 texcoord = vvVector3((pos[0] - vd->pos[0] + size2[0]) / (size2[0] * 2.0f),
(-pos[1] - vd->pos[1] + size2[1]) / (size2[1] * 2.0f),
(-pos[2] - vd->pos[2] + size2[2]) / (size2[2] * 2.0f));
// calc voxel coordinates
vvVector3i texcoordi = vvVector3i(int(texcoord[0] * float(vd->vox[0] - 1)),
int(texcoord[1] * float(vd->vox[1] - 1)),
int(texcoord[2] * float(vd->vox[2] - 1)));
int idx = texcoordi[2] * vd->vox[0] * vd->vox[1] + texcoordi[1] * vd->vox[0] + texcoordi[0];
float sample = float(raw[idx]) / 256.0f;
vvVector4 src(_rgbaTF[int(sample * 4 * getLUTSize())],
_rgbaTF[int(sample * 4 * getLUTSize()) + 1],
_rgbaTF[int(sample * 4 * getLUTSize()) + 2],
_rgbaTF[int(sample * 4 * getLUTSize()) + 3]);
if (_opacityCorrection)
{
src[3] = 1 - powf(1 - src[3], dist);
}
// pre-multiply alpha
src[0] *= src[3];
src[1] *= src[3];
src[2] *= src[3];
dst = dst + src * (1.0f - dst[3]);
if (_earlyRayTermination && (dst[3] > opacityThreshold))
{
break;
}
t += dist;
if (t > tbfar)
{
break;
}
pos += step;
}
for (int c = 0; c < 4; ++c)
{
(*colors)[y * _width * 4 + x * 4 + c] = dst[c];
}
}
}
}
}
void* vvSoftRayRend::renderFunc(void* args)
{
vvDebugMsg::msg(3, "vvSoftRayRend::renderFunc()");
Thread* thread = static_cast<Thread*>(args);
while (true)
{
pthread_mutex_lock(thread->mutex);
bool haveEvent = !thread->events.empty();
pthread_mutex_unlock(thread->mutex);
if (haveEvent)
{
pthread_mutex_lock(thread->mutex);
Thread::Event e = thread->events.front();
pthread_mutex_unlock(thread->mutex);
switch (e)
{
case Thread::VV_EXIT:
goto cleanup;
case Thread::VV_RENDER:
render(thread);
break;
}
pthread_mutex_lock(thread->mutex);
thread->events.pop();
pthread_mutex_unlock(thread->mutex);
}
}
cleanup:
pthread_exit(NULL);
return NULL;
}
void vvSoftRayRend::render(vvSoftRayRend::Thread* thread)
{
vvDebugMsg::msg(3, "vvSoftRayRend::render()");
pthread_barrier_wait(thread->barrier);
while (true)
{
pthread_mutex_lock(thread->mutex);
if (thread->tiles->empty())
{
pthread_mutex_unlock(thread->mutex);
break;
}
Tile tile = thread->tiles->back();
thread->tiles->pop_back();
pthread_mutex_unlock(thread->mutex);
thread->renderer->renderTile(tile, thread->invViewMatrix, thread->colors);
}
pthread_barrier_wait(thread->barrier);
}
<commit_msg>Use std::min/max instead of fminf/fmaxf (VC doesn't fully support C99)<commit_after>#include "vvaabb.h"
#include "vvdebugmsg.h"
#include "vvpthread.h"
#include "vvsoftrayrend.h"
#include "vvtoolshed.h"
#include "vvvoldesc.h"
#ifdef HAVE_CONFIG_H
#include "vvconfig.h"
#endif
#ifdef HAVE_GL
#include <GL/glew.h>
#include "vvgltools.h"
#endif
#include <queue>
struct Ray
{
vvVector3 o;
vvVector3 d;
};
bool intersectBox(const Ray& ray, const vvAABB& aabb,
float* tnear, float* tfar)
{
using std::min;
using std::max;
// compute intersection of ray with all six bbox planes
vvVector3 invR(1.0f / ray.d[0], 1.0f / ray.d[1], 1.0f / ray.d[2]);
float t1 = (aabb.getMin()[0] - ray.o[0]) * invR[0];
float t2 = (aabb.getMax()[0] - ray.o[0]) * invR[0];
float tmin = min(t1, t2);
float tmax = max(t1, t2);
t1 = (aabb.getMin()[1] - ray.o[1]) * invR[1];
t2 = (aabb.getMax()[1] - ray.o[1]) * invR[1];
tmin = max(min(t1, t2), tmin);
tmax = min(max(t1, t2), tmax);
t1 = (aabb.getMin()[2] - ray.o[2]) * invR[2];
t2 = (aabb.getMax()[2] - ray.o[2]) * invR[2];
tmin = max(min(t1, t2), tmin);
tmax = min(max(t1, t2), tmax);
*tnear = tmin;
*tfar = tmax;
return ((tmax >= tmin) && (tmax >= 0.0f));
}
struct vvSoftRayRend::Thread
{
int id;
pthread_t threadHandle;
vvSoftRayRend* renderer;
vvMatrix invViewMatrix;
std::vector<float>* colors;
pthread_barrier_t* barrier;
pthread_mutex_t* mutex;
std::vector<Tile>* tiles;
enum Event
{
VV_RENDER = 0,
VV_EXIT
};
std::queue<Event> events;
};
vvSoftRayRend::vvSoftRayRend(vvVolDesc* vd, vvRenderState renderState)
: vvRenderer(vd, renderState)
, _width(512)
, _height(512)
, _firstThread(NULL)
, _rgbaTF(NULL)
, _earlyRayTermination(true)
, _opacityCorrection(true)
{
vvDebugMsg::msg(1, "vvSoftRayRend::vvSoftRayRend()");
#ifdef HAVE_GL
glewInit();
#endif
updateTransferFunction();
int numThreads = vvToolshed::getNumProcessors();
pthread_barrier_t* barrier = numThreads > 0 ? new pthread_barrier_t : NULL;
pthread_mutex_t* mutex = numThreads > 0 ? new pthread_mutex_t : NULL;
pthread_barrier_init(barrier, NULL, numThreads + 1);
pthread_mutex_init(mutex, NULL);
for (int i = 0; i < numThreads; ++i)
{
Thread* thread = new Thread;
thread->id = i;
thread->renderer = this;
thread->barrier = barrier;
thread->mutex = mutex;
pthread_create(&thread->threadHandle, NULL, renderFunc, thread);
_threads.push_back(thread);
if (i == 0)
{
_firstThread = thread;
}
}
}
vvSoftRayRend::~vvSoftRayRend()
{
vvDebugMsg::msg(1, "vvSoftRayRend::~vvSoftRayRend()");
for (std::vector<Thread*>::const_iterator it = _threads.begin();
it != _threads.end(); ++it)
{
pthread_mutex_lock((*it)->mutex);
(*it)->events.push(Thread::VV_EXIT);
pthread_mutex_unlock((*it)->mutex);
if (pthread_join((*it)->threadHandle, NULL) != 0)
{
vvDebugMsg::msg(0, "vvSoftRayRend::~vvSoftRayRend(): Error joining thread");
}
}
for (std::vector<Thread*>::const_iterator it = _threads.begin();
it != _threads.end(); ++it)
{
if (it == _threads.begin())
{
pthread_barrier_destroy((*it)->barrier);
pthread_mutex_destroy((*it)->mutex);
delete (*it)->barrier;
delete (*it)->mutex;
}
delete *it;
}
}
void vvSoftRayRend::renderVolumeGL()
{
vvDebugMsg::msg(3, "vvSoftRayRend::renderVolumeGL()");
vvMatrix mv;
vvMatrix pr;
#ifdef HAVE_GL
vvGLTools::getModelviewMatrix(&mv);
vvGLTools::getProjectionMatrix(&pr);
const vvGLTools::Viewport viewport = vvGLTools::getViewport();
_width = viewport[2];
_height = viewport[3];
#endif
vvMatrix invViewMatrix = mv;
invViewMatrix.multiplyLeft(pr);
invViewMatrix.invert();
std::vector<Tile> tiles = makeTiles(_width, _height);
std::vector<float> colors;
colors.resize(_width * _height * 4);
for (std::vector<Thread*>::const_iterator it = _threads.begin();
it != _threads.end(); ++it)
{
(*it)->invViewMatrix = invViewMatrix;
(*it)->colors = &colors;
(*it)->tiles = &tiles;
(*it)->events.push(Thread::VV_RENDER);
}
pthread_barrier_wait(_firstThread->barrier);
// threads render
pthread_barrier_wait(_firstThread->barrier);
#ifdef HAVE_GL
glWindowPos2i(0, 0);
glDrawPixels(_width, _height, GL_RGBA, GL_FLOAT, &colors[0]);
#endif
}
void vvSoftRayRend::updateTransferFunction()
{
vvDebugMsg::msg(3, "vvSoftRayRend::updateTransferFunction()");
if (_firstThread != NULL && _firstThread->mutex != NULL)
{
pthread_mutex_lock(_firstThread->mutex);
}
int lutEntries = getLUTSize();
delete[] _rgbaTF;
_rgbaTF = new float[4 * lutEntries];
vd->computeTFTexture(lutEntries, 1, 1, _rgbaTF);
if (_firstThread != NULL && _firstThread->mutex != NULL)
{
pthread_mutex_unlock(_firstThread->mutex);
}
}
int vvSoftRayRend::getLUTSize() const
{
vvDebugMsg::msg(3, "vvSoftRayRend::getLUTSize()");
return (vd->getBPV()==2) ? 4096 : 256;
}
void vvSoftRayRend::setParameter(ParameterType param, const vvParam& newValue)
{
vvDebugMsg::msg(3, "vvSoftRayRend::setParameter()");
switch (param)
{
case vvRenderer::VV_OPCORR:
_opacityCorrection = newValue;
break;
case vvRenderer::VV_TERMINATEEARLY:
_earlyRayTermination = newValue;
break;
default:
vvRenderer::setParameter(param, newValue);
break;
}
}
vvParam vvSoftRayRend::getParameter(ParameterType param) const
{
vvDebugMsg::msg(3, "vvSoftRayRend::getParameter()");
switch (param)
{
case vvRenderer::VV_OPCORR:
return _opacityCorrection;
case vvRenderer::VV_TERMINATEEARLY:
return _earlyRayTermination;
default:
return vvRenderer::getParameter(param);
}
}
std::vector<vvSoftRayRend::Tile> vvSoftRayRend::makeTiles(const int w, const int h)
{
vvDebugMsg::msg(3, "vvSoftRayRend::makeTiles()");
const int tilew = 16;
const int tileh = 16;
int numtilesx = vvToolshed::iDivUp(w, tilew);
int numtilesy = vvToolshed::iDivUp(h, tileh);
std::vector<Tile> result;
for (int y = 0; y < numtilesy; ++y)
{
for (int x = 0; x < numtilesx; ++x)
{
Tile t;
t.left = tilew * x;
t.bottom = tileh * y;
t.right = t.left + tilew;
t.top = t.bottom + tileh;
result.push_back(t);
}
}
return result;
}
void vvSoftRayRend::renderTile(const vvSoftRayRend::Tile& tile, const vvMatrix& invViewMatrix, std::vector<float>* colors)
{
vvDebugMsg::msg(3, "vvSoftRayRend::renderTile()");
const float opacityThreshold = 0.95f;
vvVector3i minVox = _visibleRegion.getMin();
vvVector3i maxVox = _visibleRegion.getMax();
for (int i = 0; i < 3; ++i)
{
minVox[i] = std::max(minVox[i], 0);
maxVox[i] = std::min(maxVox[i], vd->vox[i]);
}
const vvVector3 minCorner = vd->objectCoords(minVox);
const vvVector3 maxCorner = vd->objectCoords(maxVox);
const vvAABB aabb = vvAABB(minCorner, maxCorner);
vvVector3 size2 = vd->getSize() * 0.5f;
const float diagonalVoxels = sqrtf(float(vd->vox[0] * vd->vox[0] +
vd->vox[1] * vd->vox[1] +
vd->vox[2] * vd->vox[2]));
int numSlices = std::max(1, static_cast<int>(_quality * diagonalVoxels));
uchar* raw = vd->getRaw(vd->getCurrentFrame());
for (int y = tile.bottom; y < tile.top; ++y)
{
for (int x = tile.left; x < tile.right; ++x)
{
const float u = (x / static_cast<float>(_width)) * 2.0f - 1.0f;
const float v = (y / static_cast<float>(_height)) * 2.0f - 1.0f;
vvVector4 o(u, v, -1.0f, 1.0f);
o.multiply(invViewMatrix);
vvVector4 d(u, v, 1.0f, 1.0f);
d.multiply(invViewMatrix);
Ray ray;
ray.o = vvVector3(o[0] / o[3], o[1] / o[3], o[2] / o[3]);
ray.d = vvVector3(d[0] / d[3], d[1] / d[3], d[2] / d[3]);
ray.d = ray.d - ray.o;
ray.d.normalize();
float tbnear = 0.0f;
float tbfar = 0.0f;
const bool hit = intersectBox(ray, aabb, &tbnear, &tbfar);
if (hit)
{
float dist = diagonalVoxels / float(numSlices);
float t = tbnear;
vvVector3 pos = ray.o + ray.d * tbnear;
const vvVector3 step = ray.d * dist;
vvVector4 dst(0.0f);
while (true)
{
vvVector3 texcoord = vvVector3((pos[0] - vd->pos[0] + size2[0]) / (size2[0] * 2.0f),
(-pos[1] - vd->pos[1] + size2[1]) / (size2[1] * 2.0f),
(-pos[2] - vd->pos[2] + size2[2]) / (size2[2] * 2.0f));
// calc voxel coordinates
vvVector3i texcoordi = vvVector3i(int(texcoord[0] * float(vd->vox[0] - 1)),
int(texcoord[1] * float(vd->vox[1] - 1)),
int(texcoord[2] * float(vd->vox[2] - 1)));
int idx = texcoordi[2] * vd->vox[0] * vd->vox[1] + texcoordi[1] * vd->vox[0] + texcoordi[0];
float sample = float(raw[idx]) / 256.0f;
vvVector4 src(_rgbaTF[int(sample * 4 * getLUTSize())],
_rgbaTF[int(sample * 4 * getLUTSize()) + 1],
_rgbaTF[int(sample * 4 * getLUTSize()) + 2],
_rgbaTF[int(sample * 4 * getLUTSize()) + 3]);
if (_opacityCorrection)
{
src[3] = 1 - powf(1 - src[3], dist);
}
// pre-multiply alpha
src[0] *= src[3];
src[1] *= src[3];
src[2] *= src[3];
dst = dst + src * (1.0f - dst[3]);
if (_earlyRayTermination && (dst[3] > opacityThreshold))
{
break;
}
t += dist;
if (t > tbfar)
{
break;
}
pos += step;
}
for (int c = 0; c < 4; ++c)
{
(*colors)[y * _width * 4 + x * 4 + c] = dst[c];
}
}
}
}
}
void* vvSoftRayRend::renderFunc(void* args)
{
vvDebugMsg::msg(3, "vvSoftRayRend::renderFunc()");
Thread* thread = static_cast<Thread*>(args);
while (true)
{
pthread_mutex_lock(thread->mutex);
bool haveEvent = !thread->events.empty();
pthread_mutex_unlock(thread->mutex);
if (haveEvent)
{
pthread_mutex_lock(thread->mutex);
Thread::Event e = thread->events.front();
pthread_mutex_unlock(thread->mutex);
switch (e)
{
case Thread::VV_EXIT:
goto cleanup;
case Thread::VV_RENDER:
render(thread);
break;
}
pthread_mutex_lock(thread->mutex);
thread->events.pop();
pthread_mutex_unlock(thread->mutex);
}
}
cleanup:
pthread_exit(NULL);
return NULL;
}
void vvSoftRayRend::render(vvSoftRayRend::Thread* thread)
{
vvDebugMsg::msg(3, "vvSoftRayRend::render()");
pthread_barrier_wait(thread->barrier);
while (true)
{
pthread_mutex_lock(thread->mutex);
if (thread->tiles->empty())
{
pthread_mutex_unlock(thread->mutex);
break;
}
Tile tile = thread->tiles->back();
thread->tiles->pop_back();
pthread_mutex_unlock(thread->mutex);
thread->renderer->renderTile(tile, thread->invViewMatrix, thread->colors);
}
pthread_barrier_wait(thread->barrier);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_parceldesc.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 09:44:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_parceldesc.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{
// XDocumentHandler
void SAL_CALL
ParcelDescDocHandler::startDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
m_bIsParsed = false;
}
void SAL_CALL
ParcelDescDocHandler::endDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
m_bIsParsed = true;
}
void SAL_CALL
ParcelDescDocHandler::characters( const OUString & aChars )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::ignorableWhitespace( const OUString & aWhitespaces )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::processingInstruction(
const OUString & aTarget, const OUString & aData )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::setDocumentLocator(
const Reference< xml::sax::XLocator >& xLocator )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::startElement( const OUString& aName,
const Reference< xml::sax::XAttributeList > & xAttribs )
throw ( xml::sax::SAXException,
RuntimeException )
{
OSL_TRACE("ParcelDescDocHandler::startElement() for %s",
rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
if ( !skipIndex )
{
if ( aName.equals( OUString::createFromAscii( "parcel" ) ) )
{
m_sLang = xAttribs->getValueByName( OUString::createFromAscii( "language" ) );
}
++skipIndex;
}
else
{
OSL_TRACE("ParcelDescDocHandler::startElement() skipping for %s",
rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
}
void SAL_CALL ParcelDescDocHandler::endElement( const OUString & aName )
throw ( xml::sax::SAXException, RuntimeException )
{
if ( skipIndex )
{
--skipIndex;
OSL_TRACE("ParcelDescDocHandler::endElement() skipping for %s",
rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
}
}
}
}
<commit_msg>INTEGRATION: CWS sb59 (1.4.202); FILE MERGED 2006/07/20 07:55:31 sb 1.4.202.1: #i67537# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dp_parceldesc.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-10-12 14:12:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"
#include "dp_parceldesc.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using ::rtl::OUString;
namespace css = ::com::sun::star;
namespace dp_registry
{
namespace backend
{
namespace sfwk
{
// XDocumentHandler
void SAL_CALL
ParcelDescDocHandler::startDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
m_bIsParsed = false;
}
void SAL_CALL
ParcelDescDocHandler::endDocument()
throw ( xml::sax::SAXException, RuntimeException )
{
m_bIsParsed = true;
}
void SAL_CALL
ParcelDescDocHandler::characters( const OUString & )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::ignorableWhitespace( const OUString & )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::processingInstruction(
const OUString &, const OUString & )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::setDocumentLocator(
const Reference< xml::sax::XLocator >& )
throw ( xml::sax::SAXException, RuntimeException )
{
}
void SAL_CALL
ParcelDescDocHandler::startElement( const OUString& aName,
const Reference< xml::sax::XAttributeList > & xAttribs )
throw ( xml::sax::SAXException,
RuntimeException )
{
OSL_TRACE("ParcelDescDocHandler::startElement() for %s",
rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
if ( !skipIndex )
{
if ( aName.equals( OUString::createFromAscii( "parcel" ) ) )
{
m_sLang = xAttribs->getValueByName( OUString::createFromAscii( "language" ) );
}
++skipIndex;
}
else
{
OSL_TRACE("ParcelDescDocHandler::startElement() skipping for %s",
rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
}
void SAL_CALL ParcelDescDocHandler::endElement( const OUString & aName )
throw ( xml::sax::SAXException, RuntimeException )
{
if ( skipIndex )
{
--skipIndex;
OSL_TRACE("ParcelDescDocHandler::endElement() skipping for %s",
rtl::OUStringToOString( aName, RTL_TEXTENCODING_ASCII_US ).getStr() );
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "gc/gc.hpp"
#include "builtin/compiledmethod.hpp"
#include "builtin/class.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/iseq.hpp"
#include "builtin/staticscope.hpp"
#include "builtin/symbol.hpp"
#include "builtin/tuple.hpp"
#include "builtin/string.hpp"
#include "builtin/lookuptable.hpp"
#include "builtin/call_unit.hpp"
#include "ffi.hpp"
#include "marshal.hpp"
#include "primitives.hpp"
#include "objectmemory.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"
#include "call_frame.hpp"
#include "object_utils.hpp"
#include "vm/object_utils.hpp"
#include "configuration.hpp"
#include "inline_cache.hpp"
#include "bytecode_verification.hpp"
#include "instruments/timing.hpp"
#ifdef ENABLE_LLVM
#include "llvm/jit.hpp"
#include "llvm/jit_compiler.hpp"
#include "llvm/jit_runtime.hpp"
#endif
namespace rubinius {
void CompiledMethod::init(STATE) {
GO(cmethod).set(state->new_class("CompiledMethod", G(executable), G(rubinius)));
G(cmethod)->set_object_type(state, CompiledMethodType);
G(cmethod)->name(state, state->symbol("Rubinius::CompiledMethod"));
}
CompiledMethod* CompiledMethod::create(STATE) {
CompiledMethod* cm = state->new_object<CompiledMethod>(G(cmethod));
cm->local_count(state, Fixnum::from(0));
cm->set_executor(CompiledMethod::default_executor);
cm->backend_method_ = NULL;
cm->inliners_ = NULL;
cm->prim_index_ = -1;
#ifdef ENABLE_LLVM
cm->jit_data_ = NULL;
#endif
return cm;
}
CompiledMethod* CompiledMethod::dup_cm(STATE) {
CompiledMethod* cm = CompiledMethod::create(state);
cm->copy_object(state, this);
cm->set_executor(CompiledMethod::default_executor);
cm->jit_data_ = NULL;
cm->backend_method_ = NULL;
return cm;
}
int CompiledMethod::start_line(STATE) {
if(lines_->nil_p()) return -1;
if(lines_->num_fields() < 2) return -1;
// This is fixed as one because entry 0 is always ip = 0 and
// 1 is the first line
return as<Fixnum>(lines_->at(state, 1))->to_native();
}
int CompiledMethod::start_line() {
if(lines_->nil_p()) return -1;
if(lines_->num_fields() < 2) return -1;
// This is fixed as one because entry 0 is always ip = 0 and
// 1 is the first line
return as<Fixnum>(lines_->at(1))->to_native();
}
int CompiledMethod::line(STATE, int ip) {
if(lines_->nil_p()) return -3;
size_t fin = lines_->num_fields() - 2;
for(size_t i = 0; i < fin; i += 2) {
Fixnum* start_ip = as<Fixnum>(lines_->at(state, i));
Fixnum* end_ip = as<Fixnum>(lines_->at(state, i+2));
if(start_ip->to_native() <= ip && end_ip->to_native() > ip) {
return as<Fixnum>(lines_->at(state, i+1))->to_native();
}
}
return as<Fixnum>(lines_->at(state, fin+1))->to_native();
}
VMMethod* CompiledMethod::internalize(STATE, const char** reason, int* ip) {
atomic::memory_barrier();
if(!backend_method_) {
if(lock(state) != eLocked) rubinius::abort();
if(!backend_method_) {
{
timer::Running<double, timer::milliseconds> tr(
state->shared.stats.verification_time);
BytecodeVerification bv(this);
if(!bv.verify(state)) {
if(reason) *reason = bv.failure_reason();
if(ip) *ip = bv.failure_ip();
std::cerr << "Error validating bytecode: " << bv.failure_reason() << "\n";
return 0;
}
}
VMMethod* vmm = NULL;
vmm = new VMMethod(state, this);
if(!resolve_primitive(state)) {
vmm->setup_argument_handler(this);
}
backend_method_ = vmm;
atomic::memory_barrier();
}
unlock(state);
}
return backend_method_;
}
Object* CompiledMethod::primitive_failed(STATE, CallFrame* call_frame,
Executable* exec, Module* mod, Arguments& args)
{
if(try_as<CompiledMethod>(exec)) {
return VMMethod::execute(state, call_frame, exec, mod, args);
}
// TODO fix me to raise an exception
assert(0);
return Qnil;
}
void CompiledMethod::specialize(STATE, TypeInfo* ti) {
backend_method_->specialize(state, this, ti);
}
Object* CompiledMethod::default_executor(STATE, CallFrame* call_frame,
Executable* exec, Module* mod, Arguments& args)
{
LockableScopedLock lg(state, &state->shared, __FILE__, __LINE__);
CompiledMethod* cm = as<CompiledMethod>(exec);
if(cm->execute == default_executor) {
const char* reason = 0;
int ip = -1;
if(!cm->internalize(state, &reason, &ip)) {
Exception::bytecode_error(state, call_frame, cm, ip, reason);
return 0;
}
}
lg.unlock();
return cm->execute(state, call_frame, exec, mod, args);
}
void CompiledMethod::post_marshal(STATE) {
}
size_t CompiledMethod::number_of_locals() {
return local_count_->to_native();
}
String* CompiledMethod::full_name(STATE) {
return name_->to_str(state);
}
Object* CompiledMethod::jit_now(STATE) {
return Qfalse;
#ifdef ENABLE_LLVM
if(backend_method_ == NULL) {
internalize(state);
}
if(state->shared.config.jit_show_compiling) {
std::cout << "[[[ JIT compiling " << full_name(state)->c_str() << " ]]]\n";
}
LLVMState* ls = LLVMState::get(state);
jit::Compiler jit;
jit.compile_method(ls, this, backend_method_);
if(jit.generate_function(ls)) {
backend_method_->set_jitted(jit.llvm_function(),
jit.code_bytes(), jit.function_pointer());
return Qtrue;
}
#endif
return Qfalse;
}
Object* CompiledMethod::jit_soon(STATE) {
return Qfalse;
#ifdef ENABLE_LLVM
if(backend_method_ == NULL) {
internalize(state);
}
if(state->shared.config.jit_show_compiling) {
std::cout << "[[[ JIT queueing " << full_name(state)->c_str() << " ]]]\n";
}
LLVMState::get(state)->compile_soon(state, this);
return Qtrue;
#else
return Qfalse;
#endif
}
Object* CompiledMethod::set_breakpoint(STATE, Fixnum* ip, Object* bp) {
int i = ip->to_native();
if(backend_method_ == NULL) {
if(!internalize(state)) return Primitives::failure();
}
if(!backend_method_->validate_ip(state, i)) return Primitives::failure();
if(breakpoints_->nil_p()) {
breakpoints(state, LookupTable::create(state));
}
breakpoints_->store(state, ip, bp);
backend_method_->debugging = 1;
backend_method_->run = VMMethod::debugger_interpreter;
return ip;
}
Object* CompiledMethod::clear_breakpoint(STATE, Fixnum* ip) {
int i = ip->to_native();
if(backend_method_ == NULL) return ip;
if(!backend_method_->validate_ip(state, i)) return Primitives::failure();
bool removed = false;
if(!breakpoints_->nil_p()) {
breakpoints_->remove(state, ip, &removed);
// No more breakpoints, switch back to the normal interpreter
if(breakpoints_->entries()->to_native() == 0) {
backend_method_->debugging = 0;
backend_method_->run = VMMethod::interpreter;
}
}
return removed ? Qtrue : Qfalse;
}
Object* CompiledMethod::is_breakpoint(STATE, Fixnum* ip) {
int i = ip->to_native();
if(backend_method_ == NULL) return Qfalse;
if(!backend_method_->validate_ip(state, i)) return Primitives::failure();
if(breakpoints_->nil_p()) return Qfalse;
bool found = false;
breakpoints_->fetch(state, ip, &found);
if(found) return Qtrue;
return Qfalse;
}
CompiledMethod* CompiledMethod::of_sender(STATE, CallFrame* calling_environment) {
CallFrame* caller = static_cast<CallFrame*>(calling_environment->previous);
if(caller) {
if(caller->cm) {
return caller->cm;
}
}
return nil<CompiledMethod>();
}
void CompiledMethod::Info::mark(Object* obj, ObjectMark& mark) {
auto_mark(obj, mark);
mark_inliners(obj, mark);
CompiledMethod* cm = as<CompiledMethod>(obj);
if(!cm->backend_method_) return;
VMMethod* vmm = cm->backend_method_;
vmm->set_mark();
Object* tmp;
#ifdef ENABLE_LLVM
if(cm->jit_data()) {
cm->jit_data()->set_mark();
cm->jit_data()->mark_all(cm, mark);
}
#endif
for(size_t i = 0; i < vmm->inline_cache_count(); i++) {
InlineCache* cache = &vmm->caches[i];
if(cache->module) {
tmp = mark.call(cache->module);
if(tmp) {
cache->module = (Module*)tmp;
mark.just_set(obj, tmp);
}
}
if(cache->method) {
tmp = mark.call(cache->method);
if(tmp) {
cache->method = (Executable*)tmp;
mark.just_set(obj, tmp);
}
}
if(cache->klass_) {
tmp = mark.call(cache->klass_);
if(tmp) {
cache->klass_ = (Class*)tmp;
mark.just_set(obj, tmp);
}
}
if(cache->call_unit_) {
tmp = mark.call(cache->call_unit_);
if(tmp) {
cache->call_unit_ = (CallUnit*)tmp;
mark.just_set(obj, tmp);
}
}
for(int i = 0; i < cTrackedICHits; i++) {
Module* mod = cache->seen_classes_[i].klass();
if(mod) {
tmp = mark.call(mod);
if(tmp) {
cache->seen_classes_[i].set_klass(force_as<Class>(tmp));
mark.just_set(obj, tmp);
}
}
}
}
for(IndirectLiterals::iterator i = vmm->indirect_literals().begin();
i != vmm->indirect_literals().end();
i++) {
Object** ptr = (*i);
if((tmp = mark.call(*ptr)) != NULL) {
*ptr = tmp;
mark.just_set(obj, tmp);
}
}
}
void CompiledMethod::Info::visit(Object* obj, ObjectVisitor& visit) {
auto_visit(obj, visit);
visit_inliners(obj, visit);
CompiledMethod* cm = as<CompiledMethod>(obj);
if(!cm->backend_method_) return;
VMMethod* vmm = cm->backend_method_;
#ifdef ENABLE_LLVM
if(cm->jit_data()) {
cm->jit_data()->visit_all(visit);
}
#endif
for(size_t i = 0; i < vmm->inline_cache_count(); i++) {
InlineCache* cache = &vmm->caches[i];
if(cache->module) {
visit.call(cache->module);
}
if(cache->method) {
visit.call(cache->method);
}
if(cache->klass_) {
visit.call(cache->klass_);
}
for(int i = 0; i < cTrackedICHits; i++) {
Module* mod = cache->seen_classes_[i].klass();
if(mod) visit.call(mod);
}
}
}
void CompiledMethod::Info::show(STATE, Object* self, int level) {
CompiledMethod* cm = as<CompiledMethod>(self);
class_header(state, self);
indent_attribute(++level, "file"); cm->file()->show(state, level);
indent_attribute(level, "iseq"); cm->iseq()->show(state, level);
indent_attribute(level, "lines"); cm->lines()->show_simple(state, level);
indent_attribute(level, "literals"); cm->literals()->show_simple(state, level);
indent_attribute(level, "local_count"); cm->local_count()->show(state, level);
indent_attribute(level, "local_names"); cm->local_names()->show_simple(state, level);
indent_attribute(level, "name"); cm->name()->show(state, level);
indent_attribute(level, "required_args"); cm->required_args()->show(state, level);
indent_attribute(level, "scope"); cm->scope()->show(state, level);
indent_attribute(level, "splat"); cm->splat()->show(state, level);
indent_attribute(level, "stack_size"); cm->stack_size()->show(state, level);
indent_attribute(level, "total_args"); cm->total_args()->show(state, level);
#ifdef ENABLE_LLVM
if(cm->backend_method_ && cm->backend_method_->jitted()) {
llvm::outs() << "<LLVM>\n"
<< *cm->backend_method_->llvm_function()
<< "</LLVM>\n<MachineCode>\n";
LLVMState::show_machine_code(
cm->backend_method_->jitted_impl(),
cm->backend_method_->jitted_bytes());
llvm::outs() << "</MachineCode>\n";
}
#endif
close_body(level);
}
}
<commit_msg>Move the barriers to the right places<commit_after>#include "gc/gc.hpp"
#include "builtin/compiledmethod.hpp"
#include "builtin/class.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/iseq.hpp"
#include "builtin/staticscope.hpp"
#include "builtin/symbol.hpp"
#include "builtin/tuple.hpp"
#include "builtin/string.hpp"
#include "builtin/lookuptable.hpp"
#include "builtin/call_unit.hpp"
#include "ffi.hpp"
#include "marshal.hpp"
#include "primitives.hpp"
#include "objectmemory.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"
#include "call_frame.hpp"
#include "object_utils.hpp"
#include "vm/object_utils.hpp"
#include "configuration.hpp"
#include "inline_cache.hpp"
#include "bytecode_verification.hpp"
#include "instruments/timing.hpp"
#ifdef ENABLE_LLVM
#include "llvm/jit.hpp"
#include "llvm/jit_compiler.hpp"
#include "llvm/jit_runtime.hpp"
#endif
namespace rubinius {
void CompiledMethod::init(STATE) {
GO(cmethod).set(state->new_class("CompiledMethod", G(executable), G(rubinius)));
G(cmethod)->set_object_type(state, CompiledMethodType);
G(cmethod)->name(state, state->symbol("Rubinius::CompiledMethod"));
}
CompiledMethod* CompiledMethod::create(STATE) {
CompiledMethod* cm = state->new_object<CompiledMethod>(G(cmethod));
cm->local_count(state, Fixnum::from(0));
cm->set_executor(CompiledMethod::default_executor);
cm->backend_method_ = NULL;
cm->inliners_ = NULL;
cm->prim_index_ = -1;
#ifdef ENABLE_LLVM
cm->jit_data_ = NULL;
#endif
return cm;
}
CompiledMethod* CompiledMethod::dup_cm(STATE) {
CompiledMethod* cm = CompiledMethod::create(state);
cm->copy_object(state, this);
cm->set_executor(CompiledMethod::default_executor);
cm->jit_data_ = NULL;
cm->backend_method_ = NULL;
return cm;
}
int CompiledMethod::start_line(STATE) {
if(lines_->nil_p()) return -1;
if(lines_->num_fields() < 2) return -1;
// This is fixed as one because entry 0 is always ip = 0 and
// 1 is the first line
return as<Fixnum>(lines_->at(state, 1))->to_native();
}
int CompiledMethod::start_line() {
if(lines_->nil_p()) return -1;
if(lines_->num_fields() < 2) return -1;
// This is fixed as one because entry 0 is always ip = 0 and
// 1 is the first line
return as<Fixnum>(lines_->at(1))->to_native();
}
int CompiledMethod::line(STATE, int ip) {
if(lines_->nil_p()) return -3;
size_t fin = lines_->num_fields() - 2;
for(size_t i = 0; i < fin; i += 2) {
Fixnum* start_ip = as<Fixnum>(lines_->at(state, i));
Fixnum* end_ip = as<Fixnum>(lines_->at(state, i+2));
if(start_ip->to_native() <= ip && end_ip->to_native() > ip) {
return as<Fixnum>(lines_->at(state, i+1))->to_native();
}
}
return as<Fixnum>(lines_->at(state, fin+1))->to_native();
}
VMMethod* CompiledMethod::internalize(STATE, const char** reason, int* ip) {
if(!backend_method_) {
if(lock(state) != eLocked) rubinius::abort();
if(!backend_method_) {
{
timer::Running<double, timer::milliseconds> tr(
state->shared.stats.verification_time);
BytecodeVerification bv(this);
if(!bv.verify(state)) {
if(reason) *reason = bv.failure_reason();
if(ip) *ip = bv.failure_ip();
std::cerr << "Error validating bytecode: " << bv.failure_reason() << "\n";
return 0;
}
}
VMMethod* vmm = NULL;
vmm = new VMMethod(state, this);
if(!resolve_primitive(state)) {
vmm->setup_argument_handler(this);
}
atomic::memory_barrier();
backend_method_ = vmm;
}
unlock(state);
}
atomic::memory_barrier();
return backend_method_;
}
Object* CompiledMethod::primitive_failed(STATE, CallFrame* call_frame,
Executable* exec, Module* mod, Arguments& args)
{
if(try_as<CompiledMethod>(exec)) {
return VMMethod::execute(state, call_frame, exec, mod, args);
}
// TODO fix me to raise an exception
assert(0);
return Qnil;
}
void CompiledMethod::specialize(STATE, TypeInfo* ti) {
backend_method_->specialize(state, this, ti);
}
Object* CompiledMethod::default_executor(STATE, CallFrame* call_frame,
Executable* exec, Module* mod, Arguments& args)
{
LockableScopedLock lg(state, &state->shared, __FILE__, __LINE__);
CompiledMethod* cm = as<CompiledMethod>(exec);
if(cm->execute == default_executor) {
const char* reason = 0;
int ip = -1;
if(!cm->internalize(state, &reason, &ip)) {
Exception::bytecode_error(state, call_frame, cm, ip, reason);
return 0;
}
}
lg.unlock();
return cm->execute(state, call_frame, exec, mod, args);
}
void CompiledMethod::post_marshal(STATE) {
}
size_t CompiledMethod::number_of_locals() {
return local_count_->to_native();
}
String* CompiledMethod::full_name(STATE) {
return name_->to_str(state);
}
Object* CompiledMethod::jit_now(STATE) {
return Qfalse;
#ifdef ENABLE_LLVM
if(backend_method_ == NULL) {
internalize(state);
}
if(state->shared.config.jit_show_compiling) {
std::cout << "[[[ JIT compiling " << full_name(state)->c_str() << " ]]]\n";
}
LLVMState* ls = LLVMState::get(state);
jit::Compiler jit;
jit.compile_method(ls, this, backend_method_);
if(jit.generate_function(ls)) {
backend_method_->set_jitted(jit.llvm_function(),
jit.code_bytes(), jit.function_pointer());
return Qtrue;
}
#endif
return Qfalse;
}
Object* CompiledMethod::jit_soon(STATE) {
return Qfalse;
#ifdef ENABLE_LLVM
if(backend_method_ == NULL) {
internalize(state);
}
if(state->shared.config.jit_show_compiling) {
std::cout << "[[[ JIT queueing " << full_name(state)->c_str() << " ]]]\n";
}
LLVMState::get(state)->compile_soon(state, this);
return Qtrue;
#else
return Qfalse;
#endif
}
Object* CompiledMethod::set_breakpoint(STATE, Fixnum* ip, Object* bp) {
int i = ip->to_native();
if(backend_method_ == NULL) {
if(!internalize(state)) return Primitives::failure();
}
if(!backend_method_->validate_ip(state, i)) return Primitives::failure();
if(breakpoints_->nil_p()) {
breakpoints(state, LookupTable::create(state));
}
breakpoints_->store(state, ip, bp);
backend_method_->debugging = 1;
backend_method_->run = VMMethod::debugger_interpreter;
return ip;
}
Object* CompiledMethod::clear_breakpoint(STATE, Fixnum* ip) {
int i = ip->to_native();
if(backend_method_ == NULL) return ip;
if(!backend_method_->validate_ip(state, i)) return Primitives::failure();
bool removed = false;
if(!breakpoints_->nil_p()) {
breakpoints_->remove(state, ip, &removed);
// No more breakpoints, switch back to the normal interpreter
if(breakpoints_->entries()->to_native() == 0) {
backend_method_->debugging = 0;
backend_method_->run = VMMethod::interpreter;
}
}
return removed ? Qtrue : Qfalse;
}
Object* CompiledMethod::is_breakpoint(STATE, Fixnum* ip) {
int i = ip->to_native();
if(backend_method_ == NULL) return Qfalse;
if(!backend_method_->validate_ip(state, i)) return Primitives::failure();
if(breakpoints_->nil_p()) return Qfalse;
bool found = false;
breakpoints_->fetch(state, ip, &found);
if(found) return Qtrue;
return Qfalse;
}
CompiledMethod* CompiledMethod::of_sender(STATE, CallFrame* calling_environment) {
CallFrame* caller = static_cast<CallFrame*>(calling_environment->previous);
if(caller) {
if(caller->cm) {
return caller->cm;
}
}
return nil<CompiledMethod>();
}
void CompiledMethod::Info::mark(Object* obj, ObjectMark& mark) {
auto_mark(obj, mark);
mark_inliners(obj, mark);
CompiledMethod* cm = as<CompiledMethod>(obj);
if(!cm->backend_method_) return;
VMMethod* vmm = cm->backend_method_;
vmm->set_mark();
Object* tmp;
#ifdef ENABLE_LLVM
if(cm->jit_data()) {
cm->jit_data()->set_mark();
cm->jit_data()->mark_all(cm, mark);
}
#endif
for(size_t i = 0; i < vmm->inline_cache_count(); i++) {
InlineCache* cache = &vmm->caches[i];
if(cache->module) {
tmp = mark.call(cache->module);
if(tmp) {
cache->module = (Module*)tmp;
mark.just_set(obj, tmp);
}
}
if(cache->method) {
tmp = mark.call(cache->method);
if(tmp) {
cache->method = (Executable*)tmp;
mark.just_set(obj, tmp);
}
}
if(cache->klass_) {
tmp = mark.call(cache->klass_);
if(tmp) {
cache->klass_ = (Class*)tmp;
mark.just_set(obj, tmp);
}
}
if(cache->call_unit_) {
tmp = mark.call(cache->call_unit_);
if(tmp) {
cache->call_unit_ = (CallUnit*)tmp;
mark.just_set(obj, tmp);
}
}
for(int i = 0; i < cTrackedICHits; i++) {
Module* mod = cache->seen_classes_[i].klass();
if(mod) {
tmp = mark.call(mod);
if(tmp) {
cache->seen_classes_[i].set_klass(force_as<Class>(tmp));
mark.just_set(obj, tmp);
}
}
}
}
for(IndirectLiterals::iterator i = vmm->indirect_literals().begin();
i != vmm->indirect_literals().end();
i++) {
Object** ptr = (*i);
if((tmp = mark.call(*ptr)) != NULL) {
*ptr = tmp;
mark.just_set(obj, tmp);
}
}
}
void CompiledMethod::Info::visit(Object* obj, ObjectVisitor& visit) {
auto_visit(obj, visit);
visit_inliners(obj, visit);
CompiledMethod* cm = as<CompiledMethod>(obj);
if(!cm->backend_method_) return;
VMMethod* vmm = cm->backend_method_;
#ifdef ENABLE_LLVM
if(cm->jit_data()) {
cm->jit_data()->visit_all(visit);
}
#endif
for(size_t i = 0; i < vmm->inline_cache_count(); i++) {
InlineCache* cache = &vmm->caches[i];
if(cache->module) {
visit.call(cache->module);
}
if(cache->method) {
visit.call(cache->method);
}
if(cache->klass_) {
visit.call(cache->klass_);
}
for(int i = 0; i < cTrackedICHits; i++) {
Module* mod = cache->seen_classes_[i].klass();
if(mod) visit.call(mod);
}
}
}
void CompiledMethod::Info::show(STATE, Object* self, int level) {
CompiledMethod* cm = as<CompiledMethod>(self);
class_header(state, self);
indent_attribute(++level, "file"); cm->file()->show(state, level);
indent_attribute(level, "iseq"); cm->iseq()->show(state, level);
indent_attribute(level, "lines"); cm->lines()->show_simple(state, level);
indent_attribute(level, "literals"); cm->literals()->show_simple(state, level);
indent_attribute(level, "local_count"); cm->local_count()->show(state, level);
indent_attribute(level, "local_names"); cm->local_names()->show_simple(state, level);
indent_attribute(level, "name"); cm->name()->show(state, level);
indent_attribute(level, "required_args"); cm->required_args()->show(state, level);
indent_attribute(level, "scope"); cm->scope()->show(state, level);
indent_attribute(level, "splat"); cm->splat()->show(state, level);
indent_attribute(level, "stack_size"); cm->stack_size()->show(state, level);
indent_attribute(level, "total_args"); cm->total_args()->show(state, level);
#ifdef ENABLE_LLVM
if(cm->backend_method_ && cm->backend_method_->jitted()) {
llvm::outs() << "<LLVM>\n"
<< *cm->backend_method_->llvm_function()
<< "</LLVM>\n<MachineCode>\n";
LLVMState::show_machine_code(
cm->backend_method_->jitted_impl(),
cm->backend_method_->jitted_bytes());
llvm::outs() << "</MachineCode>\n";
}
#endif
close_body(level);
}
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "entityeditorwindow.h"
// UI definition header.
#include "ui_entityeditorwindow.h"
// appleseed.studio headers.
#include "mainwindow/project/entitybrowserwindow.h"
#include "utility/interop.h"
#include "utility/tweaks.h"
// appleseed.foundation headers.
#include "foundation/utility/foreach.h"
#include "foundation/utility/string.h"
// Qt headers.
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QShortcut>
#include <QSignalMapper>
#include <Qt>
// Standard headers.
#include <cassert>
using namespace foundation;
using namespace std;
namespace appleseed {
namespace studio {
EntityEditorWindow::EntityEditorWindow(
QWidget* parent,
const string& window_title,
auto_ptr<IFormFactory> form_factory,
auto_ptr<IEntityBrowser> entity_browser,
const Dictionary& values)
: QWidget(parent)
, m_ui(new Ui::EntityEditorWindow())
, m_form_factory(form_factory)
, m_entity_browser(entity_browser)
, m_form_layout(0)
, m_signal_mapper(new QSignalMapper(this))
{
m_ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(Qt::Tool);
setWindowTitle(QString::fromStdString(window_title));
resize(400, 300);
create_form_layout();
rebuild_form(values);
connect(
m_signal_mapper, SIGNAL(mapped(const QString&)),
this, SLOT(slot_open_entity_browser(const QString&)));
connect(
m_ui->buttonbox->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
this, SLOT(slot_accept()));
connect(
m_ui->buttonbox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()),
this, SLOT(close()));
connect(
create_window_local_shortcut(this, Qt::Key_Return), SIGNAL(activated()),
this, SLOT(slot_accept()));
connect(
create_window_local_shortcut(this, Qt::Key_Escape), SIGNAL(activated()),
this, SLOT(close()));
}
EntityEditorWindow::~EntityEditorWindow()
{
for (const_each<WidgetProxyCollection> i = m_widget_proxies; i; ++i)
delete i->second;
delete m_ui;
}
namespace
{
void delete_layout_items(QLayout* layout)
{
while (!layout->isEmpty())
{
QLayoutItem* item = layout->takeAt(0);
if (item->layout())
delete_layout_items(item->layout());
else item->widget()->deleteLater();
delete item;
}
}
}
void EntityEditorWindow::rebuild_form(const Dictionary& values)
{
delete_layout_items(m_form_layout);
m_form_factory->update(values, m_widget_definitions);
for (const_each<WidgetDefinitionCollection> i = m_widget_definitions; i; ++i)
create_input_widget(*i);
}
void EntityEditorWindow::create_form_layout()
{
m_form_layout = new QFormLayout(m_ui->scrollarea_contents);
int left, top, right, bottom;
m_form_layout->getContentsMargins(&left, &top, &right, &bottom);
m_form_layout->setContentsMargins(0, top, 0, bottom);
}
Dictionary EntityEditorWindow::get_widget_definition(const string& name) const
{
for (const_each<WidgetDefinitionCollection> i = m_widget_definitions; i; ++i)
{
const Dictionary& definition = *i;
if (definition.get<string>("name") == name)
return definition;
}
return Dictionary();
}
void EntityEditorWindow::create_input_widget(const Dictionary& definition)
{
const string widget_type = definition.get<string>("widget");
if (widget_type == "text_box")
{
create_text_box_input_widget(definition);
}
else if (widget_type == "entity_picker")
{
create_entity_picker_input_widget(definition);
}
else if (widget_type == "dropdown_list")
{
create_dropdown_list_input_widget(definition);
}
else
{
assert(!"Unknown widget type.");
}
}
namespace
{
QString get_label_text(const Dictionary& definition)
{
return definition.get<QString>("label") + ":";
}
bool should_be_focused(const Dictionary& definition)
{
return
definition.strings().exist("focus") &&
definition.strings().get<bool>("focus");
}
}
void EntityEditorWindow::create_text_box_input_widget(const Dictionary& definition)
{
QLineEdit* line_edit = new QLineEdit(m_ui->scrollarea_contents);
if (definition.strings().exist("default"))
line_edit->setText(definition.strings().get<QString>("default"));
if (should_be_focused(definition))
{
line_edit->selectAll();
line_edit->setFocus();
}
m_form_layout->addRow(get_label_text(definition), line_edit);
const string name = definition.get<string>("name");
m_widget_proxies[name] = new LineEditProxy(line_edit);
}
void EntityEditorWindow::create_entity_picker_input_widget(const Dictionary& definition)
{
QLineEdit* line_edit = new QLineEdit(m_ui->scrollarea_contents);
if (definition.strings().exist("default"))
line_edit->setText(definition.strings().get<QString>("default"));
if (should_be_focused(definition))
{
line_edit->selectAll();
line_edit->setFocus();
}
QWidget* button = new QPushButton("Browse", m_ui->scrollarea_contents);
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(button, SIGNAL(clicked()), m_signal_mapper, SLOT(map()));
const string name = definition.get<string>("name");
m_signal_mapper->setMapping(button, QString::fromStdString(name));
QHBoxLayout* layout = new QHBoxLayout();
layout->addWidget(line_edit);
layout->addWidget(button);
m_form_layout->addRow(get_label_text(definition), layout);
m_widget_proxies[name] = new LineEditProxy(line_edit);
}
void EntityEditorWindow::create_dropdown_list_input_widget(const Dictionary& definition)
{
QComboBox* combo_box = new QComboBox(m_ui->scrollarea_contents);
combo_box->setEditable(false);
const StringDictionary& items = definition.dictionaries().get("dropdown_items").strings();
for (const_each<StringDictionary> i = items; i; ++i)
combo_box->addItem(i->name(), i->value<QString>());
if (definition.strings().exist("default"))
{
const QString default_value = definition.strings().get<QString>("default");
combo_box->setCurrentIndex(combo_box->findData(QVariant::fromValue(default_value)));
}
if (definition.strings().exist("on_change"))
{
const string on_change_value = definition.strings().get<string>("on_change");
if (on_change_value == "rebuild_form")
connect(combo_box, SIGNAL(currentIndexChanged(int)), this, SLOT(slot_rebuild_form()));
}
if (should_be_focused(definition))
combo_box->setFocus();
m_form_layout->addRow(get_label_text(definition), combo_box);
const string name = definition.get<string>("name");
m_widget_proxies[name] = new ComboBoxProxy(combo_box);
}
Dictionary EntityEditorWindow::get_values() const
{
Dictionary values;
for (const_each<WidgetDefinitionCollection> i = m_widget_definitions; i; ++i)
{
const Dictionary& definition = *i;
const string name = definition.get<string>("name");
const string value = m_widget_proxies.find(name)->second->get();
values.insert(name, value);
}
return values;
}
void EntityEditorWindow::slot_rebuild_form()
{
rebuild_form(get_values());
}
namespace
{
class ForwardAcceptedSignal
: public QObject
{
Q_OBJECT
public:
ForwardAcceptedSignal(QObject* parent, const QString& widget_name)
: QObject(parent)
, m_widget_name(widget_name)
{
}
public slots:
void slot_accept(QString page_name, QString entity_name)
{
emit signal_accepted(m_widget_name, page_name, entity_name);
}
signals:
void signal_accepted(QString widget_name, QString page_name, QString entity_name);
private:
const QString m_widget_name;
};
}
void EntityEditorWindow::slot_open_entity_browser(const QString& widget_name)
{
const Dictionary widget_definition = get_widget_definition(widget_name.toStdString());
EntityBrowserWindow* browser_window =
new EntityBrowserWindow(
this,
widget_definition.get<string>("label"));
const Dictionary& entity_types = widget_definition.dictionaries().get("entity_types");
for (const_each<StringDictionary> i = entity_types.strings(); i; ++i)
{
const string entity_type = i->name();
const string entity_label = i->value<string>();
const StringDictionary entities = m_entity_browser->get_entities(entity_type);
browser_window->add_items_page(entity_type, entity_label, entities);
}
ForwardAcceptedSignal* forward_signal =
new ForwardAcceptedSignal(browser_window, widget_name);
QObject::connect(
browser_window, SIGNAL(signal_accepted(QString, QString)),
forward_signal, SLOT(slot_accept(QString, QString)));
QObject::connect(
forward_signal, SIGNAL(signal_accepted(QString, QString, QString)),
this, SLOT(slot_entity_browser_accept(QString, QString, QString)));
browser_window->showNormal();
browser_window->activateWindow();
}
void EntityEditorWindow::slot_entity_browser_accept(QString widget_name, QString page_name, QString entity_name)
{
m_widget_proxies[widget_name.toStdString()]->set(entity_name.toStdString());
// Close the entity browser.
qobject_cast<QWidget*>(sender()->parent())->close();
}
void EntityEditorWindow::slot_accept()
{
emit signal_accepted(get_values());
}
} // namespace studio
} // namespace appleseed
#include "mainwindow/project/moc_cpp_entityeditorwindow.cxx"
<commit_msg>fixed the layout of the widgets inside the entity editor window.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "entityeditorwindow.h"
// UI definition header.
#include "ui_entityeditorwindow.h"
// appleseed.studio headers.
#include "mainwindow/project/entitybrowserwindow.h"
#include "utility/interop.h"
#include "utility/tweaks.h"
// appleseed.foundation headers.
#include "foundation/utility/foreach.h"
#include "foundation/utility/string.h"
// Qt headers.
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QShortcut>
#include <QSignalMapper>
#include <Qt>
// Standard headers.
#include <cassert>
using namespace foundation;
using namespace std;
namespace appleseed {
namespace studio {
EntityEditorWindow::EntityEditorWindow(
QWidget* parent,
const string& window_title,
auto_ptr<IFormFactory> form_factory,
auto_ptr<IEntityBrowser> entity_browser,
const Dictionary& values)
: QWidget(parent)
, m_ui(new Ui::EntityEditorWindow())
, m_form_factory(form_factory)
, m_entity_browser(entity_browser)
, m_form_layout(0)
, m_signal_mapper(new QSignalMapper(this))
{
m_ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(Qt::Tool);
setWindowTitle(QString::fromStdString(window_title));
resize(400, 300);
create_form_layout();
rebuild_form(values);
connect(
m_signal_mapper, SIGNAL(mapped(const QString&)),
this, SLOT(slot_open_entity_browser(const QString&)));
connect(
m_ui->buttonbox->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
this, SLOT(slot_accept()));
connect(
m_ui->buttonbox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()),
this, SLOT(close()));
connect(
create_window_local_shortcut(this, Qt::Key_Return), SIGNAL(activated()),
this, SLOT(slot_accept()));
connect(
create_window_local_shortcut(this, Qt::Key_Escape), SIGNAL(activated()),
this, SLOT(close()));
}
EntityEditorWindow::~EntityEditorWindow()
{
for (const_each<WidgetProxyCollection> i = m_widget_proxies; i; ++i)
delete i->second;
delete m_ui;
}
namespace
{
void delete_layout_items(QLayout* layout)
{
while (!layout->isEmpty())
{
QLayoutItem* item = layout->takeAt(0);
if (item->layout())
delete_layout_items(item->layout());
else item->widget()->deleteLater();
delete item;
}
}
}
void EntityEditorWindow::rebuild_form(const Dictionary& values)
{
delete_layout_items(m_form_layout);
m_form_factory->update(values, m_widget_definitions);
for (const_each<WidgetDefinitionCollection> i = m_widget_definitions; i; ++i)
create_input_widget(*i);
}
void EntityEditorWindow::create_form_layout()
{
m_form_layout = new QFormLayout(m_ui->scrollarea_contents);
m_form_layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
int left, top, right, bottom;
m_form_layout->getContentsMargins(&left, &top, &right, &bottom);
m_form_layout->setContentsMargins(0, top, 0, bottom);
}
Dictionary EntityEditorWindow::get_widget_definition(const string& name) const
{
for (const_each<WidgetDefinitionCollection> i = m_widget_definitions; i; ++i)
{
const Dictionary& definition = *i;
if (definition.get<string>("name") == name)
return definition;
}
return Dictionary();
}
void EntityEditorWindow::create_input_widget(const Dictionary& definition)
{
const string widget_type = definition.get<string>("widget");
if (widget_type == "text_box")
{
create_text_box_input_widget(definition);
}
else if (widget_type == "entity_picker")
{
create_entity_picker_input_widget(definition);
}
else if (widget_type == "dropdown_list")
{
create_dropdown_list_input_widget(definition);
}
else
{
assert(!"Unknown widget type.");
}
}
namespace
{
QString get_label_text(const Dictionary& definition)
{
return definition.get<QString>("label") + ":";
}
bool should_be_focused(const Dictionary& definition)
{
return
definition.strings().exist("focus") &&
definition.strings().get<bool>("focus");
}
}
void EntityEditorWindow::create_text_box_input_widget(const Dictionary& definition)
{
QLineEdit* line_edit = new QLineEdit(m_ui->scrollarea_contents);
if (definition.strings().exist("default"))
line_edit->setText(definition.strings().get<QString>("default"));
if (should_be_focused(definition))
{
line_edit->selectAll();
line_edit->setFocus();
}
m_form_layout->addRow(get_label_text(definition), line_edit);
const string name = definition.get<string>("name");
m_widget_proxies[name] = new LineEditProxy(line_edit);
}
void EntityEditorWindow::create_entity_picker_input_widget(const Dictionary& definition)
{
QLineEdit* line_edit = new QLineEdit(m_ui->scrollarea_contents);
if (definition.strings().exist("default"))
line_edit->setText(definition.strings().get<QString>("default"));
if (should_be_focused(definition))
{
line_edit->selectAll();
line_edit->setFocus();
}
QWidget* button = new QPushButton("Browse", m_ui->scrollarea_contents);
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(button, SIGNAL(clicked()), m_signal_mapper, SLOT(map()));
const string name = definition.get<string>("name");
m_signal_mapper->setMapping(button, QString::fromStdString(name));
QHBoxLayout* layout = new QHBoxLayout();
layout->addWidget(line_edit);
layout->addWidget(button);
m_form_layout->addRow(get_label_text(definition), layout);
m_widget_proxies[name] = new LineEditProxy(line_edit);
}
void EntityEditorWindow::create_dropdown_list_input_widget(const Dictionary& definition)
{
QComboBox* combo_box = new QComboBox(m_ui->scrollarea_contents);
combo_box->setEditable(false);
const StringDictionary& items = definition.dictionaries().get("dropdown_items").strings();
for (const_each<StringDictionary> i = items; i; ++i)
combo_box->addItem(i->name(), i->value<QString>());
if (definition.strings().exist("default"))
{
const QString default_value = definition.strings().get<QString>("default");
combo_box->setCurrentIndex(combo_box->findData(QVariant::fromValue(default_value)));
}
if (definition.strings().exist("on_change"))
{
const string on_change_value = definition.strings().get<string>("on_change");
if (on_change_value == "rebuild_form")
connect(combo_box, SIGNAL(currentIndexChanged(int)), this, SLOT(slot_rebuild_form()));
}
if (should_be_focused(definition))
combo_box->setFocus();
m_form_layout->addRow(get_label_text(definition), combo_box);
const string name = definition.get<string>("name");
m_widget_proxies[name] = new ComboBoxProxy(combo_box);
}
Dictionary EntityEditorWindow::get_values() const
{
Dictionary values;
for (const_each<WidgetDefinitionCollection> i = m_widget_definitions; i; ++i)
{
const Dictionary& definition = *i;
const string name = definition.get<string>("name");
const string value = m_widget_proxies.find(name)->second->get();
values.insert(name, value);
}
return values;
}
void EntityEditorWindow::slot_rebuild_form()
{
rebuild_form(get_values());
}
namespace
{
class ForwardAcceptedSignal
: public QObject
{
Q_OBJECT
public:
ForwardAcceptedSignal(QObject* parent, const QString& widget_name)
: QObject(parent)
, m_widget_name(widget_name)
{
}
public slots:
void slot_accept(QString page_name, QString entity_name)
{
emit signal_accepted(m_widget_name, page_name, entity_name);
}
signals:
void signal_accepted(QString widget_name, QString page_name, QString entity_name);
private:
const QString m_widget_name;
};
}
void EntityEditorWindow::slot_open_entity_browser(const QString& widget_name)
{
const Dictionary widget_definition = get_widget_definition(widget_name.toStdString());
EntityBrowserWindow* browser_window =
new EntityBrowserWindow(
this,
widget_definition.get<string>("label"));
const Dictionary& entity_types = widget_definition.dictionaries().get("entity_types");
for (const_each<StringDictionary> i = entity_types.strings(); i; ++i)
{
const string entity_type = i->name();
const string entity_label = i->value<string>();
const StringDictionary entities = m_entity_browser->get_entities(entity_type);
browser_window->add_items_page(entity_type, entity_label, entities);
}
ForwardAcceptedSignal* forward_signal =
new ForwardAcceptedSignal(browser_window, widget_name);
QObject::connect(
browser_window, SIGNAL(signal_accepted(QString, QString)),
forward_signal, SLOT(slot_accept(QString, QString)));
QObject::connect(
forward_signal, SIGNAL(signal_accepted(QString, QString, QString)),
this, SLOT(slot_entity_browser_accept(QString, QString, QString)));
browser_window->showNormal();
browser_window->activateWindow();
}
void EntityEditorWindow::slot_entity_browser_accept(QString widget_name, QString page_name, QString entity_name)
{
m_widget_proxies[widget_name.toStdString()]->set(entity_name.toStdString());
// Close the entity browser.
qobject_cast<QWidget*>(sender()->parent())->close();
}
void EntityEditorWindow::slot_accept()
{
emit signal_accepted(get_values());
}
} // namespace studio
} // namespace appleseed
#include "mainwindow/project/moc_cpp_entityeditorwindow.cxx"
<|endoftext|> |
<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimePlatformAgnosticPch.h"
#ifdef INTL_ICU
#include "Common.h"
#include "ChakraPlatform.h"
#include "Intl.h"
#define U_STATIC_IMPLEMENTATION
#define U_SHOW_CPLUSPLUS_API 0
#pragma warning(push)
#pragma warning(disable:4995) // deprecation warning
#include <unicode/uloc.h>
#include <unicode/numfmt.h>
//#include <unicode/decimfmt.h>
#pragma warning(pop)
namespace PlatformAgnostic
{
namespace Intl
{
using namespace PlatformAgnostic::Resource;
/*
// NOTE: cannot return non-pointer instance of a pure virtual class, so move ctor and move asgn will not be applicable.
// TODO (doilij): Remove if unused
template <typename T>
inline PlatformAgnosticIntlObject<T> PlatformAgnosticIntlObject<T>::operator=(PlatformAgnosticIntlObject<T> &&other)
{
// Only move if the object is different.
if (this != &other)
{
if (this->intlObject)
{
// REVIEW (doilij): Ensure that this statement is true in practice, or delete this assert.
AssertMsg(false, "FinalizableIntlObject move assignment shouldn't need to delete other->intlObject because it should be initialized to nullptr: check usage.");
delete this->intlObject;
}
this->move(other);
}
return *this;
}
*/
bool IsWellFormedLanguageTag(_In_z_ const char16 *languageTag, _In_ const charcount_t cch)
{
// Allocate memory for the UTF8 output buffer. Need 3 bytes for each (code point + null) to satisfy SAL.
const size_t inputLangTagUtf8SizeAllocated = AllocSizeMath::Mul(AllocSizeMath::Add(cch, 1), 3);
// REVIEW (doilij): not perf critical so I used HeapNewArrayZ to zero-out the allocated array
utf8char_t *inputLangTagUtf8 = HeapNewArrayZ(utf8char_t, inputLangTagUtf8SizeAllocated);
if (!inputLangTagUtf8)
{
AssertOrFailFastMsg(false, "OOM: HeapNewArrayZ failed to allocate.");
}
const size_t inputLangTagUtf8SizeActual = utf8::EncodeIntoAndNullTerminate(inputLangTagUtf8, languageTag, cch);
bool success = false;
UErrorCode error = UErrorCode::U_ZERO_ERROR;
// REVIEW (doilij): should we / do we need to zero these stack-allocated arrays?
char icuLocaleId[ULOC_FULLNAME_CAPACITY] = { 0 };
char icuLangTag[ULOC_FULLNAME_CAPACITY] = { 0 };
int32_t parsedLength = 0;
int32_t forLangTagResultLength = 0;
int32_t toLangTagResultLength = 0;
// Convert input language tag to a locale ID for use in uloc_toLanguageTag API.
forLangTagResultLength = uloc_forLanguageTag(reinterpret_cast<const char *>(inputLangTagUtf8),
icuLocaleId, ULOC_FULLNAME_CAPACITY, &parsedLength, &error);
success = (forLangTagResultLength > 0) && (parsedLength > 0) &&
U_SUCCESS(error) && ((size_t)parsedLength == inputLangTagUtf8SizeActual);
if (!success)
{
goto cleanup;
}
toLangTagResultLength = uloc_toLanguageTag(icuLocaleId, icuLangTag, ULOC_FULLNAME_CAPACITY, TRUE, &error);
success = toLangTagResultLength && U_SUCCESS(error);
if (!success)
{
if (error == UErrorCode::U_ILLEGAL_ARGUMENT_ERROR)
{
AssertMsg(false, "uloc_toLanguageTag: error U_ILLEGAL_ARGUMENT_ERROR");
}
else
{
AssertMsg(false, "uloc_toLanguageTag: unexpected error (besides U_ILLEGAL_ARGUMENT_ERROR)");
}
goto cleanup;
}
cleanup:
HeapDeleteArray(inputLangTagUtf8SizeAllocated, inputLangTagUtf8);
inputLangTagUtf8 = nullptr;
return success;
}
HRESULT NormalizeLanguageTag(_In_z_ const char16 *languageTag, _In_ const charcount_t cch,
_Out_ char16 *normalized, _Out_ size_t *normalizedLength)
{
// Allocate memory for the UTF8 output buffer. Need 3 bytes for each (code point + null) to satisfy SAL.
const size_t inputLangTagUtf8SizeAllocated = AllocSizeMath::Mul(AllocSizeMath::Add(cch, 1), 3);
// REVIEW (doilij): not perf critical so I used HeapNewArrayZ to zero-out the allocated array
utf8char_t *inputLangTagUtf8 = HeapNewArrayZ(utf8char_t, inputLangTagUtf8SizeAllocated);
if (!inputLangTagUtf8)
{
AssertOrFailFastMsg(false, "OOM: HeapNewArrayZ failed to allocate.");
}
const size_t inputLangTagUtf8SizeActual = utf8::EncodeIntoAndNullTerminate(inputLangTagUtf8, languageTag, cch);
// REVIEW (doilij): should we / do we need to zero these stack-allocated arrays?
char icuLocaleId[ULOC_FULLNAME_CAPACITY] = { 0 };
char icuLangTag[ULOC_FULLNAME_CAPACITY] = { 0 };
bool success = false;
UErrorCode error = UErrorCode::U_ZERO_ERROR;
int32_t parsedLength = 0;
int32_t forLangTagResultLength = 0;
int32_t toLangTagResultLength = 0;
// Convert input language tag to a locale ID for use in uloc_toLanguageTag API.
forLangTagResultLength = uloc_forLanguageTag(reinterpret_cast<const char *>(inputLangTagUtf8), icuLocaleId, ULOC_FULLNAME_CAPACITY, &parsedLength, &error);
success = forLangTagResultLength && parsedLength && U_SUCCESS(error);
if (!success)
{
AssertMsg(false, "uloc_forLanguageTag failed");
goto cleanup;
}
// Try to convert icuLocaleId (locale ID version of input locale string) to BCP47 language tag, using strict checks
toLangTagResultLength = uloc_toLanguageTag(icuLocaleId, icuLangTag, ULOC_FULLNAME_CAPACITY, TRUE, &error);
success = toLangTagResultLength && U_SUCCESS(error);
if (!success)
{
if (error == UErrorCode::U_ILLEGAL_ARGUMENT_ERROR)
{
AssertMsg(false, "uloc_toLanguageTag: error U_ILLEGAL_ARGUMENT_ERROR");
}
else
{
AssertMsg(false, "uloc_toLanguageTag: unexpected error (besides U_ILLEGAL_ARGUMENT_ERROR)");
}
goto cleanup;
}
*normalizedLength = utf8::DecodeUnitsIntoAndNullTerminateNoAdvance(normalized,
reinterpret_cast<const utf8char_t *>(icuLangTag), reinterpret_cast<utf8char_t *>(icuLangTag + toLangTagResultLength), utf8::doDefault);
cleanup:
HeapDeleteArray(inputLangTagUtf8SizeAllocated, inputLangTagUtf8);
inputLangTagUtf8 = nullptr;
return success ? S_OK : E_INVALIDARG;
}
// REVIEW (doilij): Is scriptContext needed as a param here?
int32_t GetCurrencyFractionDigits(_In_z_ const char16 * currencyCode)
{
UErrorCode error = UErrorCode::U_ZERO_ERROR;
const UChar *uCurrencyCode = (const UChar *)currencyCode; // UChar, like char16, is guaranteed to be 2 bytes on all platforms.
int32_t minFracDigits = 2; // REVIEW: fallback value is a good starting value here
// Note: The number of fractional digits specified for a currency is not locale-dependent.
icu::NumberFormat *nf = icu::NumberFormat::createCurrencyInstance(error); // using default locale
if (U_FAILURE(error))
{
#ifdef INTL_ICU_DEBUG
if (error == UErrorCode::U_MISSING_RESOURCE_ERROR)
{
Output::Print(_u("EntryIntl_CurrencyDigits > icu::NumberFormat::createCurrencyInstance(error) > U_MISSING_RESOURCE_ERROR (%d)\n"), error);
}
else
{
Output::Print(_u("EntryIntl_CurrencyDigits > icu::NumberFormat::createCurrencyInstance(error) > UErrorCode (%d)\n"), error);
}
#endif
goto LReturn;
}
nf->setCurrency(uCurrencyCode, error);
if (U_FAILURE(error))
{
#ifdef INTL_ICU_DEBUG
if (error == UErrorCode::U_MISSING_RESOURCE_ERROR)
{
Output::Print(_u("EntryIntl_CurrencyDigits > nf->setCurrency(uCurrencyCode (%s), error) > U_MISSING_RESOURCE_ERROR (%d)\n"), currencyCode, error);
}
else
{
Output::Print(_u("EntryIntl_CurrencyDigits > nf->setCurrency(uCurrencyCode (%s), error) > UErrorCode (%d)\n"), currencyCode, error);
}
#endif
goto LReturn;
}
minFracDigits = nf->getMinimumFractionDigits();
#ifdef INTL_ICU_DEBUG
Output::Print(_u("EntryIntl_CurrencyDigits > nf->getMinimumFractionDigits() successful > returned (%d)\n"), minFracDigits);
#endif
LReturn:
// Since something failed, return "reasonable" default of 2 fractional digits (obviously won't be the case for some currencies like JPY).
// REVIEW (doilij): What does the spec say to do if a currency is not supported?
#ifdef INTL_ICU_DEBUG
Output::Print(_u("EntryIntl_CurrencyDigits > returning (%d)\n"), minFracDigits);
#endif
return minFracDigits;
}
IPlatformAgnosticResource *CreateNumberFormat()
{
UErrorCode error = UErrorCode::U_ZERO_ERROR;
// REVIEW (doilij): is allocating with `new` here okay?
icu::NumberFormat *nf = icu::NumberFormat::createInstance(error);
IPlatformAgnosticResource *obj = new PlatformAgnosticIntlObject<icu::NumberFormat>(nf);
AssertMsg(U_SUCCESS(error), "Creating icu::NumberFormat failed");
return obj;
}
template const char16 *FormatNumber<>(IPlatformAgnosticResource *formatter, int32 val);
template const char16 *FormatNumber<>(IPlatformAgnosticResource *formatter, double val);
template <typename T>
const char16 *FormatNumber(IPlatformAgnosticResource *formatter, T val)
{
icu::UnicodeString result;
auto *formatterHolder = (PlatformAgnosticIntlObject<icu::NumberFormat> *)formatter;
AssertOrFailFastMsg(formatterHolder, "Formatter did not hold an object of type `FinalizableIntlObject<icu::NumberFormat>`");
icu::NumberFormat *numberFormatter = formatterHolder->GetInstance();
numberFormatter->format(val, result);
int32_t length = result.length();
char16 *ret = new char16[length + 1];
result.extract(0, length, ret);
ret[length] = 0;
return ret;
}
} // namespace Intl
} // namespace PlatformAgnostic
#endif // INTL_ICU
<commit_msg>Some xplat fixes.<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimePlatformAgnosticPch.h"
#ifdef INTL_ICU
// REVIEW (doilij): Where are these defined that is safe to include in PlatformAgnostic?
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
#include "Codex/Utf8Codex.h"
#ifndef _WIN32
// REVIEW (doilij): The PCH allegedly defines enough stuff to get AssertMsg to work -- why was compile failing for this file?
#ifdef AssertMsg
#undef AssertMsg
#define AssertMsg(test, message)
#endif
#ifdef AssertOrFailFastMessage
#undef AssertOrFailFastMessage
#define AssertOrFailFastMessage(test, message)
#endif
#define DECLSPEC_GUARD_OVERFLOW
#endif // !_WIN32
#include "Common/MathUtil.h"
#include "Core/AllocSizeMath.h"
#include "Intl.h"
#define U_STATIC_IMPLEMENTATION
#define U_SHOW_CPLUSPLUS_API 0
#pragma warning(push)
#pragma warning(disable:4995) // deprecation warning
#include <unicode/uloc.h>
#include <unicode/numfmt.h>
//#include <unicode/decimfmt.h>
#pragma warning(pop)
namespace PlatformAgnostic
{
namespace Intl
{
using namespace PlatformAgnostic::Resource;
/*
// NOTE: cannot return non-pointer instance of a pure virtual class, so move ctor and move asgn will not be applicable.
// TODO (doilij): Remove if unused
template <typename T>
inline PlatformAgnosticIntlObject<T> PlatformAgnosticIntlObject<T>::operator=(PlatformAgnosticIntlObject<T> &&other)
{
// Only move if the object is different.
if (this != &other)
{
if (this->intlObject)
{
// REVIEW (doilij): Ensure that this statement is true in practice, or delete this assert.
AssertMsg(false, "FinalizableIntlObject move assignment shouldn't need to delete other->intlObject because it should be initialized to nullptr: check usage.");
delete this->intlObject;
}
this->move(other);
}
return *this;
}
*/
bool IsWellFormedLanguageTag(_In_z_ const char16 *languageTag, _In_ const charcount_t cch)
{
// Allocate memory for the UTF8 output buffer. Need 3 bytes for each (code point + null) to satisfy SAL.
const size_t inputLangTagUtf8SizeAllocated = AllocSizeMath::Mul(AllocSizeMath::Add(cch, 1), 3);
// REVIEW (doilij): not perf critical so I used HeapNewArrayZ to zero-out the allocated array
unsigned char *inputLangTagUtf8 = new unsigned char[inputLangTagUtf8SizeAllocated];
if (!inputLangTagUtf8)
{
AssertOrFailFastMsg(false, "OOM: HeapNewArrayZ failed to allocate.");
}
const size_t inputLangTagUtf8SizeActual = utf8::EncodeIntoAndNullTerminate(inputLangTagUtf8, languageTag, cch);
bool success = false;
UErrorCode error = UErrorCode::U_ZERO_ERROR;
// REVIEW (doilij): should we / do we need to zero these stack-allocated arrays?
char icuLocaleId[ULOC_FULLNAME_CAPACITY] = { 0 };
char icuLangTag[ULOC_FULLNAME_CAPACITY] = { 0 };
int32_t parsedLength = 0;
int32_t forLangTagResultLength = 0;
int32_t toLangTagResultLength = 0;
// Convert input language tag to a locale ID for use in uloc_toLanguageTag API.
forLangTagResultLength = uloc_forLanguageTag(reinterpret_cast<const char *>(inputLangTagUtf8),
icuLocaleId, ULOC_FULLNAME_CAPACITY, &parsedLength, &error);
success = (forLangTagResultLength > 0) && (parsedLength > 0) &&
U_SUCCESS(error) && ((size_t)parsedLength == inputLangTagUtf8SizeActual);
if (!success)
{
goto cleanup;
}
toLangTagResultLength = uloc_toLanguageTag(icuLocaleId, icuLangTag, ULOC_FULLNAME_CAPACITY, TRUE, &error);
success = toLangTagResultLength && U_SUCCESS(error);
if (!success)
{
if (error == UErrorCode::U_ILLEGAL_ARGUMENT_ERROR)
{
AssertMsg(false, "uloc_toLanguageTag: error U_ILLEGAL_ARGUMENT_ERROR");
}
else
{
AssertMsg(false, "uloc_toLanguageTag: unexpected error (besides U_ILLEGAL_ARGUMENT_ERROR)");
}
goto cleanup;
}
cleanup:
delete[] inputLangTagUtf8;
inputLangTagUtf8 = nullptr;
return success;
}
HRESULT NormalizeLanguageTag(_In_z_ const char16 *languageTag, _In_ const charcount_t cch,
_Out_ char16 *normalized, _Out_ size_t *normalizedLength)
{
// Allocate memory for the UTF8 output buffer. Need 3 bytes for each (code point + null) to satisfy SAL.
const size_t inputLangTagUtf8SizeAllocated = AllocSizeMath::Mul(AllocSizeMath::Add(cch, 1), 3);
// REVIEW (doilij): not perf critical so I used HeapNewArrayZ to zero-out the allocated array
unsigned char *inputLangTagUtf8 = new unsigned char[inputLangTagUtf8SizeAllocated];
if (!inputLangTagUtf8)
{
AssertOrFailFastMsg(false, "OOM: HeapNewArrayZ failed to allocate.");
}
const size_t inputLangTagUtf8SizeActual = utf8::EncodeIntoAndNullTerminate(inputLangTagUtf8, languageTag, cch);
// REVIEW (doilij): should we / do we need to zero these stack-allocated arrays?
char icuLocaleId[ULOC_FULLNAME_CAPACITY] = { 0 };
char icuLangTag[ULOC_FULLNAME_CAPACITY] = { 0 };
bool success = false;
UErrorCode error = UErrorCode::U_ZERO_ERROR;
int32_t parsedLength = 0;
int32_t forLangTagResultLength = 0;
int32_t toLangTagResultLength = 0;
// Convert input language tag to a locale ID for use in uloc_toLanguageTag API.
forLangTagResultLength = uloc_forLanguageTag(reinterpret_cast<const char *>(inputLangTagUtf8), icuLocaleId, ULOC_FULLNAME_CAPACITY, &parsedLength, &error);
success = forLangTagResultLength && parsedLength && U_SUCCESS(error);
if (!success)
{
AssertMsg(false, "uloc_forLanguageTag failed");
goto cleanup;
}
// Try to convert icuLocaleId (locale ID version of input locale string) to BCP47 language tag, using strict checks
toLangTagResultLength = uloc_toLanguageTag(icuLocaleId, icuLangTag, ULOC_FULLNAME_CAPACITY, TRUE, &error);
success = toLangTagResultLength && U_SUCCESS(error);
if (!success)
{
if (error == UErrorCode::U_ILLEGAL_ARGUMENT_ERROR)
{
AssertMsg(false, "uloc_toLanguageTag: error U_ILLEGAL_ARGUMENT_ERROR");
}
else
{
AssertMsg(false, "uloc_toLanguageTag: unexpected error (besides U_ILLEGAL_ARGUMENT_ERROR)");
}
goto cleanup;
}
*normalizedLength = utf8::DecodeUnitsIntoAndNullTerminateNoAdvance(normalized,
reinterpret_cast<const utf8char_t *>(icuLangTag), reinterpret_cast<utf8char_t *>(icuLangTag + toLangTagResultLength), utf8::doDefault);
cleanup:
delete[] inputLangTagUtf8;
inputLangTagUtf8 = nullptr;
return success ? S_OK : E_INVALIDARG;
}
// REVIEW (doilij): Is scriptContext needed as a param here?
int32_t GetCurrencyFractionDigits(_In_z_ const char16 * currencyCode)
{
UErrorCode error = UErrorCode::U_ZERO_ERROR;
const UChar *uCurrencyCode = (const UChar *)currencyCode; // UChar, like char16, is guaranteed to be 2 bytes on all platforms.
int32_t minFracDigits = 2; // REVIEW: fallback value is a good starting value here
// Note: The number of fractional digits specified for a currency is not locale-dependent.
icu::NumberFormat *nf = icu::NumberFormat::createCurrencyInstance(error); // using default locale
if (U_FAILURE(error))
{
#ifdef INTL_ICU_DEBUG
if (error == UErrorCode::U_MISSING_RESOURCE_ERROR)
{
Output::Print(_u("EntryIntl_CurrencyDigits > icu::NumberFormat::createCurrencyInstance(error) > U_MISSING_RESOURCE_ERROR (%d)\n"), error);
}
else
{
Output::Print(_u("EntryIntl_CurrencyDigits > icu::NumberFormat::createCurrencyInstance(error) > UErrorCode (%d)\n"), error);
}
#endif
goto LReturn;
}
nf->setCurrency(uCurrencyCode, error);
if (U_FAILURE(error))
{
#ifdef INTL_ICU_DEBUG
if (error == UErrorCode::U_MISSING_RESOURCE_ERROR)
{
Output::Print(_u("EntryIntl_CurrencyDigits > nf->setCurrency(uCurrencyCode (%s), error) > U_MISSING_RESOURCE_ERROR (%d)\n"), currencyCode, error);
}
else
{
Output::Print(_u("EntryIntl_CurrencyDigits > nf->setCurrency(uCurrencyCode (%s), error) > UErrorCode (%d)\n"), currencyCode, error);
}
#endif
goto LReturn;
}
minFracDigits = nf->getMinimumFractionDigits();
#ifdef INTL_ICU_DEBUG
Output::Print(_u("EntryIntl_CurrencyDigits > nf->getMinimumFractionDigits() successful > returned (%d)\n"), minFracDigits);
#endif
LReturn:
// Since something failed, return "reasonable" default of 2 fractional digits (obviously won't be the case for some currencies like JPY).
// REVIEW (doilij): What does the spec say to do if a currency is not supported?
#ifdef INTL_ICU_DEBUG
Output::Print(_u("EntryIntl_CurrencyDigits > returning (%d)\n"), minFracDigits);
#endif
return minFracDigits;
}
IPlatformAgnosticResource *CreateNumberFormat()
{
UErrorCode error = UErrorCode::U_ZERO_ERROR;
// REVIEW (doilij): is allocating with `new` here okay?
icu::NumberFormat *nf = icu::NumberFormat::createInstance(error);
IPlatformAgnosticResource *obj = new PlatformAgnosticIntlObject<icu::NumberFormat>(nf);
AssertMsg(U_SUCCESS(error), "Creating icu::NumberFormat failed");
return obj;
}
template const char16 *FormatNumber<>(IPlatformAgnosticResource *formatter, int32_t val);
template const char16 *FormatNumber<>(IPlatformAgnosticResource *formatter, double val);
template <typename T>
const char16 *FormatNumber(IPlatformAgnosticResource *formatter, T val)
{
icu::UnicodeString result;
auto *formatterHolder = (PlatformAgnosticIntlObject<icu::NumberFormat> *)formatter;
AssertOrFailFastMsg(formatterHolder, "Formatter did not hold an object of type `FinalizableIntlObject<icu::NumberFormat>`");
icu::NumberFormat *numberFormatter = formatterHolder->GetInstance();
numberFormatter->format(val, result);
int32_t length = result.length();
char16 *ret = new char16[length + 1];
result.extract(0, length, (UChar *)ret);
ret[length] = 0;
return ret;
}
} // namespace Intl
} // namespace PlatformAgnostic
#endif // INTL_ICU
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Entity.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Models/Spell.hpp>
namespace RosettaStone
{
Entity::Entity(Player& _owner, Card& _card) : card(_card), owner(&_owner)
{
auraEffects = new AuraEffects(this);
for (auto& gameTag : _card.gameTags)
{
Entity::SetGameTag(gameTag.first, gameTag.second);
}
}
Entity::Entity(const Entity& ent)
{
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
}
Entity::Entity(Entity&& ent) noexcept
{
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
}
Entity::~Entity()
{
FreeMemory();
}
Entity& Entity::operator=(const Entity& ent)
{
if (this == &ent)
{
return *this;
}
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
return *this;
}
Entity& Entity::operator=(Entity&& ent) noexcept
{
if (this == &ent)
{
return *this;
}
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
return *this;
}
void Entity::Reset()
{
SetGameTag(GameTag::DAMAGE, 0);
SetGameTag(GameTag::EXHAUSTED, 0);
SetGameTag(GameTag::ATK, 0);
SetGameTag(GameTag::HEALTH, 0);
SetGameTag(GameTag::COST, 0);
SetGameTag(GameTag::TAUNT, 0);
SetGameTag(GameTag::FROZEN, 0);
SetGameTag(GameTag::CHARGE, 0);
SetGameTag(GameTag::WINDFURY, 0);
SetGameTag(GameTag::DIVINE_SHIELD, 0);
SetGameTag(GameTag::STEALTH, 0);
SetGameTag(GameTag::NUM_ATTACKS_THIS_TURN, 0);
}
int Entity::GetGameTag(GameTag tag) const
{
if (m_gameTags.find(tag) == m_gameTags.end())
{
return 0;
}
if (auraEffects != nullptr)
{
return m_gameTags.at(tag) + auraEffects->GetGameTag(tag);
}
return m_gameTags.at(tag);
}
void Entity::SetGameTag(GameTag tag, int value)
{
m_gameTags.insert_or_assign(tag, value);
}
int Entity::GetCost() const
{
return GetGameTag(GameTag::COST);
}
void Entity::SetCost(int cost)
{
SetGameTag(GameTag::COST, cost);
}
void Entity::Destroy()
{
isDestroyed = true;
}
Entity* Entity::GetFromCard(Player& player, Card&& card)
{
Entity* result;
switch (card.GetCardType())
{
case CardType::HERO:
result = new Hero(player, card);
break;
case CardType::HERO_POWER:
result = new HeroPower(player, card);
break;
case CardType::MINION:
result = new Minion(player, card);
break;
case CardType::SPELL:
result = new Spell(player, card);
break;
case CardType::WEAPON:
result = new Weapon(player, card);
break;
default:
throw std::invalid_argument(
"Generic::DrawCard() - Invalid card type!");
}
// Set entity ID
result->id = player.GetGame()->GetNextID();
return result;
}
void Entity::FreeMemory()
{
delete auraEffects;
delete onGoingEffect;
m_gameTags.clear();
}
} // namespace RosettaStone
<commit_msg>fix: Correct initialization order error<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <Rosetta/Games/Game.hpp>
#include <Rosetta/Models/Entity.hpp>
#include <Rosetta/Models/Player.hpp>
#include <Rosetta/Models/Spell.hpp>
namespace RosettaStone
{
Entity::Entity(Player& _owner, Card& _card) : owner(&_owner), card(_card)
{
auraEffects = new AuraEffects(this);
for (auto& gameTag : _card.gameTags)
{
Entity::SetGameTag(gameTag.first, gameTag.second);
}
}
Entity::Entity(const Entity& ent)
{
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
}
Entity::Entity(Entity&& ent) noexcept
{
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
}
Entity::~Entity()
{
FreeMemory();
}
Entity& Entity::operator=(const Entity& ent)
{
if (this == &ent)
{
return *this;
}
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
return *this;
}
Entity& Entity::operator=(Entity&& ent) noexcept
{
if (this == &ent)
{
return *this;
}
FreeMemory();
owner = ent.owner;
card = ent.card;
auraEffects = ent.auraEffects;
onGoingEffect = ent.onGoingEffect;
m_gameTags = ent.m_gameTags;
return *this;
}
void Entity::Reset()
{
SetGameTag(GameTag::DAMAGE, 0);
SetGameTag(GameTag::EXHAUSTED, 0);
SetGameTag(GameTag::ATK, 0);
SetGameTag(GameTag::HEALTH, 0);
SetGameTag(GameTag::COST, 0);
SetGameTag(GameTag::TAUNT, 0);
SetGameTag(GameTag::FROZEN, 0);
SetGameTag(GameTag::CHARGE, 0);
SetGameTag(GameTag::WINDFURY, 0);
SetGameTag(GameTag::DIVINE_SHIELD, 0);
SetGameTag(GameTag::STEALTH, 0);
SetGameTag(GameTag::NUM_ATTACKS_THIS_TURN, 0);
}
int Entity::GetGameTag(GameTag tag) const
{
if (m_gameTags.find(tag) == m_gameTags.end())
{
return 0;
}
if (auraEffects != nullptr)
{
return m_gameTags.at(tag) + auraEffects->GetGameTag(tag);
}
return m_gameTags.at(tag);
}
void Entity::SetGameTag(GameTag tag, int value)
{
m_gameTags.insert_or_assign(tag, value);
}
int Entity::GetCost() const
{
return GetGameTag(GameTag::COST);
}
void Entity::SetCost(int cost)
{
SetGameTag(GameTag::COST, cost);
}
void Entity::Destroy()
{
isDestroyed = true;
}
Entity* Entity::GetFromCard(Player& player, Card&& card)
{
Entity* result;
switch (card.GetCardType())
{
case CardType::HERO:
result = new Hero(player, card);
break;
case CardType::HERO_POWER:
result = new HeroPower(player, card);
break;
case CardType::MINION:
result = new Minion(player, card);
break;
case CardType::SPELL:
result = new Spell(player, card);
break;
case CardType::WEAPON:
result = new Weapon(player, card);
break;
default:
throw std::invalid_argument(
"Generic::DrawCard() - Invalid card type!");
}
// Set entity ID
result->id = player.GetGame()->GetNextID();
return result;
}
void Entity::FreeMemory()
{
delete auraEffects;
delete onGoingEffect;
m_gameTags.clear();
}
} // namespace RosettaStone
<|endoftext|> |
<commit_before><commit_msg>fix comments.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "rtos/ThisThread.h"
#include "mbed_error.h"
#include "platform/mbed_atomic.h"
#include "events/EventQueue.h"
#include "events/mbed_shared_queues.h"
#include "QUECTEL_BC95_CellularStack.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#define PACKET_SIZE_MAX 1358
#define TXFULL_EVENT_TIMEOUT 1s
#define AT_UPLINK_BUSY 159
#define AT_UART_BUFFER_ERROR 536
#define AT_BACK_OFF_TIMER 537
using namespace std::chrono;
using namespace mbed;
using namespace mbed_cellular_util;
QUECTEL_BC95_CellularStack::QUECTEL_BC95_CellularStack(ATHandler &atHandler, int cid, nsapi_ip_stack_t stack_type, AT_CellularDevice &device) :
AT_CellularStack(atHandler, cid, stack_type, device), _event_queue(mbed_event_queue()), _txfull_event_id(0)
{
_at.set_urc_handler("+NSONMI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsonmi));
_at.set_urc_handler("+NSOCLI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsocli));
}
QUECTEL_BC95_CellularStack::~QUECTEL_BC95_CellularStack()
{
if (_txfull_event_id) {
_event_queue->cancel(_txfull_event_id);
}
_at.set_urc_handler("+NSONMI:", nullptr);
_at.set_urc_handler("+NSOCLI:", nullptr);
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &address)
{
CellularSocket *socket = (CellularSocket *)handle;
_at.lock();
if (socket->id == -1) {
const nsapi_error_t error_create = create_socket_impl(socket);
if (error_create != NSAPI_ERROR_OK) {
return error_create;
}
}
_at.cmd_start("AT+NSOCO=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.cmd_stop_read_resp();
_at.unlock();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
socket->remoteAddress = address;
socket->connected = true;
return NSAPI_ERROR_OK;
}
return NSAPI_ERROR_NO_CONNECTION;
}
void QUECTEL_BC95_CellularStack::urc_nsonmi()
{
int sock_id = _at.read_int();
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->id == sock_id) {
if (sock->_cb) {
sock->_cb(sock->_data);
}
break;
}
}
}
void QUECTEL_BC95_CellularStack::urc_nsocli()
{
int sock_id = _at.read_int();
const nsapi_error_t err = _at.get_last_error();
if (err != NSAPI_ERROR_OK) {
return;
}
CellularSocket *sock = find_socket(sock_id);
if (sock) {
sock->closed = true;
if (sock->_cb) {
sock->_cb(sock->_data);
}
tr_info("Socket closed %d", sock_id);
}
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_close_impl(int sock_id)
{
CellularSocket *sock = find_socket(sock_id);
if (sock && sock->closed) {
return NSAPI_ERROR_OK;
}
sock->txfull_event = false;
nsapi_error_t err = _at.at_cmd_discard("+NSOCL", "=", "%d", sock_id);
tr_info("Close socket: %d error: %d", sock_id, err);
return err;
}
nsapi_error_t QUECTEL_BC95_CellularStack::create_socket_impl(CellularSocket *socket)
{
int sock_id = -1;
bool socketOpenWorking = false;
if (socket->proto == NSAPI_UDP) {
_at.cmd_start_stop("+NSOCR", "=DGRAM,", "%d%d%d%s", 17, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start_stop("+NSOCR", "=STREAM,", "%d%d%d%s", 6, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.resp_start();
sock_id = _at.read_int();
_at.resp_stop();
socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);
if (!socketOpenWorking || (sock_id == -1)) {
tr_error("Socket create failed!");
return NSAPI_ERROR_NO_SOCKET;
}
tr_info("Socket create id: %d", sock_id);
socket->id = sock_id;
return NSAPI_ERROR_OK;
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,
const void *data, nsapi_size_t size)
{
//AT_CellularStack::socket_sendto(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
if (_ip_ver_sendto != address.get_ip_version()) {
_ip_ver_sendto = address.get_ip_version();
socket_close_impl(socket->id);
create_socket_impl(socket);
}
int sent_len = 0;
if (size > PACKET_SIZE_MAX) {
return NSAPI_ERROR_PARAMETER;
}
int retry = 0;
retry_send:
if (socket->proto == NSAPI_UDP) {
_at.cmd_start("AT+NSOST=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.write_int(size);
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start("AT+NSOSD=");
_at.write_int(socket->id);
_at.write_int(size);
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.write_hex_string((char *)data, size);
_at.cmd_stop();
_at.resp_start();
// skip socket id
_at.skip_param();
sent_len = _at.read_int();
_at.resp_stop();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
return sent_len;
}
// check for network congestion
device_err_t err = _at.get_last_device_error();
if ((err.errType == DeviceErrorTypeErrorCME &&
(err.errCode == AT_UART_BUFFER_ERROR || err.errCode == AT_BACK_OFF_TIMER)) || err.errCode == AT_UPLINK_BUSY) {
if (socket->proto == NSAPI_UDP) {
if (retry < 3) {
retry++;
tr_warn("Socket %d sendto EAGAIN", socket->id);
rtos::ThisThread::sleep_for(30ms);
_at.clear_error();
goto retry_send;
}
return NSAPI_ERROR_NO_MEMORY;
}
_socket_mutex.lock();
if (!socket->txfull_event && !_txfull_event_id) {
tr_warn("socket %d tx full", socket->id);
socket->txfull_event = true;
_txfull_event_id = _event_queue->call_in(TXFULL_EVENT_TIMEOUT, callback(this, &QUECTEL_BC95_CellularStack::txfull_event_timeout));
if (!_txfull_event_id) {
MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_DRIVER, MBED_ERROR_CODE_ENOMEM), \
"QUECTEL_BC95_CellularStack::socket_sendto_impl(): unable to add event to queue. Increase \"events.shared-eventsize\"\n");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_MEMORY;
}
}
_socket_mutex.unlock();
return NSAPI_ERROR_WOULD_BLOCK;
}
return _at.get_last_error();
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,
void *buffer, nsapi_size_t size)
{
//AT_CellularStack::socket_recvfrom(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
nsapi_size_or_error_t recv_len = 0;
int port;
char ip_address[NSAPI_IP_SIZE];
_at.cmd_start_stop("+NSORF", "=", "%d%d", socket->id, size < PACKET_SIZE_MAX ? size : PACKET_SIZE_MAX);
_at.resp_start();
// receiving socket id
_at.skip_param();
_at.read_string(ip_address, sizeof(ip_address));
port = _at.read_int();
recv_len = _at.read_int();
int hexlen = _at.read_hex_string((char *)buffer, recv_len);
// remaining length
_at.skip_param();
_at.resp_stop();
if (!recv_len || (recv_len == -1) || (_at.get_last_error() != NSAPI_ERROR_OK)) {
return NSAPI_ERROR_WOULD_BLOCK;
}
if (address) {
address->set_ip_address(ip_address);
address->set_port(port);
}
if (recv_len != hexlen) {
tr_error("Not received as much data as expected. Should receive: %d bytes, received: %d bytes", recv_len, hexlen);
}
return recv_len;
}
void QUECTEL_BC95_CellularStack::txfull_event_timeout()
{
_socket_mutex.lock();
_txfull_event_id = 0;
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->_cb && sock->txfull_event) {
sock->txfull_event = false;
sock->_cb(sock->_data);
}
}
_socket_mutex.unlock();
}
<commit_msg>Update connectivity/drivers/cellular/QUECTEL/BC95/QUECTEL_BC95_CellularStack.cpp<commit_after>/*
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "rtos/ThisThread.h"
#include "mbed_error.h"
#include "platform/mbed_atomic.h"
#include "events/EventQueue.h"
#include "events/mbed_shared_queues.h"
#include "QUECTEL_BC95_CellularStack.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#define PACKET_SIZE_MAX 1358
#define TXFULL_EVENT_TIMEOUT 1s
#define AT_UPLINK_BUSY 159
#define AT_UART_BUFFER_ERROR 536
#define AT_BACK_OFF_TIMER 537
using namespace std::chrono;
using namespace mbed;
using namespace mbed_cellular_util;
QUECTEL_BC95_CellularStack::QUECTEL_BC95_CellularStack(ATHandler &atHandler, int cid, nsapi_ip_stack_t stack_type, AT_CellularDevice &device) :
AT_CellularStack(atHandler, cid, stack_type, device), _event_queue(mbed_event_queue()), _txfull_event_id(0)
{
_at.set_urc_handler("+NSONMI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsonmi));
_at.set_urc_handler("+NSOCLI:", mbed::Callback<void()>(this, &QUECTEL_BC95_CellularStack::urc_nsocli));
}
QUECTEL_BC95_CellularStack::~QUECTEL_BC95_CellularStack()
{
if (_txfull_event_id) {
_event_queue->cancel(_txfull_event_id);
}
_at.set_urc_handler("+NSONMI:", nullptr);
_at.set_urc_handler("+NSOCLI:", nullptr);
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_listen(nsapi_socket_t handle, int backlog)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr)
{
return NSAPI_ERROR_UNSUPPORTED;
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &address)
{
CellularSocket *socket = (CellularSocket *)handle;
_at.lock();
if (socket->id == -1) {
const nsapi_error_t error_create = create_socket_impl(socket);
if (error_create != NSAPI_ERROR_OK) {
return error_create;
}
}
_at.cmd_start("AT+NSOCO=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.cmd_stop_read_resp();
_at.unlock();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
socket->remoteAddress = address;
socket->connected = true;
return NSAPI_ERROR_OK;
}
return NSAPI_ERROR_NO_CONNECTION;
}
void QUECTEL_BC95_CellularStack::urc_nsonmi()
{
int sock_id = _at.read_int();
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->id == sock_id) {
if (sock->_cb) {
sock->_cb(sock->_data);
}
break;
}
}
}
void QUECTEL_BC95_CellularStack::urc_nsocli()
{
int sock_id = _at.read_int();
const nsapi_error_t err = _at.get_last_error();
if (err != NSAPI_ERROR_OK) {
return;
}
CellularSocket *sock = find_socket(sock_id);
if (sock) {
sock->closed = true;
if (sock->_cb) {
sock->_cb(sock->_data);
}
tr_info("Socket closed %d", sock_id);
}
}
nsapi_error_t QUECTEL_BC95_CellularStack::socket_close_impl(int sock_id)
{
CellularSocket *sock = find_socket(sock_id);
if (sock && sock->closed) {
return NSAPI_ERROR_OK;
}
sock->txfull_event = false;
nsapi_error_t err = _at.at_cmd_discard("+NSOCL", "=", "%d", sock_id);
tr_info("Close socket: %d error: %d", sock_id, err);
return err;
}
nsapi_error_t QUECTEL_BC95_CellularStack::create_socket_impl(CellularSocket *socket)
{
int sock_id = -1;
bool socketOpenWorking = false;
if (socket->proto == NSAPI_UDP) {
_at.cmd_start_stop("+NSOCR", "=DGRAM,", "%d%d%d%s", 17, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start_stop("+NSOCR", "=STREAM,", "%d%d%d%s", 6, socket->localAddress.get_port(), 1, ((_ip_ver_sendto == NSAPI_IPv4) ? "AF_INET" : "AF_INET6"));
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.resp_start();
sock_id = _at.read_int();
_at.resp_stop();
socketOpenWorking = (_at.get_last_error() == NSAPI_ERROR_OK);
if (!socketOpenWorking || (sock_id == -1)) {
tr_error("Socket create failed!");
return NSAPI_ERROR_NO_SOCKET;
}
tr_info("Socket create id: %d", sock_id);
socket->id = sock_id;
return NSAPI_ERROR_OK;
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_sendto_impl(CellularSocket *socket, const SocketAddress &address,
const void *data, nsapi_size_t size)
{
//AT_CellularStack::socket_sendto(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
if (_ip_ver_sendto != address.get_ip_version()) {
_ip_ver_sendto = address.get_ip_version();
socket_close_impl(socket->id);
create_socket_impl(socket);
}
int sent_len = 0;
if (size > PACKET_SIZE_MAX) {
return NSAPI_ERROR_PARAMETER;
}
int retry = 0;
retry_send:
if (socket->proto == NSAPI_UDP) {
_at.cmd_start("AT+NSOST=");
_at.write_int(socket->id);
_at.write_string(address.get_ip_address(), false);
_at.write_int(address.get_port());
_at.write_int(size);
} else if (socket->proto == NSAPI_TCP) {
_at.cmd_start("AT+NSOSD=");
_at.write_int(socket->id);
_at.write_int(size);
} else {
return NSAPI_ERROR_PARAMETER;
}
_at.write_hex_string((char *)data, size);
_at.cmd_stop();
_at.resp_start();
// skip socket id
_at.skip_param();
sent_len = _at.read_int();
_at.resp_stop();
if (_at.get_last_error() == NSAPI_ERROR_OK) {
return sent_len;
}
// check for network congestion
device_err_t err = _at.get_last_device_error();
if (
(
err.errType == DeviceErrorTypeErrorCME
&& (err.errCode == AT_UART_BUFFER_ERROR || err.errCode == AT_BACK_OFF_TIMER)
)
|| err.errCode == AT_UPLINK_BUSY
) {
if (socket->proto == NSAPI_UDP) {
if (retry < 3) {
retry++;
tr_warn("Socket %d sendto EAGAIN", socket->id);
rtos::ThisThread::sleep_for(30ms);
_at.clear_error();
goto retry_send;
}
return NSAPI_ERROR_NO_MEMORY;
}
_socket_mutex.lock();
if (!socket->txfull_event && !_txfull_event_id) {
tr_warn("socket %d tx full", socket->id);
socket->txfull_event = true;
_txfull_event_id = _event_queue->call_in(TXFULL_EVENT_TIMEOUT, callback(this, &QUECTEL_BC95_CellularStack::txfull_event_timeout));
if (!_txfull_event_id) {
MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_DRIVER, MBED_ERROR_CODE_ENOMEM), \
"QUECTEL_BC95_CellularStack::socket_sendto_impl(): unable to add event to queue. Increase \"events.shared-eventsize\"\n");
_socket_mutex.unlock();
return NSAPI_ERROR_NO_MEMORY;
}
}
_socket_mutex.unlock();
return NSAPI_ERROR_WOULD_BLOCK;
}
return _at.get_last_error();
}
nsapi_size_or_error_t QUECTEL_BC95_CellularStack::socket_recvfrom_impl(CellularSocket *socket, SocketAddress *address,
void *buffer, nsapi_size_t size)
{
//AT_CellularStack::socket_recvfrom(...) will create a socket on modem if it wasn't
// open already.
MBED_ASSERT(socket->id != -1);
nsapi_size_or_error_t recv_len = 0;
int port;
char ip_address[NSAPI_IP_SIZE];
_at.cmd_start_stop("+NSORF", "=", "%d%d", socket->id, size < PACKET_SIZE_MAX ? size : PACKET_SIZE_MAX);
_at.resp_start();
// receiving socket id
_at.skip_param();
_at.read_string(ip_address, sizeof(ip_address));
port = _at.read_int();
recv_len = _at.read_int();
int hexlen = _at.read_hex_string((char *)buffer, recv_len);
// remaining length
_at.skip_param();
_at.resp_stop();
if (!recv_len || (recv_len == -1) || (_at.get_last_error() != NSAPI_ERROR_OK)) {
return NSAPI_ERROR_WOULD_BLOCK;
}
if (address) {
address->set_ip_address(ip_address);
address->set_port(port);
}
if (recv_len != hexlen) {
tr_error("Not received as much data as expected. Should receive: %d bytes, received: %d bytes", recv_len, hexlen);
}
return recv_len;
}
void QUECTEL_BC95_CellularStack::txfull_event_timeout()
{
_socket_mutex.lock();
_txfull_event_id = 0;
for (int i = 0; i < _device.get_property(AT_CellularDevice::PROPERTY_SOCKET_COUNT); i++) {
CellularSocket *sock = _socket[i];
if (sock && sock->_cb && sock->txfull_event) {
sock->txfull_event = false;
sock->_cb(sock->_data);
}
}
_socket_mutex.unlock();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_DETAIL_INTRUSIVE_PARTITIONED_LIST_HPP
#define CAF_DETAIL_INTRUSIVE_PARTITIONED_LIST_HPP
#include "caf/config.hpp"
#include <memory>
#include <iterator>
#include <algorithm>
#include "caf/behavior.hpp"
#include "caf/invoke_message_result.hpp"
namespace caf {
namespace detail {
/// Describes a partitioned list of elements. The first part
/// of the list is described by the iterator pair `[begin, separator)`.
/// The second part by `[continuation, end)`. Actors use the second half
/// of the list to store previously skipped elements. Priority-aware actors
/// also use the first half of the list to sort messages by priority.
template <class T, class Delete = std::default_delete<T>>
class intrusive_partitioned_list {
public:
using value_type = T;
using pointer = value_type*;
using deleter_type = Delete;
struct iterator : std::iterator<std::bidirectional_iterator_tag, value_type> {
pointer ptr;
iterator(pointer init = nullptr) : ptr(init) {
// nop
}
iterator(const iterator&) = default;
iterator& operator=(const iterator&) = default;
iterator& operator++() {
ptr = ptr->next;
return *this;
}
iterator operator++(int) {
iterator res = *this;
ptr = ptr->next;
return res;
}
iterator& operator--() {
ptr = ptr->prev;
return *this;
}
iterator operator--(int) {
iterator res = *this;
ptr = ptr->prev;
return res;
}
value_type& operator*() {
return *ptr;
}
pointer operator->() {
return ptr;
}
bool operator==(const iterator& other) const {
return ptr == other.ptr;
}
bool operator!=(const iterator& other) const {
return ptr != other.ptr;
}
iterator next() const {
return ptr->next;
}
};
intrusive_partitioned_list() {
head_.next = &separator_;
separator_.prev = &head_;
separator_.next = &tail_;
tail_.prev = &separator_;
}
~intrusive_partitioned_list() {
clear();
}
iterator begin() {
return head_.next;
}
iterator separator() {
return &separator_;
}
iterator continuation() {
return separator_.next;
}
iterator end() {
return &tail_;
}
using range = std::pair<iterator, iterator>;
/// Returns the two iterator pairs describing the first and second part
/// of the partitioned list.
std::array<range, 2> ranges() {
return {{range{begin(), separator()}, range{continuation(), end()}}};
}
template <class F>
void clear(F f) {
for (auto& range : ranges()) {
auto i = range.first;
auto e = range.second;
while (i != e) {
auto ptr = i.ptr;
++i;
f(*ptr);
delete_(ptr);
}
}
if (head_.next != &separator_) {
head_.next = &separator_;
separator_.prev = &head_;
}
if (separator_.next != &tail_) {
separator_.next = &tail_;
tail_.prev = &separator_;
}
}
void clear() {
auto nop = [](value_type&) {};
clear(nop);
}
iterator insert(iterator next, pointer val) {
auto prev = next->prev;
val->prev = prev;
val->next = next.ptr;
prev->next = val;
next->prev = val;
return val;
}
bool empty() const {
return head_.next == &separator_ && separator_.next == &tail_;
}
pointer take(iterator pos) {
auto res = pos.ptr;
auto next = res->next;
auto prev = res->prev;
prev->next = next;
next->prev = prev;
return res;
}
iterator erase(iterator pos) {
auto next = pos->next;
delete_(take(pos));
return next;
}
size_t count(size_t max_count = std::numeric_limits<size_t>::max()) {
size_t result = 0;
for (auto& range : ranges())
for (auto i = range.first; i != range.second; ++i)
if (++result == max_count)
return max_count;
return result;
}
private:
value_type head_;
value_type separator_;
value_type tail_;
deleter_type delete_;
};
} // namespace detail
} // namespace caf
#endif // CAF_DETAIL_INTRUSIVE_PARTITIONED_LIST_HPP
<commit_msg>Fix build with MSVC<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2017 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_DETAIL_INTRUSIVE_PARTITIONED_LIST_HPP
#define CAF_DETAIL_INTRUSIVE_PARTITIONED_LIST_HPP
#include "caf/config.hpp"
#include <memory>
#include <iterator>
#include <algorithm>
#include "caf/behavior.hpp"
#include "caf/invoke_message_result.hpp"
namespace caf {
namespace detail {
/// Describes a partitioned list of elements. The first part
/// of the list is described by the iterator pair `[begin, separator)`.
/// The second part by `[continuation, end)`. Actors use the second half
/// of the list to store previously skipped elements. Priority-aware actors
/// also use the first half of the list to sort messages by priority.
template <class T, class Delete = std::default_delete<T>>
class intrusive_partitioned_list {
public:
using value_type = T;
using pointer = value_type*;
using deleter_type = Delete;
struct iterator : std::iterator<std::bidirectional_iterator_tag, value_type> {
pointer ptr;
iterator(pointer init = nullptr) : ptr(init) {
// nop
}
iterator(const iterator&) = default;
iterator& operator=(const iterator&) = default;
iterator& operator++() {
ptr = ptr->next;
return *this;
}
iterator operator++(int) {
iterator res = *this;
ptr = ptr->next;
return res;
}
iterator& operator--() {
ptr = ptr->prev;
return *this;
}
iterator operator--(int) {
iterator res = *this;
ptr = ptr->prev;
return res;
}
const value_type& operator*() const {
return *ptr;
}
value_type& operator*() {
return *ptr;
}
pointer operator->() {
return ptr;
}
bool operator==(const iterator& other) const {
return ptr == other.ptr;
}
bool operator!=(const iterator& other) const {
return ptr != other.ptr;
}
iterator next() const {
return ptr->next;
}
};
intrusive_partitioned_list() {
head_.next = &separator_;
separator_.prev = &head_;
separator_.next = &tail_;
tail_.prev = &separator_;
}
~intrusive_partitioned_list() {
clear();
}
iterator begin() {
return head_.next;
}
iterator separator() {
return &separator_;
}
iterator continuation() {
return separator_.next;
}
iterator end() {
return &tail_;
}
using range = std::pair<iterator, iterator>;
/// Returns the two iterator pairs describing the first and second part
/// of the partitioned list.
std::array<range, 2> ranges() {
return {{range{begin(), separator()}, range{continuation(), end()}}};
}
template <class F>
void clear(F f) {
for (auto& range : ranges()) {
auto i = range.first;
auto e = range.second;
while (i != e) {
auto ptr = i.ptr;
++i;
f(*ptr);
delete_(ptr);
}
}
if (head_.next != &separator_) {
head_.next = &separator_;
separator_.prev = &head_;
}
if (separator_.next != &tail_) {
separator_.next = &tail_;
tail_.prev = &separator_;
}
}
void clear() {
auto nop = [](value_type&) {};
clear(nop);
}
iterator insert(iterator next, pointer val) {
auto prev = next->prev;
val->prev = prev;
val->next = next.ptr;
prev->next = val;
next->prev = val;
return val;
}
bool empty() const {
return head_.next == &separator_ && separator_.next == &tail_;
}
pointer take(iterator pos) {
auto res = pos.ptr;
auto next = res->next;
auto prev = res->prev;
prev->next = next;
next->prev = prev;
return res;
}
iterator erase(iterator pos) {
auto next = pos->next;
delete_(take(pos));
return next;
}
size_t count(size_t max_count = std::numeric_limits<size_t>::max()) {
size_t result = 0;
for (auto& range : ranges())
for (auto i = range.first; i != range.second; ++i)
if (++result == max_count)
return max_count;
return result;
}
private:
value_type head_;
value_type separator_;
value_type tail_;
deleter_type delete_;
};
} // namespace detail
} // namespace caf
#endif // CAF_DETAIL_INTRUSIVE_PARTITIONED_LIST_HPP
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "commandwatcher.h"
#include "sconnect.h"
#include <QTextStream>
#include <QFile>
#include <QSocketNotifier>
#include <QStringList>
#include <QCoreApplication>
#include <QDebug>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <QMap>
CommandWatcher::CommandWatcher(int commandfd, QObject *parent) :
QObject(parent), commandfd(commandfd)
{
commandNotifier = new QSocketNotifier(commandfd, QSocketNotifier::Read, this);
sconnect(commandNotifier, SIGNAL(activated(int)), this, SLOT(onActivated()));
help();
}
void CommandWatcher::onActivated()
{
// read all available input to commandBuffer
static QByteArray commandBuffer = "";
static char buf[1024];
int readSize;
fcntl(commandfd, F_SETFL, O_NONBLOCK);
while ((readSize = read(commandfd, &buf, 1024)) > 0)
commandBuffer += QByteArray(buf, readSize);
// handle all available whole input lines as commands
int nextSeparator;
while ((nextSeparator = commandBuffer.indexOf('\n')) != -1) {
// split lines to separate commands by semicolons
QStringList commands = QString::fromUtf8(commandBuffer.constData()).left(nextSeparator).split(";");
foreach (QString command, commands)
interpret(command.trimmed());
commandBuffer.remove(0, nextSeparator + 1);
}
if (readSize == 0) // EOF
QCoreApplication::exit(0);
}
void CommandWatcher::help()
{
qDebug() << "Available commands:";
qDebug() << " add KEY TYPE - create new key with the given type";
qDebug() << " KEY=VALUE - set KEY to the given VALUE";
qDebug() << " flush - write FLUSHED to stderr and stdout";
qDebug() << "Any prefix of a command can be used as an abbreviation";
}
void CommandWatcher::interpret(const QString& command)
{
QTextStream out(stdout);
QTextStream err(stderr);
if (command == "") {
// Show help
help();
} else if (command.contains('=')) {
// Setter command
setCommand(command);
} else {
QStringList args = command.split(" ");
QString commandName = args[0];
args.pop_front();
// Interpret commands
if (QString("add").startsWith(commandName)) {
addCommand(args);
}
}
}
void CommandWatcher::addCommand(const QStringList& args)
{
if (args.count() < 2) {
qDebug() << "ERROR: need to specify both KEY and TYPE";
return;
}
const QString keyName = args.at(0);
const QString keyType = args.at(1);
properties.insert(keyName, keyType);
qDebug() << "Added key:" << keyName << "with type:" << keyType;
}
void CommandWatcher::setCommand(const QString& command)
{
QStringList parts = command.split("=");
const QString keyName = parts.at(0).trimmed();
const QString value = parts.at(1).trimmed();
qDebug() << "Setting key:" << keyName << "to value:" << value;
Property(keyName).setValue(value);
}
<commit_msg>Actually do set the props.<commit_after>/*
* Copyright (C) 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "commandwatcher.h"
#include "sconnect.h"
#include <QTextStream>
#include <QFile>
#include <QSocketNotifier>
#include <QStringList>
#include <QCoreApplication>
#include <QDebug>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <QMap>
CommandWatcher::CommandWatcher(int commandfd, QObject *parent) :
QObject(parent), commandfd(commandfd)
{
commandNotifier = new QSocketNotifier(commandfd, QSocketNotifier::Read, this);
sconnect(commandNotifier, SIGNAL(activated(int)), this, SLOT(onActivated()));
help();
}
void CommandWatcher::onActivated()
{
// read all available input to commandBuffer
static QByteArray commandBuffer = "";
static char buf[1024];
int readSize;
fcntl(commandfd, F_SETFL, O_NONBLOCK);
while ((readSize = read(commandfd, &buf, 1024)) > 0)
commandBuffer += QByteArray(buf, readSize);
// handle all available whole input lines as commands
int nextSeparator;
while ((nextSeparator = commandBuffer.indexOf('\n')) != -1) {
// split lines to separate commands by semicolons
QStringList commands = QString::fromUtf8(commandBuffer.constData()).left(nextSeparator).split(";");
foreach (QString command, commands)
interpret(command.trimmed());
commandBuffer.remove(0, nextSeparator + 1);
}
if (readSize == 0) // EOF
QCoreApplication::exit(0);
}
void CommandWatcher::help()
{
qDebug() << "Available commands:";
qDebug() << " add KEY TYPE - create new key with the given type";
qDebug() << " KEY=VALUE - set KEY to the given VALUE";
qDebug() << " flush - write FLUSHED to stderr and stdout";
qDebug() << "Any prefix of a command can be used as an abbreviation";
}
void CommandWatcher::interpret(const QString& command)
{
QTextStream out(stdout);
QTextStream err(stderr);
if (command == "") {
// Show help
help();
} else if (command.contains('=')) {
// Setter command
setCommand(command);
} else {
QStringList args = command.split(" ");
QString commandName = args[0];
args.pop_front();
// Interpret commands
if (QString("add").startsWith(commandName)) {
addCommand(args);
}
}
}
void CommandWatcher::addCommand(const QStringList& args)
{
if (args.count() < 2) {
qDebug() << "ERROR: need to specify both KEY and TYPE";
return;
}
const QString keyName = args.at(0);
const QString keyType = args.at(1);
if (keyType != "integer" && keyType != "string" &&
keyType != "double") {
qDebug() << "Unknown type";
return;
}
properties.insert(keyName, keyType);
qDebug() << "Added key:" << keyName << "with type:" << keyType;
}
void CommandWatcher::setCommand(const QString& command)
{
QStringList parts = command.split("=");
const QString keyName = parts.at(0).trimmed();
const QString value = parts.at(1).trimmed();
if (! properties.contains(keyName)) {
qDebug() << "ERROR: key" << keyName << "not known/added";
return;
}
const QString keyType = properties.value(keyName);
QVariant v;
if (keyType == "integer")
v = QVariant(value.toInt());
else if (keyType == "string")
v = QVariant(value);
else if (keyType == "double")
v = QVariant(value.toDouble());
qDebug() << "Setting key:" << keyName << "to value:" << value << QString("(" + keyType + ")");
Property(keyName).setValue(v);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: precompiled_lingucomponent.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-05-10 15:14:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): Generated on 2006-09-01 17:49:51.030070
#ifdef PRECOMPILED_HEADERS
#include <tools/debug.hxx>
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.68); FILE MERGED 2008/03/31 16:25:02 rt 1.3.68.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: precompiled_lingucomponent.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): Generated on 2006-09-01 17:49:51.030070
#ifdef PRECOMPILED_HEADERS
#include <tools/debug.hxx>
#endif
<|endoftext|> |
<commit_before>/***************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: altstrfunc.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2007-06-22 08:32:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_lingucomponent.hxx"
#ifndef _ALT_STRFUNC_HXX_
#include "altstrfunc.hxx"
#endif
#include <sal/types.h>
std::string upperCase(const std::string &s) {
std::string upper(s);
for(size_t i = 0; i < s.length(); i++)
upper[i] = sal::static_int_cast< char >( toupper(upper[i]) );
return upper;
}
int start(const std::string &s1, const std::string &s2){
int i;
int ret = 0;
for(i = 0; s2[i] && s1[i] && !ret; i++){
ret = toupper(s1[i]) - toupper(s2[i]);
if(s1[i] == '.' || s2[i] == '.'){ret = 0;}//. is a neutral character
}
return ret;
}
<commit_msg>INTEGRATION: CWS tl48_SRC680 (1.4.36); FILE MERGED 2007/10/22 11:07:01 tl 1.4.36.3: warning fixed 2007/10/22 11:05:15 tl 1.4.36.2: warning fixed 2007/10/17 15:05:18 tl 1.4.36.1: #i81311# fix warning with non-pro build and a possible crash<commit_after>/***************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: altstrfunc.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-11-01 10:54:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_lingucomponent.hxx"
#ifndef _ALT_STRFUNC_HXX_
#include "altstrfunc.hxx"
#endif
#include <sal/types.h>
std::string upperCase(const std::string &s) {
std::string upper(s);
for(size_t i = 0; i < s.length(); i++)
upper[i] = sal::static_int_cast< char >( toupper(upper[i]) );
return upper;
}
int start( const std::string &s1, const std::string &s2 ){
size_t i;
int ret = 0;
size_t min = s1.length();
if (min > s2.length())
min = s2.length();
for(i = 0; i < min && s2[i] && s1[i] && !ret; i++){
ret = toupper(s1[i]) - toupper(s2[i]);
if(s1[i] == '.' || s2[i] == '.'){ret = 0;}//. is a neutral character
}
return ret;
}
<|endoftext|> |
<commit_before>/*
*
* BitcoinLikeTransactionDatabaseHelper
* ledger-core
*
* Created by Pierre Pollastri on 02/06/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 <crypto/SHA256.hpp>
#include "BitcoinLikeTransactionDatabaseHelper.h"
#include <wallet/common/database/BlockDatabaseHelper.h>
#include <database/soci-option.h>
#include <database/soci-date.h>
#include <database/soci-number.h>
#include <iostream>
using namespace std;
using namespace soci;
namespace ledger {
namespace core {
bool BitcoinLikeTransactionDatabaseHelper::transactionExists(soci::session &sql, const std::string &btcTxUid) {
int32_t count = 0;
sql << "SELECT COUNT(*) FROM bitcoin_transactions WHERE transaction_uid = :btcTxUid", use(btcTxUid), into(count);
return count == 1;
}
std::string BitcoinLikeTransactionDatabaseHelper::createBitcoinTransactionUid(const std::string& accountUid, const std::string& txHash) {
auto result = SHA256::stringToHexHash(fmt::format("uid:{}+{}", accountUid, txHash));
return result;
}
std::string BitcoinLikeTransactionDatabaseHelper::createInputUid(const std::string& accountUid,
int32_t previousOutputIndex,
const std::string &previousTxHash,
const std::string &coinbase) {
return SHA256::stringToHexHash(fmt::format("uid:{}+{}+{}+{}", accountUid, previousOutputIndex, previousTxHash, coinbase));
}
bool BitcoinLikeTransactionDatabaseHelper::getTransactionByHash(soci::session &sql,
const std::string &hash,
const std::string &accountUid,
BitcoinLikeBlockchainExplorerTransaction &out) {
rowset<row> rows = (sql.prepare <<
"SELECT tx.hash, tx.version, tx.time, tx.locktime, "
"block.hash, block.height, block.time, block.currency_name "
"FROM bitcoin_transactions AS tx "
"LEFT JOIN blocks AS block ON tx.block_uid = block.uid "
"WHERE tx.hash = :hash", use(hash)
);
for (auto& row : rows) {
inflateTransaction(sql, row, accountUid, out);
return true;
}
return false;
}
bool BitcoinLikeTransactionDatabaseHelper::inflateTransaction(soci::session &sql,
const soci::row &row,
const std::string &accountUid,
BitcoinLikeBlockchainExplorerTransaction &out) {
out.hash = row.get<std::string>(0);
out.version = (uint32_t) row.get<int32_t>(1);
out.receivedAt = row.get<std::chrono::system_clock::time_point>(2);
out.lockTime = (uint64_t) row.get<int>(3);
if (row.get_indicator(4) != i_null) {
BitcoinLikeBlockchainExplorer::Block block;
block.hash = row.get<std::string>(4);
block.height = get_number<uint64_t>(row, 5);
block.time = row.get<std::chrono::system_clock::time_point>(6);
block.currencyName = row.get<std::string>(7);
out.block = block;
}
// Fetch inputs
rowset<soci::row> inputRows = (sql.prepare <<
"SELECT DISTINCT ON(ti.input_idx) ti.input_idx, i.previous_output_idx, i.previous_tx_hash, i.amount, i.address, i.coinbase,"
"i.sequence "
"FROM bitcoin_transaction_inputs AS ti "
"INNER JOIN bitcoin_inputs AS i ON ti.input_uid = i.uid "
"WHERE ti.transaction_hash = :hash ORDER BY ti.input_idx", use(out.hash)
);
for (auto& inputRow : inputRows) {
BitcoinLikeBlockchainExplorerInput input;
input.index = get_number<uint64_t>(inputRow, 0);
input.previousTxOutputIndex = inputRow.get<Option<int>>(1).map<uint32_t>([] (const int& v) {
return (uint32_t) v;
});
input.previousTxHash = inputRow.get<Option<std::string>>(2);
input.value = inputRow.get<Option<long long>>(3).map<BigInt>([] (const unsigned long long& v) {
return BigInt(v);
});
input.address = inputRow.get<Option<std::string>>(4);
input.coinbase = inputRow.get<Option<std::string>>(5);
input.sequence = get_number<uint32_t>(inputRow, 6);
out.inputs.push_back(input);
}
// Fetch outputs
//Check if the output belongs to this account
//solve case of 2 accounts in DB one as sender and one as receiver
//of same transaction (filter on account_uid won't solve the issue because
//bitcoin_outputs going to external accounts have NULL account_uid)
auto btcTxUid = BitcoinLikeTransactionDatabaseHelper::createBitcoinTransactionUid(accountUid, out.hash);
rowset<soci::row> outputRows = (sql.prepare <<
"SELECT idx, amount, script, address, block_height, replaceable "
"FROM bitcoin_outputs WHERE transaction_hash = :hash AND transaction_uid = :tx_uid "
"ORDER BY idx", use(out.hash), use(btcTxUid)
);
for (auto& outputRow : outputRows) {
BitcoinLikeBlockchainExplorerOutput output;
output.index = (uint64_t) outputRow.get<int>(0);
output.value.assignScalar(outputRow.get<long long>(1));
output.script = outputRow.get<std::string>(2);
output.address = outputRow.get<Option<std::string>>(3);
if (outputRow.get_indicator(4) != i_null) {
output.blockHeight = soci::get_number<uint64_t>(outputRow, 4);
}
output.replaceable = soci::get_number<int>(outputRow, 5) == 1;
out.outputs.push_back(std::move(output));
}
// Enjoy the silence.
return true;
}
void
BitcoinLikeTransactionDatabaseHelper::getMempoolTransactions(soci::session &sql, const std::string &accountUid,
std::vector<BitcoinLikeBlockchainExplorerTransaction> &out) {
// Query all transaction
rowset<row> txRows = (sql.prepare <<
"SELECT tx.hash, tx.version, tx.time, tx.locktime, "
"block.hash, block.height, block.time, block.currency_name "
"FROM bitcoin_transactions AS tx "
"LEFT JOIN blocks AS block ON tx.block_uid = block.uid "
"WHERE tx.hash IN ("
"SELECT tx.hash FROM operations AS op "
"JOIN bitcoin_operations AS bop ON bop.uid = op.uid "
"JOIN bitcoin_transactions AS tx ON tx.hash = bop.transaction_hash "
"WHERE op.account_uid = :uid AND op.block_uid IS NULL"
")", use(accountUid));
// Inflate all transactions
for (const auto& txRow : txRows) {
BitcoinLikeBlockchainExplorerTransaction tx;
inflateTransaction(sql, txRow, accountUid, tx);
out.emplace_back(std::move(tx));
}
}
void BitcoinLikeTransactionDatabaseHelper::removeAllMempoolOperation(soci::session &sql,
const std::string &accountUid) {
rowset<std::string> rows = (sql.prepare <<
"SELECT transaction_uid FROM bitcoin_operations AS bop "
"JOIN operations AS op ON bop.uid = op.uid "
"WHERE op.account_uid = :uid AND op.block_uid IS NULL", use(accountUid)
);
std::vector<std::string> txToDelete(rows.begin(), rows.end());
if (!txToDelete.empty()) {
sql << "DELETE FROM bitcoin_inputs WHERE uid IN ("
"SELECT input_uid FROM bitcoin_transaction_inputs "
"WHERE transaction_uid IN(:uids)"
")", use(txToDelete);
sql << "DELETE FROM operations WHERE account_uid = :uid AND block_uid is NULL", use(accountUid);
sql << "DELETE FROM bitcoin_transactions "
"WHERE transaction_uid IN (:uids)", use(txToDelete);
}
}
void BitcoinLikeTransactionDatabaseHelper::eraseDataSince(
soci::session &sql,
const std::string &accountUid,
const std::chrono::system_clock::time_point & date) {
rowset<std::string> rows = (sql.prepare <<
"SELECT transaction_uid FROM bitcoin_operations AS bop "
"JOIN operations AS op ON bop.uid = op.uid "
"WHERE op.account_uid = :uid AND op.date >= :date",
use(accountUid), use(date)
);
std::vector<std::string> txToDelete(rows.begin(), rows.end());
if (!txToDelete.empty()) {
sql << "DELETE FROM operations WHERE account_uid = :account_uid AND date >= :date",
use(accountUid), use(date);
sql << "DELETE FROM bitcoin_inputs WHERE uid IN ("
"SELECT input_uid FROM bitcoin_transaction_inputs "
"WHERE transaction_uid IN(:uids)"
")", use(txToDelete);
sql << "DELETE FROM bitcoin_transactions "
"WHERE transaction_uid IN (:uids)", use(txToDelete);
}
}
}
}
<commit_msg>VG-2191: deduplicate inputs with txuid instead of DISTINCT ON clause<commit_after>/*
*
* BitcoinLikeTransactionDatabaseHelper
* ledger-core
*
* Created by Pierre Pollastri on 02/06/2017.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 <crypto/SHA256.hpp>
#include "BitcoinLikeTransactionDatabaseHelper.h"
#include <wallet/common/database/BlockDatabaseHelper.h>
#include <database/soci-option.h>
#include <database/soci-date.h>
#include <database/soci-number.h>
#include <iostream>
using namespace std;
using namespace soci;
namespace ledger {
namespace core {
bool BitcoinLikeTransactionDatabaseHelper::transactionExists(soci::session &sql, const std::string &btcTxUid) {
int32_t count = 0;
sql << "SELECT COUNT(*) FROM bitcoin_transactions WHERE transaction_uid = :btcTxUid", use(btcTxUid), into(count);
return count == 1;
}
std::string BitcoinLikeTransactionDatabaseHelper::createBitcoinTransactionUid(const std::string& accountUid, const std::string& txHash) {
auto result = SHA256::stringToHexHash(fmt::format("uid:{}+{}", accountUid, txHash));
return result;
}
std::string BitcoinLikeTransactionDatabaseHelper::createInputUid(const std::string& accountUid,
int32_t previousOutputIndex,
const std::string &previousTxHash,
const std::string &coinbase) {
return SHA256::stringToHexHash(fmt::format("uid:{}+{}+{}+{}", accountUid, previousOutputIndex, previousTxHash, coinbase));
}
bool BitcoinLikeTransactionDatabaseHelper::getTransactionByHash(soci::session &sql,
const std::string &hash,
const std::string &accountUid,
BitcoinLikeBlockchainExplorerTransaction &out) {
rowset<row> rows = (sql.prepare <<
"SELECT tx.hash, tx.version, tx.time, tx.locktime, "
"block.hash, block.height, block.time, block.currency_name "
"FROM bitcoin_transactions AS tx "
"LEFT JOIN blocks AS block ON tx.block_uid = block.uid "
"WHERE tx.hash = :hash", use(hash)
);
for (auto& row : rows) {
inflateTransaction(sql, row, accountUid, out);
return true;
}
return false;
}
bool BitcoinLikeTransactionDatabaseHelper::inflateTransaction(soci::session &sql,
const soci::row &row,
const std::string &accountUid,
BitcoinLikeBlockchainExplorerTransaction &out) {
out.hash = row.get<std::string>(0);
out.version = (uint32_t) row.get<int32_t>(1);
out.receivedAt = row.get<std::chrono::system_clock::time_point>(2);
out.lockTime = (uint64_t) row.get<int>(3);
if (row.get_indicator(4) != i_null) {
BitcoinLikeBlockchainExplorer::Block block;
block.hash = row.get<std::string>(4);
block.height = get_number<uint64_t>(row, 5);
block.time = row.get<std::chrono::system_clock::time_point>(6);
block.currencyName = row.get<std::string>(7);
out.block = block;
}
auto btcTxUid = BitcoinLikeTransactionDatabaseHelper::createBitcoinTransactionUid(accountUid, out.hash);
// Fetch inputs
rowset<soci::row> inputRows = (sql.prepare <<
"SELECT ti.input_idx, i.previous_output_idx, i.previous_tx_hash, i.amount, i.address, i.coinbase,"
"i.sequence "
"FROM bitcoin_transaction_inputs AS ti "
"INNER JOIN bitcoin_inputs AS i ON ti.input_uid = i.uid "
"WHERE ti.transaction_uid = :txuid ORDER BY ti.input_idx", use(btcTxUid));
for (auto& inputRow : inputRows) {
BitcoinLikeBlockchainExplorerInput input;
input.index = get_number<uint64_t>(inputRow, 0);
input.previousTxOutputIndex = inputRow.get<Option<int>>(1).map<uint32_t>([] (const int& v) {
return (uint32_t) v;
});
input.previousTxHash = inputRow.get<Option<std::string>>(2);
input.value = inputRow.get<Option<long long>>(3).map<BigInt>([] (const unsigned long long& v) {
return BigInt(v);
});
input.address = inputRow.get<Option<std::string>>(4);
input.coinbase = inputRow.get<Option<std::string>>(5);
input.sequence = get_number<uint32_t>(inputRow, 6);
out.inputs.push_back(input);
}
// Fetch outputs
//Check if the output belongs to this account
//solve case of 2 accounts in DB one as sender and one as receiver
//of same transaction (filter on account_uid won't solve the issue because
//bitcoin_outputs going to external accounts have NULL account_uid)
rowset<soci::row> outputRows = (sql.prepare <<
"SELECT idx, amount, script, address, block_height, replaceable "
"FROM bitcoin_outputs WHERE transaction_hash = :hash AND transaction_uid = :tx_uid "
"ORDER BY idx", use(out.hash), use(btcTxUid)
);
for (auto& outputRow : outputRows) {
BitcoinLikeBlockchainExplorerOutput output;
output.index = (uint64_t) outputRow.get<int>(0);
output.value.assignScalar(outputRow.get<long long>(1));
output.script = outputRow.get<std::string>(2);
output.address = outputRow.get<Option<std::string>>(3);
if (outputRow.get_indicator(4) != i_null) {
output.blockHeight = soci::get_number<uint64_t>(outputRow, 4);
}
output.replaceable = soci::get_number<int>(outputRow, 5) == 1;
out.outputs.push_back(std::move(output));
}
// Enjoy the silence.
return true;
}
void
BitcoinLikeTransactionDatabaseHelper::getMempoolTransactions(soci::session &sql, const std::string &accountUid,
std::vector<BitcoinLikeBlockchainExplorerTransaction> &out) {
// Query all transaction
rowset<row> txRows = (sql.prepare <<
"SELECT tx.hash, tx.version, tx.time, tx.locktime, "
"block.hash, block.height, block.time, block.currency_name "
"FROM bitcoin_transactions AS tx "
"LEFT JOIN blocks AS block ON tx.block_uid = block.uid "
"WHERE tx.hash IN ("
"SELECT tx.hash FROM operations AS op "
"JOIN bitcoin_operations AS bop ON bop.uid = op.uid "
"JOIN bitcoin_transactions AS tx ON tx.hash = bop.transaction_hash "
"WHERE op.account_uid = :uid AND op.block_uid IS NULL"
")", use(accountUid));
// Inflate all transactions
for (const auto& txRow : txRows) {
BitcoinLikeBlockchainExplorerTransaction tx;
inflateTransaction(sql, txRow, accountUid, tx);
out.emplace_back(std::move(tx));
}
}
void BitcoinLikeTransactionDatabaseHelper::removeAllMempoolOperation(soci::session &sql,
const std::string &accountUid) {
rowset<std::string> rows = (sql.prepare <<
"SELECT transaction_uid FROM bitcoin_operations AS bop "
"JOIN operations AS op ON bop.uid = op.uid "
"WHERE op.account_uid = :uid AND op.block_uid IS NULL", use(accountUid)
);
std::vector<std::string> txToDelete(rows.begin(), rows.end());
if (!txToDelete.empty()) {
sql << "DELETE FROM bitcoin_inputs WHERE uid IN ("
"SELECT input_uid FROM bitcoin_transaction_inputs "
"WHERE transaction_uid IN(:uids)"
")", use(txToDelete);
sql << "DELETE FROM operations WHERE account_uid = :uid AND block_uid is NULL", use(accountUid);
sql << "DELETE FROM bitcoin_transactions "
"WHERE transaction_uid IN (:uids)", use(txToDelete);
}
}
void BitcoinLikeTransactionDatabaseHelper::eraseDataSince(
soci::session &sql,
const std::string &accountUid,
const std::chrono::system_clock::time_point & date) {
rowset<std::string> rows = (sql.prepare <<
"SELECT transaction_uid FROM bitcoin_operations AS bop "
"JOIN operations AS op ON bop.uid = op.uid "
"WHERE op.account_uid = :uid AND op.date >= :date",
use(accountUid), use(date)
);
std::vector<std::string> txToDelete(rows.begin(), rows.end());
if (!txToDelete.empty()) {
sql << "DELETE FROM operations WHERE account_uid = :account_uid AND date >= :date",
use(accountUid), use(date);
sql << "DELETE FROM bitcoin_inputs WHERE uid IN ("
"SELECT input_uid FROM bitcoin_transaction_inputs "
"WHERE transaction_uid IN(:uids)"
")", use(txToDelete);
sql << "DELETE FROM bitcoin_transactions "
"WHERE transaction_uid IN (:uids)", use(txToDelete);
}
}
}
}
<|endoftext|> |
<commit_before>/* vim: set ts=4 sw=4 tw=79 et :*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "TestHarness.h"
#include "base/io/Path.h"
int main(int argc, char* argv[]) {
int rv = 0;
/// Path::isAbsolute Tests
rv +=
runTest("Test empty string !isAbsolute", []() {
return !Path::isAbsolute("");
});
rv +=
runPosixOnlyTest("Test isAbsolute('/a/b/c')", []() {
return Path::isAbsolute("/a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('a/b/c')", []() {
return !Path::isAbsolute("a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('../a/b')", []() {
return !Path::isAbsolute("../a/b");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('./a/b'", []() {
return !Path::isAbsolute("./a/b");
});
rv +=
runWindowsOnlyTest("Test short/invalid path", []() {
return
!Path::isAbsolute("C:") &&
!Path::isAbsolute("C") &&
!Path::isAbsolute("F:F");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:\\Hello')", []() {
return
Path::isAbsolute("a:\\Hello") &&
Path::isAbsolute("A:\\Hello") &&
Path::isAbsolute("z:\\Hello") &&
Path::isAbsolute("Z:\\Hello");
});
// Windows supports forward slashes with this form of path
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:/Hello')", []() {
return
Path::isAbsolute("a:/Hello") &&
Path::isAbsolute("A:/Hello") &&
Path::isAbsolute("z:/Hello") &&
Path::isAbsolute("Z:/Hello");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\Path')", []() {
return Path::isAbsolute("\\\\Path");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('//Path/')", []() {
return Path::isAbsolute("//Path/");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\Single\\Slash')", []() {
return Path::isAbsolute("\\Single\\Slash");
});
/*
* This '\\?\' prefix is not used as part of the path itself. They indicate
* that the path should be passed to the system with minimal modification,
* which means that you cannot use forward slashes to represent path
* separators, or a period to represent the current directory, or double
* dots to represent the parent directory. Basically, anything using this
* prefix kind of has to be an absolute path for it to work.
*/
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\?\\a:\\Long\\Path')", []() {
return
Path::isAbsolute("\\\\?\\a:\\Long\\Path") &&
Path::isAbsolute("\\\\?\\UNC\\Long\\Path");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('..\\File.ext')", []() {
return !Path::isAbsolute("..\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('.\\File.ext')", []() {
return !Path::isAbsolute(".\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('<driveletter>:RelativePath')", []() {
return
!Path::isAbsolute("A:RelativePath") &&
!Path::isAbsolute("a:RelativePath") &&
!Path::isAbsolute("z:RelativePath") &&
!Path::isAbsolute("Z:RelativePath");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('A\\F\\ile.ext')", []() {
return !Path::isAbsolute("A\\F\\ile.ext");
});
return rv;
}
<commit_msg>Whitespace (VS is configured to use tabs apparently)<commit_after>/* vim: set ts=4 sw=4 tw=79 et :*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "TestHarness.h"
#include "base/io/Path.h"
int main(int argc, char* argv[]) {
int rv = 0;
/// Path::isAbsolute Tests
rv +=
runTest("Test empty string !isAbsolute", []() {
return !Path::isAbsolute("");
});
rv +=
runPosixOnlyTest("Test isAbsolute('/a/b/c')", []() {
return Path::isAbsolute("/a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('a/b/c')", []() {
return !Path::isAbsolute("a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('../a/b')", []() {
return !Path::isAbsolute("../a/b");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('./a/b'", []() {
return !Path::isAbsolute("./a/b");
});
rv +=
runWindowsOnlyTest("Test short/invalid path", []() {
return
!Path::isAbsolute("C:") &&
!Path::isAbsolute("C") &&
!Path::isAbsolute("F:F");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:\\Hello')", []() {
return
Path::isAbsolute("a:\\Hello") &&
Path::isAbsolute("A:\\Hello") &&
Path::isAbsolute("z:\\Hello") &&
Path::isAbsolute("Z:\\Hello");
});
// Windows supports forward slashes with this form of path
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:/Hello')", []() {
return
Path::isAbsolute("a:/Hello") &&
Path::isAbsolute("A:/Hello") &&
Path::isAbsolute("z:/Hello") &&
Path::isAbsolute("Z:/Hello");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\Path')", []() {
return Path::isAbsolute("\\\\Path");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('//Path/')", []() {
return Path::isAbsolute("//Path/");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\Single\\Slash')", []() {
return Path::isAbsolute("\\Single\\Slash");
});
/*
* This '\\?\' prefix is not used as part of the path itself. They indicate
* that the path should be passed to the system with minimal modification,
* which means that you cannot use forward slashes to represent path
* separators, or a period to represent the current directory, or double
* dots to represent the parent directory. Basically, anything using this
* prefix kind of has to be an absolute path for it to work.
*/
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\?\\a:\\Long\\Path')", []() {
return
Path::isAbsolute("\\\\?\\a:\\Long\\Path") &&
Path::isAbsolute("\\\\?\\UNC\\Long\\Path");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('..\\File.ext')", []() {
return !Path::isAbsolute("..\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('.\\File.ext')", []() {
return !Path::isAbsolute(".\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('<driveletter>:RelativePath')", []() {
return
!Path::isAbsolute("A:RelativePath") &&
!Path::isAbsolute("a:RelativePath") &&
!Path::isAbsolute("z:RelativePath") &&
!Path::isAbsolute("Z:RelativePath");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('A\\F\\ile.ext')", []() {
return !Path::isAbsolute("A\\F\\ile.ext");
});
return rv;
}
<|endoftext|> |
<commit_before>#include <numeric>
#include <pqxx/transaction>
#include "../test_helpers.hxx"
namespace
{
void test_move_constructor()
{
pqxx::connection c1;
PQXX_CHECK(c1.is_open(), "New connection is not open.");
pqxx::connection c2{std::move(c1)};
PQXX_CHECK(not c1.is_open(), "Moving did not close original connection.");
PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");
pqxx::work tx{c2};
PQXX_CHECK_EQUAL(tx.query_value<int>("SELECT 5"), 5, "Weird result!");
PQXX_CHECK_THROWS(
pqxx::connection c3{std::move(c2)}, pqxx::usage_error,
"Moving a connection with a transaction open should be an error.");
}
void test_move_assign()
{
pqxx::connection c1;
pqxx::connection c2;
c2.close();
c2 = std::move(c1);
PQXX_CHECK(not c1.is_open(), "Connection still open after being moved out.");
PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");
{
pqxx::work tx1{c2};
PQXX_CHECK_EQUAL(tx1.query_value<int>("SELECT 8"), 8, "What!?");
pqxx::connection c3;
PQXX_CHECK_THROWS(
c3 = std::move(c2), pqxx::usage_error,
"Moving a connection with a transaction open should be an error.");
PQXX_CHECK_THROWS(
c2 = std::move(c3), pqxx::usage_error,
"Moving a connection onto one with a transaction open should be "
"an error.");
}
// After failed move attempts, the connection is still usable.
pqxx::work tx2{c2};
PQXX_CHECK_EQUAL(tx2.query_value<int>("SELECT 6"), 6, "Huh!?");
}
void test_encrypt_password()
{
pqxx::connection c;
auto pw{c.encrypt_password("user", "password")};
PQXX_CHECK(not std::empty(pw), "Encrypted password was empty.");
PQXX_CHECK_EQUAL(
std::strlen(pw.c_str()), std::size(pw),
"Encrypted password contains a null byte.");
}
void test_connection_string()
{
pqxx::connection c;
std::string const connstr{c.connection_string()};
if (std::getenv("PGUSER") == nullptr)
{
PQXX_CHECK(
connstr.find("user=" + std::string{c.username()}) != std::string::npos,
"Connection string did not specify user name: " + connstr);
}
else
{
PQXX_CHECK(
connstr.find("user=" + std::string{c.username()}) == std::string::npos,
"Connection string specified user name, even when using default: " +
connstr);
}
}
#if defined(PQXX_HAVE_CONCEPTS)
template<typename STR> std::size_t length(STR const &str)
{
return std::size(str);
}
std::size_t length(char const str[])
{
return std::strlen(str);
}
#endif // PQXX_HAVE_CONCEPTS
template<typename MAP> void test_params_type()
{
#if defined(PQXX_HAVE_CONCEPTS)
using item_t = std::remove_reference_t<
decltype(*std::declval<std::ranges::iterator_t<MAP>>())>;
using key_t = decltype(std::get<0>(std::declval<item_t>()));
using value_t = decltype(std::get<1>(std::declval<item_t>()));
// Set some parameters that are relatively safe to change arbitrarily.
MAP const params{{
{key_t{"application_name"}, value_t{"pqxx-test"}},
{key_t{"connect_timeout"}, value_t{"96"}},
{key_t{"keepalives_idle"}, value_t{"771"}},
}};
// Can we create a connection from these parameters?
pqxx::connection c{params};
// Check that the parameters came through in the connection string.
// We don't know the exact format, but the parameters have to be in there.
auto const min_size{std::accumulate(
std::cbegin(params), std::cend(params), std::size(params) - 1,
[](auto count, auto item) {
return count + length(std::get<0>(item)) + 1 + length(std::get<1>(item));
})};
auto const connstr{c.connection_string()};
PQXX_CHECK_GREATER_EQUAL(
std::size(connstr), min_size,
"Connection string can't possibly contain the options we gave.");
for (auto const &[key, value] : params)
{
PQXX_CHECK_NOT_EQUAL(
connstr.find(key), std::string::npos,
"Could not find param name '" + std::string{key} +
"' in connection string: " + connstr);
PQXX_CHECK_NOT_EQUAL(
connstr.find(value), std::string::npos,
"Could not find value for '" + std::string{value} +
"' in connection string: " + connstr);
}
#endif // PQXX_HAVE_CONCEPTS
}
void test_connection_params()
{
// Connecting in this way supports a wide variety of formats for the
// parameters.
test_params_type<std::map<char const *, char const *>>();
test_params_type<std::map<pqxx::zview, pqxx::zview>>();
test_params_type<std::map<std::string, std::string>>();
test_params_type<std::map<std::string, pqxx::zview>>();
test_params_type<std::map<pqxx::zview, char const *>>();
test_params_type<std::vector<std::tuple<char const *, char const *>>>();
test_params_type<std::vector<std::tuple<pqxx::zview, std::string>>>();
test_params_type<std::vector<std::pair<std::string, char const *>>>();
test_params_type<std::vector<std::array<std::string, 2>>>();
}
PQXX_REGISTER_TEST(test_move_constructor);
PQXX_REGISTER_TEST(test_move_assign);
PQXX_REGISTER_TEST(test_encrypt_password);
PQXX_REGISTER_TEST(test_connection_string);
PQXX_REGISTER_TEST(test_connection_params);
} // namespace
<commit_msg>Unit-test connection string types.<commit_after>#include <numeric>
#include <pqxx/transaction>
#include "../test_helpers.hxx"
namespace
{
void test_connection_string_constructor()
{
pqxx::connection c1{""};
pqxx::connection c2{std::string{}};
}
void test_move_constructor()
{
pqxx::connection c1;
PQXX_CHECK(c1.is_open(), "New connection is not open.");
pqxx::connection c2{std::move(c1)};
PQXX_CHECK(not c1.is_open(), "Moving did not close original connection.");
PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");
pqxx::work tx{c2};
PQXX_CHECK_EQUAL(tx.query_value<int>("SELECT 5"), 5, "Weird result!");
PQXX_CHECK_THROWS(
pqxx::connection c3{std::move(c2)}, pqxx::usage_error,
"Moving a connection with a transaction open should be an error.");
}
void test_move_assign()
{
pqxx::connection c1;
pqxx::connection c2;
c2.close();
c2 = std::move(c1);
PQXX_CHECK(not c1.is_open(), "Connection still open after being moved out.");
PQXX_CHECK(c2.is_open(), "Moved constructor is not open.");
{
pqxx::work tx1{c2};
PQXX_CHECK_EQUAL(tx1.query_value<int>("SELECT 8"), 8, "What!?");
pqxx::connection c3;
PQXX_CHECK_THROWS(
c3 = std::move(c2), pqxx::usage_error,
"Moving a connection with a transaction open should be an error.");
PQXX_CHECK_THROWS(
c2 = std::move(c3), pqxx::usage_error,
"Moving a connection onto one with a transaction open should be "
"an error.");
}
// After failed move attempts, the connection is still usable.
pqxx::work tx2{c2};
PQXX_CHECK_EQUAL(tx2.query_value<int>("SELECT 6"), 6, "Huh!?");
}
void test_encrypt_password()
{
pqxx::connection c;
auto pw{c.encrypt_password("user", "password")};
PQXX_CHECK(not std::empty(pw), "Encrypted password was empty.");
PQXX_CHECK_EQUAL(
std::strlen(pw.c_str()), std::size(pw),
"Encrypted password contains a null byte.");
}
void test_connection_string()
{
pqxx::connection c;
std::string const connstr{c.connection_string()};
if (std::getenv("PGUSER") == nullptr)
{
PQXX_CHECK(
connstr.find("user=" + std::string{c.username()}) != std::string::npos,
"Connection string did not specify user name: " + connstr);
}
else
{
PQXX_CHECK(
connstr.find("user=" + std::string{c.username()}) == std::string::npos,
"Connection string specified user name, even when using default: " +
connstr);
}
}
#if defined(PQXX_HAVE_CONCEPTS)
template<typename STR> std::size_t length(STR const &str)
{
return std::size(str);
}
std::size_t length(char const str[])
{
return std::strlen(str);
}
#endif // PQXX_HAVE_CONCEPTS
template<typename MAP> void test_params_type()
{
#if defined(PQXX_HAVE_CONCEPTS)
using item_t = std::remove_reference_t<
decltype(*std::declval<std::ranges::iterator_t<MAP>>())>;
using key_t = decltype(std::get<0>(std::declval<item_t>()));
using value_t = decltype(std::get<1>(std::declval<item_t>()));
// Set some parameters that are relatively safe to change arbitrarily.
MAP const params{{
{key_t{"application_name"}, value_t{"pqxx-test"}},
{key_t{"connect_timeout"}, value_t{"96"}},
{key_t{"keepalives_idle"}, value_t{"771"}},
}};
// Can we create a connection from these parameters?
pqxx::connection c{params};
// Check that the parameters came through in the connection string.
// We don't know the exact format, but the parameters have to be in there.
auto const min_size{std::accumulate(
std::cbegin(params), std::cend(params), std::size(params) - 1,
[](auto count, auto item) {
return count + length(std::get<0>(item)) + 1 + length(std::get<1>(item));
})};
auto const connstr{c.connection_string()};
PQXX_CHECK_GREATER_EQUAL(
std::size(connstr), min_size,
"Connection string can't possibly contain the options we gave.");
for (auto const &[key, value] : params)
{
PQXX_CHECK_NOT_EQUAL(
connstr.find(key), std::string::npos,
"Could not find param name '" + std::string{key} +
"' in connection string: " + connstr);
PQXX_CHECK_NOT_EQUAL(
connstr.find(value), std::string::npos,
"Could not find value for '" + std::string{value} +
"' in connection string: " + connstr);
}
#endif // PQXX_HAVE_CONCEPTS
}
void test_connection_params()
{
// Connecting in this way supports a wide variety of formats for the
// parameters.
test_params_type<std::map<char const *, char const *>>();
test_params_type<std::map<pqxx::zview, pqxx::zview>>();
test_params_type<std::map<std::string, std::string>>();
test_params_type<std::map<std::string, pqxx::zview>>();
test_params_type<std::map<pqxx::zview, char const *>>();
test_params_type<std::vector<std::tuple<char const *, char const *>>>();
test_params_type<std::vector<std::tuple<pqxx::zview, std::string>>>();
test_params_type<std::vector<std::pair<std::string, char const *>>>();
test_params_type<std::vector<std::array<std::string, 2>>>();
}
PQXX_REGISTER_TEST(test_connection_string_constructor);
PQXX_REGISTER_TEST(test_move_constructor);
PQXX_REGISTER_TEST(test_move_assign);
PQXX_REGISTER_TEST(test_encrypt_password);
PQXX_REGISTER_TEST(test_connection_string);
PQXX_REGISTER_TEST(test_connection_params);
} // namespace
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCubeSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkCubeSource.h"
#include "vtkPoints.h"
#include "vtkNormals.h"
vtkCubeSource::vtkCubeSource(float xL, float yL, float zL)
{
this->XLength = fabs(xL);
this->YLength = fabs(yL);
this->ZLength = fabs(zL);
this->Center[0] = 0.0;
this->Center[1] = 0.0;
this->Center[2] = 0.0;
}
void vtkCubeSource::Execute()
{
float x[3], n[3];
int numPolys=6, numPts=24;
int i, j, k;
int pts[4];
vtkPoints *newPoints;
vtkNormals *newNormals;
vtkCellArray *newPolys;
vtkPolyData *output = this->GetOutput();
vtkDebugMacro(<<"Creating polygonal cube");
//
// Set things up; allocate memory
//
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
newNormals = vtkNormals::New();
newNormals->Allocate(numPts);
newPolys = vtkCellArray::New();
newPolys->Allocate(newPolys->EstimateSize(numPolys,4));
//
// Generate points and normals
//
numPts = 0;
for (x[0]=Center[0]-this->XLength/2.0, n[0]=(-1.0), n[1]=n[2]=0.0, i=0;
i<2; i++, x[0]+=this->XLength, n[0]+=2.0)
{
for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
j++, x[1]+=this->YLength)
{
for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
k++, x[2]+=this->ZLength)
{
newPoints->InsertNextPoint(x);
newNormals->InsertNextNormal(n);
}
}
}
pts[0] = 0; pts[1] = 1; pts[2] = 3; pts[3] = 2;
newPolys->InsertNextCell(4,pts);
pts[0] = 4; pts[1] = 6; pts[2] = 7; pts[3] = 5;
newPolys->InsertNextCell(4,pts);
for (x[1]=Center[1]-this->YLength/2.0, n[1]=(-1.0), n[0]=n[2]=0.0, i=0;
i<2; i++, x[1]+=this->YLength, n[1]+=2.0)
{
for (x[0]=Center[0]-this->XLength/2.0, j=0; j<2;
j++, x[0]+=this->XLength)
{
for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
k++, x[2]+=this->ZLength)
{
newPoints->InsertNextPoint(x);
newNormals->InsertNextNormal(n);
}
}
}
pts[0] = 8; pts[1] = 10; pts[2] = 11; pts[3] = 9;
newPolys->InsertNextCell(4,pts);
pts[0] = 12; pts[1] = 13; pts[2] = 15; pts[3] = 14;
newPolys->InsertNextCell(4,pts);
for (x[2]=Center[2]-this->ZLength/2.0, n[2]=(-1.0), n[0]=n[1]=0.0, i=0;
i<2; i++, x[2]+=this->ZLength, n[2]+=2.0)
{
for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
j++, x[1]+=this->YLength)
{
for (x[0]=Center[0]-this->XLength/2.0, k=0; k<2;
k++, x[0]+=this->XLength)
{
newPoints->InsertNextPoint(x);
newNormals->InsertNextNormal(n);
}
}
}
pts[0] = 16; pts[1] = 18; pts[2] = 19; pts[3] = 17;
newPolys->InsertNextCell(4,pts);
pts[0] = 20; pts[1] = 21; pts[2] = 23; pts[3] = 22;
newPolys->InsertNextCell(4,pts);
//
// Update ourselves and release memory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetNormals(newNormals);
newNormals->Delete();
newPolys->Squeeze(); // since we've estimated size; reclaim some space
output->SetPolys(newPolys);
newPolys->Delete();
}
// Description:
// Convenience method allows creation of cube by specifying bounding box.
void vtkCubeSource::SetBounds(float bounds[6])
{
this->SetXLength(bounds[1]-bounds[0]);
this->SetYLength(bounds[3]-bounds[2]);
this->SetZLength(bounds[5]-bounds[4]);
this->SetCenter((bounds[1]+bounds[0])/2.0, (bounds[3]+bounds[2])/2.0,
(bounds[5]+bounds[4])/2.0);
}
void vtkCubeSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataSource::PrintSelf(os,indent);
os << indent << "X Length: " << this->XLength << "\n";
os << indent << "Y Length: " << this->YLength << "\n";
os << indent << "Z Length: " << this->ZLength << "\n";
os << indent << "Center: (" << this->Center[0] << ", "
<< this->Center[1] << ", " << this->Center[2] << ")\n";
}
<commit_msg>ENH: Added texture mapping to vtkCubeSource<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCubeSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkCubeSource.h"
#include "vtkPoints.h"
#include "vtkNormals.h"
vtkCubeSource::vtkCubeSource(float xL, float yL, float zL)
{
this->XLength = fabs(xL);
this->YLength = fabs(yL);
this->ZLength = fabs(zL);
this->Center[0] = 0.0;
this->Center[1] = 0.0;
this->Center[2] = 0.0;
}
void vtkCubeSource::Execute()
{
float x[3], n[3], tc[3];
int numPolys=6, numPts=24;
int i, j, k;
int pts[4];
vtkPoints *newPoints;
vtkNormals *newNormals;
vtkTCoords *newTCoords; // CCS 7/27/98 Added for Texture Mapping
vtkCellArray *newPolys;
vtkPolyData *output = this->GetOutput();
vtkDebugMacro(<<"Creating polygonal cube");
//
// Set things up; allocate memory
//
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
newNormals = vtkNormals::New();
newNormals->Allocate(numPts);
newTCoords = vtkTCoords::New();
newTCoords->Allocate(numPts);
newPolys = vtkCellArray::New();
newPolys->Allocate(newPolys->EstimateSize(numPolys,4));
//
// Generate points and normals
//
numPts = 0;
for (x[0]=Center[0]-this->XLength/2.0, n[0]=(-1.0), n[1]=n[2]=0.0, i=0;
i<2; i++, x[0]+=this->XLength, n[0]+=2.0)
{
for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
j++, x[1]+=this->YLength)
{
tc[1] = x[1] + 0.5;
for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
k++, x[2]+=this->ZLength)
{
tc[0] = (x[2] + 0.5) * ( 1 - 2*i );
newPoints->InsertNextPoint(x);
newTCoords->InsertNextTCoord(tc);
newNormals->InsertNextNormal(n);
}
}
}
pts[0] = 0; pts[1] = 1; pts[2] = 3; pts[3] = 2;
newPolys->InsertNextCell(4,pts);
pts[0] = 4; pts[1] = 6; pts[2] = 7; pts[3] = 5;
newPolys->InsertNextCell(4,pts);
for (x[1]=Center[1]-this->YLength/2.0, n[1]=(-1.0), n[0]=n[2]=0.0, i=0;
i<2; i++, x[1]+=this->YLength, n[1]+=2.0)
{
for (x[0]=Center[0]-this->XLength/2.0, j=0; j<2;
j++, x[0]+=this->XLength)
{
tc[0] = ( x[0] + 0.5 ) * ( 2*i - 1 );
for (x[2]=Center[2]-this->ZLength/2.0, k=0; k<2;
k++, x[2]+=this->ZLength)
{
tc[1] = ( x[2] + 0.5 ) * -1;
newPoints->InsertNextPoint(x);
newTCoords->InsertNextTCoord(tc);
newNormals->InsertNextNormal(n);
}
}
}
pts[0] = 8; pts[1] = 10; pts[2] = 11; pts[3] = 9;
newPolys->InsertNextCell(4,pts);
pts[0] = 12; pts[1] = 13; pts[2] = 15; pts[3] = 14;
newPolys->InsertNextCell(4,pts);
for (x[2]=Center[2]-this->ZLength/2.0, n[2]=(-1.0), n[0]=n[1]=0.0, i=0;
i<2; i++, x[2]+=this->ZLength, n[2]+=2.0)
{
for (x[1]=Center[1]-this->YLength/2.0, j=0; j<2;
j++, x[1]+=this->YLength)
{
tc[1] = x[1] + 0.5;
for (x[0]=Center[0]-this->XLength/2.0, k=0; k<2;
k++, x[0]+=this->XLength)
{
tc[0] = ( x[0] + 0.5 ) * ( 2*i - 1 );
newPoints->InsertNextPoint(x);
newTCoords->InsertNextTCoord(tc);
newNormals->InsertNextNormal(n);
}
}
}
pts[0] = 16; pts[1] = 18; pts[2] = 19; pts[3] = 17;
newPolys->InsertNextCell(4,pts);
pts[0] = 20; pts[1] = 21; pts[2] = 23; pts[3] = 22;
newPolys->InsertNextCell(4,pts);
//
// Update ourselves and release memory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetNormals(newNormals);
newNormals->Delete();
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
newPolys->Squeeze(); // since we've estimated size; reclaim some space
output->SetPolys(newPolys);
newPolys->Delete();
}
// Description:
// Convenience method allows creation of cube by specifying bounding box.
void vtkCubeSource::SetBounds(float bounds[6])
{
this->SetXLength(bounds[1]-bounds[0]);
this->SetYLength(bounds[3]-bounds[2]);
this->SetZLength(bounds[5]-bounds[4]);
this->SetCenter((bounds[1]+bounds[0])/2.0, (bounds[3]+bounds[2])/2.0,
(bounds[5]+bounds[4])/2.0);
}
void vtkCubeSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataSource::PrintSelf(os,indent);
os << indent << "X Length: " << this->XLength << "\n";
os << indent << "Y Length: " << this->YLength << "\n";
os << indent << "Z Length: " << this->ZLength << "\n";
os << indent << "Center: (" << this->Center[0] << ", "
<< this->Center[1] << ", " << this->Center[2] << ")\n";
}
<|endoftext|> |
<commit_before>/*
AddressBookSelectorWidget
Copyright (c) 2005 by Duncan Mac-Vicar Prett <[email protected]>
Based on LinkAddressBookUI whose code was shamelessly stolen from
kopete's add new contact wizard, used in Konversation, and then
reappropriated by Kopete.
LinkAddressBookUI:
Copyright (c) 2004 by John Tapsell <[email protected]>
Copyright (c) 2003-2005 by Will Stephenson <[email protected]>
Copyright (c) 2002 by Nick Betcher <[email protected]>
Copyright (c) 2002 by Duncan Mac-Vicar Prett <[email protected]>
Kopete (c) 2002-2004 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qcheckbox.h>
#include <kapplication.h>
#include <kconfig.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kdeversion.h>
#include <kinputdialog.h>
#include <kpushbutton.h>
#include <kactivelabel.h>
#include <kdebug.h>
#include <klistview.h>
#include <klistviewsearchline.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <q3whatsthis.h>
#include "addressbookselectorwidget.h"
#include <addresseeitem.h>
#include "kabcpersistence.h"
using namespace Kopete::UI;
namespace Kopete
{
namespace UI
{
AddressBookSelectorWidget::AddressBookSelectorWidget( QWidget *parent, const char *name )
: AddressBookSelectorWidget_Base( parent, name )
{
m_addressBook = Kopete::KABCPersistence::self()->addressBook();
// Addressee validation connections
connect( addAddresseeButton, SIGNAL( clicked() ), SLOT( slotAddAddresseeClicked() ) );
connect( addAddresseeButton, SIGNAL( clicked() ), SIGNAL( addAddresseeClicked() ) );
connect( addresseeListView, SIGNAL( clicked(Q3ListViewItem * ) ),
SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
connect( addresseeListView, SIGNAL( selectionChanged( Q3ListViewItem * ) ),
SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
connect( addresseeListView, SIGNAL( spacePressed( Q3ListViewItem * ) ),
SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );
//We should add a clear KAction here. But we can't really do that with a designer file :\ this sucks
addresseeListView->setColumnText(2, SmallIconSet(QString::fromLatin1("email")), i18n("Email"));
kListViewSearchLine->setListView(addresseeListView);
slotLoadAddressees();
addresseeListView->setColumnWidthMode(0, Q3ListView::Manual);
addresseeListView->setColumnWidth(0, 63); //Photo is 60, and it's nice to have a small gap, imho
}
AddressBookSelectorWidget::~AddressBookSelectorWidget()
{
disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );
}
KABC::Addressee AddressBookSelectorWidget::addressee()
{
AddresseeItem *item = 0L;
item = static_cast<AddresseeItem *>( addresseeListView->selectedItem() );
if ( item )
m_addressee = item->addressee();
return m_addressee;
}
void AddressBookSelectorWidget::selectAddressee( const QString &uid )
{
// iterate trough list view
Q3ListViewItemIterator it( addresseeListView );
while( it.current() )
{
AddresseeItem *addrItem = (AddresseeItem *) it.current();
if ( addrItem->addressee().uid() == uid )
{
// select the contact item
addresseeListView->setSelected( addrItem, true );
addresseeListView->ensureItemVisible( addrItem );
}
++it;
}
}
bool AddressBookSelectorWidget::addresseeSelected()
{
return addresseeListView->selectedItem() ? true : false;
}
/** Read in contacts from addressbook, and select the contact that is for our nick. */
void AddressBookSelectorWidget::slotLoadAddressees()
{
addresseeListView->clear();
KABC::AddressBook::Iterator it;
AddresseeItem *addr;
for( it = m_addressBook->begin(); it != m_addressBook->end(); ++it )
{
addr = new AddresseeItem( addresseeListView, (*it));
}
}
void AddressBookSelectorWidget::setLabelMessage( const QString &msg )
{
lblHeader->setText(msg);
}
void AddressBookSelectorWidget::slotAddAddresseeClicked()
{
// Pop up add addressee dialog
QString addresseeName = KInputDialog::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this );
if ( !addresseeName.isEmpty() )
{
KABC::Addressee addr;
addr.setNameFromString( addresseeName );
m_addressBook->insertAddressee(addr);
Kopete::KABCPersistence::self()->writeAddressBook( 0 );
slotLoadAddressees();
// select the addressee we just added
Q3ListViewItem * added = addresseeListView->findItem( addresseeName, 1 );
addresseeListView->setSelected( added, true );
addresseeListView->ensureItemVisible( added );
}
}
} // namespace UI
} // namespace Kopete
#include "addressbookselectorwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>backport BUG: 110896<commit_after>/*
AddressBookSelectorWidget
Copyright (c) 2005 by Duncan Mac-Vicar Prett <[email protected]>
Based on LinkAddressBookUI whose code was shamelessly stolen from
kopete's add new contact wizard, used in Konversation, and then
reappropriated by Kopete.
LinkAddressBookUI:
Copyright (c) 2004 by John Tapsell <[email protected]>
Copyright (c) 2003-2005 by Will Stephenson <[email protected]>
Copyright (c) 2002 by Nick Betcher <[email protected]>
Copyright (c) 2002 by Duncan Mac-Vicar Prett <[email protected]>
Kopete (c) 2002-2004 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qcheckbox.h>
#include <kapplication.h>
#include <kconfig.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kdeversion.h>
#include <kinputdialog.h>
#include <kpushbutton.h>
#include <kactivelabel.h>
#include <kdebug.h>
#include <klistview.h>
#include <klistviewsearchline.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <q3whatsthis.h>
#include "addressbookselectorwidget.h"
#include <addresseeitem.h>
#include "kabcpersistence.h"
using namespace Kopete::UI;
namespace Kopete
{
namespace UI
{
AddressBookSelectorWidget::AddressBookSelectorWidget( QWidget *parent, const char *name )
: AddressBookSelectorWidget_Base( parent, name )
{
m_addressBook = Kopete::KABCPersistence::self()->addressBook();
// Addressee validation connections
connect( addAddresseeButton, SIGNAL( clicked() ), SLOT( slotAddAddresseeClicked() ) );
connect( addAddresseeButton, SIGNAL( clicked() ), SIGNAL( addAddresseeClicked() ) );
connect( addresseeListView, SIGNAL( clicked(Q3ListViewItem * ) ),
SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
connect( addresseeListView, SIGNAL( selectionChanged( Q3ListViewItem * ) ),
SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
connect( addresseeListView, SIGNAL( spacePressed( Q3ListViewItem * ) ),
SIGNAL( addresseeListClicked( Q3ListViewItem * ) ) );
connect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );
//We should add a clear KAction here. But we can't really do that with a designer file :\ this sucks
addresseeListView->setColumnText(2, SmallIconSet(QString::fromLatin1("email")), i18n("Email"));
kListViewSearchLine->setListView(addresseeListView);
slotLoadAddressees();
addresseeListView->setColumnWidthMode(0, Q3ListView::Manual);
addresseeListView->setColumnWidth(0, 63); //Photo is 60, and it's nice to have a small gap, imho
}
AddressBookSelectorWidget::~AddressBookSelectorWidget()
{
disconnect( m_addressBook, SIGNAL( addressBookChanged( AddressBook * ) ), this, SLOT( slotLoadAddressees() ) );
}
KABC::Addressee AddressBookSelectorWidget::addressee()
{
AddresseeItem *item = 0L;
item = static_cast<AddresseeItem *>( addresseeListView->selectedItem() );
if ( item )
m_addressee = item->addressee();
return m_addressee;
}
void AddressBookSelectorWidget::selectAddressee( const QString &uid )
{
// iterate trough list view
Q3ListViewItemIterator it( addresseeListView );
while( it.current() )
{
AddresseeItem *addrItem = (AddresseeItem *) it.current();
if ( addrItem->addressee().uid() == uid )
{
// select the contact item
addresseeListView->setSelected( addrItem, true );
addresseeListView->ensureItemVisible( addrItem );
}
++it;
}
}
bool AddressBookSelectorWidget::addresseeSelected()
{
return addresseeListView->selectedItem() ? true : false;
}
/** Read in contacts from addressbook, and select the contact that is for our nick. */
void AddressBookSelectorWidget::slotLoadAddressees()
{
addresseeListView->clear();
KABC::AddressBook::Iterator it;
AddresseeItem *addr;
for( it = m_addressBook->begin(); it != m_addressBook->end(); ++it )
{
addr = new AddresseeItem( addresseeListView, (*it));
}
}
void AddressBookSelectorWidget::setLabelMessage( const QString &msg )
{
lblHeader->setText(msg);
}
void AddressBookSelectorWidget::slotAddAddresseeClicked()
{
// Pop up add addressee dialog
QString addresseeName = KInputDialog::getText( i18n( "New Address Book Entry" ), i18n( "Name the new entry:" ), QString::null, 0, this );
if ( !addresseeName.isEmpty() )
{
KABC::Addressee addr;
addr.setNameFromString( addresseeName );
m_addressBook->insertAddressee(addr);
Kopete::KABCPersistence::self()->writeAddressBook( 0 );
slotLoadAddressees();
// select the addressee we just added
Q3ListViewItem * added = addresseeListView->findItem( addresseeName, 1 );
kListViewSearchLine->clear();
kListViewSearchLine->updateSearch();
addresseeListView->setSelected( added, true );
addresseeListView->ensureItemVisible( added );
}
}
} // namespace UI
} // namespace Kopete
#include "addressbookselectorwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>//===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code used to execute the program utilizing one of the
// various ways of running LLVM bytecode.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "llvm/Support/ToolRunner.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/SystemUtils.h"
#include <fstream>
using namespace llvm;
namespace {
// OutputType - Allow the user to specify the way code should be run, to test
// for miscompilation.
//
enum OutputType {
AutoPick, RunLLI, RunJIT, RunLLC, RunCBE
};
cl::opt<OutputType>
InterpreterSel(cl::desc("Specify how LLVM code should be executed:"),
cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
clEnumValN(RunLLI, "run-int",
"Execute with the interpreter"),
clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
clEnumValN(RunCBE, "run-cbe", "Compile with CBE"),
clEnumValEnd),
cl::init(AutoPick));
cl::opt<bool>
CheckProgramExitCode("check-exit-code",
cl::desc("Assume nonzero exit code is failure (default on)"),
cl::init(true));
cl::opt<std::string>
InputFile("input", cl::init("/dev/null"),
cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
cl::list<std::string>
AdditionalSOs("additional-so",
cl::desc("Additional shared objects to load "
"into executing programs"));
cl::opt<unsigned>
TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
cl::desc("Number of seconds program is allowed to run before it "
"is killed (default is 300s), 0 disables timeout"));
}
namespace llvm {
// Anything specified after the --args option are taken as arguments to the
// program being debugged.
cl::list<std::string>
InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
cl::ZeroOrMore, cl::PositionalEatsArgs);
cl::list<std::string>
ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
cl::ZeroOrMore, cl::PositionalEatsArgs);
}
//===----------------------------------------------------------------------===//
// BugDriver method implementation
//
/// initializeExecutionEnvironment - This method is used to set up the
/// environment for executing LLVM programs.
///
bool BugDriver::initializeExecutionEnvironment() {
std::cout << "Initializing execution environment: ";
// Create an instance of the AbstractInterpreter interface as specified on
// the command line
cbe = 0;
std::string Message;
switch (InterpreterSel) {
case AutoPick:
InterpreterSel = RunCBE;
Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
&ToolArgv);
if (!Interpreter) {
InterpreterSel = RunJIT;
Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
&ToolArgv);
}
if (!Interpreter) {
InterpreterSel = RunLLC;
Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
&ToolArgv);
}
if (!Interpreter) {
InterpreterSel = RunLLI;
Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
&ToolArgv);
}
if (!Interpreter) {
InterpreterSel = AutoPick;
Message = "Sorry, I can't automatically select an interpreter!\n";
}
break;
case RunLLI:
Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
&ToolArgv);
break;
case RunLLC:
Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
&ToolArgv);
break;
case RunJIT:
Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
&ToolArgv);
break;
case RunCBE:
Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
&ToolArgv);
break;
default:
Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
break;
}
std::cerr << Message;
// Initialize auxiliary tools for debugging
if (!cbe) {
cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
}
gcc = GCC::create(getToolName(), Message);
if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }
// If there was an error creating the selected interpreter, quit with error.
return Interpreter == 0;
}
/// compileProgram - Try to compile the specified module, throwing an exception
/// if an error occurs, or returning normally if not. This is used for code
/// generation crash testing.
///
void BugDriver::compileProgram(Module *M) {
// Emit the program to a bytecode file...
sys::Path BytecodeFile ("bugpoint-test-program.bc");
BytecodeFile.makeUnique();
if (writeProgramToFile(BytecodeFile.toString(), M)) {
std::cerr << ToolName << ": Error emitting bytecode to file '"
<< BytecodeFile << "'!\n";
exit(1);
}
// Remove the temporary bytecode file when we are done.
FileRemover BytecodeFileRemover(BytecodeFile);
// Actually compile the program!
Interpreter->compileProgram(BytecodeFile.toString());
}
/// executeProgram - This method runs "Program", capturing the output of the
/// program to a file, returning the filename of the file. A recommended
/// filename may be optionally specified.
///
std::string BugDriver::executeProgram(std::string OutputFile,
std::string BytecodeFile,
const std::string &SharedObj,
AbstractInterpreter *AI,
bool *ProgramExitedNonzero) {
if (AI == 0) AI = Interpreter;
assert(AI && "Interpreter should have been created already!");
bool CreatedBytecode = false;
if (BytecodeFile.empty()) {
// Emit the program to a bytecode file...
sys::Path uniqueFilename("bugpoint-test-program.bc");
uniqueFilename.makeUnique();
BytecodeFile = uniqueFilename.toString();
if (writeProgramToFile(BytecodeFile, Program)) {
std::cerr << ToolName << ": Error emitting bytecode to file '"
<< BytecodeFile << "'!\n";
exit(1);
}
CreatedBytecode = true;
}
// Remove the temporary bytecode file when we are done.
FileRemover BytecodeFileRemover(sys::Path(BytecodeFile), CreatedBytecode);
if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
// Check to see if this is a valid output filename...
sys::Path uniqueFile(OutputFile);
uniqueFile.makeUnique();
OutputFile = uniqueFile.toString();
// Figure out which shared objects to run, if any.
std::vector<std::string> SharedObjs(AdditionalSOs);
if (!SharedObj.empty())
SharedObjs.push_back(SharedObj);
// Actually execute the program!
int RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
OutputFile, SharedObjs, TimeoutValue);
if (RetVal == -1) {
std::cerr << "<timeout>";
static bool FirstTimeout = true;
if (FirstTimeout) {
std::cout << "\n"
"*** Program execution timed out! This mechanism is designed to handle\n"
" programs stuck in infinite loops gracefully. The -timeout option\n"
" can be used to change the timeout threshold or disable it completely\n"
" (with -timeout=0). This message is only displayed once.\n";
FirstTimeout = false;
}
}
if (ProgramExitedNonzero != 0)
*ProgramExitedNonzero = (RetVal != 0);
// Return the filename we captured the output to.
return OutputFile;
}
/// executeProgramWithCBE - Used to create reference output with the C
/// backend, if reference output is not provided.
///
std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
bool ProgramExitedNonzero;
std::string outFN = executeProgram(OutputFile, "", "",
(AbstractInterpreter*)cbe,
&ProgramExitedNonzero);
if (ProgramExitedNonzero) {
std::cerr
<< "Warning: While generating reference output, program exited with\n"
<< "non-zero exit code. This will NOT be treated as a failure.\n";
CheckProgramExitCode = false;
}
return outFN;
}
std::string BugDriver::compileSharedObject(const std::string &BytecodeFile) {
assert(Interpreter && "Interpreter should have been created already!");
sys::Path OutputCFile;
// Using CBE
cbe->OutputC(BytecodeFile, OutputCFile);
#if 0 /* This is an alternative, as yet unimplemented */
// Using LLC
std::string Message;
LLC *llc = createLLCtool(Message);
if (llc->OutputAsm(BytecodeFile, OutputFile)) {
std::cerr << "Could not generate asm code with `llc', exiting.\n";
exit(1);
}
#endif
std::string SharedObjectFile;
if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
SharedObjectFile))
exit(1);
// Remove the intermediate C file
OutputCFile.destroyFile();
return "./" + SharedObjectFile;
}
/// diffProgram - This method executes the specified module and diffs the output
/// against the file specified by ReferenceOutputFile. If the output is
/// different, true is returned.
///
bool BugDriver::diffProgram(const std::string &BytecodeFile,
const std::string &SharedObject,
bool RemoveBytecode) {
bool ProgramExitedNonzero;
// Execute the program, generating an output file...
sys::Path Output (executeProgram("", BytecodeFile, SharedObject, 0,
&ProgramExitedNonzero));
// If we're checking the program exit code, assume anything nonzero is bad.
if (CheckProgramExitCode && ProgramExitedNonzero) {
Output.destroyFile();
if (RemoveBytecode)
sys::Path(BytecodeFile).destroyFile();
return true;
}
std::string Error;
bool FilesDifferent = false;
if (DiffFiles(ReferenceOutputFile, Output.toString(), &Error)) {
if (!Error.empty()) {
std::cerr << "While diffing output: " << Error << '\n';
exit(1);
}
FilesDifferent = true;
}
// Remove the generated output.
Output.destroyFile();
// Remove the bytecode file if we are supposed to.
if (RemoveBytecode) sys::Path(BytecodeFile).destroyFile();
return FilesDifferent;
}
bool BugDriver::isExecutingJIT() {
return InterpreterSel == RunJIT;
}
<commit_msg>Fix the build on PowerPC/Darwin - it thought we were declaring a new function or something. Since FileRemover takes a const reference to sys::Path, we need to pass an actual sys::Path variable.<commit_after>//===- ExecutionDriver.cpp - Allow execution of LLVM program --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code used to execute the program utilizing one of the
// various ways of running LLVM bytecode.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "llvm/Support/ToolRunner.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/SystemUtils.h"
#include <fstream>
using namespace llvm;
namespace {
// OutputType - Allow the user to specify the way code should be run, to test
// for miscompilation.
//
enum OutputType {
AutoPick, RunLLI, RunJIT, RunLLC, RunCBE
};
cl::opt<OutputType>
InterpreterSel(cl::desc("Specify how LLVM code should be executed:"),
cl::values(clEnumValN(AutoPick, "auto", "Use best guess"),
clEnumValN(RunLLI, "run-int",
"Execute with the interpreter"),
clEnumValN(RunJIT, "run-jit", "Execute with JIT"),
clEnumValN(RunLLC, "run-llc", "Compile with LLC"),
clEnumValN(RunCBE, "run-cbe", "Compile with CBE"),
clEnumValEnd),
cl::init(AutoPick));
cl::opt<bool>
CheckProgramExitCode("check-exit-code",
cl::desc("Assume nonzero exit code is failure (default on)"),
cl::init(true));
cl::opt<std::string>
InputFile("input", cl::init("/dev/null"),
cl::desc("Filename to pipe in as stdin (default: /dev/null)"));
cl::list<std::string>
AdditionalSOs("additional-so",
cl::desc("Additional shared objects to load "
"into executing programs"));
cl::opt<unsigned>
TimeoutValue("timeout", cl::init(300), cl::value_desc("seconds"),
cl::desc("Number of seconds program is allowed to run before it "
"is killed (default is 300s), 0 disables timeout"));
}
namespace llvm {
// Anything specified after the --args option are taken as arguments to the
// program being debugged.
cl::list<std::string>
InputArgv("args", cl::Positional, cl::desc("<program arguments>..."),
cl::ZeroOrMore, cl::PositionalEatsArgs);
cl::list<std::string>
ToolArgv("tool-args", cl::Positional, cl::desc("<tool arguments>..."),
cl::ZeroOrMore, cl::PositionalEatsArgs);
}
//===----------------------------------------------------------------------===//
// BugDriver method implementation
//
/// initializeExecutionEnvironment - This method is used to set up the
/// environment for executing LLVM programs.
///
bool BugDriver::initializeExecutionEnvironment() {
std::cout << "Initializing execution environment: ";
// Create an instance of the AbstractInterpreter interface as specified on
// the command line
cbe = 0;
std::string Message;
switch (InterpreterSel) {
case AutoPick:
InterpreterSel = RunCBE;
Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
&ToolArgv);
if (!Interpreter) {
InterpreterSel = RunJIT;
Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
&ToolArgv);
}
if (!Interpreter) {
InterpreterSel = RunLLC;
Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
&ToolArgv);
}
if (!Interpreter) {
InterpreterSel = RunLLI;
Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
&ToolArgv);
}
if (!Interpreter) {
InterpreterSel = AutoPick;
Message = "Sorry, I can't automatically select an interpreter!\n";
}
break;
case RunLLI:
Interpreter = AbstractInterpreter::createLLI(getToolName(), Message,
&ToolArgv);
break;
case RunLLC:
Interpreter = AbstractInterpreter::createLLC(getToolName(), Message,
&ToolArgv);
break;
case RunJIT:
Interpreter = AbstractInterpreter::createJIT(getToolName(), Message,
&ToolArgv);
break;
case RunCBE:
Interpreter = cbe = AbstractInterpreter::createCBE(getToolName(), Message,
&ToolArgv);
break;
default:
Message = "Sorry, this back-end is not supported by bugpoint right now!\n";
break;
}
std::cerr << Message;
// Initialize auxiliary tools for debugging
if (!cbe) {
cbe = AbstractInterpreter::createCBE(getToolName(), Message, &ToolArgv);
if (!cbe) { std::cout << Message << "\nExiting.\n"; exit(1); }
}
gcc = GCC::create(getToolName(), Message);
if (!gcc) { std::cout << Message << "\nExiting.\n"; exit(1); }
// If there was an error creating the selected interpreter, quit with error.
return Interpreter == 0;
}
/// compileProgram - Try to compile the specified module, throwing an exception
/// if an error occurs, or returning normally if not. This is used for code
/// generation crash testing.
///
void BugDriver::compileProgram(Module *M) {
// Emit the program to a bytecode file...
sys::Path BytecodeFile ("bugpoint-test-program.bc");
BytecodeFile.makeUnique();
if (writeProgramToFile(BytecodeFile.toString(), M)) {
std::cerr << ToolName << ": Error emitting bytecode to file '"
<< BytecodeFile << "'!\n";
exit(1);
}
// Remove the temporary bytecode file when we are done.
FileRemover BytecodeFileRemover(BytecodeFile);
// Actually compile the program!
Interpreter->compileProgram(BytecodeFile.toString());
}
/// executeProgram - This method runs "Program", capturing the output of the
/// program to a file, returning the filename of the file. A recommended
/// filename may be optionally specified.
///
std::string BugDriver::executeProgram(std::string OutputFile,
std::string BytecodeFile,
const std::string &SharedObj,
AbstractInterpreter *AI,
bool *ProgramExitedNonzero) {
if (AI == 0) AI = Interpreter;
assert(AI && "Interpreter should have been created already!");
bool CreatedBytecode = false;
if (BytecodeFile.empty()) {
// Emit the program to a bytecode file...
sys::Path uniqueFilename("bugpoint-test-program.bc");
uniqueFilename.makeUnique();
BytecodeFile = uniqueFilename.toString();
if (writeProgramToFile(BytecodeFile, Program)) {
std::cerr << ToolName << ": Error emitting bytecode to file '"
<< BytecodeFile << "'!\n";
exit(1);
}
CreatedBytecode = true;
}
// Remove the temporary bytecode file when we are done.
sys::Path BytecodePath (BytecodeFile);
FileRemover BytecodeFileRemover(BytecodePath, CreatedBytecode);
if (OutputFile.empty()) OutputFile = "bugpoint-execution-output";
// Check to see if this is a valid output filename...
sys::Path uniqueFile(OutputFile);
uniqueFile.makeUnique();
OutputFile = uniqueFile.toString();
// Figure out which shared objects to run, if any.
std::vector<std::string> SharedObjs(AdditionalSOs);
if (!SharedObj.empty())
SharedObjs.push_back(SharedObj);
// Actually execute the program!
int RetVal = AI->ExecuteProgram(BytecodeFile, InputArgv, InputFile,
OutputFile, SharedObjs, TimeoutValue);
if (RetVal == -1) {
std::cerr << "<timeout>";
static bool FirstTimeout = true;
if (FirstTimeout) {
std::cout << "\n"
"*** Program execution timed out! This mechanism is designed to handle\n"
" programs stuck in infinite loops gracefully. The -timeout option\n"
" can be used to change the timeout threshold or disable it completely\n"
" (with -timeout=0). This message is only displayed once.\n";
FirstTimeout = false;
}
}
if (ProgramExitedNonzero != 0)
*ProgramExitedNonzero = (RetVal != 0);
// Return the filename we captured the output to.
return OutputFile;
}
/// executeProgramWithCBE - Used to create reference output with the C
/// backend, if reference output is not provided.
///
std::string BugDriver::executeProgramWithCBE(std::string OutputFile) {
bool ProgramExitedNonzero;
std::string outFN = executeProgram(OutputFile, "", "",
(AbstractInterpreter*)cbe,
&ProgramExitedNonzero);
if (ProgramExitedNonzero) {
std::cerr
<< "Warning: While generating reference output, program exited with\n"
<< "non-zero exit code. This will NOT be treated as a failure.\n";
CheckProgramExitCode = false;
}
return outFN;
}
std::string BugDriver::compileSharedObject(const std::string &BytecodeFile) {
assert(Interpreter && "Interpreter should have been created already!");
sys::Path OutputCFile;
// Using CBE
cbe->OutputC(BytecodeFile, OutputCFile);
#if 0 /* This is an alternative, as yet unimplemented */
// Using LLC
std::string Message;
LLC *llc = createLLCtool(Message);
if (llc->OutputAsm(BytecodeFile, OutputFile)) {
std::cerr << "Could not generate asm code with `llc', exiting.\n";
exit(1);
}
#endif
std::string SharedObjectFile;
if (gcc->MakeSharedObject(OutputCFile.toString(), GCC::CFile,
SharedObjectFile))
exit(1);
// Remove the intermediate C file
OutputCFile.destroyFile();
return "./" + SharedObjectFile;
}
/// diffProgram - This method executes the specified module and diffs the output
/// against the file specified by ReferenceOutputFile. If the output is
/// different, true is returned.
///
bool BugDriver::diffProgram(const std::string &BytecodeFile,
const std::string &SharedObject,
bool RemoveBytecode) {
bool ProgramExitedNonzero;
// Execute the program, generating an output file...
sys::Path Output (executeProgram("", BytecodeFile, SharedObject, 0,
&ProgramExitedNonzero));
// If we're checking the program exit code, assume anything nonzero is bad.
if (CheckProgramExitCode && ProgramExitedNonzero) {
Output.destroyFile();
if (RemoveBytecode)
sys::Path(BytecodeFile).destroyFile();
return true;
}
std::string Error;
bool FilesDifferent = false;
if (DiffFiles(ReferenceOutputFile, Output.toString(), &Error)) {
if (!Error.empty()) {
std::cerr << "While diffing output: " << Error << '\n';
exit(1);
}
FilesDifferent = true;
}
// Remove the generated output.
Output.destroyFile();
// Remove the bytecode file if we are supposed to.
if (RemoveBytecode) sys::Path(BytecodeFile).destroyFile();
return FilesDifferent;
}
bool BugDriver::isExecutingJIT() {
return InterpreterSel == RunJIT;
}
<|endoftext|> |
<commit_before>//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs Clang on a single
/// input. This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Tooling.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Option/Option.h"
using namespace clang;
extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
std::string s((const char *)data, size);
llvm::opt::ArgStringList CC1Args;
CC1Args.push_back("-cc1");
CC1Args.push_back("./test.cc");
llvm::IntrusiveRefCntPtr<FileManager> Files(
new FileManager(FileSystemOptions()));
IgnoringDiagConsumer Diags;
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
&Diags, false);
std::unique_ptr<clang::CompilerInvocation> Invocation(
tooling::newInvocation(&Diagnostics, CC1Args));
std::unique_ptr<llvm::MemoryBuffer> Input =
llvm::MemoryBuffer::getMemBuffer(s);
Invocation->getPreprocessorOpts().addRemappedFile("./test.cc", Input.release());
std::unique_ptr<tooling::ToolAction> action(
tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>());
std::shared_ptr<PCHContainerOperations> PCHContainerOps =
std::make_shared<PCHContainerOperations>();
action->runInvocation(Invocation.release(), Files.get(), PCHContainerOps,
&Diags);
return 0;
}
<commit_msg>Add missing header in ClangFuzzer (after r275882 cleanup)<commit_after>//===-- ClangFuzzer.cpp - Fuzz Clang --------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file implements a function that runs Clang on a single
/// input. This function is then linked into the Fuzzer library.
///
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Tooling.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/Option/Option.h"
using namespace clang;
extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
std::string s((const char *)data, size);
llvm::opt::ArgStringList CC1Args;
CC1Args.push_back("-cc1");
CC1Args.push_back("./test.cc");
llvm::IntrusiveRefCntPtr<FileManager> Files(
new FileManager(FileSystemOptions()));
IgnoringDiagConsumer Diags;
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
DiagnosticsEngine Diagnostics(
IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
&Diags, false);
std::unique_ptr<clang::CompilerInvocation> Invocation(
tooling::newInvocation(&Diagnostics, CC1Args));
std::unique_ptr<llvm::MemoryBuffer> Input =
llvm::MemoryBuffer::getMemBuffer(s);
Invocation->getPreprocessorOpts().addRemappedFile("./test.cc", Input.release());
std::unique_ptr<tooling::ToolAction> action(
tooling::newFrontendActionFactory<clang::SyntaxOnlyAction>());
std::shared_ptr<PCHContainerOperations> PCHContainerOps =
std::make_shared<PCHContainerOperations>();
action->runInvocation(Invocation.release(), Files.get(), PCHContainerOps,
&Diags);
return 0;
}
<|endoftext|> |
<commit_before>/*********************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2015 Viktor Richter *
* *
* 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 "hungarian/hungarian.hpp"
#include <map>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <algorithm>
typedef unsigned int uint;
typedef std::string Id;
typedef std::vector<int> Preferences;
typedef std::pair<Id,Preferences> Entity;
std::vector<std::string> split(const std::string& data, char delimiter) {
std::vector<std::string> result;
std::stringstream stream(data);
std::string element;
while(std::getline(stream, element, delimiter)){
result.push_back(element);
}
return result;
}
template<typename T>
T parse(const std::string& data){
std::istringstream istream(data);
T result;
istream >> result;
return result;
}
template<typename T>
std::vector<T> parse_vector(const std::vector<std::string>& data, uint start_at=0){
std::vector<T> result;
for(uint i = start_at; i < data.size(); ++i){
result.push_back(parse<T>(data[i]));
}
return result;
}
Entity parseEntity(const std::string& csv){
std::vector<std::string> vector = split(csv,',');
Entity result;
result.first = parse<std::string>(vector.front());
result.second = parse_vector<int>(vector,1);
return result;
}
int main(int arg_num, char** args) {
// process command line arguments
for(int i = 1; i < arg_num; ++i){
std::string arg = args[i];
if(arg == "--help" || arg == "-h"){
std::cout << "This application uses preferences to sort entities into groups. Input data is read from stdin.\n"\
<< "Usage: assign < preferences.csv\n\n"
<< "Parameters:\n"
<< "\t -h | --help \t\t print this message and leave.\n"
<< "\t -e | --example \t print an example preferences document in the correct format and leave."
<< std::endl;
std::exit(0);
} else if (arg == "--example" || arg == "-e"){
std::cout << "jack,1,5,6,2,3" << std::endl;
std::cout << "jill,6,2,4,6,2" << std::endl;
std::cout << "paul,3,3,5,2,1" << std::endl;
std::cout << "will,2,9,7,4,3" << std::endl;
std::cout << "jenn,5,6,3,7,1" << std::endl;
std::exit(0);
}
}
// process data from sidin into vectors
std::vector<Id> entity_ids;
std::vector<Preferences> entity_preferences;
uint group_count = 0;
uint line = 1;
while(std::cin) {
std::string entity_csv;
std::getline(std::cin, entity_csv);
if(std::cin.eof()) break;
Entity entity = parseEntity(entity_csv);
entity_ids.push_back(entity.first);
entity_preferences.push_back(entity.second);
if(line == 1){
group_count = entity.second.size();
} else {
if(entity.second.size() != group_count){
std::cerr << "Error: Group count in line #" << line << " is defferent from previous. "
<< entity.second.size() << " != " << group_count << "(previous)." << std::endl;
std::exit(-1);
}
}
++line;
}
for(uint i = 0; i < entity_ids.size(); ++i){
std::cout << entity_ids[i] << ":\t";
for (int j = 0; j < entity_preferences[i].size(); ++j){
std::cout << entity_preferences[i][j] << " ";
}
std::cout << std::endl;
}
// create cost matrix
uint group_size = (entity_ids.size() / group_count);
if(entity_ids.size() % group_count) ++group_size;
std::vector<std::vector<int> > matrix;
matrix.resize(entity_ids.size(),std::vector<int>(group_count*group_size,0));
for(uint i = 0; i < entity_ids.size(); ++i){
std::vector<int>& row = matrix[i];
for(uint j = 0; j < group_size; ++j){
std::copy(entity_preferences[i].begin(), entity_preferences[i].end(), row.begin()+(j*group_count));
}
}
/* initialize the hungarian_problem using the cost matrix*/
Hungarian hungarian(matrix, matrix.size(),matrix.front().size(), HUNGARIAN_MODE_MINIMIZE_COST) ;
/* some output */
fprintf(stderr, "cost-matrix:");
hungarian.print_cost();
/* solve the assignement problem */
hungarian.solve();
/* some output */
fprintf(stderr, "assignment:");
hungarian.print_assignment();
return 0;
}
<commit_msg>Refactor assign, Fix matrix transposed<commit_after>/*********************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2015 Viktor Richter *
* *
* 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 "hungarian/hungarian.hpp"
#include <map>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <cassert>
typedef unsigned int uint;
typedef int Cost;
typedef std::vector<std::vector<Cost> > CostMatrix;
typedef std::string Id;
typedef std::vector<int> Preferences;
typedef std::pair<Id,Preferences> Entity;
std::vector<std::string> split(const std::string& data, char delimiter) {
std::vector<std::string> result;
std::stringstream stream(data);
std::string element;
while(std::getline(stream, element, delimiter)){
result.push_back(element);
}
return result;
}
template<typename T>
T parse(const std::string& data){
std::istringstream istream(data);
T result;
istream >> result;
return result;
}
template<typename T>
std::vector<T> parse_vector(const std::vector<std::string>& data, uint start_at=0){
std::vector<T> result;
for(uint i = start_at; i < data.size(); ++i){
result.push_back(parse<T>(data[i]));
}
return result;
}
Entity parseEntity(const std::string& csv){
std::vector<std::string> vector = split(csv,',');
Entity result;
result.first = parse<std::string>(vector.front());
result.second = parse_vector<int>(vector,1);
return result;
}
void process_args(int arg_num, char** args){
for(int i = 1; i < arg_num; ++i){
std::string arg = args[i];
if(arg == "--help" || arg == "-h"){
std::cout << "This application uses preferences to sort entities into groups. Input data is read from stdin.\n"\
<< "Usage: assign < preferences.csv\n\n"
<< "Parameters:\n"
<< "\t -h | --help \t\t print this message and leave.\n"
<< "\t -e | --example \t print an example preferences document in the correct format and leave."
<< std::endl;
std::exit(0);
} else if (arg == "--example" || arg == "-e"){
std::cout << "jack,1,5,6,2,3" << std::endl;
std::cout << "jill,6,2,4,6,2" << std::endl;
std::cout << "paul,3,3,5,2,1" << std::endl;
std::cout << "will,2,9,7,4,3" << std::endl;
std::cout << "jenn,5,6,3,7,1" << std::endl;
std::exit(0);
}
}
}
void parse_csv_data(std::vector<Id>& entity_ids, std::vector<Preferences>& entity_preferences){
uint group_count = 0;
uint line = 1;
while(std::cin) {
std::string entity_csv;
std::getline(std::cin, entity_csv);
if(std::cin.eof()) break;
Entity entity = parseEntity(entity_csv);
entity_ids.push_back(entity.first);
entity_preferences.push_back(entity.second);
if(line == 1){
group_count = entity.second.size();
} else {
if(entity.second.size() != group_count){
std::cerr << "Error: Group count in line #" << line << " is defferent from previous. "
<< entity.second.size() << " != " << group_count << "(previous)." << std::endl;
std::exit(-1);
}
}
++line;
}
}
void print_data(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences, std::ostream& dst){
assert(entity_ids.size() == entity_preferences.size());
for(uint i = 0; i < entity_ids.size(); ++i){
dst << entity_ids[i] << ":\t";
for (int j = 0; j < entity_preferences[i].size(); ++j){
dst << entity_preferences[i][j] << " ";
}
dst << std::endl;
}
}
void fill_cost_matrix(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences,
uint group_count,
CostMatrix& cost_matrix)
{
uint group_size = entity_ids.size() / group_count;
if(entity_ids.size() % group_count) { ++group_size; } // rounding up
uint columns = entity_ids.size(); // true count of entities
uint rows = group_count * group_size;
cost_matrix.clear();
cost_matrix.reserve(columns);
// fill the first rows with preferences
for(uint row = 0; row < group_count; ++row){
cost_matrix.push_back(std::vector<Cost>(columns,0));
for(uint column = 0; column < entity_preferences.size(); ++column){
cost_matrix[row][column] = entity_preferences[column][row]; // transposing
}
}
// fill the other rows by copying the first ones.
for(uint row = group_count; row < rows; ++row){
cost_matrix.push_back(cost_matrix[row % group_count]);
}
}
int main(int arg_num, char** args) {
process_args(arg_num,args);
std::vector<Id> entity_ids;
std::vector<Preferences> entity_preferences;
parse_csv_data(entity_ids, entity_preferences);
print_data(entity_ids,entity_preferences,std::cout);
// create cost matrix
CostMatrix cost_matrix;
uint group_count = entity_preferences.front().size(); // #groups == #group preferences
fill_cost_matrix(entity_ids,entity_preferences,group_count,cost_matrix);
/* initialize the hungarian_problem using the cost matrix*/
Hungarian hungarian(cost_matrix, cost_matrix.size(), cost_matrix.front().size(), HUNGARIAN_MODE_MINIMIZE_COST) ;
/* some output */
fprintf(stderr, "cost-matrix:");
hungarian.print_cost();
/* solve the assignement problem */
hungarian.solve();
/* some output */
fprintf(stderr, "assignment:");
hungarian.print_assignment();
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include <tools/svlibrary.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/xPropertySet.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/string.hxx>
#include <rtl/uri.hxx>
using namespace com::sun::star;
static uno::Sequence< rtl::OUString > GetMultiPaths_Impl()
{
uno::Sequence< rtl::OUString > aRes;
uno::Sequence< rtl::OUString > aInternalPaths;
uno::Sequence< rtl::OUString > aUserPaths;
bool bSuccess = true;
uno::Reference< lang::XMultiServiceFactory > xMgr( comphelper::getProcessServiceFactory() );
if (xMgr.is())
{
try
{
String aInternal;
aInternal.AppendAscii("Libraries");
String aUser;
aUser.AppendAscii("Libraries");
aInternal .AppendAscii( "_internal" );
aUser .AppendAscii( "_user" );
uno::Reference< beans::XPropertySet > xPathSettings( xMgr->createInstance(
rtl::OUString::createFromAscii( "com.sun.star.util.PathSettings" ) ), uno::UNO_QUERY_THROW );
xPathSettings->getPropertyValue( aInternal ) >>= aInternalPaths;
xPathSettings->getPropertyValue( aUser ) >>= aUserPaths;
}
catch (uno::Exception &)
{
bSuccess = false;
}
}
if (bSuccess)
{
sal_Int32 nMaxEntries = aInternalPaths.getLength() + aUserPaths.getLength();
aRes.realloc( nMaxEntries );
rtl::OUString *pRes = aRes.getArray();
sal_Int32 nCount = 0; // number of actually added entries
for (int i = 0; i < 2; ++i)
{
const uno::Sequence< rtl::OUString > &rPathSeq = i == 0 ? aUserPaths : aInternalPaths;
const rtl::OUString *pPathSeq = rPathSeq.getConstArray();
for (sal_Int32 k = 0; k < rPathSeq.getLength(); ++k)
{
const bool bAddUser = (&rPathSeq == &aUserPaths);
const bool bAddInternal = (&rPathSeq == &aInternalPaths);
if ((bAddUser || bAddInternal) && pPathSeq[k].getLength() > 0)
pRes[ nCount++ ] = pPathSeq[k];
}
}
aRes.realloc( nCount );
}
return aRes;
}
bool SvLibrary::LoadModule( osl::Module& rModule, const rtl::OUString& rLibName, ::oslGenericFunction baseModule, ::sal_Int32 mode )
{
static uno::Sequence < rtl::OUString > aPaths = GetMultiPaths_Impl();
bool bLoaded = false;
for (sal_Int32 n=0; n<aPaths.getLength(); n++)
{
rtl::OUString aMod = aPaths[n];
if ( aPaths[n].indexOfAsciiL("vnd.sun.star.expand",19) == 0)
{
uno::Reference< uno::XComponentContext > xComponentContext = comphelper::getProcessComponentContext();
uno::Reference< util::XMacroExpander > xMacroExpander;
xComponentContext->getValueByName(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.util.theMacroExpander") ) )
>>= xMacroExpander;
aMod = aMod.copy( sizeof("vnd.sun.star.expand:") -1 );
aMod = ::rtl::Uri::decode( aMod, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
aMod = xMacroExpander->expandMacros( aMod );
}
aMod += ::rtl::OUString( sal_Unicode('/') );
aMod += rLibName;
bLoaded = rModule.load( aMod, mode );
if ( bLoaded )
break;
}
if (!bLoaded )
bLoaded = rModule.loadRelative( baseModule, rLibName, mode );
return bLoaded;
}
<commit_msg>CWS mba33issues01: typo<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include <tools/svlibrary.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/string.hxx>
#include <rtl/uri.hxx>
using namespace com::sun::star;
static uno::Sequence< rtl::OUString > GetMultiPaths_Impl()
{
uno::Sequence< rtl::OUString > aRes;
uno::Sequence< rtl::OUString > aInternalPaths;
uno::Sequence< rtl::OUString > aUserPaths;
bool bSuccess = true;
uno::Reference< lang::XMultiServiceFactory > xMgr( comphelper::getProcessServiceFactory() );
if (xMgr.is())
{
try
{
String aInternal;
aInternal.AppendAscii("Libraries");
String aUser;
aUser.AppendAscii("Libraries");
aInternal .AppendAscii( "_internal" );
aUser .AppendAscii( "_user" );
uno::Reference< beans::XPropertySet > xPathSettings( xMgr->createInstance(
rtl::OUString::createFromAscii( "com.sun.star.util.PathSettings" ) ), uno::UNO_QUERY_THROW );
xPathSettings->getPropertyValue( aInternal ) >>= aInternalPaths;
xPathSettings->getPropertyValue( aUser ) >>= aUserPaths;
}
catch (uno::Exception &)
{
bSuccess = false;
}
}
if (bSuccess)
{
sal_Int32 nMaxEntries = aInternalPaths.getLength() + aUserPaths.getLength();
aRes.realloc( nMaxEntries );
rtl::OUString *pRes = aRes.getArray();
sal_Int32 nCount = 0; // number of actually added entries
for (int i = 0; i < 2; ++i)
{
const uno::Sequence< rtl::OUString > &rPathSeq = i == 0 ? aUserPaths : aInternalPaths;
const rtl::OUString *pPathSeq = rPathSeq.getConstArray();
for (sal_Int32 k = 0; k < rPathSeq.getLength(); ++k)
{
const bool bAddUser = (&rPathSeq == &aUserPaths);
const bool bAddInternal = (&rPathSeq == &aInternalPaths);
if ((bAddUser || bAddInternal) && pPathSeq[k].getLength() > 0)
pRes[ nCount++ ] = pPathSeq[k];
}
}
aRes.realloc( nCount );
}
return aRes;
}
bool SvLibrary::LoadModule( osl::Module& rModule, const rtl::OUString& rLibName, ::oslGenericFunction baseModule, ::sal_Int32 mode )
{
static uno::Sequence < rtl::OUString > aPaths = GetMultiPaths_Impl();
bool bLoaded = false;
for (sal_Int32 n=0; n<aPaths.getLength(); n++)
{
rtl::OUString aMod = aPaths[n];
if ( aPaths[n].indexOfAsciiL("vnd.sun.star.expand",19) == 0)
{
uno::Reference< uno::XComponentContext > xComponentContext = comphelper::getProcessComponentContext();
uno::Reference< util::XMacroExpander > xMacroExpander;
xComponentContext->getValueByName(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/singletons/com.sun.star.util.theMacroExpander") ) )
>>= xMacroExpander;
aMod = aMod.copy( sizeof("vnd.sun.star.expand:") -1 );
aMod = ::rtl::Uri::decode( aMod, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
aMod = xMacroExpander->expandMacros( aMod );
}
aMod += ::rtl::OUString( sal_Unicode('/') );
aMod += rLibName;
bLoaded = rModule.load( aMod, mode );
if ( bLoaded )
break;
}
if (!bLoaded )
bLoaded = rModule.loadRelative( baseModule, rLibName, mode );
return bLoaded;
}
<|endoftext|> |
<commit_before>//===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/Module.h"
#include "llvm/Config/config.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
using namespace clang;
using namespace clang::driver;
// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// GetMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement GetMainExecutable
// without being given the address of a function in the main executable).
llvm::sys::Path GetExecutablePath(const char *Argv0) {
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *MainAddr = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
}
static int Execute(llvm::Module *Mod, char * const *envp) {
llvm::InitializeNativeTarget();
std::string Error;
llvm::OwningPtr<llvm::ExecutionEngine> EE(
llvm::ExecutionEngine::createJIT(Mod, &Error));
if (!EE) {
llvm::errs() << "unable to make execution engine: " << Error << "\n";
return 255;
}
llvm::Function *EntryFn = Mod->getFunction("main");
if (!EntryFn) {
llvm::errs() << "'main' function not found in module.\n";
return 255;
}
// FIXME: Support passing arguments.
std::vector<std::string> Args;
Args.push_back(Mod->getModuleIdentifier());
return EE->runFunctionAsMain(EntryFn, Args, envp);
}
int main(int argc, const char **argv, char * const *envp) {
void *MainAddr = (void*) (intptr_t) GetExecutablePath;
llvm::sys::Path Path = GetExecutablePath(argv[0]);
TextDiagnosticPrinter *DiagClient =
new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
DiagnosticsEngine Diags(DiagID, DiagClient);
Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
"a.out", /*IsProduction=*/false, Diags);
TheDriver.setTitle("clang interpreter");
// FIXME: This is a hack to try to force the driver to do something we can
// recognize. We need to extend the driver library to support this use model
// (basically, exactly one input, and the operation mode is hard wired).
llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
Args.push_back("-fsyntax-only");
llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args));
if (!C)
return 0;
// FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
// We expect to get back exactly one command job, if we didn't something
// failed. Extract that job from the compilation.
const driver::JobList &Jobs = C->getJobs();
if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
llvm::SmallString<256> Msg;
llvm::raw_svector_ostream OS(Msg);
C->PrintJob(OS, C->getJobs(), "; ", true);
Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
return 1;
}
const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Diags.Report(diag::err_fe_expected_clang_command);
return 1;
}
// Initialize a compiler invocation object from the clang (-cc1) arguments.
const driver::ArgStringList &CCArgs = Cmd->getArguments();
llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
CompilerInvocation::CreateFromArgs(*CI,
const_cast<const char **>(CCArgs.data()),
const_cast<const char **>(CCArgs.data()) +
CCArgs.size(),
Diags);
// Show the invocation, with -v.
if (CI->getHeaderSearchOpts().Verbose) {
llvm::errs() << "clang invocation:\n";
C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
llvm::errs() << "\n";
}
// FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
// Create a compiler instance to handle the actual work.
CompilerInstance Clang;
Clang.setInvocation(CI.take());
// Create the compilers actual diagnostics engine.
Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));
if (!Clang.hasDiagnostics())
return 1;
// Infer the builtin include path if unspecified.
if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
Clang.getHeaderSearchOpts().ResourceDir.empty())
Clang.getHeaderSearchOpts().ResourceDir =
CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
// Create and execute the frontend to generate an LLVM bitcode module.
llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
if (!Clang.ExecuteAction(*Act))
return 1;
int Res = 255;
if (llvm::Module *Module = Act->takeModule())
Res = Execute(Module, envp);
// Shutdown.
llvm::llvm_shutdown();
return Res;
}
<commit_msg>Add missing include to clang-interpreter example, to make it work on Windows. Patch by Dean Pavlekovic.<commit_after>//===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/Tool.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/DiagnosticOptions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "llvm/Module.h"
#include "llvm/Config/config.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
using namespace clang;
using namespace clang::driver;
// This function isn't referenced outside its translation unit, but it
// can't use the "static" keyword because its address is used for
// GetMainExecutable (since some platforms don't support taking the
// address of main, and some platforms can't implement GetMainExecutable
// without being given the address of a function in the main executable).
llvm::sys::Path GetExecutablePath(const char *Argv0) {
// This just needs to be some symbol in the binary; C++ doesn't
// allow taking the address of ::main however.
void *MainAddr = (void*) (intptr_t) GetExecutablePath;
return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
}
static int Execute(llvm::Module *Mod, char * const *envp) {
llvm::InitializeNativeTarget();
std::string Error;
llvm::OwningPtr<llvm::ExecutionEngine> EE(
llvm::ExecutionEngine::createJIT(Mod, &Error));
if (!EE) {
llvm::errs() << "unable to make execution engine: " << Error << "\n";
return 255;
}
llvm::Function *EntryFn = Mod->getFunction("main");
if (!EntryFn) {
llvm::errs() << "'main' function not found in module.\n";
return 255;
}
// FIXME: Support passing arguments.
std::vector<std::string> Args;
Args.push_back(Mod->getModuleIdentifier());
return EE->runFunctionAsMain(EntryFn, Args, envp);
}
int main(int argc, const char **argv, char * const *envp) {
void *MainAddr = (void*) (intptr_t) GetExecutablePath;
llvm::sys::Path Path = GetExecutablePath(argv[0]);
TextDiagnosticPrinter *DiagClient =
new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
DiagnosticsEngine Diags(DiagID, DiagClient);
Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
"a.out", /*IsProduction=*/false, Diags);
TheDriver.setTitle("clang interpreter");
// FIXME: This is a hack to try to force the driver to do something we can
// recognize. We need to extend the driver library to support this use model
// (basically, exactly one input, and the operation mode is hard wired).
llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
Args.push_back("-fsyntax-only");
llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args));
if (!C)
return 0;
// FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
// We expect to get back exactly one command job, if we didn't something
// failed. Extract that job from the compilation.
const driver::JobList &Jobs = C->getJobs();
if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
llvm::SmallString<256> Msg;
llvm::raw_svector_ostream OS(Msg);
C->PrintJob(OS, C->getJobs(), "; ", true);
Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
return 1;
}
const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Diags.Report(diag::err_fe_expected_clang_command);
return 1;
}
// Initialize a compiler invocation object from the clang (-cc1) arguments.
const driver::ArgStringList &CCArgs = Cmd->getArguments();
llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
CompilerInvocation::CreateFromArgs(*CI,
const_cast<const char **>(CCArgs.data()),
const_cast<const char **>(CCArgs.data()) +
CCArgs.size(),
Diags);
// Show the invocation, with -v.
if (CI->getHeaderSearchOpts().Verbose) {
llvm::errs() << "clang invocation:\n";
C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
llvm::errs() << "\n";
}
// FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
// Create a compiler instance to handle the actual work.
CompilerInstance Clang;
Clang.setInvocation(CI.take());
// Create the compilers actual diagnostics engine.
Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));
if (!Clang.hasDiagnostics())
return 1;
// Infer the builtin include path if unspecified.
if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
Clang.getHeaderSearchOpts().ResourceDir.empty())
Clang.getHeaderSearchOpts().ResourceDir =
CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
// Create and execute the frontend to generate an LLVM bitcode module.
llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
if (!Clang.ExecuteAction(*Act))
return 1;
int Res = 255;
if (llvm::Module *Module = Act->takeModule())
Res = Execute(Module, envp);
// Shutdown.
llvm::llvm_shutdown();
return Res;
}
<|endoftext|> |
<commit_before>// basic file operations
#include <iostream>
#include <fstream>
#include <algorithm> // std::max, min
#include <dai/alldai.h> // Include main libDAI header file
#include <CImg.h> // This example needs CImg to be installed
#include <map>
#include <dai/utils/timer.h>
using namespace dai;
using namespace std;
Factor createFactorRecommendation(const Var &n1, const Var &n2, Real alpha) {
VarSet var_set = VarSet(n1, n2);
Factor fac(var_set);
map<Var, size_t> state;
for (size_t i = 0; i < n1.states(); ++i) {
state[n1] = i;
for (size_t j = 0; j < n2.states(); ++j) {
state[n2] = j;
size_t index = calcLinearState(var_set, state);
if (i == j) {
fac.set(index, 0.5 + alpha);
} else {
fac.set(index, 0.5 - alpha);
}
}
}
return fac;
}
FactorGraph example2fg() {
vector<Var> vars;
vector<Factor> factors;
size_t N = 5;
size_t M = 5;
Real alpha = 0.1;
// Reserve memory for the variables
vars.reserve(N + M);
// Create a binary variable for each movie/person
for (size_t i = 0; i < N + M; i++)
vars.push_back(Var(i, 2));
factors.push_back(createFactorRecommendation(vars[0], vars[N], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N + 3], alpha));
Factor fac1(vars[2]);
fac1.set(0, 0.9);
Factor fac2(vars[3]);
fac2.set(0, 0.9);
factors.push_back(fac1);
factors.push_back(fac2);
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph(factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size());
}
double doInference(FactorGraph &fg, string algOpts, size_t maxIter, double tol, vector<double> &m) {
// Construct inference algorithm
cout << "Inference algorithm: " << algOpts << endl;
cout << "Constructing inference algorithm object..." << endl;
InfAlg *ia = newInfAlgFromString(algOpts, fg);
// Initialize inference algorithm
cout << "Initializing inference algorithm..." << endl;
ia->init();
// Initialize vector for storing the recommendations
m = vector<double>(fg.nrVars(), 0.0);
// maxDiff stores the current convergence level
double maxDiff = 1.0;
// Iterate while maximum number of iterations has not been
// reached and requested convergence level has not been reached
cout << "Starting inference algorithm..." << endl;
for (size_t iter = 0; iter < maxIter && maxDiff > tol; iter++) {
// Set recommendations to beliefs
for (size_t i = 0; i < fg.nrVars(); i++)
m[i] = ia->beliefV(i)[0];
// Perform the requested inference algorithm for only one step
ia->setMaxIter(iter + 1);
maxDiff = ia->run();
// Output progress
cout << " Iterations = " << iter << ", maxDiff = " << maxDiff << endl;
}
cout << "Finished inference algorithm" << endl;
// Clean up inference algorithm
delete ia;
// Return reached convergence level
return maxDiff;
}
// vector of users, containing a vector of ratings. Each rating consists of a movie id (first) and the rating (second)
vector<vector<pair<int, int> > > extract_ratings(string file_name) {
ifstream fin;
fin.open(file_name.c_str(), ifstream::in);
vector<vector<pair<int, int> > > ratings;
int num_entries;
fin >> num_entries;
for (int i = 0; i < num_entries; ++i) {
size_t user;
int movie, rating;
long long time;
fin >> user >> movie >> rating >> time;
user--;
//cout << user << " " << movie << " " << rating << endl;
while (user >= ratings.size()) {
ratings.push_back(vector<pair<int, int> >());
}
ratings[user].push_back(make_pair(movie, rating));
}
return ratings;
}
FactorGraph data2fg(const vector<vector<pair<int, int> > > &votings, int user) {
// We will create a variable for every potential user/movie. We know the number of users, let us estimate the number of movies.
int num_users = votings.size();
int num_movies = 0;
for (size_t i = 0; i < votings.size(); ++i) {
if (votings[i].size() > 0) {
num_movies = max(num_movies, votings[i][votings[i].size() - 1].first);
}
}
// We add one to avoid the case where movies start counting at 1, leading to one additional movie.
num_movies++;
Real alpha = 0.0001;
int threshold = 4;
vector<Var> vars;
vector<Factor> factors;
// Reserve memory for the variables
cout << "Estimated num_users/num_movies: " << num_users << "/" << num_movies << endl;
vars.reserve(num_users + num_movies);
// Create a binary variable for each movie/person
for (size_t i = 0; i < (size_t) (num_users + num_movies); i++)
vars.push_back(Var(i, 2));
for (size_t i = 0; i < votings.size(); ++i) {
for (size_t j = 0; j < votings[i].size(); ++j) {
if (votings[i][j].second >= threshold) {
factors.push_back(createFactorRecommendation(vars[i], vars[num_users + votings[i][j].first], alpha));
}
}
}
cout << "Factors created. Dealing with the user now..." << endl;
// calculate some metrics for the user.
int normalization_factor_p = 4;
double sum = 0;
double sq_sum = 0;
for (size_t i = 0; i < votings[user].size(); ++i) {
sum += votings[user][i].second;
}
double mean = sum / votings[user].size();
for (size_t i = 0; i < votings[user].size(); ++i) {
sq_sum += pow(votings[user][i].second - mean, 2);
}
double stdev = std::sqrt(sq_sum / votings[user].size());
for (size_t i = 0; i < votings[user].size(); ++i) {
Factor fac(vars[num_users + votings[user][i].first]);
double like = max(0.1, min(0.9, 0.5 + (votings[user][i].second - mean) / (stdev * normalization_factor_p)));
//cout << votings[user][i].second << " to " << like << endl;
fac.set(0, like);
factors.push_back(fac);
}
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph(factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size());
}
pair<double, double> getPrecisionAndRecall(const vector<vector<pair<int, int> > > &test_data,
const vector<pair<double, int> > &ratings, int user, size_t N) {
// get the top predicted elements.
vector<int> predicted;
for (size_t i = 0; i < std::min(N, ratings.size()); ++i) {
predicted.push_back(ratings[i].second);
}
vector<int> wanted;
for (size_t i = 0; i < test_data[user].size(); ++i) {
if (test_data[user][i].second >= 5) {
wanted.push_back(test_data[user][i].first);
}
}
// compute the intersection.
vector<int> v(N);
sort(predicted.begin(), predicted.end());
sort(wanted.begin(), wanted.end());
vector<int>::iterator it = set_intersection(predicted.begin(), predicted.end(), wanted.begin(), wanted.end(),
v.begin());
v.resize(it - v.begin());
//std::cout << "The intersection has " << (v.size()) << " elements:\n";
if (wanted.size() == 0) {
// dummy element to prevent division by zero.
wanted.push_back(0);
}
return make_pair<double, double>(v.size() / static_cast<double>(N), v.size() / static_cast<double>(wanted.size()));
}
/// Main program
int main(int argc, char **argv) {
cimg_usage("This example shows how libDAI can be used for a simple recommendation task");
const char *infname = cimg_option("-method", "BP[updates=SEQMAX,maxiter=100,tol=1e-15,logdomain=0]",
"Inference method in format name[key1=val1,...,keyn=valn]");
const size_t maxiter = cimg_option("-maxiter", 100, "Maximum number of iterations for inference method");
const double tol = cimg_option("-tol", 1e-15, "Desired tolerance level for inference method");
cout << "reading data now..." << endl;
vector<vector<pair<int, int> > > input_data = extract_ratings("uV2New1.base");
vector<vector<pair<int, int> > > test_data = extract_ratings("uV2New1.test");
const int N = 1;
double p10 = 0;
double p20 = 0;
double r10 = 0;
double r20 = 0;
Timer timer;
timer.tic();
for (int user=0; user<N; ++user) {
cout << "building factor graph for user " << user << " out of " << N << endl;
FactorGraph fg = data2fg(input_data, user);
vector<double> m; // Stores the final recommendations
cout << "Solving the inference problem...please be patient!" << endl;
doInference(fg, infname, maxiter, tol, m);
vector<pair<double, int> > ratings;
for (size_t i = input_data.size(); i < m.size(); ++i) {
// push back the negative so we can use the standard sorting.
ratings.push_back(make_pair<double, int>(-m[i], i - input_data.size() + 1));
}
sort(ratings.begin(), ratings.end());
pair<double, double> pr10 = getPrecisionAndRecall(test_data, ratings, user, 10);
pair<double, double> pr20 = getPrecisionAndRecall(test_data, ratings, user, 20);
p10 += pr10.first;
p20 += pr20.first;
r10 += pr10.second;
r20 += pr20.second;
cout << "Precision (N=10): " << pr10.first << endl;
cout << "Precision (N=20): " << pr20.first << endl;
cout << "Recall (N=10): " << pr10.second << endl;
cout << "Recall (N=20): " << pr20.second << endl;
}
double elapsed_secs = timer.toc();
p10 = p10 / static_cast<double>(N);
p20 = p20 / static_cast<double>(N);
r10 = r20 / static_cast<double>(N);
r20 = r20 / static_cast<double>(N);
cout << "Final estimated:" << endl;
cout << "Precision (N=10): " << p10 << endl;
cout << "Precision (N=20): " << p20 << endl;
cout << "Recall (N=10): " << r10 << endl;
cout << "Recall (N=20): " << r20 << endl;
cout << "Time in seconds: " << elapsed_secs << endl;
return 0;
}
<commit_msg>measure cycles in doInference() AND remove cout messages in inference loop<commit_after>// basic file operations
#include <iostream>
#include <fstream>
#include <algorithm> // std::max, min
#include <dai/alldai.h> // Include main libDAI header file
#include <CImg.h> // This example needs CImg to be installed
#include <map>
#include <dai/utils/timer.h>
using namespace dai;
using namespace std;
Factor createFactorRecommendation(const Var &n1, const Var &n2, Real alpha) {
VarSet var_set = VarSet(n1, n2);
Factor fac(var_set);
map<Var, size_t> state;
for (size_t i = 0; i < n1.states(); ++i) {
state[n1] = i;
for (size_t j = 0; j < n2.states(); ++j) {
state[n2] = j;
size_t index = calcLinearState(var_set, state);
if (i == j) {
fac.set(index, 0.5 + alpha);
} else {
fac.set(index, 0.5 - alpha);
}
}
}
return fac;
}
FactorGraph example2fg() {
vector<Var> vars;
vector<Factor> factors;
size_t N = 5;
size_t M = 5;
Real alpha = 0.1;
// Reserve memory for the variables
vars.reserve(N + M);
// Create a binary variable for each movie/person
for (size_t i = 0; i < N + M; i++)
vars.push_back(Var(i, 2));
factors.push_back(createFactorRecommendation(vars[0], vars[N], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N + 3], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N + 1], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N + 2], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N + 3], alpha));
Factor fac1(vars[2]);
fac1.set(0, 0.9);
Factor fac2(vars[3]);
fac2.set(0, 0.9);
factors.push_back(fac1);
factors.push_back(fac2);
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph(factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size());
}
pair<size_t, double> doInference(FactorGraph &fg, string algOpts, size_t maxIter, double tol, vector<double> &m) {
InfAlg *ia = newInfAlgFromString(algOpts, fg);
// Initialize inference algorithm
//cout << "Initializing inference algorithm..." << endl;
ia->init();
// Initialize vector for storing the recommendations
m = vector<double>(fg.nrVars(), 0.0);
// maxDiff stores the current convergence level
double maxDiff = 1.0;
// Iterate while maximum number of iterations has not been
// reached and requested convergence level has not been reached
//cout << "Starting inference algorithm..." << endl;
size_t iter;
for (iter = 0; iter < maxIter && maxDiff > tol; iter++) {
// Set recommendations to beliefs
for (size_t i = 0; i < fg.nrVars(); i++)
m[i] = ia->beliefV(i)[0];
// Perform the requested inference algorithm for only one step
ia->setMaxIter(iter + 1);
maxDiff = ia->run();
// Output progress
//cout << " Iterations = " << iter << ", maxDiff = " << maxDiff << endl;
}
//cout << "Finished inference algorithm" << endl;
// Clean up inference algorithm
delete ia;
// Return num of iterations and reached convergence level
return make_pair(++iter, maxDiff);
}
// vector of users, containing a vector of ratings. Each rating consists of a movie id (first) and the rating (second)
vector<vector<pair<int, int> > > extract_ratings(string file_name) {
ifstream fin;
fin.open(file_name.c_str(), ifstream::in);
vector<vector<pair<int, int> > > ratings;
int num_entries;
fin >> num_entries;
for (int i = 0; i < num_entries; ++i) {
size_t user;
int movie, rating;
long long time;
fin >> user >> movie >> rating >> time;
user--;
//cout << user << " " << movie << " " << rating << endl;
while (user >= ratings.size()) {
ratings.push_back(vector<pair<int, int> >());
}
ratings[user].push_back(make_pair(movie, rating));
}
return ratings;
}
FactorGraph data2fg(const vector<vector<pair<int, int> > > &votings, int user) {
// We will create a variable for every potential user/movie. We know the number of users, let us estimate the number of movies.
int num_users = votings.size();
int num_movies = 0;
for (size_t i = 0; i < votings.size(); ++i) {
if (votings[i].size() > 0) {
num_movies = max(num_movies, votings[i][votings[i].size() - 1].first);
}
}
// We add one to avoid the case where movies start counting at 1, leading to one additional movie.
num_movies++;
Real alpha = 0.0001;
int threshold = 4;
vector<Var> vars;
vector<Factor> factors;
// Reserve memory for the variables
cout << "Estimated num_users/num_movies: " << num_users << "/" << num_movies << endl;
vars.reserve(num_users + num_movies);
// Create a binary variable for each movie/person
for (size_t i = 0; i < (size_t) (num_users + num_movies); i++)
vars.push_back(Var(i, 2));
for (size_t i = 0; i < votings.size(); ++i) {
for (size_t j = 0; j < votings[i].size(); ++j) {
if (votings[i][j].second >= threshold) {
factors.push_back(createFactorRecommendation(vars[i], vars[num_users + votings[i][j].first], alpha));
}
}
}
cout << "Factors created. Dealing with the user now..." << endl;
// calculate some metrics for the user.
int normalization_factor_p = 4;
double sum = 0;
double sq_sum = 0;
for (size_t i = 0; i < votings[user].size(); ++i) {
sum += votings[user][i].second;
}
double mean = sum / votings[user].size();
for (size_t i = 0; i < votings[user].size(); ++i) {
sq_sum += pow(votings[user][i].second - mean, 2);
}
double stdev = std::sqrt(sq_sum / votings[user].size());
for (size_t i = 0; i < votings[user].size(); ++i) {
Factor fac(vars[num_users + votings[user][i].first]);
double like = max(0.1, min(0.9, 0.5 + (votings[user][i].second - mean) / (stdev * normalization_factor_p)));
//cout << votings[user][i].second << " to " << like << endl;
fac.set(0, like);
factors.push_back(fac);
}
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph(factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size());
}
pair<double, double> getPrecisionAndRecall(const vector<vector<pair<int, int> > > &test_data,
const vector<pair<double, int> > &ratings, int user, size_t N) {
// get the top predicted elements.
vector<int> predicted;
for (size_t i = 0; i < std::min(N, ratings.size()); ++i) {
predicted.push_back(ratings[i].second);
}
vector<int> wanted;
for (size_t i = 0; i < test_data[user].size(); ++i) {
if (test_data[user][i].second >= 5) {
wanted.push_back(test_data[user][i].first);
}
}
// compute the intersection.
vector<int> v(N);
sort(predicted.begin(), predicted.end());
sort(wanted.begin(), wanted.end());
vector<int>::iterator it = set_intersection(predicted.begin(), predicted.end(), wanted.begin(), wanted.end(),
v.begin());
v.resize(it - v.begin());
//std::cout << "The intersection has " << (v.size()) << " elements:\n";
if (wanted.size() == 0) {
// dummy element to prevent division by zero.
wanted.push_back(0);
}
return make_pair<double, double>(v.size() / static_cast<double>(N), v.size() / static_cast<double>(wanted.size()));
}
/// Main program
int main(int argc, char **argv) {
cimg_usage("This example shows how libDAI can be used for a simple recommendation task");
const char *infname = cimg_option("-method", "BP[updates=SEQMAX,maxiter=100,tol=1e-15,logdomain=0]",
"Inference method in format name[key1=val1,...,keyn=valn]");
const size_t maxiter = cimg_option("-maxiter", 100, "Maximum number of iterations for inference method");
const double tol = cimg_option("-tol", 1e-15, "Desired tolerance level for inference method");
cout << "reading data now..." << endl;
vector<vector<pair<int, int> > > input_data = extract_ratings("uV2New1.base");
vector<vector<pair<int, int> > > test_data = extract_ratings("uV2New1.test");
const int N = 1;
double p10 = 0;
double p20 = 0;
double r10 = 0;
double r20 = 0;
long measured_cycles = 0;
Timer timer;
for (int user=0; user<N; ++user) {
cout << "building factor graph for user " << user << " out of " << N << endl;
FactorGraph fg = data2fg(input_data, user);
vector<double> m; // Stores the final recommendations
cout << "Inference algorithm: " << infname << endl;
cout << "Solving the inference problem...please be patient!" << endl;
cout << "Note: There's no output during the inference. You may have to wait a bit..." << endl;
timer.tic();
pair<size_t, double> result = doInference(fg, infname, maxiter, tol, m);
measured_cycles += timer.toc();
cout << "Iterations = " << result.first << ", maxDiff = " << result.second << endl;
vector<pair<double, int> > ratings;
for (size_t i = input_data.size(); i < m.size(); ++i) {
// push back the negative so we can use the standard sorting.
ratings.push_back(make_pair<double, int>(-m[i], i - input_data.size() + 1));
}
sort(ratings.begin(), ratings.end());
pair<double, double> pr10 = getPrecisionAndRecall(test_data, ratings, user, 10);
pair<double, double> pr20 = getPrecisionAndRecall(test_data, ratings, user, 20);
p10 += pr10.first;
p20 += pr20.first;
r10 += pr10.second;
r20 += pr20.second;
cout << "Precision (N=10): " << pr10.first << endl;
cout << "Precision (N=20): " << pr20.first << endl;
cout << "Recall (N=10): " << pr10.second << endl;
cout << "Recall (N=20): " << pr20.second << endl;
}
timer.toc();
p10 = p10 / static_cast<double>(N);
p20 = p20 / static_cast<double>(N);
r10 = r20 / static_cast<double>(N);
r20 = r20 / static_cast<double>(N);
cout << "Final estimated:" << endl;
cout << "Precision (N=10): " << p10 << endl;
cout << "Precision (N=20): " << p20 << endl;
cout << "Recall (N=10): " << r10 << endl;
cout << "Recall (N=20): " << r20 << endl;
cout << "Measured cycles: " << measured_cycles << endl;
return 0;
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// <h1>Introduction Example 2 - Defining a Simple System</h1>
// \author Benjamin S. Kirk
// \date 2003
//
// This is the second example program. It demonstrates how to
// create an equation system for a simple scalar system. This
// example will also introduce some of the issues involved with using PETSc
// in your application.
//
// This is the first example program that indirectly
// uses the PETSc library. By default equation data is stored
// in PETSc vectors, which may span multiple processors. Before
// PETSc is used it must be initialized via libMesh::init(). Note that
// by passing argc and argv to PETSc you may specify
// command line arguments to PETSc. For example, you might
// try running this example as:
//
// ./introduction_ex2 -log_info
//
// to see what PETSc is doing behind the scenes or
//
// ./introduction_ex2 -log_summary
//
// to get a summary of what PETSc did.
// Among other things, libMesh::init() initializes the MPI
// communications library and PETSc numeric library on your system if
// you haven't already done so.
// C++ include files that we need
#include <iostream>
//Basic include file needed for the mesh functionality.
#include "libmesh/libmesh.h"
#include "libmesh/mesh.h"
#include "libmesh/enum_xdr_mode.h"
// Include file that defines various mesh generation utilities
#include "libmesh/mesh_generation.h"
// Include file that defines (possibly multiple) systems of equations.
#include "libmesh/equation_systems.h"
// Include files that define a simple steady system
#include "libmesh/linear_implicit_system.h"
#include "libmesh/transient_system.h"
#include "libmesh/explicit_system.h"
#include "libmesh/enum_solver_package.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
int main (int argc, char ** argv)
{
LibMeshInit init (argc, argv);
// Skip this 2D example if libMesh was compiled as 1D-only.
libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
// This example requires a linear solver package.
libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
"--enable-petsc, --enable-trilinos, or --enable-eigen");
// A brief message to the user to inform her of the
// exact name of the program being run, and its command line.
libMesh::out << "Running " << argv[0];
for (int i=1; i<argc; i++)
libMesh::out << " " << argv[i];
libMesh::out << std::endl << std::endl;
// Create a mesh, with dimension to be overridden later, distributed
// across the default MPI communicator.
Mesh mesh(init.comm());
// Use the MeshTools::Generation mesh generator to create a uniform
// 2D grid on the unit square. By default a mesh of QUAD4
// elements will be created. We instruct the mesh generator
// to build a mesh of 5x5 elements.
MeshTools::Generation::build_square (mesh, 5, 5);
// Create an equation systems object. This object can
// contain multiple systems of different
// flavors for solving loosely coupled physics. Each system can
// contain multiple variables of different approximation orders.
// Here we will simply create a single system with one variable.
// Later on, other flavors of systems will be introduced. For the
// moment, we use the general system.
// The EquationSystems object needs a reference to the mesh
// object, so the order of construction here is important.
EquationSystems equation_systems (mesh);
// Add a flag "test" that is visible for all systems. This
// helps in inter-system communication.
equation_systems.parameters.set<bool> ("test") = true;
// Set a simulation-specific parameter visible for all systems.
// This helps in inter-system-communication.
equation_systems.parameters.set<Real> ("dummy") = 42.;
// Set another simulation-specific parameter
equation_systems.parameters.set<Real> ("nobody") = 0.;
// Now we declare the system and its variables.
// We begin by adding a "TransientLinearImplicitSystem" to the
// EquationSystems object, and we give it the name
// "Simple System".
equation_systems.add_system<TransientLinearImplicitSystem> ("Simple System");
// Adds the variable "u" to "Simple System". "u"
// will be approximated using first-order approximation.
equation_systems.get_system("Simple System").add_variable("u", FIRST);
// Next we'll by add an "ExplicitSystem" to the
// EquationSystems object, and we give it the name
// "Complex System".
equation_systems.add_system<ExplicitSystem> ("Complex System");
// Give "Complex System" three variables -- each with a different approximation
// order. Variables "c" and "T" will use first-order Lagrange approximation,
// while variable "dv" will use a second-order discontinuous
// approximation space.
equation_systems.get_system("Complex System").add_variable("c", FIRST);
equation_systems.get_system("Complex System").add_variable("T", FIRST);
equation_systems.get_system("Complex System").add_variable("dv", SECOND, MONOMIAL);
// Initialize the data structures for the equation system.
equation_systems.init();
// Print information about the mesh to the screen.
mesh.print_info();
// Prints information about the system to the screen.
equation_systems.print_info();
// Write the equation system if the user specified an
// output file name. Note that there are two possible
// formats to write to. Specifying WRITE will
// create a formatted ASCII file. Optionally, you can specify
// ENCODE and get an XDR-encoded binary file.
//
// We will write the data, clear the object, and read the file
// we just wrote. This is simply to demonstrate capability.
// Note that you might use this in an application to periodically
// dump the state of your simulation. You can then restart from
// this data later.
if (argc > 1)
if (argv[1][0] != '-')
{
libMesh::out << "<<< Writing system to file " << argv[1]
<< std::endl;
// Write the system.
equation_systems.write (argv[1], WRITE);
// Clear the equation systems data structure.
equation_systems.clear ();
libMesh::out << ">>> Reading system from file " << argv[1]
<< std::endl << std::endl;
// Read the file we just wrote. This better
// work!
equation_systems.read (argv[1], READ);
// Print the information again.
equation_systems.print_info();
}
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
<commit_msg>Recommend non-deprecated options in example.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// <h1>Introduction Example 2 - Defining a Simple System</h1>
// \author Benjamin S. Kirk
// \date 2003
//
// This is the second example program. It demonstrates how to
// create an equation system for a simple scalar system. This
// example will also introduce some of the issues involved with using PETSc
// in your application.
//
// This is the first example program that indirectly
// uses the PETSc library. By default equation data is stored
// in PETSc vectors, which may span multiple processors. Before
// PETSc is used it must be initialized via libMesh::init(). Note that
// by passing argc and argv to PETSc you may specify
// command line arguments to PETSc. For example, you might
// try running this example as:
// ./introduction_ex2 -info
//
// to see what PETSc is doing behind the scenes or
//
// ./introduction_ex2 -log_view
//
// to get a summary of what PETSc did.
// Among other things, libMesh::init() initializes the MPI
// communications library and PETSc numeric library on your system if
// you haven't already done so.
// C++ include files that we need
#include <iostream>
//Basic include file needed for the mesh functionality.
#include "libmesh/libmesh.h"
#include "libmesh/mesh.h"
#include "libmesh/enum_xdr_mode.h"
// Include file that defines various mesh generation utilities
#include "libmesh/mesh_generation.h"
// Include file that defines (possibly multiple) systems of equations.
#include "libmesh/equation_systems.h"
// Include files that define a simple steady system
#include "libmesh/linear_implicit_system.h"
#include "libmesh/transient_system.h"
#include "libmesh/explicit_system.h"
#include "libmesh/enum_solver_package.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
int main (int argc, char ** argv)
{
LibMeshInit init (argc, argv);
// Skip this 2D example if libMesh was compiled as 1D-only.
libmesh_example_requires(2 <= LIBMESH_DIM, "2D support");
// This example requires a linear solver package.
libmesh_example_requires(libMesh::default_solver_package() != INVALID_SOLVER_PACKAGE,
"--enable-petsc, --enable-trilinos, or --enable-eigen");
// A brief message to the user to inform her of the
// exact name of the program being run, and its command line.
libMesh::out << "Running " << argv[0];
for (int i=1; i<argc; i++)
libMesh::out << " " << argv[i];
libMesh::out << std::endl << std::endl;
// Create a mesh, with dimension to be overridden later, distributed
// across the default MPI communicator.
Mesh mesh(init.comm());
// Use the MeshTools::Generation mesh generator to create a uniform
// 2D grid on the unit square. By default a mesh of QUAD4
// elements will be created. We instruct the mesh generator
// to build a mesh of 5x5 elements.
MeshTools::Generation::build_square (mesh, 5, 5);
// Create an equation systems object. This object can
// contain multiple systems of different
// flavors for solving loosely coupled physics. Each system can
// contain multiple variables of different approximation orders.
// Here we will simply create a single system with one variable.
// Later on, other flavors of systems will be introduced. For the
// moment, we use the general system.
// The EquationSystems object needs a reference to the mesh
// object, so the order of construction here is important.
EquationSystems equation_systems (mesh);
// Add a flag "test" that is visible for all systems. This
// helps in inter-system communication.
equation_systems.parameters.set<bool> ("test") = true;
// Set a simulation-specific parameter visible for all systems.
// This helps in inter-system-communication.
equation_systems.parameters.set<Real> ("dummy") = 42.;
// Set another simulation-specific parameter
equation_systems.parameters.set<Real> ("nobody") = 0.;
// Now we declare the system and its variables.
// We begin by adding a "TransientLinearImplicitSystem" to the
// EquationSystems object, and we give it the name
// "Simple System".
equation_systems.add_system<TransientLinearImplicitSystem> ("Simple System");
// Adds the variable "u" to "Simple System". "u"
// will be approximated using first-order approximation.
equation_systems.get_system("Simple System").add_variable("u", FIRST);
// Next we'll by add an "ExplicitSystem" to the
// EquationSystems object, and we give it the name
// "Complex System".
equation_systems.add_system<ExplicitSystem> ("Complex System");
// Give "Complex System" three variables -- each with a different approximation
// order. Variables "c" and "T" will use first-order Lagrange approximation,
// while variable "dv" will use a second-order discontinuous
// approximation space.
equation_systems.get_system("Complex System").add_variable("c", FIRST);
equation_systems.get_system("Complex System").add_variable("T", FIRST);
equation_systems.get_system("Complex System").add_variable("dv", SECOND, MONOMIAL);
// Initialize the data structures for the equation system.
equation_systems.init();
// Print information about the mesh to the screen.
mesh.print_info();
// Prints information about the system to the screen.
equation_systems.print_info();
// Write the equation system if the user specified an
// output file name. Note that there are two possible
// formats to write to. Specifying WRITE will
// create a formatted ASCII file. Optionally, you can specify
// ENCODE and get an XDR-encoded binary file.
//
// We will write the data, clear the object, and read the file
// we just wrote. This is simply to demonstrate capability.
// Note that you might use this in an application to periodically
// dump the state of your simulation. You can then restart from
// this data later.
if (argc > 1)
if (argv[1][0] != '-')
{
libMesh::out << "<<< Writing system to file " << argv[1]
<< std::endl;
// Write the system.
equation_systems.write (argv[1], WRITE);
// Clear the equation systems data structure.
equation_systems.clear ();
libMesh::out << ">>> Reading system from file " << argv[1]
<< std::endl << std::endl;
// Read the file we just wrote. This better
// work!
equation_systems.read (argv[1], READ);
// Print the information again.
equation_systems.print_info();
}
// All done. libMesh objects are destroyed here. Because the
// LibMeshInit object was created first, its destruction occurs
// last, and it's destructor finalizes any external libraries and
// checks for leaked memory.
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright © 2012-2013 Institut für Nachrichtentechnik, Universität Rostock *
* Copyright © 2006-2012 Quality & Usability Lab, *
* Telekom Innovation Laboratories, TU Berlin *
* *
* This file is part of the Audio Processing Framework (APF). *
* *
* The APF is free software: you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free *
* Software Foundation, either version 3 of the License, or (at your option) *
* any later version. *
* *
* The APF is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS *
* FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* http://AudioProcessingFramework.github.com *
******************************************************************************/
// Tests for math functions.
#include "apf/math.h"
#include "catch/catch.hpp"
using namespace apf::math;
TEST_CASE("math", "Test all functions of math namespace")
{
SECTION("pi", "")
{
CHECK(pi<float>() == 4.0f * std::atan(1.0f));
CHECK(pi<double>() == 4.0 * std::atan(1.0));
CHECK(pi<long double>() == 4.0l * std::atan(1.0l));
// pi divided by 180
CHECK((pi_div_180<float>() * 180.0f / pi<float>()) == 1.0f);
CHECK((pi_div_180<double>() * 180.0 / pi<double>()) == 1.0);
CHECK((pi_div_180<long double>() * 180.0l / pi<long double>()) == 1.0l);
}
SECTION("square", "a*a")
{
CHECK(square(2.0f) == 4.0f);
CHECK(square(2.0) == 4.0f);
CHECK(square(2.0l) == 4.0l);
}
SECTION("dB2linear", "")
{
CHECK(dB2linear(6.0f) == Approx(1.99526231));
CHECK(dB2linear(6.0) == Approx(1.99526231));
// Approx doesn't exist for long double
CHECK(static_cast<double>(dB2linear(6.0l)) == Approx(1.99526231));
// now with the "power" option
CHECK(dB2linear(3.0f, true) == Approx(1.99526231));
CHECK(dB2linear(3.0, true) == Approx(1.99526231));
CHECK(static_cast<double>(dB2linear(3.0l, true)) == Approx(1.99526231));
}
SECTION("linear2dB", "")
{
CHECK(linear2dB(1.99526231f) == Approx(6.0));
CHECK(linear2dB(1.99526231) == Approx(6.0));
CHECK(static_cast<double>(linear2dB(1.99526231l)) == Approx(6.0));
CHECK(linear2dB(1.99526231f, true) == Approx(3.0));
CHECK(linear2dB(1.99526231, true) == Approx(3.0));
CHECK(static_cast<double>(linear2dB(1.99526231l, true)) == Approx(3.0));
CHECK(linear2dB(0.0f) == -std::numeric_limits<float>::infinity());
CHECK(linear2dB(0.0) == -std::numeric_limits<double>::infinity());
CHECK(linear2dB(0.0l) == -std::numeric_limits<long double>::infinity());
// TODO: how to check NaN results?
// linear2dB(-0.1f)
// linear2dB(-0.1)
// linear2dB(-0.1l)
}
SECTION("deg2rad", "")
{
CHECK(deg2rad(180.0f) == pi<float>());
CHECK(deg2rad(180.0) == pi<double>());
CHECK(deg2rad(180.0l) == pi<long double>());
}
SECTION("rad2deg", "")
{
CHECK(rad2deg(pi<float>()) == 180.0f);
CHECK(rad2deg(pi<double>()) == 180.0);
CHECK(rad2deg(pi<long double>()) == 180.0l);
}
SECTION("next_power_of_2", "")
{
CHECK(next_power_of_2(-3) == 1);
CHECK(next_power_of_2(-2) == 1);
CHECK(next_power_of_2(-1) == 1);
CHECK(next_power_of_2(0) == 1);
CHECK(next_power_of_2(1) == 1);
CHECK(next_power_of_2(2) == 2);
CHECK(next_power_of_2(3) == 4);
CHECK(next_power_of_2(1.0f) == 1.0f);
CHECK(next_power_of_2(2.0f) == 2.0f);
CHECK(next_power_of_2(3.0f) == 4.0f);
CHECK(next_power_of_2(1.0) == 1.0);
CHECK(next_power_of_2(2.0) == 2.0);
CHECK(next_power_of_2(2.5) == 4.0);
CHECK(next_power_of_2(3.0) == 4.0);
CHECK(next_power_of_2(1.0l) == 1.0l);
CHECK(next_power_of_2(2.0l) == 2.0l);
CHECK(next_power_of_2(3.0l) == 4.0l);
}
SECTION("max_amplitude", "")
{
std::vector<double> sig(5);
CHECK(max_amplitude(sig.begin(), sig.end()) == 0.0);
sig[2] = -2.0;
CHECK(max_amplitude(sig.begin(), sig.end()) == 2.0);
sig[3] = 4.0;
CHECK(max_amplitude(sig.begin(), sig.end()) == 4.0);
}
SECTION("rms", "")
{
std::vector<double> sig(5);
CHECK(rms(sig.begin(), sig.end()) == 0.0);
sig[0] = -1.0;
sig[1] = -1.0;
sig[2] = -1.0;
sig[3] = 1.0;
sig[4] = 1.0;
CHECK(rms(sig.begin(), sig.end()) == 1.0);
}
SECTION("raised_cosine", "")
{
raised_cosine<float> rc1(1.5f);
CHECK(rc1(0.75f) == 0.0f);
CHECK(rc1(1.5f) == 1.0f);
raised_cosine<double> rc2(1.5);
CHECK(rc2(0.75) == 0.0);
CHECK(rc2(1.5) == 1.0);
raised_cosine<double> rc3(360);
CHECK(rc3(60) == 0.75);
}
SECTION("linear_interpolator", "")
{
linear_interpolator<double> in(1.5, 3.0, 3.0);
CHECK(in(0.0) == 1.5);
CHECK(in(1.0) == 2.0);
CHECK(in(2.0) == 2.5);
// using default length 1:
in = make_linear_interpolator(5.0, 6.0);
CHECK(in(0.0) == 5.0);
CHECK(in(0.5) == 5.5);
CHECK(in(1.0) == 6.0);
}
SECTION("linear_interpolator, integer index", "")
{
linear_interpolator<double, int> in(5.0, 6.0, 2);
CHECK(in(0) == 5.0);
CHECK(in(1) == 5.5);
}
SECTION("linear_interpolator, integer index converted to double", "")
{
linear_interpolator<double> in(1.0, 2.0, 4);
CHECK(in(0) == 1.0);
CHECK(in(1) == 1.25);
}
SECTION("identity", "")
{
identity<float> id;
CHECK(id(0.5f) == 0.5f);
}
} // TEST_CASE
// Settings for Vim (http://www.vim.org/), please do not remove:
// vim:softtabstop=2:shiftwidth=2:expandtab:textwidth=80:cindent
<commit_msg>Unit tests for math::wrap()<commit_after>/******************************************************************************
* Copyright © 2012-2013 Institut für Nachrichtentechnik, Universität Rostock *
* Copyright © 2006-2012 Quality & Usability Lab, *
* Telekom Innovation Laboratories, TU Berlin *
* *
* This file is part of the Audio Processing Framework (APF). *
* *
* The APF is free software: you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free *
* Software Foundation, either version 3 of the License, or (at your option) *
* any later version. *
* *
* The APF is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS *
* FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* http://AudioProcessingFramework.github.com *
******************************************************************************/
// Tests for math functions.
#include "apf/math.h"
#include "catch/catch.hpp"
using namespace apf::math;
TEST_CASE("math", "Test all functions of math namespace")
{
SECTION("pi", "")
{
CHECK(pi<float>() == 4.0f * std::atan(1.0f));
CHECK(pi<double>() == 4.0 * std::atan(1.0));
CHECK(pi<long double>() == 4.0l * std::atan(1.0l));
// pi divided by 180
CHECK((pi_div_180<float>() * 180.0f / pi<float>()) == 1.0f);
CHECK((pi_div_180<double>() * 180.0 / pi<double>()) == 1.0);
CHECK((pi_div_180<long double>() * 180.0l / pi<long double>()) == 1.0l);
}
SECTION("square", "a*a")
{
CHECK(square(2.0f) == 4.0f);
CHECK(square(2.0) == 4.0f);
CHECK(square(2.0l) == 4.0l);
}
SECTION("dB2linear", "")
{
CHECK(dB2linear(6.0f) == Approx(1.99526231));
CHECK(dB2linear(6.0) == Approx(1.99526231));
// Approx doesn't exist for long double
CHECK(static_cast<double>(dB2linear(6.0l)) == Approx(1.99526231));
// now with the "power" option
CHECK(dB2linear(3.0f, true) == Approx(1.99526231));
CHECK(dB2linear(3.0, true) == Approx(1.99526231));
CHECK(static_cast<double>(dB2linear(3.0l, true)) == Approx(1.99526231));
}
SECTION("linear2dB", "")
{
CHECK(linear2dB(1.99526231f) == Approx(6.0));
CHECK(linear2dB(1.99526231) == Approx(6.0));
CHECK(static_cast<double>(linear2dB(1.99526231l)) == Approx(6.0));
CHECK(linear2dB(1.99526231f, true) == Approx(3.0));
CHECK(linear2dB(1.99526231, true) == Approx(3.0));
CHECK(static_cast<double>(linear2dB(1.99526231l, true)) == Approx(3.0));
CHECK(linear2dB(0.0f) == -std::numeric_limits<float>::infinity());
CHECK(linear2dB(0.0) == -std::numeric_limits<double>::infinity());
CHECK(linear2dB(0.0l) == -std::numeric_limits<long double>::infinity());
// TODO: how to check NaN results?
// linear2dB(-0.1f)
// linear2dB(-0.1)
// linear2dB(-0.1l)
}
SECTION("deg2rad", "")
{
CHECK(deg2rad(180.0f) == pi<float>());
CHECK(deg2rad(180.0) == pi<double>());
CHECK(deg2rad(180.0l) == pi<long double>());
}
SECTION("rad2deg", "")
{
CHECK(rad2deg(pi<float>()) == 180.0f);
CHECK(rad2deg(pi<double>()) == 180.0);
CHECK(rad2deg(pi<long double>()) == 180.0l);
}
SECTION("wrap int", "")
{
CHECK(wrap(-1, 7) == 6);
CHECK(wrap(0, 7) == 0);
CHECK(wrap(6, 7) == 6);
CHECK(wrap(7, 7) == 0);
CHECK(wrap(8, 7) == 1);
}
SECTION("wrap double", "")
{
CHECK(wrap(-0.5, 360.0) == 359.5);
CHECK(wrap(0.0, 360.0) == 0.0);
CHECK(wrap(359.5, 360.0) == 359.5);
CHECK(wrap(360.0, 360.0) == 0.0);
CHECK(wrap(360.5, 360.0) == 0.5);
}
SECTION("next_power_of_2", "")
{
CHECK(next_power_of_2(-3) == 1);
CHECK(next_power_of_2(-2) == 1);
CHECK(next_power_of_2(-1) == 1);
CHECK(next_power_of_2(0) == 1);
CHECK(next_power_of_2(1) == 1);
CHECK(next_power_of_2(2) == 2);
CHECK(next_power_of_2(3) == 4);
CHECK(next_power_of_2(1.0f) == 1.0f);
CHECK(next_power_of_2(2.0f) == 2.0f);
CHECK(next_power_of_2(3.0f) == 4.0f);
CHECK(next_power_of_2(1.0) == 1.0);
CHECK(next_power_of_2(2.0) == 2.0);
CHECK(next_power_of_2(2.5) == 4.0);
CHECK(next_power_of_2(3.0) == 4.0);
CHECK(next_power_of_2(1.0l) == 1.0l);
CHECK(next_power_of_2(2.0l) == 2.0l);
CHECK(next_power_of_2(3.0l) == 4.0l);
}
SECTION("max_amplitude", "")
{
std::vector<double> sig(5);
CHECK(max_amplitude(sig.begin(), sig.end()) == 0.0);
sig[2] = -2.0;
CHECK(max_amplitude(sig.begin(), sig.end()) == 2.0);
sig[3] = 4.0;
CHECK(max_amplitude(sig.begin(), sig.end()) == 4.0);
}
SECTION("rms", "")
{
std::vector<double> sig(5);
CHECK(rms(sig.begin(), sig.end()) == 0.0);
sig[0] = -1.0;
sig[1] = -1.0;
sig[2] = -1.0;
sig[3] = 1.0;
sig[4] = 1.0;
CHECK(rms(sig.begin(), sig.end()) == 1.0);
}
SECTION("raised_cosine", "")
{
raised_cosine<float> rc1(1.5f);
CHECK(rc1(0.75f) == 0.0f);
CHECK(rc1(1.5f) == 1.0f);
raised_cosine<double> rc2(1.5);
CHECK(rc2(0.75) == 0.0);
CHECK(rc2(1.5) == 1.0);
raised_cosine<double> rc3(360);
CHECK(rc3(60) == 0.75);
}
SECTION("linear_interpolator", "")
{
linear_interpolator<double> in(1.5, 3.0, 3.0);
CHECK(in(0.0) == 1.5);
CHECK(in(1.0) == 2.0);
CHECK(in(2.0) == 2.5);
// using default length 1:
in = make_linear_interpolator(5.0, 6.0);
CHECK(in(0.0) == 5.0);
CHECK(in(0.5) == 5.5);
CHECK(in(1.0) == 6.0);
}
SECTION("linear_interpolator, integer index", "")
{
linear_interpolator<double, int> in(5.0, 6.0, 2);
CHECK(in(0) == 5.0);
CHECK(in(1) == 5.5);
}
SECTION("linear_interpolator, integer index converted to double", "")
{
linear_interpolator<double> in(1.0, 2.0, 4);
CHECK(in(0) == 1.0);
CHECK(in(1) == 1.25);
}
SECTION("identity", "")
{
identity<float> id;
CHECK(id(0.5f) == 0.5f);
}
} // TEST_CASE
// Settings for Vim (http://www.vim.org/), please do not remove:
// vim:softtabstop=2:shiftwidth=2:expandtab:textwidth=80:cindent
<|endoftext|> |
<commit_before>/*
* galleryenlargeshrinkplugin.cpp
*
* Copyright (C) 2012 Igalia, S.L.
* Author: Antia Puentes <[email protected]>
*
* This file is part of the Gallery Enlarge/Shrink Plugin.
*
* 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; 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, see http://www.gnu.org/licenses/ *
*/
#include "galleryenlargeshrinkplugin.h"
#include "galleryenlargeshrinkplugin_p.h"
#include "galleryenlargeshrinkwidget.h"
#include <galleryedituiprovider.h>
#include <MLibrary>
#include <MApplication>
#include <MBanner>
#include <MMessageBox>
#include <MLabel>
#include <QGraphicsSceneMouseEvent>
#include <QDesktopServices>
#include <QUrl>
#include <QTextOption>
#include <QuillImageFilter>
static const float EFFECT_FORCE = 1.0;
static const int TAP_DISTANCE = 20;
static const int PORTRAIT_HEIGHT = 224;
static const int LANDSCAPE_HEIGHT = 112;
static const int INFOBANNER_TIMEOUT = 2 * 1000;
static const int IMAGE_MAX_HEIGHT = 512;
static const int IMAGE_MAX_WIDTH = 512;
M_LIBRARY
GalleryEnlargeShrinkPluginPrivate::GalleryEnlargeShrinkPluginPrivate() :
m_focusPosition(),
m_validImage(true)
{
}
GalleryEnlargeShrinkPluginPrivate::~GalleryEnlargeShrinkPluginPrivate()
{
}
GalleryEnlargeShrinkPlugin::GalleryEnlargeShrinkPlugin(QObject* parent) :
GalleryEditPlugin(parent),
d_ptr(new GalleryEnlargeShrinkPluginPrivate())
{
}
GalleryEnlargeShrinkPlugin::~GalleryEnlargeShrinkPlugin()
{
delete d_ptr;
}
QString GalleryEnlargeShrinkPlugin::name() const
{
return QString("Enlarge - Shrink");
}
QString GalleryEnlargeShrinkPlugin::iconID() const
{
return QString("icon-m-image-edit-enlarge-shrink");
}
bool GalleryEnlargeShrinkPlugin::containsUi() const
{
return true;
}
bool GalleryEnlargeShrinkPlugin::zoomingAllowed() const
{
return true;
}
QGraphicsWidget* GalleryEnlargeShrinkPlugin::createToolBarWidget(QGraphicsItem* parent)
{
GalleryEnlargeShrinkWidget* widget = new GalleryEnlargeShrinkWidget(parent);
connect(widget, SIGNAL(aboutLinkActivated(QString)),
this, SLOT(onAboutLinkActivated(QString)));
return widget;
}
const QSize GalleryEnlargeShrinkPlugin::toolBarWidgetSize(const M::Orientation& orientation) const
{
QSize size = GalleryEditPlugin::toolBarWidgetSize(orientation);
if (M::Portrait == orientation) {
size.setHeight(PORTRAIT_HEIGHT);
} else {
size.setHeight(LANDSCAPE_HEIGHT);
}
return size;
}
bool GalleryEnlargeShrinkPlugin::receiveMouseEvent(QGraphicsSceneMouseEvent *event)
{
if (event &&
event->type() == QEvent::GraphicsSceneMouseRelease &&
event->button() == Qt::LeftButton &&
(event->scenePos() - event->buttonDownScenePos(Qt::LeftButton)).manhattanLength() < TAP_DISTANCE) {
Q_D(GalleryEnlargeShrinkPlugin);
if (d->m_validImage) {
d->m_focusPosition = event->pos().toPoint();
performEditOperation();
return true;
} else {
showInfoBanner("Plugin disabled for this image size");
}
}
return false;
}
void GalleryEnlargeShrinkPlugin::activate()
{
if (editUiProvider()) {
Q_D(GalleryEnlargeShrinkPlugin);
d->m_validImage = editUiProvider()->fullImageSize().height() <= IMAGE_MAX_HEIGHT &&
editUiProvider()->fullImageSize().width() <= IMAGE_MAX_WIDTH;
if (d->m_validImage) {
showInfoBanner("Tap on an area to keep it focused");
} else {
showMessageBox("Enlarge Shrink plugin limitations",
"Gallery Enlarge Shrink plugin is currently limited to "
"small images (512x512)<br />"
"For a given image:"
"<ol>"
"<li>Scale it or crop it</li>"
"<li>Save it with a different name</li>"
"<li>Apply the filter to the new one</li>"
"</ol>");
GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget());
widget->enableInput(d->m_validImage);
}
}
}
void GalleryEnlargeShrinkPlugin::performEditOperation()
{
if (editUiProvider()) {
Q_D(GalleryEnlargeShrinkPlugin);
QHash<QuillImageFilter::QuillFilterOption, QVariant> optionHash;
const QPoint imagePosition = editUiProvider()->convertScreenCoordToImageCoord(d->m_focusPosition);
if (imagePosition != QPoint(-1, -1)) {
GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget());
optionHash.insert(QuillImageFilter::Center, QVariant(imagePosition));
double radius = widget->radius() / 100.0 * qMin(editUiProvider()->fullImageSize().width(),
editUiProvider()->fullImageSize().height());
optionHash.insert(QuillImageFilter::Radius, radius);
// To enlarge (punch effect) "force" must be positive
// To shrink (pinch effect) "force" must be negative
optionHash.insert("force", EFFECT_FORCE * (widget->shrink()? -1 : 1));
editUiProvider()->runEditFilter("com.igalia.enlargeshrink", optionHash);
emit editOperationPerformed();
}
}
}
MMessageBox* GalleryEnlargeShrinkPlugin::showMessageBox(const QString& title, const QString& text) const
{
MMessageBox* messageBox = new MMessageBox(title, "");
MLabel* innerLabel = new MLabel(messageBox);
innerLabel->setWordWrap(true);
innerLabel->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
innerLabel->setStyleName("CommonQueryText");
innerLabel->setText(text);
innerLabel->setAlignment(Qt::AlignHCenter);
messageBox->setCentralWidget(innerLabel);
connect(this, SIGNAL(deactivated()),
messageBox, SLOT(disappear()));
messageBox->appear(MSceneWindow::DestroyWhenDone);
return messageBox;
}
MBanner* GalleryEnlargeShrinkPlugin::showInfoBanner(const QString& title) const
{
MBanner *infoBanner = new MBanner;
infoBanner->setStyleName(MBannerType::InformationBanner);
infoBanner->setTitle(title);
infoBanner->model()->setDisappearTimeout(INFOBANNER_TIMEOUT);
connect(this, SIGNAL(deactivated()),
infoBanner, SLOT(disappear()));
infoBanner->appear(MApplication::activeWindow(), MSceneWindow::DestroyWhenDone);
return infoBanner;
}
void GalleryEnlargeShrinkPlugin::onAboutLinkActivated(const QString &link)
{
if (link.toLower().startsWith("http") || link.toLower().startsWith("mailto")) {
QDesktopServices::openUrl(QUrl(link));
} else {
showMessageBox("About Enlarge Shrink plugin",
"Copyright (c) 2012 Igalia S.L."
"<br /><br />"
"<a href=\"mailto:[email protected]\">[email protected]</a> | "
"<a href=\"http://www.igalia.com\">www.igalia.com</a>"
"<br /><br />"
"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; version 2.1 of "
"the License, or (at your option) any later version.");
}
}
Q_EXPORT_PLUGIN2(galleryenlargeshrinkplugin, GalleryEnlargeShrinkPlugin)
<commit_msg>GalleryEnlargeShrinkPlugin: use the PACKAGEVERSION define in the disclaimer<commit_after>/*
* galleryenlargeshrinkplugin.cpp
*
* Copyright (C) 2012 Igalia, S.L.
* Author: Antia Puentes <[email protected]>
*
* This file is part of the Gallery Enlarge/Shrink Plugin.
*
* 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; 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, see http://www.gnu.org/licenses/ *
*/
#include "galleryenlargeshrinkplugin.h"
#include "galleryenlargeshrinkplugin_p.h"
#include "galleryenlargeshrinkwidget.h"
#include <galleryedituiprovider.h>
#include <MLibrary>
#include <MApplication>
#include <MBanner>
#include <MMessageBox>
#include <MLabel>
#include <QGraphicsSceneMouseEvent>
#include <QDesktopServices>
#include <QUrl>
#include <QTextOption>
#include <QuillImageFilter>
static const float EFFECT_FORCE = 1.0;
static const int TAP_DISTANCE = 20;
static const int PORTRAIT_HEIGHT = 224;
static const int LANDSCAPE_HEIGHT = 112;
static const int INFOBANNER_TIMEOUT = 2 * 1000;
static const int IMAGE_MAX_HEIGHT = 512;
static const int IMAGE_MAX_WIDTH = 512;
M_LIBRARY
GalleryEnlargeShrinkPluginPrivate::GalleryEnlargeShrinkPluginPrivate() :
m_focusPosition(),
m_validImage(true)
{
}
GalleryEnlargeShrinkPluginPrivate::~GalleryEnlargeShrinkPluginPrivate()
{
}
GalleryEnlargeShrinkPlugin::GalleryEnlargeShrinkPlugin(QObject* parent) :
GalleryEditPlugin(parent),
d_ptr(new GalleryEnlargeShrinkPluginPrivate())
{
}
GalleryEnlargeShrinkPlugin::~GalleryEnlargeShrinkPlugin()
{
delete d_ptr;
}
QString GalleryEnlargeShrinkPlugin::name() const
{
return QString("Enlarge - Shrink");
}
QString GalleryEnlargeShrinkPlugin::iconID() const
{
return QString("icon-m-image-edit-enlarge-shrink");
}
bool GalleryEnlargeShrinkPlugin::containsUi() const
{
return true;
}
bool GalleryEnlargeShrinkPlugin::zoomingAllowed() const
{
return true;
}
QGraphicsWidget* GalleryEnlargeShrinkPlugin::createToolBarWidget(QGraphicsItem* parent)
{
GalleryEnlargeShrinkWidget* widget = new GalleryEnlargeShrinkWidget(parent);
connect(widget, SIGNAL(aboutLinkActivated(QString)),
this, SLOT(onAboutLinkActivated(QString)));
return widget;
}
const QSize GalleryEnlargeShrinkPlugin::toolBarWidgetSize(const M::Orientation& orientation) const
{
QSize size = GalleryEditPlugin::toolBarWidgetSize(orientation);
if (M::Portrait == orientation) {
size.setHeight(PORTRAIT_HEIGHT);
} else {
size.setHeight(LANDSCAPE_HEIGHT);
}
return size;
}
bool GalleryEnlargeShrinkPlugin::receiveMouseEvent(QGraphicsSceneMouseEvent *event)
{
if (event &&
event->type() == QEvent::GraphicsSceneMouseRelease &&
event->button() == Qt::LeftButton &&
(event->scenePos() - event->buttonDownScenePos(Qt::LeftButton)).manhattanLength() < TAP_DISTANCE) {
Q_D(GalleryEnlargeShrinkPlugin);
if (d->m_validImage) {
d->m_focusPosition = event->pos().toPoint();
performEditOperation();
return true;
} else {
showInfoBanner("Plugin disabled for this image size");
}
}
return false;
}
void GalleryEnlargeShrinkPlugin::activate()
{
if (editUiProvider()) {
Q_D(GalleryEnlargeShrinkPlugin);
d->m_validImage = editUiProvider()->fullImageSize().height() <= IMAGE_MAX_HEIGHT &&
editUiProvider()->fullImageSize().width() <= IMAGE_MAX_WIDTH;
if (d->m_validImage) {
showInfoBanner("Tap on an area to keep it focused");
} else {
showMessageBox("Enlarge Shrink plugin limitations",
"Gallery Enlarge Shrink plugin is currently limited to "
"small images (512x512)<br />"
"For a given image:"
"<ol>"
"<li>Scale it or crop it</li>"
"<li>Save it with a different name</li>"
"<li>Apply the filter to the new one</li>"
"</ol>");
GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget());
widget->enableInput(d->m_validImage);
}
}
}
void GalleryEnlargeShrinkPlugin::performEditOperation()
{
if (editUiProvider()) {
Q_D(GalleryEnlargeShrinkPlugin);
QHash<QuillImageFilter::QuillFilterOption, QVariant> optionHash;
const QPoint imagePosition = editUiProvider()->convertScreenCoordToImageCoord(d->m_focusPosition);
if (imagePosition != QPoint(-1, -1)) {
GalleryEnlargeShrinkWidget* widget = static_cast<GalleryEnlargeShrinkWidget*>(toolBarWidget());
optionHash.insert(QuillImageFilter::Center, QVariant(imagePosition));
double radius = widget->radius() / 100.0 * qMin(editUiProvider()->fullImageSize().width(),
editUiProvider()->fullImageSize().height());
optionHash.insert(QuillImageFilter::Radius, radius);
// To enlarge (punch effect) "force" must be positive
// To shrink (pinch effect) "force" must be negative
optionHash.insert("force", EFFECT_FORCE * (widget->shrink()? -1 : 1));
editUiProvider()->runEditFilter("com.igalia.enlargeshrink", optionHash);
emit editOperationPerformed();
}
}
}
MMessageBox* GalleryEnlargeShrinkPlugin::showMessageBox(const QString& title, const QString& text) const
{
MMessageBox* messageBox = new MMessageBox(title, "");
MLabel* innerLabel = new MLabel(messageBox);
innerLabel->setWordWrap(true);
innerLabel->setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
innerLabel->setStyleName("CommonQueryText");
innerLabel->setText(text);
innerLabel->setAlignment(Qt::AlignHCenter);
messageBox->setCentralWidget(innerLabel);
connect(this, SIGNAL(deactivated()),
messageBox, SLOT(disappear()));
messageBox->appear(MSceneWindow::DestroyWhenDone);
return messageBox;
}
MBanner* GalleryEnlargeShrinkPlugin::showInfoBanner(const QString& title) const
{
MBanner *infoBanner = new MBanner;
infoBanner->setStyleName(MBannerType::InformationBanner);
infoBanner->setTitle(title);
infoBanner->model()->setDisappearTimeout(INFOBANNER_TIMEOUT);
connect(this, SIGNAL(deactivated()),
infoBanner, SLOT(disappear()));
infoBanner->appear(MApplication::activeWindow(), MSceneWindow::DestroyWhenDone);
return infoBanner;
}
void GalleryEnlargeShrinkPlugin::onAboutLinkActivated(const QString &link)
{
if (link.toLower().startsWith("http") || link.toLower().startsWith("mailto")) {
QDesktopServices::openUrl(QUrl(link));
} else {
showMessageBox(QString("About Enlarge Shrink plugin - %1").arg(PACKAGEVERSION),
"Copyright (c) 2012 Igalia S.L."
"<br /><br />"
"<a href=\"mailto:[email protected]\">[email protected]</a> | "
"<a href=\"http://www.igalia.com\">www.igalia.com</a>"
"<br /><br />"
"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; version 2.1 of "
"the License, or (at your option) any later version.");
}
}
Q_EXPORT_PLUGIN2(galleryenlargeshrinkplugin, GalleryEnlargeShrinkPlugin)
<|endoftext|> |
<commit_before>//============================================================================
// Name : ImageProcessingController.cpp
// Author : ITM13
// Version : 1.0
// Copyright : Copyright (c) 2014 Swank Rat, MIT License (MIT)
// Description :
//============================================================================
#include "ImageProcessingController.h"
#include "..\shared\Logger.h"
ImageProcessingController::ImageProcessingController()
{
webcamService = new WebcamService();
}
ImageProcessingController::~ImageProcessingController()
{
StopImageProcessing();
webcamService = NULL;
}
void ImageProcessingController::StartImageProcessing() {
webcamService->StartRecording();
}
bool ImageProcessingController::StopImageProcessing() {
webcamService->StopRecording();
return true;
}
void ImageProcessingController::Update(WebcamService* observable) {
Logger::addMessage("New image available");
observable->GetLastImage();
}
<commit_msg>Modified image proc controller<commit_after>//============================================================================
// Name : ImageProcessingController.cpp
// Author : ITM13
// Version : 1.0
// Copyright : Copyright (c) 2014 Swank Rat, MIT License (MIT)
// Description :
//============================================================================
#include "ImageProcessingController.h"
#include "..\shared\Logger.h"
ImageProcessingController::ImageProcessingController()
{
webcamService = new WebcamService();
}
ImageProcessingController::~ImageProcessingController()
{
StopImageProcessing();
webcamService = NULL;
}
void ImageProcessingController::StartImageProcessing() {
webcamService->StartRecording();
}
bool ImageProcessingController::StopImageProcessing() {
webcamService->StopRecording();
return true;
}
void ImageProcessingController::Update(WebcamService* observable) {
Logger::addMessage("New image available");
observable->GetLastImage();
}
<|endoftext|> |
<commit_before>/**
* \file
* \brief BufferingBlockDevice class header
*
* \author Copyright (C) 2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef INCLUDE_DISTORTOS_DEVICES_MEMORY_BUFFERINGBLOCKDEVICE_HPP_
#define INCLUDE_DISTORTOS_DEVICES_MEMORY_BUFFERINGBLOCKDEVICE_HPP_
#include "distortos/devices/memory/BlockDevice.hpp"
namespace distortos
{
namespace devices
{
class BlockDevice;
/**
* BufferingBlockDevice class is a buffering wrapper for BlockDevice.
*
* This class tries to minimize amount of BlockDevice operations by buffering both reads and writes. This can give
* signigicant gain in case of devices like SD cards, where each operation may cause the device to become "busy" for a
* noticeable amount of time. With this class several adjacent reads or writes can be combined into a single larger
* operation, which is much faster overall when you also include the waits for the SD card to become "idle".
*
* Another use for this class is as a proxy between a file system and a block device which requires specific alignment.
*
* \ingroup devices
*/
class BufferingBlockDevice : public BlockDevice
{
public:
/**
* \brief BufferingBlockDevice's constructor
*
* \param [in] blockDevice is a reference to associated block device
* \param [in] readBuffer is a pointer to buffer for reads, its address must be aligned to
* `DISTORTOS_BLOCKDEVICE_BUFFER_ALIGNMENT` bytes
* \param [in] readBufferSize is the size of \a readBuffer, bytes, must be a multiple of \a blockDevice block size
* \param [in] writeBuffer is a pointer to buffer for writes, its address must be aligned to
* `DISTORTOS_BLOCKDEVICE_BUFFER_ALIGNMENT` bytes
* \param [in] writeBufferSize is the size of \a writeBuffer, bytes, must be a multiple of \a blockDevice block size
*/
constexpr explicit BufferingBlockDevice(BlockDevice& blockDevice, void* const readBuffer,
const size_t readBufferSize, void* const writeBuffer, const size_t writeBufferSize) :
readBufferAddress_{},
writeBufferAddress_{},
blockDevice_{blockDevice},
readBuffer_{readBuffer},
readBufferSize_{readBufferSize},
writeBuffer_{writeBuffer},
writeBufferSize_{writeBufferSize},
writeBufferValidSize_{},
openCount_{},
readBufferValid_{}
{
}
/**
* \brief BufferingBlockDevice's destructor
*
* \pre Device is closed.
*/
~BufferingBlockDevice() override;
/**
* \brief Closes device.
*
* \note Even if error code is returned, the device must not be used from the context which opened it (until it is
* successfully opened again).
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer();
* - error codes returned by BlockDevice::close();
*/
int close() override;
/**
* \brief Erases blocks on a device.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
* \pre \a address and \a size are valid.
* \pre Selected range is within address space of device.
*
* \param [in] address is the address of range that will be erased, must be a multiple of block size
* \param [in] size is the size of erased range, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer(size_t);
* - error codes returned by BlockDevice::erase();
*/
int erase(uint64_t address, uint64_t size) override;
/**
* \return block size, bytes
*/
size_t getBlockSize() const override;
/**
* \return size of block device, bytes
*/
uint64_t getSize() const override;
/**
* \brief Locks the device for exclusive use by current thread.
*
* When the object is locked, any call to any member function from other thread will be blocked until the object is
* unlocked. Locking is optional, but may be useful when more than one transaction must be done atomically.
*
* \note Locks are recursive.
*
* \warning This function must not be called from interrupt context!
*
* \pre The number of recursive locks of device is less than 65535.
*
* \post Device is locked.
*/
void lock() override;
/**
* \brief Opens device.
*
* \warning This function must not be called from interrupt context!
*
* \pre The number of times the device is opened is less than 255.
* \pre Addresses of associated read and write buffers are aligned to `DISTORTOS_BLOCKDEVICE_BUFFER_ALIGNMENT`
* bytes.
* \pre Sizes of associated read and write buffers are non-zero multiples of associated block device's block size.
*
* \return 0 on success, error code otherwise:
* - error codes returned by BlockDevice::open();
*/
int open() override;
/**
* \brief Reads data from a device.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
* \pre \a address and \a buffer and \a size are valid.
* \pre Selected range is within address space of device.
*
* \param [in] address is the address of data that will be read, must be a multiple of block size
* \param [out] buffer is the buffer into which the data will be read, must be valid
* \param [in] size is the size of \a buffer, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by readImplementation();
*/
int read(uint64_t address, void* buffer, size_t size) override;
/**
* \brief Synchronizes state of a device, ensuring all cached writes are finished.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer();
* - error codes returned by BlockDevice::synchronize();
*/
int synchronize() override;
/**
* \brief Unlocks the device which was previously locked by current thread.
*
* \note Locks are recursive.
*
* \warning This function must not be called from interrupt context!
*
* \pre This function is called by the thread that locked the device.
*/
void unlock() override;
/**
* \brief Writes data to a device.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
* \pre \a address and \a buffer and \a size are valid.
* \pre Selected range is within address space of device.
*
* \param [in] address is the address of data that will be written, must be a multiple of block size
* \param [in] buffer is the buffer with data that will be written, must be valid
* \param [in] size is the size of \a buffer, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer();
*/
int write(uint64_t address, const void* buffer, size_t size) override;
private:
/**
* \brief Flushes whole write buffer to the associated block device.
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer(size_t);
*/
int flushWriteBuffer()
{
return flushWriteBuffer(writeBufferValidSize_);
}
/**
* \brief Flushes write buffer to the associated block device.
*
* \param [in] size is the max amount of data that will be flushed, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by BlockDevice::write();
*/
int flushWriteBuffer(size_t size);
/**
* \brief Implementation of read()
*
* \pre Selected range must either not intersect with read buffer or the address of intersection must be equal to
* the address of read buffer.
*
* \param [in] address is the address of data that will be read, must be a multiple of block size
* \param [out] buffer is the buffer into which the data will be read, must be valid
* \param [in] size is the size of \a buffer, bytes, must be a multiple of block size
* \param [in] deviceSize is the size of block device, bytes
*
* \return 0 on success, error code otherwise:
* - error codes returned by BlockDevice::read();
*/
int readImplementation(uint64_t address, void* buffer, size_t size, uint64_t deviceSize);
/// address of data in read buffer
uint64_t readBufferAddress_;
/// address of data in write buffer
uint64_t writeBufferAddress_;
/// reference to associated block device
BlockDevice& blockDevice_;
/// pointer to buffer for reads
void* readBuffer_;
/// size of \a readBuffer_, bytes
size_t readBufferSize_;
/// pointer to buffer for writes
void* writeBuffer_;
/// size of \a writeBuffer_, bytes
size_t writeBufferSize_;
/// amount of data pending to be written in write buffer, bytes
size_t writeBufferValidSize_;
/// number of times this device was opened but not yet closed
uint8_t openCount_;
/// true if read buffer holds valid data, false otherwise
bool readBufferValid_;
};
} // namespace devices
} // namespace distortos
#endif // INCLUDE_DISTORTOS_DEVICES_MEMORY_BUFFERINGBLOCKDEVICE_HPP_
<commit_msg>fixup BufferingBlockDevice<commit_after>/**
* \file
* \brief BufferingBlockDevice class header
*
* \author Copyright (C) 2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef INCLUDE_DISTORTOS_DEVICES_MEMORY_BUFFERINGBLOCKDEVICE_HPP_
#define INCLUDE_DISTORTOS_DEVICES_MEMORY_BUFFERINGBLOCKDEVICE_HPP_
#include "distortos/devices/memory/BlockDevice.hpp"
namespace distortos
{
namespace devices
{
class BlockDevice;
/**
* BufferingBlockDevice class is a buffering wrapper for BlockDevice.
*
* This class tries to minimize amount of BlockDevice operations by buffering both reads and writes. Such buffering can
* give signigicant gain in case of devices like SD cards, where each operation may cause the device to become "busy"
* for a noticeable amount of time. With this class several adjacent reads or writes can be combined into a single
* larger operation, which is much faster overall when you also include the waits for the SD card to become "idle".
*
* Another use for this class is as a proxy between a file system and a block device which requires specific alignment.
*
* \ingroup devices
*/
class BufferingBlockDevice : public BlockDevice
{
public:
/**
* \brief BufferingBlockDevice's constructor
*
* \param [in] blockDevice is a reference to associated block device
* \param [in] readBuffer is a pointer to buffer for reads, its address must be aligned to
* `DISTORTOS_BLOCKDEVICE_BUFFER_ALIGNMENT` bytes
* \param [in] readBufferSize is the size of \a readBuffer, bytes, must be a multiple of \a blockDevice block size
* \param [in] writeBuffer is a pointer to buffer for writes, its address must be aligned to
* `DISTORTOS_BLOCKDEVICE_BUFFER_ALIGNMENT` bytes
* \param [in] writeBufferSize is the size of \a writeBuffer, bytes, must be a multiple of \a blockDevice block size
*/
constexpr explicit BufferingBlockDevice(BlockDevice& blockDevice, void* const readBuffer,
const size_t readBufferSize, void* const writeBuffer, const size_t writeBufferSize) :
readBufferAddress_{},
writeBufferAddress_{},
blockDevice_{blockDevice},
readBuffer_{readBuffer},
readBufferSize_{readBufferSize},
writeBuffer_{writeBuffer},
writeBufferSize_{writeBufferSize},
writeBufferValidSize_{},
openCount_{},
readBufferValid_{}
{
}
/**
* \brief BufferingBlockDevice's destructor
*
* \pre Device is closed.
*/
~BufferingBlockDevice() override;
/**
* \brief Closes device.
*
* \note Even if error code is returned, the device must not be used from the context which opened it (until it is
* successfully opened again).
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer();
* - error codes returned by BlockDevice::close();
*/
int close() override;
/**
* \brief Erases blocks on a device.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
* \pre \a address and \a size are valid.
* \pre Selected range is within address space of device.
*
* \param [in] address is the address of range that will be erased, must be a multiple of block size
* \param [in] size is the size of erased range, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer(size_t);
* - error codes returned by BlockDevice::erase();
*/
int erase(uint64_t address, uint64_t size) override;
/**
* \return block size, bytes
*/
size_t getBlockSize() const override;
/**
* \return size of block device, bytes
*/
uint64_t getSize() const override;
/**
* \brief Locks the device for exclusive use by current thread.
*
* When the object is locked, any call to any member function from other thread will be blocked until the object is
* unlocked. Locking is optional, but may be useful when more than one transaction must be done atomically.
*
* \note Locks are recursive.
*
* \warning This function must not be called from interrupt context!
*
* \pre The number of recursive locks of device is less than 65535.
*
* \post Device is locked.
*/
void lock() override;
/**
* \brief Opens device.
*
* \warning This function must not be called from interrupt context!
*
* \pre The number of times the device is opened is less than 255.
* \pre Addresses of associated read and write buffers are aligned to `DISTORTOS_BLOCKDEVICE_BUFFER_ALIGNMENT`
* bytes.
* \pre Sizes of associated read and write buffers are non-zero multiples of associated block device's block size.
*
* \return 0 on success, error code otherwise:
* - error codes returned by BlockDevice::open();
*/
int open() override;
/**
* \brief Reads data from a device.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
* \pre \a address and \a buffer and \a size are valid.
* \pre Selected range is within address space of device.
*
* \param [in] address is the address of data that will be read, must be a multiple of block size
* \param [out] buffer is the buffer into which the data will be read, must be valid
* \param [in] size is the size of \a buffer, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by readImplementation();
*/
int read(uint64_t address, void* buffer, size_t size) override;
/**
* \brief Synchronizes state of a device, ensuring all cached writes are finished.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer();
* - error codes returned by BlockDevice::synchronize();
*/
int synchronize() override;
/**
* \brief Unlocks the device which was previously locked by current thread.
*
* \note Locks are recursive.
*
* \warning This function must not be called from interrupt context!
*
* \pre This function is called by the thread that locked the device.
*/
void unlock() override;
/**
* \brief Writes data to a device.
*
* \warning This function must not be called from interrupt context!
*
* \pre Device is opened.
* \pre \a address and \a buffer and \a size are valid.
* \pre Selected range is within address space of device.
*
* \param [in] address is the address of data that will be written, must be a multiple of block size
* \param [in] buffer is the buffer with data that will be written, must be valid
* \param [in] size is the size of \a buffer, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer();
*/
int write(uint64_t address, const void* buffer, size_t size) override;
private:
/**
* \brief Flushes whole write buffer to the associated block device.
*
* \return 0 on success, error code otherwise:
* - error codes returned by flushWriteBuffer(size_t);
*/
int flushWriteBuffer()
{
return flushWriteBuffer(writeBufferValidSize_);
}
/**
* \brief Flushes write buffer to the associated block device.
*
* \param [in] size is the max amount of data that will be flushed, bytes, must be a multiple of block size
*
* \return 0 on success, error code otherwise:
* - error codes returned by BlockDevice::write();
*/
int flushWriteBuffer(size_t size);
/**
* \brief Implementation of read()
*
* \pre Selected range must either not intersect with read buffer or the address of intersection must be equal to
* the address of read buffer.
*
* \param [in] address is the address of data that will be read, must be a multiple of block size
* \param [out] buffer is the buffer into which the data will be read, must be valid
* \param [in] size is the size of \a buffer, bytes, must be a multiple of block size
* \param [in] deviceSize is the size of block device, bytes
*
* \return 0 on success, error code otherwise:
* - error codes returned by BlockDevice::read();
*/
int readImplementation(uint64_t address, void* buffer, size_t size, uint64_t deviceSize);
/// address of data in read buffer
uint64_t readBufferAddress_;
/// address of data in write buffer
uint64_t writeBufferAddress_;
/// reference to associated block device
BlockDevice& blockDevice_;
/// pointer to buffer for reads
void* readBuffer_;
/// size of \a readBuffer_, bytes
size_t readBufferSize_;
/// pointer to buffer for writes
void* writeBuffer_;
/// size of \a writeBuffer_, bytes
size_t writeBufferSize_;
/// amount of data pending to be written in write buffer, bytes
size_t writeBufferValidSize_;
/// number of times this device was opened but not yet closed
uint8_t openCount_;
/// true if read buffer holds valid data, false otherwise
bool readBufferValid_;
};
} // namespace devices
} // namespace distortos
#endif // INCLUDE_DISTORTOS_DEVICES_MEMORY_BUFFERINGBLOCKDEVICE_HPP_
<|endoftext|> |
<commit_before>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/HAL/Target/LLVM/Builtins/Device.h"
#include "iree/builtins/device/bin/libdevice.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Support/MemoryBufferRef.h"
#include "mlir/Support/LLVM.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
static const iree_file_toc_t *lookupDeviceFile(StringRef filename) {
for (size_t i = 0; i < iree_builtins_libdevice_size(); ++i) {
const auto &file_toc = iree_builtins_libdevice_create()[i];
if (filename == file_toc.name) return &file_toc;
}
return nullptr;
}
static const iree_file_toc_t *lookupDeviceFile(
llvm::TargetMachine *targetMachine) {
const auto &triple = targetMachine->getTargetTriple();
// NOTE: other arch-specific checks go here.
if (triple.isWasm()) {
// TODO(benvanik): feature detect simd and such.
// auto features = targetMachine->getTargetFeatureString();
if (triple.isArch32Bit()) {
return lookupDeviceFile("libdevice_wasm32_generic.bc");
} else if (triple.isArch64Bit()) {
return lookupDeviceFile("libdevice_wasm64_generic.bc");
}
}
// Fallback path using the generic wasm variants as they are largely
// machine-agnostic.
if (triple.isArch32Bit()) {
return lookupDeviceFile("libdevice_wasm32_generic.bc");
} else if (triple.isArch64Bit()) {
return lookupDeviceFile("libdevice_wasm64_generic.bc");
} else {
return nullptr;
}
}
// TODO(benvanik): move to a common file so we can reuse it.
static void overridePlatformGlobal(llvm::Module &module, StringRef globalName,
uint32_t newValue) {
// NOTE: the global will not be defined if it is not used in the module.
auto *globalValue = module.getNamedGlobal(globalName);
if (!globalValue) return;
globalValue->setLinkage(llvm::GlobalValue::PrivateLinkage);
globalValue->setDSOLocal(true);
globalValue->setConstant(true);
globalValue->setInitializer(
llvm::ConstantInt::get(globalValue->getValueType(), APInt(32, newValue)));
}
llvm::Expected<std::unique_ptr<llvm::Module>> loadDeviceBitcode(
llvm::TargetMachine *targetMachine, llvm::LLVMContext &context) {
// Find a bitcode file for the current architecture.
const auto *file = lookupDeviceFile(targetMachine);
if (!file) {
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"no matching architecture bitcode file");
}
// Load the generic bitcode file contents.
llvm::MemoryBufferRef bitcodeBufferRef(
llvm::StringRef(file->data, file->size), file->name);
auto bitcodeModuleValue = llvm::parseBitcodeFile(bitcodeBufferRef, context);
if (!bitcodeModuleValue) return bitcodeModuleValue;
auto bitcodeModule = std::move(bitcodeModuleValue.get());
// Inject target-specific flags.
overridePlatformGlobal(*bitcodeModule, "libdevice_platform_example_flag", 0u);
return bitcodeModule;
}
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>Fix compile GCC error (#7862)<commit_after>// Copyright 2021 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/HAL/Target/LLVM/Builtins/Device.h"
#include "iree/builtins/device/bin/libdevice.h"
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/Support/MemoryBufferRef.h"
#include "mlir/Support/LLVM.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
static const iree_file_toc_t *lookupDeviceFile(StringRef filename) {
for (size_t i = 0; i < iree_builtins_libdevice_size(); ++i) {
const auto &file_toc = iree_builtins_libdevice_create()[i];
if (filename == file_toc.name) return &file_toc;
}
return nullptr;
}
static const iree_file_toc_t *lookupDeviceFile(
llvm::TargetMachine *targetMachine) {
const auto &triple = targetMachine->getTargetTriple();
// NOTE: other arch-specific checks go here.
if (triple.isWasm()) {
// TODO(benvanik): feature detect simd and such.
// auto features = targetMachine->getTargetFeatureString();
if (triple.isArch32Bit()) {
return lookupDeviceFile("libdevice_wasm32_generic.bc");
} else if (triple.isArch64Bit()) {
return lookupDeviceFile("libdevice_wasm64_generic.bc");
}
}
// Fallback path using the generic wasm variants as they are largely
// machine-agnostic.
if (triple.isArch32Bit()) {
return lookupDeviceFile("libdevice_wasm32_generic.bc");
} else if (triple.isArch64Bit()) {
return lookupDeviceFile("libdevice_wasm64_generic.bc");
} else {
return nullptr;
}
}
// TODO(benvanik): move to a common file so we can reuse it.
static void overridePlatformGlobal(llvm::Module &module, StringRef globalName,
uint32_t newValue) {
// NOTE: the global will not be defined if it is not used in the module.
auto *globalValue = module.getNamedGlobal(globalName);
if (!globalValue) return;
globalValue->setLinkage(llvm::GlobalValue::PrivateLinkage);
globalValue->setDSOLocal(true);
globalValue->setConstant(true);
globalValue->setInitializer(
llvm::ConstantInt::get(globalValue->getValueType(), APInt(32, newValue)));
}
llvm::Expected<std::unique_ptr<llvm::Module>> loadDeviceBitcode(
llvm::TargetMachine *targetMachine, llvm::LLVMContext &context) {
// Find a bitcode file for the current architecture.
const auto *file = lookupDeviceFile(targetMachine);
if (!file) {
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"no matching architecture bitcode file");
}
// Load the generic bitcode file contents.
llvm::MemoryBufferRef bitcodeBufferRef(
llvm::StringRef(file->data, file->size), file->name);
auto bitcodeModuleValue = llvm::parseBitcodeFile(bitcodeBufferRef, context);
if (!bitcodeModuleValue) return bitcodeModuleValue;
auto bitcodeModule = std::move(bitcodeModuleValue.get());
// Inject target-specific flags.
overridePlatformGlobal(*bitcodeModule, "libdevice_platform_example_flag", 0u);
return std::move(bitcodeModule);
}
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|> |
<commit_before>//! @Alan
//! Exercise 11.14:
//! Extend the map of children to their family name that you wrote for the
//! exercises in § 11.2.1 (p. 424) by having the vector store a pair that
//! holds a child’s name and birthday.
//!
//! @Alan
//!
//! Exercise 11.7:
//! Define a map for which the key is the family’s last name and
//! the value is a vector of the children’s names. Write code to
//! add new families and to add new children to an existing family.
//!
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
int main()
{
//! define a map as required.
std::map<std::string, std::vector<std::pair<std::string,std::string>>>
famlies_map;
//! declare three strings to store the input
std::string lastName, childName, birthday;
while([&](){//! a lambda to read lastName and check if should quit
std::cout << "last name:\n";
std::cin >> lastName;
return lastName != "@q";
}())
{
while([&](){//! a lambda to read child name and birthday and check if should quit
std::cout << "child's name:\n";
std::cin >> childName;
std::cout << "his birthday:\n";
std::cin >> birthday;
return childName != "@q" && birthday != "@q";
}())
{
famlies_map[lastName].push_back({childName, birthday});
//! ^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
//! use lastName as the key create a pair using {}.
}
}
//! print the content.
for(const auto &e : famlies_map)
{
std::cout << e.first <<":\n";
for (const auto &l : e.second)
{
std::cout << l.first << " "
<< l.second << " ";
}
}
return 0;
}
<commit_msg>Update ex11_14.cpp<commit_after>//! @Alan
//! Exercise 11.14:
//! Extend the map of children to their family name that you wrote for the
//! exercises in § 11.2.1 (p. 424) by having the vector store a pair that
//! holds a child’s name and birthday.
//!
//! @Alan
//!
//! Exercise 11.7:
//! Define a map for which the key is the family’s last name and
//! the value is a vector of the children’s names. Write code to
//! add new families and to add new children to an existing family.
//!
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
int main()
{
//! define a map as required.
std::map<std::string, std::vector<std::pair<std::string,std::string>>>
famlies_map;
//! declare three strings to store the input
std::string lastName, childName, birthday;
while([&](){//! a lambda to read lastName and check if should quit
std::cout << "last name:\n";
std::cin >> lastName;
return lastName != "@q";
}())
{
while([&](){//! a lambda to read child name and birthday and check if should quit
std::cout << "child's name:\n";
std::cin >> childName;
std::cout << "his birthday:\n";
std::cin >> birthday;
return childName != "@q" && birthday != "@q";
}())
{
famlies_map[lastName].push_back({childName, birthday});
//! ^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
//! use lastName as the key create a pair using {}.
}
}
//! print the content.
for(const auto &e : famlies_map)
{
std::cout << e.first <<":\n";
for (const auto &l : e.second)
{
std::cout << l.first << " "
<< l.second << " ";
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "picodbc.h"
#include <iostream>
using namespace std;
template<class T>
void show(picodbc::result results)
{
const short columns = results.columns();
long rows_displayed = 0;
cout << "\nDisplaying " << results.affected_rows() << " rows (" << results.rowset_size() << " at a time):" << endl;
cout << "row\t";
for(short i = 0; i < columns; ++i)
cout << results.column_name(i) << "\t";
cout << endl;
while(results.next())
{
const unsigned long rows = results.rows();
for(unsigned long row = 0; row < rows; ++row)
{
cout << rows_displayed++ << "\t";
for(short col = 0; col < columns; ++col)
{
if(results.is_null(col, row))
cout << "(null)";
else
cout << "(" << results.get<T>(col, row) << ")";
cout << "\t";
}
cout << endl;
}
}
}
int main()
{
// const char* connection_string = "A Data Source Connection String";
// #define EXAMPLE_TABLE "public.example_table"
const char* connection_string = "Driver=vertica;Servername=sandbox03;Port=5433;Database=vertica01;UserName=dbadmin;Password=;";
#define EXAMPLE_TABLE "public.amytest"
try
{
// Establishing connections
picodbc::connection connection(connection_string);
// or picodbc::connection connection(connection_string, timeout_seconds);
// or picodbc::connection connection("data source name", "username", "password");
// or picodbc::connection connection("data source name", "username", "password", timeout_seconds);
cout << "Connected with driver " << connection.driver_name() << endl;
picodbc::statement statement;
picodbc::result results;
// Direct execution
results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";");
show<string>(results);
// Direct execution, bulk fetching 2 rows at a time
results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";", 2);
show<string>(results);
// Binding parameters
statement.prepare(connection, "select * from " EXAMPLE_TABLE " where cast(a as float) = ?;");
statement.bind_parameter(0, 1.0);
results = statement.execute();
show<string>(results);
// Transactions
{
picodbc::transaction transaction(connection);
statement.execute_direct(connection, "delete from " EXAMPLE_TABLE " where true;");
// transaction will be rolled back if we don't call transaction.commit()
}
// The resources used by connection and statement are cleaned up automatically or
// you can explicitly call statement.close() and/or connection.disconnect().
}
catch(const exception& e)
{
cerr << "exception: " << e.what() << endl;
}
}<commit_msg>Removed testing code.<commit_after>#include "picodbc.h"
#include <iostream>
using namespace std;
template<class T>
void show(picodbc::result results)
{
const short columns = results.columns();
long rows_displayed = 0;
cout << "\nDisplaying " << results.affected_rows() << " rows (" << results.rowset_size() << " at a time):" << endl;
cout << "row\t";
for(short i = 0; i < columns; ++i)
cout << results.column_name(i) << "\t";
cout << endl;
while(results.next())
{
const unsigned long rows = results.rows();
for(unsigned long row = 0; row < rows; ++row)
{
cout << rows_displayed++ << "\t";
for(short col = 0; col < columns; ++col)
{
if(results.is_null(col, row))
cout << "(null)";
else
cout << "(" << results.get<T>(col, row) << ")";
cout << "\t";
}
cout << endl;
}
}
}
int main()
{
const char* connection_string = "A Data Source Connection String";
#define EXAMPLE_TABLE "public.example_table"
try
{
// Establishing connections
picodbc::connection connection(connection_string);
// or picodbc::connection connection(connection_string, timeout_seconds);
// or picodbc::connection connection("data source name", "username", "password");
// or picodbc::connection connection("data source name", "username", "password", timeout_seconds);
cout << "Connected with driver " << connection.driver_name() << endl;
picodbc::statement statement;
picodbc::result results;
// Direct execution
results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";");
show<string>(results);
// Direct execution, bulk fetching 2 rows at a time
results = statement.execute_direct(connection, "select * from " EXAMPLE_TABLE ";", 2);
show<string>(results);
// Binding parameters
statement.prepare(connection, "select * from " EXAMPLE_TABLE " where cast(a as float) = ?;");
statement.bind_parameter(0, 1.0);
results = statement.execute();
show<string>(results);
// Transactions
{
picodbc::transaction transaction(connection);
statement.execute_direct(connection, "delete from " EXAMPLE_TABLE " where true;");
// transaction will be rolled back if we don't call transaction.commit()
}
// The resources used by connection and statement are cleaned up automatically or
// you can explicitly call statement.close() and/or connection.disconnect().
}
catch(const exception& e)
{
cerr << "exception: " << e.what() << endl;
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: htags.cpp,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-20 00:54:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
/* NAME
* PURPOSE
*
* NOTES
*
* HISTORY
* frog - Aug 6, 1998: Created.
*/
#include "precompile.h"
#ifdef __GNUG__
#pragma implementation "htags.h"
#endif
#include <string.h>
#include "hwplib.h"
#include "hwpfile.h"
#include "htags.h"
#include "himgutil.h"
bool HyperText::Read(HWPFile & hwpf)
{
hwpf.Read1b(filename, 256);
hwpf.Read2b(bookmark, 16);
hwpf.Read1b(macro, 325);
hwpf.Read1b(&type, 1);
hwpf.Read1b(reserve, 3);
if( type == 2 )
{
for( int i = 1; i < 256; i++)
{
filename[i-1] = filename[i];
if( filename[i] == 0 )
break;
}
}
return true;
}
EmPicture::EmPicture(int tsize):size(tsize - 32)
{
if (size <= 0)
data = 0;
else
data = new uchar[size];
}
#ifdef WIN32
#define unlink _unlink
#endif
EmPicture::~EmPicture(void)
{
// clear temporary image file
char *fname = (char *) GetEmbImgname(this);
if (fname && access(fname, 0) == 0)
unlink(fname);
if (data)
delete[]data;
};
bool EmPicture::Read(HWPFile & hwpf)
{
if (size <= 0)
return false;
hwpf.Read1b(name, 16);
hwpf.Read1b(type, 16);
name[0] = 'H';
name[1] = 'W';
name[2] = 'P';
if (hwpf.ReadBlock(data, size) == 0)
return false;
return true;
}
OlePicture::OlePicture(int tsize)
{
size = tsize - 4;
if (size <= 0)
return;
#ifdef WIN32
pis = 0L;
#else
pis = new char[size];
#endif
};
OlePicture::~OlePicture(void)
{
#ifdef WIN32
if( pis )
pis->Release();
#else
delete[] pis;
#endif
};
#define FILESTG_SIGNATURE_NORMAL 0xF8995568
bool OlePicture::Read(HWPFile & hwpf)
{
if (size <= 0)
return false;
// We process only FILESTG_SIGNATURE_NORMAL.
hwpf.Read4b(&signature, 1);
if (signature != FILESTG_SIGNATURE_NORMAL)
return false;
#ifdef WIN32
char *data;
data = new char[size];
if( data == 0 || hwpf.ReadBlock(data,size) == 0 )
return false;
FILE *fp;
char tname[200];
wchar_t wtname[200];
tmpnam(tname);
if (0 == (fp = fopen(tname, "wb")))
return false;
fwrite(data, size, 1, fp);
fclose(fp);
MultiByteToWideChar(CP_ACP, 0, tname, -1, wtname, 200);
if( StgOpenStorage(wtname, NULL,
STGM_READWRITE|STGM_SHARE_EXCLUSIVE|STGM_TRANSACTED,
NULL, 0, &pis) != S_OK ) {
pis = 0;
unlink(tname);
return false;
}
unlink(tname);
delete [] data;
#else
if (pis == 0 || hwpf.ReadBlock(pis, size) == 0)
return false;
#endif
return true;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.42); FILE MERGED 2008/03/28 15:36:39 rt 1.3.42.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: htags.cpp,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
/* NAME
* PURPOSE
*
* NOTES
*
* HISTORY
* frog - Aug 6, 1998: Created.
*/
#include "precompile.h"
#ifdef __GNUG__
#pragma implementation "htags.h"
#endif
#include <string.h>
#include "hwplib.h"
#include "hwpfile.h"
#include "htags.h"
#include "himgutil.h"
bool HyperText::Read(HWPFile & hwpf)
{
hwpf.Read1b(filename, 256);
hwpf.Read2b(bookmark, 16);
hwpf.Read1b(macro, 325);
hwpf.Read1b(&type, 1);
hwpf.Read1b(reserve, 3);
if( type == 2 )
{
for( int i = 1; i < 256; i++)
{
filename[i-1] = filename[i];
if( filename[i] == 0 )
break;
}
}
return true;
}
EmPicture::EmPicture(int tsize):size(tsize - 32)
{
if (size <= 0)
data = 0;
else
data = new uchar[size];
}
#ifdef WIN32
#define unlink _unlink
#endif
EmPicture::~EmPicture(void)
{
// clear temporary image file
char *fname = (char *) GetEmbImgname(this);
if (fname && access(fname, 0) == 0)
unlink(fname);
if (data)
delete[]data;
};
bool EmPicture::Read(HWPFile & hwpf)
{
if (size <= 0)
return false;
hwpf.Read1b(name, 16);
hwpf.Read1b(type, 16);
name[0] = 'H';
name[1] = 'W';
name[2] = 'P';
if (hwpf.ReadBlock(data, size) == 0)
return false;
return true;
}
OlePicture::OlePicture(int tsize)
{
size = tsize - 4;
if (size <= 0)
return;
#ifdef WIN32
pis = 0L;
#else
pis = new char[size];
#endif
};
OlePicture::~OlePicture(void)
{
#ifdef WIN32
if( pis )
pis->Release();
#else
delete[] pis;
#endif
};
#define FILESTG_SIGNATURE_NORMAL 0xF8995568
bool OlePicture::Read(HWPFile & hwpf)
{
if (size <= 0)
return false;
// We process only FILESTG_SIGNATURE_NORMAL.
hwpf.Read4b(&signature, 1);
if (signature != FILESTG_SIGNATURE_NORMAL)
return false;
#ifdef WIN32
char *data;
data = new char[size];
if( data == 0 || hwpf.ReadBlock(data,size) == 0 )
return false;
FILE *fp;
char tname[200];
wchar_t wtname[200];
tmpnam(tname);
if (0 == (fp = fopen(tname, "wb")))
return false;
fwrite(data, size, 1, fp);
fclose(fp);
MultiByteToWideChar(CP_ACP, 0, tname, -1, wtname, 200);
if( StgOpenStorage(wtname, NULL,
STGM_READWRITE|STGM_SHARE_EXCLUSIVE|STGM_TRANSACTED,
NULL, 0, &pis) != S_OK ) {
pis = 0;
unlink(tname);
return false;
}
unlink(tname);
delete [] data;
#else
if (pis == 0 || hwpf.ReadBlock(pis, size) == 0)
return false;
#endif
return true;
}
<|endoftext|> |
<commit_before>//
// Name: UtilDlg.cpp
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "UtilDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"
#include "vtlib/vtlib.h"
#include "vtlib/core/Route.h"
#include "vtlib/core/TerrainScene.h"
#include "UtilDlg.h"
#include "EnviroGUI.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// UtilDlg
//----------------------------------------------------------------------------
// WDR: event table for UtilDlg
BEGIN_EVENT_TABLE(UtilDlg,AutoDialog)
EVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )
END_EVENT_TABLE()
UtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
UtilDialogFunc( this, TRUE );
m_pChoice = GetStructtype();
}
// WDR: handler implementations for UtilDlg
void UtilDlg::OnStructType( wxCommandEvent &event )
{
TransferDataFromWindow();
g_App.SetRouteOptions(m_pChoice->GetStringSelection().mb_str());
g_App.start_new_fence();
}
void UtilDlg::OnInitDialog(wxInitDialogEvent& event)
{
AddValidator(ID_STRUCTTYPE, &m_iType);
m_iType = 0;
vtContentManager &mng = vtGetContent();
m_pChoice->Clear();
for (unsigned int i = 0; i < mng.NumItems(); i++)
{
vtString str;
vtItem *item = mng.GetItem(i);
if (item->GetValueString("type", str))
{
if (str == "utility pole")
m_pChoice->Append(wxString::FromAscii(item->m_name));
}
}
TransferDataToWindow();
g_App.SetRouteOptions(m_pChoice->GetStringSelection().mb_str());
}
<commit_msg>unicode fix<commit_after>//
// Name: UtilDlg.cpp
//
// Copyright (c) 2002-2004 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "UtilDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/image.h"
#include "vtlib/vtlib.h"
#include "vtlib/core/Route.h"
#include "vtlib/core/TerrainScene.h"
#include "UtilDlg.h"
#include "EnviroGUI.h"
#include "vtui/wxString2.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// UtilDlg
//----------------------------------------------------------------------------
// WDR: event table for UtilDlg
BEGIN_EVENT_TABLE(UtilDlg,AutoDialog)
EVT_CHOICE( ID_STRUCTTYPE, UtilDlg::OnStructType )
END_EVENT_TABLE()
UtilDlg::UtilDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
UtilDialogFunc( this, TRUE );
m_pChoice = GetStructtype();
}
// WDR: handler implementations for UtilDlg
void UtilDlg::OnStructType( wxCommandEvent &event )
{
TransferDataFromWindow();
wxString2 val = m_pChoice->GetStringSelection();
g_App.SetRouteOptions(val.mb_str());
g_App.start_new_fence();
}
void UtilDlg::OnInitDialog(wxInitDialogEvent& event)
{
AddValidator(ID_STRUCTTYPE, &m_iType);
m_iType = 0;
vtContentManager &mng = vtGetContent();
m_pChoice->Clear();
for (unsigned int i = 0; i < mng.NumItems(); i++)
{
vtString str;
vtItem *item = mng.GetItem(i);
if (item->GetValueString("type", str))
{
if (str == "utility pole")
m_pChoice->Append(wxString::FromAscii(item->m_name));
}
}
TransferDataToWindow();
wxString2 val = m_pChoice->GetStringSelection();
g_App.SetRouteOptions(val.mb_str());
}
<|endoftext|> |
<commit_before>/*
** File Name: utility.hpp
** Author: Aditya Ramesh
** Date: 07/01/2014
** Contact: [email protected]
*/
#ifndef ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3
#define ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3
#include <ccbase/utility/accessors.hpp>
#include <ccbase/utility/bitmask_enum.hpp>
#include <ccbase/utility/bytes.hpp>
#endif
<commit_msg>Fixed wrong header name.<commit_after>/*
** File Name: utility.hpp
** Author: Aditya Ramesh
** Date: 07/01/2014
** Contact: [email protected]
*/
#ifndef ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3
#define ZAE2F1C3F_A2C8_47F5_8DED_AC1232AEFFD3
#include <ccbase/utility/accessors.hpp>
#include <ccbase/utility/enum_bitmask.hpp>
#include <ccbase/utility/bytes.hpp>
#endif
<|endoftext|> |
<commit_before>#pragma once
/**
@file
@brief int type definition and macros
@author MITSUNARI Shigeo(@herumi)
*/
#if defined(_MSC_VER) && (MSC_VER <= 1500) && !defined(CYBOZU_DEFINED_INTXX)
#define CYBOZU_DEFINED_INTXX
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int uint32_t;
typedef int int32_t;
typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned char uint8_t;
typedef signed char int8_t;
#else
#include <stdint.h>
#endif
#ifdef _MSC_VER
#ifndef CYBOZU_DEFINED_SSIZE_T
#define CYBOZU_DEFINED_SSIZE_T
#ifdef _WIN64
typedef int64_t ssize_t;
#else
typedef int32_t ssize_t;
#endif
#endif
#else
#include <unistd.h> // for ssize_t
#endif
#ifndef CYBOZU_ALIGN
#ifdef _MSC_VER
#define CYBOZU_ALIGN(x) __declspec(align(x))
#else
#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
#ifndef CYBOZU_FORCE_INLINE
#ifdef _MSC_VER
#define CYBOZU_FORCE_INLINE __forceinline
#else
#define CYBOZU_FORCE_INLINE __attribute__((always_inline))
#endif
#endif
#ifndef CYBOZU_UNUSED
#ifdef __GNUC__
#define CYBOZU_UNUSED __attribute__((unused))
#else
#define CYBOZU_UNUSED
#endif
#endif
#ifndef CYBOZU_ALLOCA
#ifdef _MSC_VER
#include <malloc.h>
#define CYBOZU_ALLOCA(x) _malloca(x)
#else
#define CYBOZU_ALLOCA(x) __builtin_alloca(x)
#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
#if defined(_MSC_VER) && (_MSC_VER < 1900)
#define CYBOZU_SNPRINTF(x, len, ...) (void)_snprintf_s(x, len, len - 1, __VA_ARGS__)
#else
#define CYBOZU_SNPRINTF(x, len, ...) (void)snprintf(x, len, __VA_ARGS__)
#endif
#endif
// LLONG_MIN in limits.h is not defined in some env.
#define CYBOZU_LLONG_MIN (-9223372036854775807ll-1)
#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2
#define CYBOZU_CPP_VERSION_CPP14 3
#define CYBOZU_CPP_VERSION_CPP17 4
#ifdef __GNUC__
#define CYBOZU_GNUC_PREREQ(major, minor) ((__GNUC__) * 100 + (__GNUC_MINOR__) >= (major) * 100 + (minor))
#else
#define CYBOZU_GNUC_PREREQ(major, minor) 0
#endif
#if (__cplusplus >= 201703)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP17
#elif (__cplusplus >= 201402)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP14
#elif (__cplusplus >= 201103) || (defined(_MSC_VER) && _MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
#if defined(_MSC_VER) && (_MSC_VER <= 1600)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
#endif
#elif CYBOZU_GNUC_PREREQ(4, 5) || (CYBOZU_GNUC_PREREQ(4, 2) && (defined(__GLIBCXX__) &&__GLIBCXX__ >= 20070719)) || defined(__INTEL_COMPILER) || (__clang_major__ >= 3)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif
#ifdef CYBOZU_USE_BOOST
#define CYBOZU_NAMESPACE_STD boost
#define CYBOZU_NAMESPACE_TR1_BEGIN
#define CYBOZU_NAMESPACE_TR1_END
#elif (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1) && !defined(__APPLE__)
#define CYBOZU_NAMESPACE_STD std::tr1
#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
#define CYBOZU_NAMESPACE_TR1_END }
#else
#define CYBOZU_NAMESPACE_STD std
#define CYBOZU_NAMESPACE_TR1_BEGIN
#define CYBOZU_NAMESPACE_TR1_END
#endif
#ifndef CYBOZU_OS_BIT
#if defined(_WIN64) || defined(__x86_64__) || defined(__AARCH64EL__) || defined(__EMSCRIPTEN__)
#define CYBOZU_OS_BIT 64
#else
#define CYBOZU_OS_BIT 32
#endif
#endif
#ifndef CYBOZU_HOST
#define CYBOZU_HOST_UNKNOWN 0
#define CYBOZU_HOST_INTEL 1
#define CYBOZU_HOST_ARM 2
#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
#define CYBOZU_HOST CYBOZU_HOST_INTEL
#elif defined(__arm__) || defined(__AARCH64EL__)
#define CYBOZU_HOST CYBOZU_HOST_ARM
#else
#define CYBOZU_HOST CYBOZU_HOST_UNKNOWN
#endif
#endif
#ifndef CYBOZU_ENDIAN
#define CYBOZU_ENDIAN_UNKNOWN 0
#define CYBOZU_ENDIAN_LITTLE 1
#define CYBOZU_ENDIAN_BIG 2
#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
#elif (CYBOZU_HOST == CYBOZU_HOST_ARM) && (defined(__ARM_EABI__) || defined(__AARCH64EL__))
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
#else
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
#endif
#endif
#if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11
#define CYBOZU_NOEXCEPT noexcept
#define CYBOZU_NULLPTR nullptr
#else
#define CYBOZU_NOEXCEPT throw()
#define CYBOZU_NULLPTR 0
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<commit_msg>check LP64 and s390x<commit_after>#pragma once
/**
@file
@brief int type definition and macros
@author MITSUNARI Shigeo(@herumi)
*/
#if defined(_MSC_VER) && (MSC_VER <= 1500) && !defined(CYBOZU_DEFINED_INTXX)
#define CYBOZU_DEFINED_INTXX
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned int uint32_t;
typedef int int32_t;
typedef unsigned short uint16_t;
typedef short int16_t;
typedef unsigned char uint8_t;
typedef signed char int8_t;
#else
#include <stdint.h>
#endif
#ifdef _MSC_VER
#ifndef CYBOZU_DEFINED_SSIZE_T
#define CYBOZU_DEFINED_SSIZE_T
#ifdef _WIN64
typedef int64_t ssize_t;
#else
typedef int32_t ssize_t;
#endif
#endif
#else
#include <unistd.h> // for ssize_t
#endif
#ifndef CYBOZU_ALIGN
#ifdef _MSC_VER
#define CYBOZU_ALIGN(x) __declspec(align(x))
#else
#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))
#endif
#endif
#ifndef CYBOZU_FORCE_INLINE
#ifdef _MSC_VER
#define CYBOZU_FORCE_INLINE __forceinline
#else
#define CYBOZU_FORCE_INLINE __attribute__((always_inline))
#endif
#endif
#ifndef CYBOZU_UNUSED
#ifdef __GNUC__
#define CYBOZU_UNUSED __attribute__((unused))
#else
#define CYBOZU_UNUSED
#endif
#endif
#ifndef CYBOZU_ALLOCA
#ifdef _MSC_VER
#include <malloc.h>
#define CYBOZU_ALLOCA(x) _malloca(x)
#else
#define CYBOZU_ALLOCA(x) __builtin_alloca(x)
#endif
#endif
#ifndef CYBOZU_NUM_OF_ARRAY
#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) / sizeof(*x))
#endif
#ifndef CYBOZU_SNPRINTF
#if defined(_MSC_VER) && (_MSC_VER < 1900)
#define CYBOZU_SNPRINTF(x, len, ...) (void)_snprintf_s(x, len, len - 1, __VA_ARGS__)
#else
#define CYBOZU_SNPRINTF(x, len, ...) (void)snprintf(x, len, __VA_ARGS__)
#endif
#endif
// LLONG_MIN in limits.h is not defined in some env.
#define CYBOZU_LLONG_MIN (-9223372036854775807ll-1)
#define CYBOZU_CPP_VERSION_CPP03 0
#define CYBOZU_CPP_VERSION_TR1 1
#define CYBOZU_CPP_VERSION_CPP11 2
#define CYBOZU_CPP_VERSION_CPP14 3
#define CYBOZU_CPP_VERSION_CPP17 4
#ifdef __GNUC__
#define CYBOZU_GNUC_PREREQ(major, minor) ((__GNUC__) * 100 + (__GNUC_MINOR__) >= (major) * 100 + (minor))
#else
#define CYBOZU_GNUC_PREREQ(major, minor) 0
#endif
#if (__cplusplus >= 201703)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP17
#elif (__cplusplus >= 201402)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP14
#elif (__cplusplus >= 201103) || (defined(_MSC_VER) && _MSC_VER >= 1500) || defined(__GXX_EXPERIMENTAL_CXX0X__)
#if defined(_MSC_VER) && (_MSC_VER <= 1600)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP11
#endif
#elif CYBOZU_GNUC_PREREQ(4, 5) || (CYBOZU_GNUC_PREREQ(4, 2) && (defined(__GLIBCXX__) &&__GLIBCXX__ >= 20070719)) || defined(__INTEL_COMPILER) || (__clang_major__ >= 3)
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_TR1
#else
#define CYBOZU_CPP_VERSION CYBOZU_CPP_VERSION_CPP03
#endif
#ifdef CYBOZU_USE_BOOST
#define CYBOZU_NAMESPACE_STD boost
#define CYBOZU_NAMESPACE_TR1_BEGIN
#define CYBOZU_NAMESPACE_TR1_END
#elif (CYBOZU_CPP_VERSION == CYBOZU_CPP_VERSION_TR1) && !defined(__APPLE__)
#define CYBOZU_NAMESPACE_STD std::tr1
#define CYBOZU_NAMESPACE_TR1_BEGIN namespace tr1 {
#define CYBOZU_NAMESPACE_TR1_END }
#else
#define CYBOZU_NAMESPACE_STD std
#define CYBOZU_NAMESPACE_TR1_BEGIN
#define CYBOZU_NAMESPACE_TR1_END
#endif
#ifndef CYBOZU_OS_BIT
#if defined(_WIN64) || defined(__x86_64__) || defined(__AARCH64EL__) || defined(__EMSCRIPTEN__) || defined(__LP64__)
#define CYBOZU_OS_BIT 64
#else
#define CYBOZU_OS_BIT 32
#endif
#endif
#ifndef CYBOZU_HOST
#define CYBOZU_HOST_UNKNOWN 0
#define CYBOZU_HOST_INTEL 1
#define CYBOZU_HOST_ARM 2
#if defined(_M_IX86) || defined(_M_AMD64) || defined(__x86_64__) || defined(__i386__)
#define CYBOZU_HOST CYBOZU_HOST_INTEL
#elif defined(__arm__) || defined(__AARCH64EL__)
#define CYBOZU_HOST CYBOZU_HOST_ARM
#else
#define CYBOZU_HOST CYBOZU_HOST_UNKNOWN
#endif
#endif
#ifndef CYBOZU_ENDIAN
#define CYBOZU_ENDIAN_UNKNOWN 0
#define CYBOZU_ENDIAN_LITTLE 1
#define CYBOZU_ENDIAN_BIG 2
#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
#elif (CYBOZU_HOST == CYBOZU_HOST_ARM) && (defined(__ARM_EABI__) || defined(__AARCH64EL__))
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_LITTLE
#elif defined(__s390x__)
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_BIG
#else
#define CYBOZU_ENDIAN CYBOZU_ENDIAN_UNKNOWN
#endif
#endif
#if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11
#define CYBOZU_NOEXCEPT noexcept
#define CYBOZU_NULLPTR nullptr
#else
#define CYBOZU_NOEXCEPT throw()
#define CYBOZU_NULLPTR 0
#endif
namespace cybozu {
template<class T>
void disable_warning_unused_variable(const T&) { }
template<class T, class S>
T cast(const S* ptr) { return static_cast<T>(static_cast<const void*>(ptr)); }
template<class T, class S>
T cast(S* ptr) { return static_cast<T>(static_cast<void*>(ptr)); }
} // cybozu
<|endoftext|> |
<commit_before>#ifndef _litesql_sqlast_hpp_
#define _litesql_sqlast_hpp_
#include "litesql/sql.hpp"
namespace litesql {
namespace sql {
class Translator;
/** Abstract syntax tree node */
class AST {
public:
virtual ~AST() {}
virtual std::string toString() const=0;
virtual SQL* translate(Translator& t) = 0;
};
/** Raw SQL-injection */
class Raw {
public:
virtual void accept(Visitor& v);
};
/** SQL SELECT statement */
class Select : public Stmt {
public:
virtual void accept(Visitor& v);
};
/** SELECT result set field or expression */
class Result : public AST {
public:
virtual void accept(Visitor& v);
};
/** FROM-expression in SELECT-clause */
class Sources : public AST {
public:
virtual void accept(Visitor& v);
};
/** Single FROM-source in SELECT-clause */
class FromSource : public AST {
};
/** FROM (table)-expression in SELECT-clause */
class FromTable : public FromSource {
};
/** FROM (select)-expression in SELECT-clause */
class FromSelect : public FromSource {
};
/** Base class for joins */
class Join : public AST {
};
/** CROSS JOIN */
class CrossJoin : public Join {
};
/** INNER JOIN _ ON _ */
class InnerJoin : public Join {
};
/** LEFT OUTER JOIN _ ON _ */
class LeftOuterJoin : public Join {
};
/** RIGHT OUTER JOIN _ ON _ */
class RightOuterJoin : public Join {
};
/** FULL OUTER JOIN _ ON _ */
class FullOuterJoin : public Join {
};
/** Base class for compound operations */
class CompoundOp : public AST {
};
/** UNION SELECT _ */
class Union : public CompoundOp {
};
/** INTERSECT SELECT _ */
class Intersect : public CompoundOp {
};
/** EXCEPT SELECT _ */
class Except : public CompoundOp {
};
/** ORDER BY-part of SELECT-statement */
class OrderBy : public AST {
};
/** Base class for expressions */
class Expr : public AST {
};
/** Base class for unary operator expressions */
class UnOp : public Expr {
};
/** NOT (_) */
class Not : public UnOp {
};
/** -(_) */
class UnaryMinus : public UnOp {
};
/** Base class for binary operator expressions */
class BinOp : public Expr {
};
/** _ = _ */
class Eq : public BinOp {
};
/** _ <> _ */
class Neq : public BinOp {
};
/** _ < _ */
class Lt : public BinOp {
};
/** _ <= _ */
class LtEq : public BinOp {
};
/** _ > _ */
class Gt : public BinOp {
};
/** _ >= _ */
class GtEq : public BinOp {
};
/** (_) OR (_) */
class Or : public BinOp {
};
/** (_) AND (_) */
class And : public BinOp {
};
/** _ LIKE _ */
class Like : public BinOp {
};
/** _ REGEXP _ */
class RegExp : public BinOp {
};
/** _ IS NULL */
class IsNull : public BinOp {
};
/** _ IN (_) */
class In : public BinOp {
};
/** _ || _ */
class Concat : public BinOp {
};
/** _ % _ */
class Mod : public BinOp {
};
/** _ / _ */
class Div : public BinOp {
};
/** _ * _ */
class Mul : public BinOp {
};
/** _ + _ */
class Add : public BinOp {
};
/** _ - _ */
class Sub : public BinOp {
};
/** Converts a list of values to a list expression */
class List : public BinOp {
};
/** Converts a value (int, string, whatever) to an expression */
class ValueExpr : public Expr {
};
/** Value of a field of the result set-expression */
class FieldExpr : public Expr {
};
/** The sequence used in the INSERT-operation */
class FromSequence : public AST {
};
/** Atomic multi-table insert that will assign rows with
same new unique identifier to multiple tables */
class Insert : public Stmt {
};
/** Insertion to one table */
class ToTable : public AST {
};
/** Assignment to a field */
class Assign : public AST {
};
/** UPDATE statement */
class Update : public Stmt {
};
/** DELETE statement */
class Delete : public Stmt {
};
/** CREATE TABLE statement */
class CreateTable : public Stmt {
};
/** DROP TABLE statement */
class DropTable : public Stmt {
};
/** Field definition to be used in CREATE table statement */
class Field : public AST {
};
/** Base class for field constraints */
class FieldConstraint : public AST {
};
/** NOT NULL constraint for a field */
class FieldNotNull : public FieldConstraint {
};
/** PRIMARY KEY constraint for a field */
class FieldPrimaryKey : public FieldConstraint {
};
/** UNIQUE constraint for a field */
class FieldUnique : public FieldConstraint {
};
/** CHECK constraint for a field */
class FieldCheck : public FieldConstraint {
};
/** DEFAULT value for a field */
class FieldDefault : public FieldConstraint {
};
/** FOREIGN KEY reference for a field */
class FieldReference : public FieldConstraint {
};
/** Base class for actions */
class Action : public AST {
};
/** CASCADE action (when a referenced row is deleted) */
class Cascade : public Action {
};
/** SET NULL action (when a referenced row is deleted) */
class SetNull : public Action {
};
/** Base class for table specific constraints */
class TableConstraint : public AST {
};
/** multiple field PRIMARY KEY constraint */
class TablePrimaryKey : public TableConstraint {
};
/** CREATE INDEX statement */
class CreateIndex : public Stmt {
};
/** DROP INDEX statement */
class DropIndex : public Stmt {
};
/** AST translator base class */
class Translator {
public:
virtual SQL* trnsRaw(Raw*);
virtual SQL* trnsSelect(Select*);
virtual SQL* trnsResult(Result*);
virtual SQL* trnsSources(Sources*);
virtual SQL* trnsFromSource(FromSource*);
virtual SQL* trnsFromSelect(FromSelect*);
virtual SQL* trnsCrossJoin(CrossJoin*);
virtual SQL* trnsInnerJoin(InnerJoin*);
virtual SQL* trnsLeftOuterJoin(LeftOuterJoin*);
virtual SQL* trnsRightOuterJoin(RightOuterJoin*);
virtual SQL* trnsFullOuterJoin(FullOuterJoin*);
virtual SQL* trnsUnion(Union*);
virtual SQL* trnsIntersect(Intersect*);
virtual SQL* trnsExcept(Except*);
virtual SQL* trnsOrderBy(OrderBy*);
virtual SQL* trnsNot(Not*);
virtual SQL* trnsUnaryMinus(UnaryMinus*);
virtual SQL* trnsEq(Eq*);
virtual SQL* trnsNeq(Neq*);
virtual SQL* trnsLt(Lt*);
virtual SQL* trnsLtEq(LtEq*);
virtual SQL* trnsGt(Gt*);
virtual SQL* trnsGtEq(GtEq*);
virtual SQL* trnsOr(Or*);
virtual SQL* trnsAnd(And*);
virtual SQL* trnsLike(Like*);
virtual SQL* trnsRegExp(RegExp*);
virtual SQL* trnsIsNull(IsNull*);
virtual SQL* trnsIn(In*);
virtual SQL* trnsConcat(Concat*);
virtual SQL* trnsMod(Mod*);
virtual SQL* trnsDiv(Div*);
virtual SQL* trnsMul(Mul*);
virtual SQL* trnsAdd(Add*);
virtual SQL* trnsSub(Sub*);
virtual SQL* trnsList(List*);
virtual SQL* trnsValueExpr(ValueExpr*);
virtual SQL* trnsFieldExpr(FieldExpr*);
virtual SQL* trnsFromSequence(FromSequence*);
virtual SQL* trnsInsert(Insert*);
virtual SQL* trnsToTable(ToTable*);
virtual SQL* trnsAssign(Assign*);
virtual SQL* trnsUpdate(Update*);
virtual SQL* trnsDelete(Delete*);
virtual SQL* trnsCreateTable(CreateTable*);
virtual SQL* trnsDropTable(DropTable*);
virtual SQL* trnsField(Field*);
virtual SQL* trnsFieldConstraint(FieldConstraint*);
virtual SQL* trnsFieldPrimaryKey(FieldPrimaryKey*);
virtual SQL* trnsFieldUnique(FieldUnique*);
virtual SQL* trnsFieldCheck(FieldCheck*);
virtual SQL* trnsFieldDefault(FieldDefault*);
virtual SQL* trnsFieldReference(FieldReference*);
virtual SQL* trnsCascade(Cascade*);
virtual SQL* trnsSetNull(SetNull*);
virtual SQL* trnsTablePrimaryKey(TablePrimaryKey*);
virtual SQL* trnsCreateIndex(CreateIndex*);
virtual SQL* trnsDropIndex(DropIndex*);
};
}
}
#endif
<commit_msg>translate methods<commit_after>#ifndef _litesql_sqlast_hpp_
#define _litesql_sqlast_hpp_
#include "litesql/sql.hpp"
namespace litesql {
namespace ast {
class Raw;
class Select;
class Result;
class Sources;
class FromSource;
class FromSelect;
class CrossJoin;
class InnerJoin;
class LeftOuterJoin;
class RightOuterJoin;
class FullOuterJoin;
class Union;
class Intersect;
class Except;
class OrderBy;
class Not;
class UnaryMinus;
class Eq;
class Neq;
class Lt;
class LtEq;
class Gt;
class GtEq;
class Or;
class And;
class Like;
class RegExp;
class IsNull;
class In;
class Concat;
class Mod;
class Div;
class Mul;
class Add;
class Sub;
class List;
class ValueExpr;
class FieldExpr;
class FromSequence;
class Insert;
class ToTable;
class Assign;
class Update;
class Delete;
class CreateTable;
class DropTable;
class Field;
class FieldConstraint;
class FieldPrimaryKey;
class FieldUnique;
class FieldCheck;
class FieldDefault;
class FieldReference;
class Cascade;
class SetNull;
class TablePrimaryKey;
class CreateIndex;
class DropIndex;
/** AST translator base class */
class Translator {
public:
virtual ~Translator() {}
virtual sql::SQL* translateRaw(Raw*)=0;
virtual sql::SQL* translateSelect(Select*)=0;
virtual sql::SQL* translateResult(Result*)=0;
virtual sql::SQL* translateSources(Sources*)=0;
virtual sql::SQL* translateFromSource(FromSource*)=0;
virtual sql::SQL* translateFromSelect(FromSelect*)=0;
virtual sql::SQL* translateCrossJoin(CrossJoin*)=0;
virtual sql::SQL* translateInnerJoin(InnerJoin*)=0;
virtual sql::SQL* translateLeftOuterJoin(LeftOuterJoin*)=0;
virtual sql::SQL* translateRightOuterJoin(RightOuterJoin*)=0;
virtual sql::SQL* translateFullOuterJoin(FullOuterJoin*)=0;
virtual sql::SQL* translateUnion(Union*)=0;
virtual sql::SQL* translateIntersect(Intersect*)=0;
virtual sql::SQL* translateExcept(Except*)=0;
virtual sql::SQL* translateOrderBy(OrderBy*)=0;
virtual sql::SQL* translateNot(Not*)=0;
virtual sql::SQL* translateUnaryMinus(UnaryMinus*)=0;
virtual sql::SQL* translateEq(Eq*)=0;
virtual sql::SQL* translateNeq(Neq*)=0;
virtual sql::SQL* translateLt(Lt*)=0;
virtual sql::SQL* translateLtEq(LtEq*)=0;
virtual sql::SQL* translateGt(Gt*)=0;
virtual sql::SQL* translateGtEq(GtEq*)=0;
virtual sql::SQL* translateOr(Or*)=0;
virtual sql::SQL* translateAnd(And*)=0;
virtual sql::SQL* translateLike(Like*)=0;
virtual sql::SQL* translateRegExp(RegExp*)=0;
virtual sql::SQL* translateIsNull(IsNull*)=0;
virtual sql::SQL* translateIn(In*)=0;
virtual sql::SQL* translateConcat(Concat*)=0;
virtual sql::SQL* translateMod(Mod*)=0;
virtual sql::SQL* translateDiv(Div*)=0;
virtual sql::SQL* translateMul(Mul*)=0;
virtual sql::SQL* translateAdd(Add*)=0;
virtual sql::SQL* translateSub(Sub*)=0;
virtual sql::SQL* translateList(List*)=0;
virtual sql::SQL* translateValueExpr(ValueExpr*)=0;
virtual sql::SQL* translateFieldExpr(FieldExpr*)=0;
virtual sql::SQL* translateFromSequence(FromSequence*)=0;
virtual sql::SQL* translateInsert(Insert*)=0;
virtual sql::SQL* translateToTable(ToTable*)=0;
virtual sql::SQL* translateAssign(Assign*)=0;
virtual sql::SQL* translateUpdate(Update*)=0;
virtual sql::SQL* translateDelete(Delete*)=0;
virtual sql::SQL* translateCreateTable(CreateTable*)=0;
virtual sql::SQL* translateDropTable(DropTable*)=0;
virtual sql::SQL* translateField(Field*)=0;
virtual sql::SQL* translateFieldConstraint(FieldConstraint*)=0;
virtual sql::SQL* translateFieldPrimaryKey(FieldPrimaryKey*)=0;
virtual sql::SQL* translateFieldUnique(FieldUnique*)=0;
virtual sql::SQL* translateFieldCheck(FieldCheck*)=0;
virtual sql::SQL* translateFieldDefault(FieldDefault*)=0;
virtual sql::SQL* translateFieldReference(FieldReference*)=0;
virtual sql::SQL* translateCascade(Cascade*)=0;
virtual sql::SQL* translateSetNull(SetNull*)=0;
virtual sql::SQL* translateTablePrimaryKey(TablePrimaryKey*)=0;
virtual sql::SQL* translateCreateIndex(CreateIndex*)=0;
virtual sql::SQL* translateDropIndex(DropIndex*)=0;
};
/** Abstract syntax tree node */
class AST {
public:
virtual ~AST() {}
virtual std::string toString() const=0;
virtual sql::SQL* translate(Translator& t) = 0;
};
/** AST base template which generates
a translate method */
template <class Base, class T>
class ASTBase : public Base {
public:
virtual sql::SQL* translate(Translator& translator) {
return translator.translate(reinterpret_cast<T*>(this));
}
};
/** Raw sql::SQL-injection */
class Raw : public ASTBase<AST, Raw> {
public:
};
/** sql::SQL SELECT statement */
class Select : public ASTBase<Stmt, Raw> {
public:
};
/** SELECT result set field or expression */
class Result : public ASTBase<AST, Result> {
public:
};
/** FROM-expression in SELECT-clause */
class Sources : public ASTBase<AST, Sources> {
public:
};
/** Single FROM-source in SELECT-clause */
class FromSource : public AST {
};
/** FROM (table)-expression in SELECT-clause */
class FromTable : public ASTBase<FromSource, FromTable> {
};
/** FROM (select)-expression in SELECT-clause */
class FromSelect : public ASTBase<FromSource, FromSelect> {
};
/** Base class for joins */
class Join : public AST {
};
/** CROSS JOIN */
class CrossJoin : public ASTBase<Join, CrossJoin> {
};
/** INNER JOIN _ ON _ */
class InnerJoin : public ASTBase<Join, InnerJoin> {
};
/** LEFT OUTER JOIN _ ON _ */
class LeftOuterJoin : public ASTBase<Join, LeftOuterJoin> {
};
/** RIGHT OUTER JOIN _ ON _ */
class RightOuterJoin : public ASTBase<Join, RightOuterJoin> {
};
/** FULL OUTER JOIN _ ON _ */
class FullOuterJoin : public ASTBase<Join, FullOuterJoin> {
};
/** Base class for compound operations */
class CompoundOp : public AST {
};
/** UNION SELECT _ */
class Union : public ASTBase<CompoundOp, Union> {
};
/** INTERSECT SELECT _ */
class Intersect : public ASTBase<CompoundOp, Intersect> {
};
/** EXCEPT SELECT _ */
class Except : public ASTBase<CompoundOp, Except> {
};
/** ORDER BY-part of SELECT-statement */
class OrderBy : public ASTBase<AST, OrderBy> {
};
/** Base class for expressions */
class Expr : public AST {
};
/** Base class for unary operator expressions */
class UnOp : public Expr {
};
/** NOT (_) */
class Not : public ASTBase<UnOp, Not> {
};
/** -(_) */
class UnaryMinus : public ASTBase<UnOp, UnaryMinus> {
};
/** Base class for binary operator expressions */
class BinOp : public Expr {
};
/** _ = _ */
class Eq : public ASTBase<BinOp, Eq> {
};
/** _ <> _ */
class Neq : public ASTBase<BinOp, Neq> {
};
/** _ < _ */
class Lt : public ASTBase<BinOp, Lt> {
};
/** _ <= _ */
class LtEq : public ASTBase<BinOp, LtEq> {
};
/** _ > _ */
class Gt : public ASTBase<BinOp, Gt> {
};
/** _ >= _ */
class GtEq : public ASTBase<BinOp, GtEq> {
};
/** (_) OR (_) */
class Or : public ASTBase<BinOp, Or> {
};
/** (_) AND (_) */
class And : public ASTBase<BinOp, And> {
};
/** _ LIKE _ */
class Like : public ASTBase<BinOp, Like> {
};
/** _ REGEXP _ */
class RegExp : public ASTBase<BinOp, RegExp> {
};
/** _ IS NULL */
class IsNull : public ASTBase<BinOp, IsNull> {
};
/** _ IN (_) */
class In : public ASTBase<BinOp, In> {
};
/** _ || _ */
class Concat : public ASTBase<BinOp, Concat> {
};
/** _ % _ */
class Mod : public ASTBase<BinOp, Mod> {
};
/** _ / _ */
class Div : public ASTBase<BinOp, Div> {
};
/** _ * _ */
class Mul : public ASTBase<BinOp, Mul> {
};
/** _ + _ */
class Add : public ASTBase<BinOp, Add> {
};
/** _ - _ */
class Sub : public ASTBase<BinOp, Sub> {
};
/** Converts a list of values to a list expression */
class List : public ASTBase<BinOp, List> {
};
/** Converts a value (int, string, whatever) to an expression */
class ValueExpr : public ASTBase<BinOp, ValueExpr> {
};
/** Value of a field of the result set-expression */
class FieldExpr : public ASTBase<BinOp, FieldExpr> {
};
/** The sequence used in the INSERT-operation */
class FromSequence : public ASTBase<Ast, FromSequence> {
};
/** Atomic multi-table insert that will assign rows with
same new unique identifier to multiple tables */
class Insert : public ASTBase<Stmt, Insert> {
};
/** Insertion to one table */
class ToTable : public ASTBase<AST, ToTable> {
};
/** Assignment to a field */
class Assign : public ASTBase<AST, Assign> {
};
/** UPDATE statement */
class Update : public ASTBase<Stmt, Update> {
};
/** DELETE statement */
class Delete : public ASTBase<Stmt, Delete> {
};
/** CREATE TABLE statement */
class CreateTable : public ASTBase<Stmt, CreateTable> {
};
/** DROP TABLE statement */
class DropTable : public ASTBase<Stmt, DropTable> {
};
/** Field definition to be used in CREATE table statement */
class Field : public ASTBase<AST, Field> {
};
/** Base class for field constraints */
class FieldConstraint : public ASTBase<AST, FieldConstraint> {
};
/** NOT NULL constraint for a field */
class FieldNotNull : public ASTBase<FieldConstraint, FieldNotNull> {
};
/** PRIMARY KEY constraint for a field */
class FieldPrimaryKey : public ASTBase<FieldConstraint, FieldPrimaryKey> {
};
/** UNIQUE constraint for a field */
class FieldUnique : public ASTBase<FieldConstraint, FieldUnique> {
};
/** CHECK constraint for a field */
class FieldCheck : public ASTBase<FieldConstraint, FieldCheck> {
};
/** DEFAULT value for a field */
class FieldDefault : public ASTBase<FieldConstraint, FieldDefault> {
};
/** FOREIGN KEY reference for a field */
class FieldReference : public ASTBase<FieldConstraint, FieldReference> {
};
/** Base class for actions */
class Action : public AST {
};
/** CASCADE action (when a referenced row is deleted) */
class Cascade : public ASTBase<Action, Cascade> {
};
/** SET NULL action (when a referenced row is deleted) */
class SetNull : public ASTBase<Action, SetNull> {
};
/** Base class for table specific constraints */
class TableConstraint : public AST {
};
/** multiple field PRIMARY KEY constraint */
class TablePrimaryKey : public ASTBase<TableConstraint,
TablePrimaryKey> {
};
/** CREATE INDEX statement */
class CreateIndex : public ASTBase<Stmt, CreateIndex> {
};
/** DROP INDEX statement */
class DropIndex : public ASTBase<Stmt, DropIndex> {
};
}
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP
#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>
extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}
namespace mapnik {
static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
std::streamsize request_size = size;
if (static_cast<tsize_t>(request_size) != size)
return static_cast<tsize_t>(-1);
out->write(reinterpret_cast<const char*>(buf), size);
if( static_cast<std::streamsize>(pos) == -1 )
{
return size;
}
else
{
return static_cast<tsize_t>(out->tellp()-pos);
}
}
static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
if( out->fail() )
return static_cast<toff_t>(-1);
if( static_cast<std::streamsize>(out->tellp()) == -1)
return static_cast< toff_t >( 0 );
switch(whence)
{
case SEEK_SET:
out->seekp(off, std::ios_base::beg);
break;
case SEEK_CUR:
out->seekp(off, std::ios_base::cur);
break;
case SEEK_END:
out->seekp(off, std::ios_base::end);
break;
}
// grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
std::ios::pos_type pos = out->tellp();
// second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size
if( out->fail() || static_cast<std::streamoff>(off) != pos)
{
std::ios::iostate old_state;
std::ios::pos_type origin;
old_state = out->rdstate();
// reset the fail bit or else tellp() won't work below
out->clear(out->rdstate() & ~std::ios::failbit);
switch( whence )
{
case SEEK_SET:
default:
origin = 0L;
break;
case SEEK_CUR:
origin = out->tellp();
break;
case SEEK_END:
out->seekp(0, std::ios::end);
origin = out->tellp();
break;
}
// restore original stream state
out->clear(old_state);
// only do something if desired seek position is valid
if( (static_cast<uint64_t>(origin) + off) > 0L)
{
uint64_t num_fill;
// clear the fail bit
out->clear(out->rdstate() & ~std::ios::failbit);
// extend the stream to the expected size
out->seekp(0, std::ios::end);
num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
for( uint64_t i = 0; i < num_fill; ++i)
out->put('\0');
// retry the seek
out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
}
}
return static_cast<toff_t>(out->tellp());
}
static inline int tiff_close_proc(thandle_t fd)
{
std::ostream* out = (std::ostream*)fd;
out->flush();
return 0;
}
static inline toff_t tiff_size_proc(thandle_t fd)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
out->seekp(0, std::ios::end);
std::ios::pos_type len = out->tellp();
out->seekp(pos);
return static_cast<toff_t>(len);
}
static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
return 0;
}
static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}
static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
return 0;
}
struct tiff_config
{
tiff_config()
: compression(COMPRESSION_ADOBE_DEFLATE),
zlevel(4),
scanline(false) {}
int compression;
int zlevel;
bool scanline;
};
struct tag_setter : public mapnik::util::static_visitor<>
{
tag_setter(TIFF * output, tiff_config & config)
: output_(output),
config_(config) {}
template <typename T>
void operator() (T const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - unknown image type provided");
}
inline void operator() (image_data_rgba8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray32f const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
}
}
inline void operator() (image_data_gray16 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_null const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - Null image provided");
}
private:
TIFF * output_;
tiff_config config_;
};
void set_tiff_config(TIFF* output, tiff_config & config)
{
// Set some constant tiff information that doesn't vary based on type of data
// or image size
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
// Set the compression for the TIFF
TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);
if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
{
// Set the zip level for the compression
// http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
// Changes the time spent trying to compress
TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
}
}
template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
const int width = image.width();
const int height = image.height();
TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
"wm",
(thandle_t)&file,
tiff_dummy_read_proc,
tiff_write_proc,
tiff_seek_proc,
tiff_close_proc,
tiff_size_proc,
tiff_dummy_map_proc,
tiff_dummy_unmap_proc);
if (! output)
{
throw ImageWriterException("Could not write TIFF");
}
TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);
set_tiff_config(output, config);
// Set tags that vary based on the type of data being provided.
tag_setter set(output, config);
set(image);
//util::apply_visitor(set, image);
// If the image is greater then 8MB uncompressed, then lets use scanline rather then
// tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
// a multiple of 16, if they are not we will use scanline.
if (image.getSize() > 8 * 32 * 1024 * 1024
|| width % 16 != 0
|| height % 16 != 0
|| config.scanline)
{
// Process Scanline
TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);
int next_scanline = 0;
while (next_scanline < height)
{
TIFFWriteScanline(output, const_cast<typename T2::pixel_type*>(image.getRow(next_scanline)), next_scanline, 0);
++next_scanline;
}
}
else
{
TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
TIFFSetField(output, TIFFTAG_TILELENGTH, height);
TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
// Process as tiles
TIFFWriteTile(output, const_cast<typename T2::pixel_type*>(image.getData()), 0, 0, 0, 0);
}
// TODO - handle palette images
// std::vector<mapnik::rgb> const& palette
// unsigned short r[256], g[256], b[256];
// for (int i = 0; i < (1 << 24); ++i)
// {
// r[i] = (unsigned short)palette[i * 3 + 0] << 8;
// g[i] = (unsigned short)palette[i * 3 + 1] << 8;
// b[i] = (unsigned short)palette[i * 3 + 2] << 8;
// }
// TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
// TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);
RealTIFFClose(output);
}
}
#endif // MAPNIK_TIFF_IO_HPP
<commit_msg>Revert "avoid allocating memory"<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2014 Artem Pavlenko
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_TIFF_IO_HPP
#define MAPNIK_TIFF_IO_HPP
#include <mapnik/global.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/image_data_any.hpp>
#include <mapnik/util/variant.hpp>
extern "C"
{
#include <tiffio.h>
#define RealTIFFOpen TIFFClientOpen
#define RealTIFFClose TIFFClose
}
namespace mapnik {
static inline tsize_t tiff_write_proc(thandle_t fd, tdata_t buf, tsize_t size)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
std::streamsize request_size = size;
if (static_cast<tsize_t>(request_size) != size)
return static_cast<tsize_t>(-1);
out->write(reinterpret_cast<const char*>(buf), size);
if( static_cast<std::streamsize>(pos) == -1 )
{
return size;
}
else
{
return static_cast<tsize_t>(out->tellp()-pos);
}
}
static inline toff_t tiff_seek_proc(thandle_t fd, toff_t off, int whence)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
if( out->fail() )
return static_cast<toff_t>(-1);
if( static_cast<std::streamsize>(out->tellp()) == -1)
return static_cast< toff_t >( 0 );
switch(whence)
{
case SEEK_SET:
out->seekp(off, std::ios_base::beg);
break;
case SEEK_CUR:
out->seekp(off, std::ios_base::cur);
break;
case SEEK_END:
out->seekp(off, std::ios_base::end);
break;
}
// grow std::stringstream buffer (re: libtiff/tif_stream.cxx)
std::ios::pos_type pos = out->tellp();
// second check needed for clang (libcxx doesn't set failbit when seeking beyond the current buffer size
if( out->fail() || static_cast<std::streamoff>(off) != pos)
{
std::ios::iostate old_state;
std::ios::pos_type origin;
old_state = out->rdstate();
// reset the fail bit or else tellp() won't work below
out->clear(out->rdstate() & ~std::ios::failbit);
switch( whence )
{
case SEEK_SET:
default:
origin = 0L;
break;
case SEEK_CUR:
origin = out->tellp();
break;
case SEEK_END:
out->seekp(0, std::ios::end);
origin = out->tellp();
break;
}
// restore original stream state
out->clear(old_state);
// only do something if desired seek position is valid
if( (static_cast<uint64_t>(origin) + off) > 0L)
{
uint64_t num_fill;
// clear the fail bit
out->clear(out->rdstate() & ~std::ios::failbit);
// extend the stream to the expected size
out->seekp(0, std::ios::end);
num_fill = (static_cast<uint64_t>(origin)) + off - out->tellp();
for( uint64_t i = 0; i < num_fill; ++i)
out->put('\0');
// retry the seek
out->seekp(static_cast<std::ios::off_type>(static_cast<uint64_t>(origin) + off), std::ios::beg);
}
}
return static_cast<toff_t>(out->tellp());
}
static inline int tiff_close_proc(thandle_t fd)
{
std::ostream* out = (std::ostream*)fd;
out->flush();
return 0;
}
static inline toff_t tiff_size_proc(thandle_t fd)
{
std::ostream* out = reinterpret_cast<std::ostream*>(fd);
std::ios::pos_type pos = out->tellp();
out->seekp(0, std::ios::end);
std::ios::pos_type len = out->tellp();
out->seekp(pos);
return static_cast<toff_t>(len);
}
static inline tsize_t tiff_dummy_read_proc(thandle_t , tdata_t , tsize_t)
{
return 0;
}
static inline void tiff_dummy_unmap_proc(thandle_t , tdata_t , toff_t) {}
static inline int tiff_dummy_map_proc(thandle_t , tdata_t*, toff_t* )
{
return 0;
}
struct tiff_config
{
tiff_config()
: compression(COMPRESSION_ADOBE_DEFLATE),
zlevel(4),
scanline(false) {}
int compression;
int zlevel;
bool scanline;
};
struct tag_setter : public mapnik::util::static_visitor<>
{
tag_setter(TIFF * output, tiff_config & config)
: output_(output),
config_(config) {}
template <typename T>
void operator() (T const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - unknown image type provided");
}
inline void operator() (image_data_rgba8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 4);
uint16 extras[] = { EXTRASAMPLE_UNASSALPHA };
TIFFSetField(output_, TIFFTAG_EXTRASAMPLES, 1, extras);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray32f const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 32);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
}
}
inline void operator() (image_data_gray16 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 16);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_gray8 const&) const
{
TIFFSetField(output_, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
TIFFSetField(output_, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
TIFFSetField(output_, TIFFTAG_BITSPERSAMPLE, 8);
TIFFSetField(output_, TIFFTAG_SAMPLESPERPIXEL, 1);
if (config_.compression == COMPRESSION_DEFLATE
|| config_.compression == COMPRESSION_ADOBE_DEFLATE
|| config_.compression == COMPRESSION_LZW)
{
TIFFSetField(output_, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
}
}
inline void operator() (image_data_null const&) const
{
// Assume this would be null type
throw ImageWriterException("Could not write TIFF - Null image provided");
}
private:
TIFF * output_;
tiff_config config_;
};
void set_tiff_config(TIFF* output, tiff_config & config)
{
// Set some constant tiff information that doesn't vary based on type of data
// or image size
TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
// Set the compression for the TIFF
TIFFSetField(output, TIFFTAG_COMPRESSION, config.compression);
if (COMPRESSION_ADOBE_DEFLATE == config.compression || COMPRESSION_DEFLATE == config.compression)
{
// Set the zip level for the compression
// http://en.wikipedia.org/wiki/DEFLATE#Encoder.2Fcompressor
// Changes the time spent trying to compress
TIFFSetField(output, TIFFTAG_ZIPQUALITY, config.zlevel);
}
}
template <typename T1, typename T2>
void save_as_tiff(T1 & file, T2 const& image, tiff_config & config)
{
const int width = image.width();
const int height = image.height();
TIFF* output = RealTIFFOpen("mapnik_tiff_stream",
"wm",
(thandle_t)&file,
tiff_dummy_read_proc,
tiff_write_proc,
tiff_seek_proc,
tiff_close_proc,
tiff_size_proc,
tiff_dummy_map_proc,
tiff_dummy_unmap_proc);
if (! output)
{
throw ImageWriterException("Could not write TIFF");
}
TIFFSetField(output, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(output, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(output, TIFFTAG_IMAGEDEPTH, 1);
set_tiff_config(output, config);
// Set tags that vary based on the type of data being provided.
tag_setter set(output, config);
set(image);
//util::apply_visitor(set, image);
// If the image is greater then 8MB uncompressed, then lets use scanline rather then
// tile. TIFF also requires that all TIFFTAG_TILEWIDTH and TIFF_TILELENGTH all be
// a multiple of 16, if they are not we will use scanline.
if (image.getSize() > 8 * 32 * 1024 * 1024
|| width % 16 != 0
|| height % 16 != 0
|| config.scanline)
{
// Process Scanline
TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, 1);
int next_scanline = 0;
typename T2::pixel_type * row = reinterpret_cast<typename T2::pixel_type*>(::operator new(image.getRowSize()));
while (next_scanline < height)
{
memcpy(row, image.getRow(next_scanline), image.getRowSize());
//typename T2::pixel_type * row = const_cast<typename T2::pixel_type *>(image.getRow(next_scanline));
TIFFWriteScanline(output, row, next_scanline, 0);
++next_scanline;
}
::operator delete(row);
}
else
{
TIFFSetField(output, TIFFTAG_TILEWIDTH, width);
TIFFSetField(output, TIFFTAG_TILELENGTH, height);
TIFFSetField(output, TIFFTAG_TILEDEPTH, 1);
// Process as tiles
typename T2::pixel_type * image_data = reinterpret_cast<typename T2::pixel_type*>(::operator new(image.getSize()));
memcpy(image_data, image.getData(), image.getSize());
//typename T2::pixel_type * image_data = const_cast<typename T2::pixel_type *>(image.getData());
TIFFWriteTile(output, image_data, 0, 0, 0, 0);
::operator delete(image_data);
}
// TODO - handle palette images
// std::vector<mapnik::rgb> const& palette
// unsigned short r[256], g[256], b[256];
// for (int i = 0; i < (1 << 24); ++i)
// {
// r[i] = (unsigned short)palette[i * 3 + 0] << 8;
// g[i] = (unsigned short)palette[i * 3 + 1] << 8;
// b[i] = (unsigned short)palette[i * 3 + 2] << 8;
// }
// TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
// TIFFSetField(output, TIFFTAG_COLORMAP, r, g, b);
RealTIFFClose(output);
}
}
#endif // MAPNIK_TIFF_IO_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>
#include <circular_iterator.hpp>
namespace helene
{
template <class T,
std::size_t Size,
template <class, class, std::size_t> class StoragePolicy>
class sliding_window
: public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
storage_policy;
public:
static const std::size_t size = Size;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef circular_iterator<T*> iterator;
typedef circular_iterator<const T*> const_iterator;
public:
sliding_window()
: storage_policy(),
head_(storage_policy::begin(),
storage_policy::end(),
storage_policy::begin()),
tail_(storage_policy::begin(),
storage_policy::end(),
storage_policy::end())
{
}
template <class Iterator>
sliding_window(Iterator first, Iterator last) : sliding_window()
{
for(; first != last; ++first, ++head_, ++tail_)
{
*head_ = *first;
}
}
void
push_back(const T& value)
{
*tail_ = value;
++tail_;
++head_;
}
void
push_back(const T& value, size_type n)
{
std::fill_n(tail_, n, value);
tail_ += n;
head_ += n;
}
void
push_front(const T& value)
{
--head_;
*head_ = value;
--tail_;
}
reference
front()
{
return *head_;
}
const_reference
front() const
{
return *head_;
}
reference
back()
{
return *(tail_ - 1);
}
const_reference
back() const
{
return *(tail_ - 1);
}
reference operator[](size_type n)
{
return head_[n];
}
const_reference operator[](size_type n) const
{
return head_[n];
}
iterator
begin()
{
return head_;
}
iterator
end()
{
return tail_;
}
private:
iterator head_;
iterator tail_;
};
template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
stack_storage() : buffer_{}
{
}
T*
begin()
{
return buffer_;
}
T*
end()
{
return buffer_ + Size;
}
protected:
T buffer_[Size];
};
template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
static_heap_storage() : buffer_(new T[Size]{})
{
}
T*
begin()
{
return buffer_.get();
}
T*
end()
{
return buffer_.get() + Size;
}
protected:
std::unique_ptr<T[]> buffer_;
};
template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;
template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;
namespace detail
{
struct runtime_ratio
{
runtime_ratio() : num(1), den(1)
{
}
template <std::intmax_t Num, std::intmax_t Denom>
constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
{
}
std::intmax_t num;
std::intmax_t den;
};
template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}
template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
return rhs * lhs;
}
template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail
template <class KeyType,
class ValueType,
std::size_t Size,
class Compare = std::less<KeyType>>
class sliding_window_map
{
public:
sliding_window_map() = default;
template <std::intmax_t Num, std::intmax_t Denom>
sliding_window_map(std::ratio<Num, Denom>)
: sliding_buffer_(), origin_(), precision_(std::ratio<Num, Denom>())
{
}
std::pair<KeyType, KeyType>
extent() const
{
return std::make_pair(origin_, origin_ + Size * precision_);
}
////////////////////////////////////////////////////////////////////////////
// map like interface
ValueType&
at(KeyType k)
{
const auto index = index_of_key(k);
const Compare c;
if(c(index, 0) || (!c(index, Size)))
{
throw std::out_of_range("Key outside of current window");
}
return sliding_buffer_[index];
}
private:
std::size_t
index_of_key(KeyType k)
{
return (k - origin_) / precision_;
}
private:
static_heap_sliding_window<ValueType, Size> sliding_buffer_;
KeyType origin_;
detail::runtime_ratio precision_;
};
} // namespace helene
<commit_msg>Add constructor to sliding_window taking initializer_list. modified: include/sliding_window.hpp<commit_after>#pragma once
#include <cstddef>
#include <memory>
#include <functional>
#include <ratio>
#include <iterator>
#include <initializer_list>
#include <circular_iterator.hpp>
namespace helene
{
template <class T,
std::size_t Size,
template <class, class, std::size_t> class StoragePolicy>
class sliding_window
: public StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
{
typedef StoragePolicy<sliding_window<T, Size, StoragePolicy>, T, Size>
storage_policy;
public:
static const std::size_t size = Size;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef circular_iterator<T*> iterator;
typedef circular_iterator<const T*> const_iterator;
public:
sliding_window()
: storage_policy(),
head_(storage_policy::begin(),
storage_policy::end(),
storage_policy::begin()),
tail_(storage_policy::begin(),
storage_policy::end(),
storage_policy::end())
{
}
template <class Iterator>
sliding_window(Iterator first, Iterator last) : sliding_window()
{
for(; first != last; ++first, ++head_, ++tail_)
{
*head_ = *first;
}
}
sliding_window(std::initializer_list<T> il)
: sliding_window(il.begin(), il.end())
{
}
void
push_back(const T& value)
{
*tail_ = value;
++tail_;
++head_;
}
void
push_back(const T& value, size_type n)
{
std::fill_n(tail_, n, value);
tail_ += n;
head_ += n;
}
void
push_front(const T& value)
{
--head_;
*head_ = value;
--tail_;
}
reference
front()
{
return *head_;
}
const_reference
front() const
{
return *head_;
}
reference
back()
{
return *(tail_ - 1);
}
const_reference
back() const
{
return *(tail_ - 1);
}
reference operator[](size_type n)
{
return head_[n];
}
const_reference operator[](size_type n) const
{
return head_[n];
}
iterator
begin()
{
return head_;
}
iterator
end()
{
return tail_;
}
private:
iterator head_;
iterator tail_;
};
template <class Derived, class T, std::size_t Size>
class stack_storage
{
public:
stack_storage() : buffer_{}
{
}
T*
begin()
{
return buffer_;
}
T*
end()
{
return buffer_ + Size;
}
protected:
T buffer_[Size];
};
template <class Derived, class T, std::size_t Size>
class static_heap_storage
{
public:
static_heap_storage() : buffer_(new T[Size]{})
{
}
T*
begin()
{
return buffer_.get();
}
T*
end()
{
return buffer_.get() + Size;
}
protected:
std::unique_ptr<T[]> buffer_;
};
template <class T, std::size_t Size>
using stack_sliding_window = sliding_window<T, Size, stack_storage>;
template <class T, std::size_t Size>
using static_heap_sliding_window = sliding_window<T, Size, static_heap_storage>;
namespace detail
{
struct runtime_ratio
{
runtime_ratio() : num(1), den(1)
{
}
template <std::intmax_t Num, std::intmax_t Denom>
constexpr runtime_ratio(std::ratio<Num, Denom>) : num(Num), den(Denom)
{
}
std::intmax_t num;
std::intmax_t den;
};
template <class Numeric>
Numeric operator*(const runtime_ratio& lhs, Numeric rhs)
{
return rhs * static_cast<Numeric>(lhs.num) / static_cast<Numeric>(lhs.den);
}
template <class Numeric>
Numeric operator*(Numeric lhs, const runtime_ratio& rhs)
{
return rhs * lhs;
}
template <class Numeric>
Numeric
operator/(Numeric lhs, const runtime_ratio& rhs)
{
return lhs * static_cast<Numeric>(rhs.den) / static_cast<Numeric>(rhs.num);
}
} // namespace detail
template <class KeyType,
class ValueType,
std::size_t Size,
class Compare = std::less<KeyType>>
class sliding_window_map
{
public:
sliding_window_map() = default;
template <std::intmax_t Num, std::intmax_t Denom>
sliding_window_map(std::ratio<Num, Denom>)
: sliding_buffer_(), origin_(), precision_(std::ratio<Num, Denom>())
{
}
std::pair<KeyType, KeyType>
extent() const
{
return std::make_pair(origin_, origin_ + Size * precision_);
}
////////////////////////////////////////////////////////////////////////////
// map like interface
ValueType&
at(KeyType k)
{
const auto index = index_of_key(k);
const Compare c;
if(c(index, 0) || (!c(index, Size)))
{
throw std::out_of_range("Key outside of current window");
}
return sliding_buffer_[index];
}
private:
std::size_t
index_of_key(KeyType k)
{
return (k - origin_) / precision_;
}
private:
static_heap_sliding_window<ValueType, Size> sliding_buffer_;
KeyType origin_;
detail::runtime_ratio precision_;
};
} // namespace helene
<|endoftext|> |
<commit_before>/*!
\file thread.inl
\brief Thread abstraction inline implementation
\author Ivan Shynkarenka
\date 27.01.2016
\copyright MIT License
*/
namespace CppCommon {
template <class Fn, class... Args>
inline std::thread Thread::Start(Fn&& fn, Args&&... args)
{
return std::thread([=]()
{
// Setup exception handler for the new thread
ExceptionsHandler::SetupThread();
// Call the base thread function
fn(args...);
});
}
} // namespace CppCommon
<commit_msg>Bugfix<commit_after>/*!
\file thread.inl
\brief Thread abstraction inline implementation
\author Ivan Shynkarenka
\date 27.01.2016
\copyright MIT License
*/
namespace CppCommon {
template <class Fn, class... Args>
inline std::thread Thread::Start(Fn&& fn, Args&&... args)
{
return std::thread([fn = fn, args...]()
{
// Setup exception handler for the new thread
ExceptionsHandler::SetupThread();
// Call the base thread function
fn(std::move(args)...);
});
}
} // namespace CppCommon
<|endoftext|> |
<commit_before>#include "StdAfx.h"
#include "Progress.h"
CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject)
: CControlBaseFont(hWnd, pDuiObject)
{
m_bRunTime = false;
m_nMaxProgress = 100;
m_nCount = 0;
m_nTimerCount = 3;
SetBitmapCount(2);
m_pImageBackGround = NULL;
m_sizeBackGround = CSize(0, 0);
m_pImageForeGround = NULL;
m_sizeForeGround = CSize(0, 0);
m_nHeadLength = 0;
m_clrText = Color(254, 128, 128, 128);
m_uAlignment = Align_Center;
m_uVAlignment = VAlign_Middle;
m_bShowText = FALSE;
m_nProgress = 0;
SetProgress(0);
}
CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject, UINT uControlID, CRect rc, int nProgress/* = 0*/,
BOOL bIsVisible/* = TRUE*/, BOOL bIsDisable/* = FALSE*/)
: CControlBaseFont(hWnd, pDuiObject, uControlID, rc, TEXT(""), bIsVisible, bIsDisable)
{
m_bRunTime = false;
m_nMaxProgress = 100;
m_nCount = 0;
m_nTimerCount = 3;
SetBitmapCount(2);
m_pImageBackGround = NULL;
m_sizeBackGround = CSize(0, 0);
m_pImageForeGround = NULL;
m_sizeForeGround = CSize(0, 0);
m_nHeadLength = 0;
m_clrText = Color(254, 128, 128, 128);
m_uAlignment = Align_Center;
m_uVAlignment = VAlign_Middle;
m_bShowText = FALSE;
m_nProgress = 0;
SetProgress(nProgress);
}
CDuiProgress::~CDuiProgress(void)
{
if(m_pImageBackGround != NULL)
{
delete m_pImageBackGround;
m_pImageBackGround = NULL;
}
if(m_pImageForeGround != NULL)
{
delete m_pImageForeGround;
m_pImageForeGround = NULL;
}
}
// ͼƬԵʵ
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, BackGround, 1)
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, ForeGround, 1)
int CDuiProgress::SetProgress(int nProgress)
{
if(GetDisable())
{
return m_nProgress;
}
if(nProgress > m_nMaxProgress)
{
// ֵֵ,ԶΪֵ
nProgress = m_nMaxProgress;
}
if(nProgress >= 0 && nProgress <= m_nMaxProgress && m_nProgress != nProgress)
{
m_nProgress = nProgress;
if(GetVisible())
{
UpdateControl(true);
}
}
return m_nProgress;
}
// ǷԶ
BOOL CDuiProgress::SetRun(BOOL bRun, int nIndex/* = -1*/)
{
if(GetDisable())
{
return m_bRunTime;
}
BOOL bOldRunTime = m_bRunTime;
int nOldProgress = m_nProgress;
m_bRunTime = bRun;
if(nIndex >= 0 && nIndex <= m_nMaxProgress)
{
m_nProgress = nIndex;
}
if(GetVisible() && ((bOldRunTime != m_bRunTime) || (nOldProgress != m_nProgress)))
{
UpdateControl(true);
}
return m_bRunTime;
}
// XMLԶ
HRESULT CDuiProgress::OnAttributeRun(const CString& strValue, BOOL bLoading)
{
if (strValue.IsEmpty()) return E_FAIL;
BOOL bRun = (strValue == _T("true"));
SetRun(bRun);
return bLoading?S_FALSE:S_OK;
}
BOOL CDuiProgress::OnControlTimer()
{
if(!m_bRunTime || !m_bIsVisible)
{
return FALSE;
}
if(++m_nCount >= m_nTimerCount)
{
m_nCount = 0;
if(++m_nProgress >= m_nMaxProgress)
{
m_nProgress = 0;
}
if(GetVisible())
{
UpdateControl(true);
}
return true;
}
return false;
}
void CDuiProgress::DrawControl(CDC &dc, CRect rcUpdate)
{
int nWidth = m_rc.Width();
int nHeight = m_rc.Height();
if(!m_bUpdate)
{
UpdateMemDC(dc, nWidth, nHeight);
m_memDC.BitBlt(0, 0, nWidth, nHeight, &dc, m_rc.left ,m_rc.top, SRCCOPY);
Graphics graphics(m_memDC);
if(m_pImageForeGround != NULL) // ʹñǰͼƬ
{
if(m_pImageBackGround != NULL) //
{
DrawImageFrameMID(graphics, m_pImageBackGround, CRect(0, 0, nWidth, nHeight),
0, 0, m_sizeBackGround.cx, m_sizeBackGround.cy,
m_nHeadLength, 0, m_nHeadLength, 0);
}
if(m_nProgress != 0) // ǰ
{
DrawImageFrameMID(graphics, m_pImageForeGround, CRect(0, 0, nWidth * m_nProgress / 100, nHeight),
0, 0, m_sizeForeGround.cx, m_sizeForeGround.cy,
m_nHeadLength, 0, m_nHeadLength, 0);
}
}else
if(m_pImage != NULL) // ʹõͼƬ
{
DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth, nHeight),
0, 0, m_sizeImage.cx, m_sizeImage.cy, 2);
if(m_nProgress != 0)
{
DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth * m_nProgress / 100, nHeight),
m_sizeImage.cx, 0, m_sizeImage.cx, m_sizeImage.cy, 2);
}
}
//
if(m_bShowText)
{
BSTR bsFont = m_strFont.AllocSysString();
FontFamily fontFamily(bsFont);
Font font(&fontFamily, (REAL)m_nFontWidth, m_fontStyle, UnitPixel);
::SysFreeString(bsFont);
SolidBrush solidBrush(m_clrText);
graphics.SetTextRenderingHint( TextRenderingHintClearTypeGridFit );
// ˮƽʹֱ뷽ʽ
DUI_STRING_ALIGN_DEFINE();
strFormat.SetFormatFlags( StringFormatFlagsNoClip | StringFormatFlagsMeasureTrailingSpaces);
CString strText;
strText.Format(L"%s%d%s", m_strTitle, m_nProgress, (m_nMaxProgress == 100) ? L"%" : L"");
BSTR bsTitle = strText.AllocSysString();
RectF rect((Gdiplus::REAL)(0), (Gdiplus::REAL)0, (Gdiplus::REAL)nWidth, (Gdiplus::REAL)nHeight);
graphics.DrawString(bsTitle, (INT)wcslen(bsTitle), &font, rect, &strFormat, &solidBrush);
::SysFreeString(bsTitle);
}
}
dc.BitBlt(m_rc.left,m_rc.top, m_rc.Width(), m_rc.Height(), &m_memDC, 0, 0, SRCCOPY);
}<commit_msg>progress控件可以设置进度最大值,不一定是100。<commit_after>#include "StdAfx.h"
#include "Progress.h"
CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject)
: CControlBaseFont(hWnd, pDuiObject)
{
m_bRunTime = false;
m_nMaxProgress = 100;
m_nCount = 0;
m_nTimerCount = 3;
SetBitmapCount(2);
m_pImageBackGround = NULL;
m_sizeBackGround = CSize(0, 0);
m_pImageForeGround = NULL;
m_sizeForeGround = CSize(0, 0);
m_nHeadLength = 0;
m_clrText = Color(254, 128, 128, 128);
m_uAlignment = Align_Center;
m_uVAlignment = VAlign_Middle;
m_bShowText = FALSE;
m_nProgress = 0;
SetProgress(0);
}
CDuiProgress::CDuiProgress(HWND hWnd, CDuiObject* pDuiObject, UINT uControlID, CRect rc, int nProgress/* = 0*/,
BOOL bIsVisible/* = TRUE*/, BOOL bIsDisable/* = FALSE*/)
: CControlBaseFont(hWnd, pDuiObject, uControlID, rc, TEXT(""), bIsVisible, bIsDisable)
{
m_bRunTime = false;
m_nMaxProgress = 100;
m_nCount = 0;
m_nTimerCount = 3;
SetBitmapCount(2);
m_pImageBackGround = NULL;
m_sizeBackGround = CSize(0, 0);
m_pImageForeGround = NULL;
m_sizeForeGround = CSize(0, 0);
m_nHeadLength = 0;
m_clrText = Color(254, 128, 128, 128);
m_uAlignment = Align_Center;
m_uVAlignment = VAlign_Middle;
m_bShowText = FALSE;
m_nProgress = 0;
SetProgress(nProgress);
}
CDuiProgress::~CDuiProgress(void)
{
if(m_pImageBackGround != NULL)
{
delete m_pImageBackGround;
m_pImageBackGround = NULL;
}
if(m_pImageForeGround != NULL)
{
delete m_pImageForeGround;
m_pImageForeGround = NULL;
}
}
// ͼƬԵʵ
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, BackGround, 1)
DUI_IMAGE_ATTRIBUTE_IMPLEMENT(CDuiProgress, ForeGround, 1)
int CDuiProgress::SetProgress(int nProgress)
{
if(GetDisable())
{
return m_nProgress;
}
if(nProgress > m_nMaxProgress)
{
// ֵֵ,ԶΪֵ
nProgress = m_nMaxProgress;
}
if(nProgress >= 0 && nProgress <= m_nMaxProgress && m_nProgress != nProgress)
{
m_nProgress = nProgress;
if(GetVisible())
{
UpdateControl(true);
}
}
return m_nProgress;
}
// ǷԶ
BOOL CDuiProgress::SetRun(BOOL bRun, int nIndex/* = -1*/)
{
if(GetDisable())
{
return m_bRunTime;
}
BOOL bOldRunTime = m_bRunTime;
int nOldProgress = m_nProgress;
m_bRunTime = bRun;
if(nIndex >= 0 && nIndex <= m_nMaxProgress)
{
m_nProgress = nIndex;
}
if(GetVisible() && ((bOldRunTime != m_bRunTime) || (nOldProgress != m_nProgress)))
{
UpdateControl(true);
}
return m_bRunTime;
}
// XMLԶ
HRESULT CDuiProgress::OnAttributeRun(const CString& strValue, BOOL bLoading)
{
if (strValue.IsEmpty()) return E_FAIL;
BOOL bRun = (strValue == _T("true"));
SetRun(bRun);
return bLoading?S_FALSE:S_OK;
}
BOOL CDuiProgress::OnControlTimer()
{
if(!m_bRunTime || !m_bIsVisible)
{
return FALSE;
}
if(++m_nCount >= m_nTimerCount)
{
m_nCount = 0;
if(++m_nProgress >= m_nMaxProgress)
{
m_nProgress = 0;
}
if(GetVisible())
{
UpdateControl(true);
}
return true;
}
return false;
}
void CDuiProgress::DrawControl(CDC &dc, CRect rcUpdate)
{
int nWidth = m_rc.Width();
int nHeight = m_rc.Height();
if(!m_bUpdate)
{
UpdateMemDC(dc, nWidth, nHeight);
m_memDC.BitBlt(0, 0, nWidth, nHeight, &dc, m_rc.left ,m_rc.top, SRCCOPY);
Graphics graphics(m_memDC);
if(m_pImageForeGround != NULL) // ʹñǰͼƬ
{
if(m_pImageBackGround != NULL) //
{
DrawImageFrameMID(graphics, m_pImageBackGround, CRect(0, 0, nWidth, nHeight),
0, 0, m_sizeBackGround.cx, m_sizeBackGround.cy,
m_nHeadLength, 0, m_nHeadLength, 0);
}
if(m_nProgress != 0) // ǰ
{
DrawImageFrameMID(graphics, m_pImageForeGround, CRect(0, 0, nWidth * m_nProgress / m_nMaxProgress, nHeight),
0, 0, m_sizeForeGround.cx, m_sizeForeGround.cy,
m_nHeadLength, 0, m_nHeadLength, 0);
}
}else
if(m_pImage != NULL) // ʹõͼƬ
{
DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth, nHeight),
0, 0, m_sizeImage.cx, m_sizeImage.cy, 2);
if(m_nProgress != 0)
{
DrawImageFrame(graphics, m_pImage, CRect(0, 0, nWidth * m_nProgress / m_nMaxProgress, nHeight),
m_sizeImage.cx, 0, m_sizeImage.cx, m_sizeImage.cy, 2);
}
}
//
if(m_bShowText)
{
BSTR bsFont = m_strFont.AllocSysString();
FontFamily fontFamily(bsFont);
Font font(&fontFamily, (REAL)m_nFontWidth, m_fontStyle, UnitPixel);
::SysFreeString(bsFont);
SolidBrush solidBrush(m_clrText);
graphics.SetTextRenderingHint( TextRenderingHintClearTypeGridFit );
// ˮƽʹֱ뷽ʽ
DUI_STRING_ALIGN_DEFINE();
strFormat.SetFormatFlags( StringFormatFlagsNoClip | StringFormatFlagsMeasureTrailingSpaces);
CString strText;
// ֵֻΪ100²Żʾٷֺ
strText.Format(L"%s%d%s", m_strTitle, m_nProgress, (m_nMaxProgress == 100) ? L"%" : L"");
BSTR bsTitle = strText.AllocSysString();
RectF rect((Gdiplus::REAL)(0), (Gdiplus::REAL)0, (Gdiplus::REAL)nWidth, (Gdiplus::REAL)nHeight);
graphics.DrawString(bsTitle, (INT)wcslen(bsTitle), &font, rect, &strFormat, &solidBrush);
::SysFreeString(bsTitle);
}
}
dc.BitBlt(m_rc.left,m_rc.top, m_rc.Width(), m_rc.Height(), &m_memDC, 0, 0, SRCCOPY);
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 SLIBIO. All Rights Reserved.
*
* This file is part of the SLib.io project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <slib/core.h>
using namespace slib;
int main(int argc, const char * argv[])
{
// List Example
{
int i;
List<String> list = {"a", "b", "c", "de", "a", "b"};
Println("Original List");
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
Println("Member Access");
Println("[3]=%s", list[3]);
// Insert some values into the list
for (i = 0; i < 5; i++) {
list.add(String::format("t%d", i));
}
Println("List after insertion");
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
// Remove some values from the list
list.removeRange(7, 3);
list.removeAt(3);
list.removeValues("b");
Println("List after removal");
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
}
// Map Example
{
HashMap<String, int> map = {{"a", 1}, {"b", 2}, {"c", 3}, {"ab", 11}, {"cd", 34}};
Println("HashMap");
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
Println("Member Access");
Println("[ab]=%s", map["ab"]);
// Insert some values into the map
Println("HashMap after insertion");
map.put("ab", 12);
map.put("aaa", 111);
map.put("abc", 123);
map.put("baa", 211);
map.put("bac", 213);
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Remove some values from the map
map.remove("ab");
map.remove("cd");
Println("HashMap after removal");
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Convert to TreeMap
Map<String, int> tree;
tree.putAll(map);
Println("Map");
for (auto& item : tree) {
Println("[%s]=%d", item.key, item.value);
}
}
return 0;
}
<commit_msg>example: minor change<commit_after>/*
* Copyright (c) 2017 SLIBIO. All Rights Reserved.
*
* This file is part of the SLib.io project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <slib/core.h>
using namespace slib;
int main(int argc, const char * argv[])
{
// List Example
{
int i;
List<String> list = {"a", "b", "c", "de", "a", "b"};
Println("List Original (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
Println("Member Access");
Println("[3]=%s", list[3]);
// Insert some values into the list
for (i = 0; i < 5; i++) {
list.add(String::format("t%d", i));
}
Println("List after insertion (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
// Remove some values from the list
list.removeRange(7, 3);
list.removeAt(3);
list.removeValues("b");
Println("List after removal (Count: %d)", list.getCount());
i = 0;
for (auto& item : list) {
Println("[%d]=%s", i++, item);
}
}
// Map Example
{
HashMap<String, int> map = {{"a", 1}, {"b", 2}, {"c", 3}, {"ab", 11}, {"cd", 34}};
Println("HashMap Original (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
Println("Member Access");
Println("[ab]=%s", map["ab"]);
// Insert some values into the map
map.put("ab", 12);
map.put("aaa", 111);
map.put("abc", 123);
map.put("baa", 211);
map.put("bac", 213);
Println("HashMap after insertion (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Remove some values from the map
map.remove("ab");
map.remove("cd");
Println("HashMap after removal (Count: %d)", map.getCount());
for (auto& item : map) {
Println("[%s]=%d", item.key, item.value);
}
// Convert to Ordered Map
Map<String, int> tree;
tree.putAll(map);
Println("Ordered Map (Count: %d)", tree.getCount());
for (auto& item : tree) {
Println("[%s]=%d", item.key, item.value);
}
}
return 0;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// This file is part of the BWEM Library.
// BWEM is free software, licensed under the MIT/X11 License.
// A copy of the license is provided with the library in the LICENSE file.
// Copyright (c) 2015, 2016, Igor Dimitrijevic
//
//////////////////////////////////////////////////////////////////////////
#include "cp.h"
#include "mapImpl.h"
#include "neutral.h"
using namespace BWAPI;
using namespace BWAPI::UnitTypes::Enum;
namespace { auto & bw = Broodwar; }
using namespace std;
namespace BWEM {
using namespace detail;
using namespace BWAPI_ext;
//////////////////////////////////////////////////////////////////////////////////////////////
// //
// class ChokePoint
// //
//////////////////////////////////////////////////////////////////////////////////////////////
ChokePoint::ChokePoint(detail::Graph * pGraph, index idx, const Area * area1, const Area * area2, const deque<WalkPosition> & Geometry, Neutral * pBlockingNeutral)
: m_pGraph(pGraph), m_index(idx), m_Areas(area1, area2), m_Geometry(Geometry),
m_pBlockingNeutral(pBlockingNeutral), m_blocked(pBlockingNeutral != nullptr), m_pseudo(pBlockingNeutral != nullptr)
{
bwem_assert(!Geometry.empty());
// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
if (m_pBlockingNeutral) m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();
m_nodes[end1] = Geometry.front();
m_nodes[end2] = Geometry.back();
int i = Geometry.size() / 2;
while ((i > 0) && (GetMap()->GetMiniTile(Geometry[i-1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) --i;
while ((i < (int)Geometry.size()-1) && (GetMap()->GetMiniTile(Geometry[i+1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) ++i;
m_nodes[middle] = Geometry[i];
for (int n = 0 ; n < node_count ; ++n)
for (const Area * pArea : {area1, area2})
{
WalkPosition & nodeInArea = (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
nodeInArea = GetMap()->BreadthFirstSearch(m_nodes[n],
[pArea, this](const MiniTile & miniTile, WalkPosition w) // findCond
{ return (miniTile.AreaId() == pArea->Id()) && !GetMap()->GetTile(TilePosition(w), check_t::no_check).GetNeutral(); },
[pArea, this](const MiniTile & miniTile, WalkPosition) // visitCond
{ return (miniTile.AreaId() == pArea->Id()) || (Blocked() && (miniTile.Blocked())); }
);
}
}
ChokePoint::ChokePoint(const ChokePoint & Other)
: m_pGraph(Other.m_pGraph), m_index(0), m_pseudo(false)
{
bwem_assert(false);
}
Map * ChokePoint::GetMap() const
{
return m_pGraph->GetMap();
}
const BWAPI::WalkPosition & ChokePoint::PosInArea(node n, const Area * pArea) const
{
bwem_assert((pArea == m_Areas.first) || (pArea == m_Areas.second));
return (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
}
int ChokePoint::DistanceFrom(const ChokePoint * cp) const
{
return GetGraph()->Distance(this, cp);
}
const CPPath & ChokePoint::GetPathTo(const ChokePoint * cp) const
{
return GetGraph()->GetPath(this, cp);
}
// Assumes pBlocking->RemoveFromTiles() has been called
void ChokePoint::OnBlockingNeutralDestroyed(const Neutral * pBlocking)
{
bwem_assert(pBlocking && pBlocking->Blocking());
if (m_pBlockingNeutral == pBlocking)
{
// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();
if (!m_pBlockingNeutral)
if (GetGraph()->GetMap()->AutomaticPathUpdate())
m_blocked = false;
}
}
} // namespace BWEM
<commit_msg>Applied 'Electric Circuit' bugfix.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// This file is part of the BWEM Library.
// BWEM is free software, licensed under the MIT/X11 License.
// A copy of the license is provided with the library in the LICENSE file.
// Copyright (c) 2015, 2016, Igor Dimitrijevic
//
//////////////////////////////////////////////////////////////////////////
#include "cp.h"
#include "mapImpl.h"
#include "neutral.h"
using namespace BWAPI;
using namespace BWAPI::UnitTypes::Enum;
namespace { auto & bw = Broodwar; }
using namespace std;
namespace BWEM {
using namespace detail;
using namespace BWAPI_ext;
//////////////////////////////////////////////////////////////////////////////////////////////
// //
// class ChokePoint
// //
//////////////////////////////////////////////////////////////////////////////////////////////
ChokePoint::ChokePoint(detail::Graph * pGraph, index idx, const Area * area1, const Area * area2, const deque<WalkPosition> & Geometry, Neutral * pBlockingNeutral)
: m_pGraph(pGraph), m_index(idx), m_Areas(area1, area2), m_Geometry(Geometry),
m_pBlockingNeutral(pBlockingNeutral), m_blocked(pBlockingNeutral != nullptr), m_pseudo(pBlockingNeutral != nullptr)
{
bwem_assert(!Geometry.empty());
// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
if (m_pBlockingNeutral) m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();
m_nodes[end1] = Geometry.front();
m_nodes[end2] = Geometry.back();
int i = Geometry.size() / 2;
while ((i > 0) && (GetMap()->GetMiniTile(Geometry[i-1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) --i;
while ((i < (int)Geometry.size()-1) && (GetMap()->GetMiniTile(Geometry[i+1]).Altitude() > GetMap()->GetMiniTile(Geometry[i]).Altitude())) ++i;
m_nodes[middle] = Geometry[i];
for (int n = 0 ; n < node_count ; ++n)
for (const Area * pArea : {area1, area2})
{
WalkPosition & nodeInArea = (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
nodeInArea = GetMap()->BreadthFirstSearch(m_nodes[n],
[pArea, this](const MiniTile & miniTile, WalkPosition w) // findCond
{ return (miniTile.AreaId() == pArea->Id()) && !GetMap()->GetTile(TilePosition(w), check_t::no_check).GetNeutral(); },
[pArea, this](const MiniTile & miniTile, WalkPosition w) // visitCond
{ return (miniTile.AreaId() == pArea->Id()) || (Blocked() && (miniTile.Blocked() || GetMap()->GetTile(TilePosition(w), check_t::no_check).GetNeutral())); }
);
}
}
ChokePoint::ChokePoint(const ChokePoint & Other)
: m_pGraph(Other.m_pGraph), m_index(0), m_pseudo(false)
{
bwem_assert(false);
}
Map * ChokePoint::GetMap() const
{
return m_pGraph->GetMap();
}
const BWAPI::WalkPosition & ChokePoint::PosInArea(node n, const Area * pArea) const
{
bwem_assert((pArea == m_Areas.first) || (pArea == m_Areas.second));
return (pArea == m_Areas.first) ? m_nodesInArea[n].first : m_nodesInArea[n].second;
}
int ChokePoint::DistanceFrom(const ChokePoint * cp) const
{
return GetGraph()->Distance(this, cp);
}
const CPPath & ChokePoint::GetPathTo(const ChokePoint * cp) const
{
return GetGraph()->GetPath(this, cp);
}
// Assumes pBlocking->RemoveFromTiles() has been called
void ChokePoint::OnBlockingNeutralDestroyed(const Neutral * pBlocking)
{
bwem_assert(pBlocking && pBlocking->Blocking());
if (m_pBlockingNeutral == pBlocking)
{
// Ensures that in the case where several neutrals are stacked, m_pBlockingNeutral points to the bottom one:
m_pBlockingNeutral = GetMap()->GetTile(m_pBlockingNeutral->TopLeft()).GetNeutral();
if (!m_pBlockingNeutral)
if (GetGraph()->GetMap()->AutomaticPathUpdate())
m_blocked = false;
}
}
} // namespace BWEM
<|endoftext|> |
<commit_before>#pragma once
#include <map>
namespace Doremi
{
namespace Core
{
/**
The audio component contains the handle to the soundchannel and a handle to the sound
*/
// If you add someone,
enum class AudioCompEnum : int32_t
{
Jump,
Death,
DamageTaken,
DebugSound,
Num_Sounds,
};
struct AudioComponent
{
// std::map<AudioCompEnum, int> m_enumToSoundID;
int32_t m_enumToSoundID[(int32_t)(AudioCompEnum::Num_Sounds)]; // +1]; //Todo maybe bugs out
// int mySoundID = sounds[(int)AudioCompEnum::Jump];
AudioComponent()
{
for(int32_t i = 0; i < (int32_t)AudioCompEnum::Num_Sounds; i++)
{
m_enumToSoundID[i] = (int32_t)AudioCompEnum::DebugSound;
}
}
};
}
}<commit_msg>All sounds in audio component are initialized as-1<commit_after>#pragma once
#include <map>
namespace Doremi
{
namespace Core
{
/**
The audio component contains the handle to the soundchannel and a handle to the sound
*/
// If you add someone,
enum class AudioCompEnum : int32_t
{
Jump,
Death,
DamageTaken,
DebugSound,
Num_Sounds,
};
struct AudioComponent
{
// std::map<AudioCompEnum, int> m_enumToSoundID;
int32_t m_enumToSoundID[(int32_t)(AudioCompEnum::Num_Sounds)]; // +1]; //Todo maybe bugs out
// int mySoundID = sounds[(int)AudioCompEnum::Jump];
AudioComponent()
{
for(int32_t i = 0; i < (int32_t)AudioCompEnum::Num_Sounds; i++)
{
m_enumToSoundID[i] = -1;
}
}
};
}
}<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2019 Inviwo Foundation
* 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 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 <modules/base/processors/randomspheregenerator.h>
#include <inviwo/core/util/indexmapper.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/algorithm/boundingbox.h>
#include <numeric>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo RandomSphereGenerator::processorInfo_{
"org.inviwo.RandomSphereGenerator", // Class identifier
"Random Sphere Generator", // Display name
"Mesh Creation", // Category
CodeState::Stable, // Code state
Tags::CPU, // Tags
};
const ProcessorInfo RandomSphereGenerator::getProcessorInfo() const { return processorInfo_; }
RandomSphereGenerator::RandomSphereGenerator()
: Processor()
, meshOut_("mesh")
, seed_("seed", "Seed", 0, 0, std::mt19937::max())
, reseed_("reseed_", "Seed")
, scale_("scale", "Scale", 12.0f, 0.001f, 100.0f, 0.1f)
, size_("size", "Size", 1.0f, 0.001f, 10.0f, 0.1f)
, gridDim_("gridDim", "Grid Dimension", ivec3(12, 12, 12), ivec3(1), ivec3(128))
, jigglePos_("jigglePos", "Jiggle Positions", true)
, enablePicking_("enablePicking", "Enable Picking", false)
, camera_("camera", "Camera", util::boundingBox(meshOut_))
, spherePicking_(
this, gridDim_.get().x * gridDim_.get().y * gridDim_.get().z, [&](PickingEvent* p) {
handlePicking(p, [&](vec3 delta) {
if (positionBuffer_) {
auto& pos = positionBuffer_->getDataContainer();
pos[p->getPickedId()] += delta;
positionBuffer_->getOwner()->invalidateAllOther(positionBuffer_.get());
}
});
}) {
addPort(meshOut_);
addProperty(scale_);
addProperty(size_);
addProperty(gridDim_);
addProperty(jigglePos_);
addProperty(seed_);
addProperty(reseed_);
addProperty(enablePicking_);
addProperty(camera_);
camera_.setInvalidationLevel(InvalidationLevel::Valid);
camera_.setCollapsed(true);
seed_.setSemantics(PropertySemantics::Text);
reseed_.onChange([&]() {
seed_.set(static_cast<glm::i64>(rand(0.0f, static_cast<float>(seed_.getMaxValue()))));
rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));
});
}
void RandomSphereGenerator::process() {
rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));
const vec3 bboxMin(-scale_.get());
const vec3 extent(scale_.get() * 2.0f);
const vec3 delta(extent / vec3(gridDim_.get()));
auto randPos = [&]() { return randVec3(-0.5f, 0.5f); };
auto randColor = [&]() { return vec4(randVec3(0.5, 1.0), 1); };
auto randRadius = [&]() { return size_.get() * rand(0.1f, 1.0f); };
const bool dirty = seed_.isModified() || size_.isModified() || scale_.isModified() ||
enablePicking_.isModified();
if (gridDim_.isModified() || dirty || !positionBuffer_) {
const auto dim = gridDim_.get();
const int numSpheres = dim.x * dim.y * dim.z;
spherePicking_.resize(numSpheres);
auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None);
auto vertexRAM = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres);
auto colorRAM = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres);
auto radiiRAM = std::make_shared<BufferRAMPrecision<float>>(numSpheres);
// keep a reference to vertex position buffer for picking
positionBuffer_ = vertexRAM;
radiiBuffer_ = radiiRAM;
mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib),
std::make_shared<Buffer<vec3>>(vertexRAM));
mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib),
std::make_shared<Buffer<vec4>>(colorRAM));
mesh->addBuffer(Mesh::BufferInfo(BufferType::RadiiAttrib),
std::make_shared<Buffer<float>>(radiiRAM));
if (enablePicking_.get()) {
auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres);
auto& data = pickingRAM->getDataContainer();
// fill in picking IDs
std::iota(data.begin(), data.end(),
static_cast<uint32_t>(spherePicking_.getPickingId(0)));
mesh->addBuffer(Mesh::BufferInfo(BufferType::PickingAttrib),
std::make_shared<Buffer<uint32_t>>(pickingRAM));
}
auto& vertices = vertexRAM->getDataContainer();
auto& colors = colorRAM->getDataContainer();
auto& radii = radiiRAM->getDataContainer();
util::IndexMapper<3, int> indexmapper(dim);
if (jigglePos_.get()) {
for (int i = 0; i < numSpheres; i++) {
vertices[i] = (vec3(indexmapper(i)) + randPos()) * delta + bboxMin;
colors[i] = randColor();
radii[i] = randRadius();
}
} else {
for (int i = 0; i < numSpheres; i++) {
vertices[i] = vec3(indexmapper(i)) * delta + bboxMin;
colors[i] = randColor();
radii[i] = randRadius();
}
}
meshOut_.setData(mesh);
}
}
float RandomSphereGenerator::rand(const float min, const float max) const {
return min + dis_(rand_) * (max - min);
}
vec3 RandomSphereGenerator::randVec3(const float min, const float max) const {
float x = rand(min, max);
float y = rand(min, max);
float z = rand(min, max);
return vec3(x, y, z);
}
vec3 RandomSphereGenerator::randVec3(const vec3& min, const vec3& max) const {
float x = rand(min.x, max.x);
float y = rand(min.y, max.y);
float z = rand(min.z, max.z);
return vec3(x, y, z);
}
void RandomSphereGenerator::handlePicking(PickingEvent* p, std::function<void(vec3)> callback) {
if (enablePicking_) {
if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == MouseEvent::chash()) {
auto me = p->getEventAs<MouseEvent>();
if ((me->buttonState() & MouseButton::Left) && me->state() == MouseState::Move) {
auto delta = getDelta(camera_, p);
callback(delta);
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
} else if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == TouchEvent::chash()) {
auto te = p->getEventAs<TouchEvent>();
if (!te->touchPoints().empty() && te->touchPoints()[0].state() == TouchState::Updated) {
auto delta = getDelta(camera_, p);
callback(delta);
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
}
else if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == WheelEvent::chash()) {
auto we = p->getEventAs<WheelEvent>();
LogInfo("wheel event: " << we->delta().y);
if (radiiBuffer_) {
auto& radii = radiiBuffer_->getDataContainer();
radii[p->getPickedId()] *= 1.0f - 0.05f * static_cast<float>(-we->delta().y);
radiiBuffer_->getOwner()->invalidateAllOther(radiiBuffer_.get());
}
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
}
}
vec3 RandomSphereGenerator::getDelta(const Camera& camera, PickingEvent* p) {
auto currNDC = p->getNDC();
auto prevNDC = p->getPreviousNDC();
// Use depth of initial press as reference to move in the image plane.
auto refDepth = p->getPressedDepth();
currNDC.z = refDepth;
prevNDC.z = refDepth;
auto corrWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(currNDC));
auto prevWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(prevNDC));
return (corrWorld - prevWorld);
}
} // namespace inviwo
<commit_msg>Base: removed debug output<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2019 Inviwo Foundation
* 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 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 <modules/base/processors/randomspheregenerator.h>
#include <inviwo/core/util/indexmapper.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/interaction/events/touchevent.h>
#include <inviwo/core/interaction/events/wheelevent.h>
#include <inviwo/core/datastructures/geometry/mesh.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <inviwo/core/algorithm/boundingbox.h>
#include <numeric>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo RandomSphereGenerator::processorInfo_{
"org.inviwo.RandomSphereGenerator", // Class identifier
"Random Sphere Generator", // Display name
"Mesh Creation", // Category
CodeState::Stable, // Code state
Tags::CPU, // Tags
};
const ProcessorInfo RandomSphereGenerator::getProcessorInfo() const { return processorInfo_; }
RandomSphereGenerator::RandomSphereGenerator()
: Processor()
, meshOut_("mesh")
, seed_("seed", "Seed", 0, 0, std::mt19937::max())
, reseed_("reseed_", "Seed")
, scale_("scale", "Scale", 12.0f, 0.001f, 100.0f, 0.1f)
, size_("size", "Size", 1.0f, 0.001f, 10.0f, 0.1f)
, gridDim_("gridDim", "Grid Dimension", ivec3(12, 12, 12), ivec3(1), ivec3(128))
, jigglePos_("jigglePos", "Jiggle Positions", true)
, enablePicking_("enablePicking", "Enable Picking", false)
, camera_("camera", "Camera", util::boundingBox(meshOut_))
, spherePicking_(
this, gridDim_.get().x * gridDim_.get().y * gridDim_.get().z, [&](PickingEvent* p) {
handlePicking(p, [&](vec3 delta) {
if (positionBuffer_) {
auto& pos = positionBuffer_->getDataContainer();
pos[p->getPickedId()] += delta;
positionBuffer_->getOwner()->invalidateAllOther(positionBuffer_.get());
}
});
}) {
addPort(meshOut_);
addProperty(scale_);
addProperty(size_);
addProperty(gridDim_);
addProperty(jigglePos_);
addProperty(seed_);
addProperty(reseed_);
addProperty(enablePicking_);
addProperty(camera_);
camera_.setInvalidationLevel(InvalidationLevel::Valid);
camera_.setCollapsed(true);
seed_.setSemantics(PropertySemantics::Text);
reseed_.onChange([&]() {
seed_.set(static_cast<glm::i64>(rand(0.0f, static_cast<float>(seed_.getMaxValue()))));
rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));
});
}
void RandomSphereGenerator::process() {
rand_.seed(static_cast<std::mt19937::result_type>(seed_.get()));
const vec3 bboxMin(-scale_.get());
const vec3 extent(scale_.get() * 2.0f);
const vec3 delta(extent / vec3(gridDim_.get()));
auto randPos = [&]() { return randVec3(-0.5f, 0.5f); };
auto randColor = [&]() { return vec4(randVec3(0.5, 1.0), 1); };
auto randRadius = [&]() { return size_.get() * rand(0.1f, 1.0f); };
const bool dirty = seed_.isModified() || size_.isModified() || scale_.isModified() ||
enablePicking_.isModified();
if (gridDim_.isModified() || dirty || !positionBuffer_) {
const auto dim = gridDim_.get();
const int numSpheres = dim.x * dim.y * dim.z;
spherePicking_.resize(numSpheres);
auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None);
auto vertexRAM = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres);
auto colorRAM = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres);
auto radiiRAM = std::make_shared<BufferRAMPrecision<float>>(numSpheres);
// keep a reference to vertex position buffer for picking
positionBuffer_ = vertexRAM;
radiiBuffer_ = radiiRAM;
mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib),
std::make_shared<Buffer<vec3>>(vertexRAM));
mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib),
std::make_shared<Buffer<vec4>>(colorRAM));
mesh->addBuffer(Mesh::BufferInfo(BufferType::RadiiAttrib),
std::make_shared<Buffer<float>>(radiiRAM));
if (enablePicking_.get()) {
auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres);
auto& data = pickingRAM->getDataContainer();
// fill in picking IDs
std::iota(data.begin(), data.end(),
static_cast<uint32_t>(spherePicking_.getPickingId(0)));
mesh->addBuffer(Mesh::BufferInfo(BufferType::PickingAttrib),
std::make_shared<Buffer<uint32_t>>(pickingRAM));
}
auto& vertices = vertexRAM->getDataContainer();
auto& colors = colorRAM->getDataContainer();
auto& radii = radiiRAM->getDataContainer();
util::IndexMapper<3, int> indexmapper(dim);
if (jigglePos_.get()) {
for (int i = 0; i < numSpheres; i++) {
vertices[i] = (vec3(indexmapper(i)) + randPos()) * delta + bboxMin;
colors[i] = randColor();
radii[i] = randRadius();
}
} else {
for (int i = 0; i < numSpheres; i++) {
vertices[i] = vec3(indexmapper(i)) * delta + bboxMin;
colors[i] = randColor();
radii[i] = randRadius();
}
}
meshOut_.setData(mesh);
}
}
float RandomSphereGenerator::rand(const float min, const float max) const {
return min + dis_(rand_) * (max - min);
}
vec3 RandomSphereGenerator::randVec3(const float min, const float max) const {
float x = rand(min, max);
float y = rand(min, max);
float z = rand(min, max);
return vec3(x, y, z);
}
vec3 RandomSphereGenerator::randVec3(const vec3& min, const vec3& max) const {
float x = rand(min.x, max.x);
float y = rand(min.y, max.y);
float z = rand(min.z, max.z);
return vec3(x, y, z);
}
void RandomSphereGenerator::handlePicking(PickingEvent* p, std::function<void(vec3)> callback) {
if (enablePicking_) {
if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == MouseEvent::chash()) {
auto me = p->getEventAs<MouseEvent>();
if ((me->buttonState() & MouseButton::Left) && me->state() == MouseState::Move) {
auto delta = getDelta(camera_, p);
callback(delta);
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
} else if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == TouchEvent::chash()) {
auto te = p->getEventAs<TouchEvent>();
if (!te->touchPoints().empty() && te->touchPoints()[0].state() == TouchState::Updated) {
auto delta = getDelta(camera_, p);
callback(delta);
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
}
else if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == WheelEvent::chash()) {
auto we = p->getEventAs<WheelEvent>();
if (radiiBuffer_) {
auto& radii = radiiBuffer_->getDataContainer();
radii[p->getPickedId()] *= 1.0f - 0.05f * static_cast<float>(-we->delta().y);
radiiBuffer_->getOwner()->invalidateAllOther(radiiBuffer_.get());
}
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
}
}
vec3 RandomSphereGenerator::getDelta(const Camera& camera, PickingEvent* p) {
auto currNDC = p->getNDC();
auto prevNDC = p->getPreviousNDC();
// Use depth of initial press as reference to move in the image plane.
auto refDepth = p->getPressedDepth();
currNDC.z = refDepth;
prevNDC.z = refDepth;
auto corrWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(currNDC));
auto prevWorld = camera.getWorldPosFromNormalizedDeviceCoords(static_cast<vec3>(prevNDC));
return (corrWorld - prevWorld);
}
} // namespace inviwo
<|endoftext|> |
<commit_before>// inverse.cpp: example program comparing float vs posit using Gauss-Jordan algorithm
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.
#include <chrono>
//
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <universal/blas/blas.hpp>
#include <universal/functions/isrepresentable.hpp>
template<size_t nbits, size_t es, size_t capacity = 10>
void ComparePositDecompositions(sw::unum::blas::matrix< sw::unum::posit<nbits, es> >& A, sw::unum::blas::vector< sw::unum::posit<nbits, es> >& x, sw::unum::blas::vector< sw::unum::posit<nbits, es> >& b) {
using namespace std;
using namespace sw::unum;
using namespace sw::unum::blas;
assert(num_rows(A) == num_cols(A));
{
using namespace std::chrono;
steady_clock::time_point t1 = steady_clock::now();
auto Ainv = inv(A);
steady_clock::time_point t2 = steady_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
double elapsed = time_span.count();
std::cout << "Gauss-Jordan took " << elapsed << " seconds." << std::endl;
std::cout << "Performance " << (uint32_t)(N*N*N / (1000 * elapsed)) << " KOPS/s" << std::endl;
x = Ainv * b;
cout << "Inverse\n" << Ainv << endl;
cout << "Solution\n" << x << endl;
cout << "RHS\n" << b << endl;
}
std::cout << std::endl;
}
template<size_t nbits, size_t es>
void GaussianEliminationTest() {
using namespace std;
using namespace sw::unum;
using namespace sw::unum::blas;
using Scalar = sw::unum::posit<nbits, es>;
using Vector = sw::unum::blas::vector<Scalar>;
using Matrix = sw::unum::blas::matrix<Scalar>;
cout << "Using " << dynamic_range<nbits, es>() << endl;
// repeat set up for posits
cout << "Posit inputs\n";
Matrix U = { // define the upper triangular matrix
{ 1.0, 2.0, 3.0, 4.0, 5.0 },
{ 0.0, 1.0, 2.0, 3.0, 4.0 },
{ 0.0, 0.0, 1.0, 2.0, 3.0 },
{ 0.0, 0.0, 0.0, 1.0, 2.0 },
{ 0.0, 0.0, 0.0, 0.0, 1.0 },
};
Matrix L = { // define the lower triangular matrix
{ 1.0, 0.0, 0.0, 0.0, 0.0 },
{ 2.0, 1.0, 0.0, 0.0, 0.0 },
{ 3.0, 2.0, 1.0, 0.0, 0.0 },
{ 4.0, 3.0, 2.0, 1.0, 0.0 },
{ 5.0, 4.0, 3.0, 2.0, 1.0 },
};
auto A = L * U; // construct the A matrix to solve
cout << "L\n" << L << endl;
cout << "U\n" << U << endl;
cout << "A\n" << A << endl;
// define a difficult solution
Scalar epsplus = Scalar(1) + numeric_limits<Scalar>::epsilon();
Vector x = {
epsplus,
epsplus,
epsplus,
epsplus,
epsplus
};
auto b = fmv(A, x); // construct the right hand side
cout << "b" << b << endl;
cout << endl << ">>>>>>>>>>>>>>>>" << endl;
cout << "LinearSolve fused-dot product" << endl;
ComparePositDecompositions(A, x, b);
}
int main(int argc, char** argv)
try {
using namespace std;
using namespace sw::unum;
using namespace sw::unum::blas;
using Scalar = float;
using Matrix = sw::unum::blas::matrix<Scalar>;
using Vector = sw::unum::blas::vector<Scalar>;
Matrix A = {
{ 2, -1, 0, 0, 0 },
{ -1, 2, -1, 0, 0 },
{ 0, -1, 2, -1, 0 },
{ 0, 0, -1, 2, -1 },
{ 0, 0, 0, -1, 2 }
};
auto Ainv = inv(A);
cout << Ainv << endl;
cout << Ainv * A << endl;
// A = L + D + U decomposition
auto D = diag(diag(A));
auto L = tril(A) - D;
auto U = triu(A) - D;
auto I = eye<Scalar>(num_cols(A));
L += I;
auto Linv = inv(L);
cout << Linv << endl;
cout << Linv * L << endl << L * Linv << endl;
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
std::cerr << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<commit_msg>float vs posit comparison for Gauss-Jordan<commit_after>// inverse.cpp: example program comparing float vs posit using Gauss-Jordan algorithm
//
// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.
//
// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.
#include <chrono>
//
// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
// enable fast posit<32,2>
#define POSIT_FAST_POSIT_32_2 1
#include <universal/posit/posit>
#include <universal/blas/blas.hpp>
#include <universal/blas/generators.hpp>
#include <universal/functions/isrepresentable.hpp>
template<typename Matrix, typename Vector>
void BenchmarkGaussJordan(const Matrix& A, Vector& x, const Vector& b) {
using namespace std;
using namespace sw::unum;
using namespace sw::unum::blas;
assert(num_rows(A) == num_cols(A));
size_t N = num_cols(A);
{
using namespace std::chrono;
steady_clock::time_point t1 = steady_clock::now();
auto Ainv = inv(A);
steady_clock::time_point t2 = steady_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
double elapsed = time_span.count();
std::cout << "Gauss-Jordan took " << elapsed << " seconds." << std::endl;
std::cout << "Performance " << (uint32_t)(N*N*N / (1000000.0 * elapsed)) << " MOPS/s" << std::endl;
x = Ainv * b;
cout << "Inverse\n" << Ainv << endl;
cout << "Solution\n" << x << endl;
cout << "RHS\n" << b << endl;
}
std::cout << std::endl;
}
void Test1() {
using namespace std;
using namespace sw::unum;
using namespace sw::unum::blas;
using Scalar = float;
using Matrix = sw::unum::blas::matrix<Scalar>;
using Vector = sw::unum::blas::vector<Scalar>;
Matrix A = {
{ 2, -1, 0, 0, 0 },
{ -1, 2, -1, 0, 0 },
{ 0, -1, 2, -1, 0 },
{ 0, 0, -1, 2, -1 },
{ 0, 0, 0, -1, 2 }
};
auto Ainv = inv(A);
cout << Ainv << endl;
cout << Ainv * A << endl;
// A = L + D + U decomposition
auto D = diag(diag(A));
auto L = tril(A) - D;
auto U = triu(A) - D;
auto I = eye<Scalar>(num_cols(A));
L += I;
auto Linv = inv(L);
cout << Linv << endl;
cout << Linv * L << endl << L * Linv << endl;
}
int main(int argc, char** argv)
try {
using namespace std;
using namespace sw::unum;
using namespace sw::unum::blas;
{
using Scalar = float;
using Matrix = sw::unum::blas::matrix<Scalar>;
using Vector = sw::unum::blas::vector<Scalar>;
constexpr size_t N = 5;
Matrix A;
ftcs_fd1D(A, N, N);
cout << "Finite Difference Matrix\n" << A << endl;
Vector x(N);
x = Scalar(1);
auto b = A * x;
BenchmarkGaussJordan(A, x, b);
// visual feedback
auto Ainv = inv(A);
cout << Ainv << endl;
cout << Ainv * A << endl;
}
{
using Scalar = sw::unum::posit<32,2>;
using Matrix = sw::unum::blas::matrix<Scalar>;
using Vector = sw::unum::blas::vector<Scalar>;
constexpr size_t N = 5;
Matrix A;
ftcs_fd1D(A, N, N);
cout << "Finite Difference Matrix\n" << A << endl;
Vector x(N);
x = Scalar(1);
auto b = A * x;
BenchmarkGaussJordan(A, x, b);
// visual feedback
auto Ainv = inv(A);
cout << Ainv << endl;
cout << Ainv * A << endl;
}
return EXIT_SUCCESS;
}
catch (char const* msg) {
std::cerr << msg << std::endl;
return EXIT_FAILURE;
}
catch (const posit_arithmetic_exception& err) {
std::cerr << "Uncaught posit arithmetic exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const quire_exception& err) {
std::cerr << "Uncaught quire exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const posit_internal_exception& err) {
std::cerr << "Uncaught posit internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (std::runtime_error& err) {
std::cerr << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <nr.h>
#include <sys/types.h>
#ifdef WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif
#include <map>
char *output_name = NULL, **input_names = NULL;
char *mask_name = NULL;
long ran2Seed;
long ran2initialSeed;
// first short is the label, second short is the number of images voting
// for that label.
typedef map<short, short> countMap;
map<short, short>::iterator iter;
short getMostPopular(countMap cMap){
short maxCount = 0, mostPopLabel = -1;
if (cMap.size() == 0){
// No votes to count, treat as background.
return 0;
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second > maxCount){
maxCount = iter->second;
mostPopLabel = iter->first;
}
}
return mostPopLabel;
}
bool isEquivocal(countMap cMap){
short maxCount = 0;
short numberWithMax = 0;
if (cMap.size() == 0){
// No votes to count, treat as background.
return false;
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second > maxCount){
maxCount = iter->second;
}
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second == maxCount){
++numberWithMax;
}
}
if (numberWithMax > 1){
return true;
} else {
return false;
}
}
short decideOnTie(countMap cMap){
short maxCount = 0;
short numberWithMax = 0;
int index, count;
short temp;
double val;
if (cMap.size() == 0){
// No votes to count, treat as background.
return false;
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second > maxCount){
maxCount = iter->second;
}
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second == maxCount){
++numberWithMax;
}
}
short *tiedLabels = new short[numberWithMax];
count = 0;
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second == maxCount){
tiedLabels[count] = iter->first;
++count;
}
}
val = ran2(&ran2Seed);
index = (int) round(val * (count - 1));
temp = tiedLabels[index];
delete tiedLabels;
return temp;
}
void usage()
{
cerr << " " << endl;
cerr << " Usage: combineLabels [output] [N] [input1] .. [inputN] <-options>" << endl;
cerr << " " << endl;
cerr << " Combine [N] label images into a consensus labelling using the vote rule." << endl;
cerr << " Labels for voxels where the vote is tied for are decided randomly." << endl;
cerr << " " << endl;
cerr << " The images [input1] .. [inputN] are assumed to contain labellings on the" << endl;
cerr << " same voxel grid. For each voxel, the modal label from the images is used " << endl;
cerr << " to generate a label in the output image." << endl;
cerr << " " << endl;
cerr << " Options:" << endl;
cerr << " -u [filename] Write out a volume showing the unanimous voxels." << endl;
cerr << " -pad [value] Padding value, default = -1." << endl;
cerr << " " << endl;
exit(1);
}
int main(int argc, char **argv)
{
int numberOfClassifiers, i, v, ok, voxels, contendedVoxelCount, contendedVoxelIndex, equivocalCount;
irtkGreyPixel *pIn, *pIn_0, *pOut;
irtkGreyImage input, output;
irtkGreyImage *input_0;
irtkByteImage mask;
irtkBytePixel *pMask;
int writeMask = false;
int pad = -1;
// Check command line
if (argc < 4){
usage();
}
output_name = argv[1];
argc--;
argv++;
numberOfClassifiers = atoi(argv[1]);
argc--;
argv++;
input_names = new char *[numberOfClassifiers];
for (i = 0; i < numberOfClassifiers; i++){
input_names[i] = argv[1];
argc--;
argv++;
}
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-u") == 0)){
argc--; argv++;
mask_name = argv[1];
writeMask = true;
argc--; argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-pad") == 0)){
argc--; argv++;
pad = atoi(argv[1]);
argc--; argv++;
ok = true;
}
if (ok == false){
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
// Mask has a value of 1 for all uncontended voxels.
mask.Read(input_names[0]);
voxels = mask.GetNumberOfVoxels();
// Reset mask so that all voxels are marked as unanimous.
pMask = mask.GetPointerToVoxels();
for (i = 0; i < voxels; ++i){
*pMask = 1;
++pMask;
}
input_0 = new irtkGreyImage(input_names[0]);
for (i = 1; i < numberOfClassifiers; ++i){
input.Read(input_names[i]);
pIn = input.GetPointerToVoxels();
pIn_0 = input_0->GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
for (v = 0; v < voxels; ++v){
if (*pIn != *pIn_0 && (*pIn > pad || *pIn_0 > pad) ){
*pMask = 0;
}
++pIn;
++pIn_0;
++pMask;
}
}
// Do we need to write out the `unanimask'?
if (writeMask == true && mask_name != NULL){
mask.Write(mask_name);
}
// free some memory.
delete input_0;
contendedVoxelCount = 0;
pMask = mask.GetPointerToVoxels();
for (i = 0; i < voxels; ++i){
if (*pMask == 0){
++contendedVoxelCount;
}
++pMask;
}
cout << "Number of contended voxels = " << contendedVoxelCount << " = ";
cout << 100.0 * contendedVoxelCount / ((double) voxels) << "%" << endl;
countMap *counts = new countMap[contendedVoxelCount];
for (i = 0; i < numberOfClassifiers; ++i){
input.Read(input_names[i]);
pIn = input.GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
contendedVoxelIndex = 0;
for (v = 0; v < voxels; ++v){
//Is the current voxel contended?
if (*pMask == 0){
if (*pIn > pad){
++counts[contendedVoxelIndex][*pIn];
}
++contendedVoxelIndex;
}
++pIn;
++pMask;
}
}
// Initialise output image using first input image, all inputs assumed
// same size etc..
output.Read(input_names[0]);
pOut = output.GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
contendedVoxelIndex = 0;
for (v = 0; v < voxels; ++v){
//Is the current voxel contentded?
if (*pMask == 0){
*pOut = getMostPopular(counts[contendedVoxelIndex]);
++contendedVoxelIndex;
}
++pOut;
++pMask;
}
// Get ready for random stuff.
time_t tv;
tv = time(NULL);
ran2Seed = tv;
ran2initialSeed = -1 * ran2Seed;
(void) ran2(&ran2initialSeed);
contendedVoxelIndex = 0;
equivocalCount = 0;
pOut = output.GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
for (v = 0; v < voxels; ++v){
//Is the current voxel contended?
if (*pMask == 0){
if (isEquivocal(counts[contendedVoxelIndex])){
++equivocalCount;
*pOut = decideOnTie(counts[contendedVoxelIndex]);
}
++contendedVoxelIndex;
}
++pOut;
++pMask;
}
cout << "Number of equivocal voxels = " << equivocalCount << " = ";
cout << 100.0 * equivocalCount / ((double) voxels) << "%" << endl;
output.Write(output_name);
delete [] counts;
}
<commit_msg>Fixed bug in random choice when deciding on a tied voxel.<commit_after>/*=========================================================================
Library : Image Registration Toolkit (IRTK)
Module : $Id$
Copyright : Imperial College, Department of Computing
Visual Information Processing (VIP), 2008 onwards
Date : $Date$
Version : $Revision$
Changes : $Author$
=========================================================================*/
#include <irtkImage.h>
#include <nr.h>
#include <sys/types.h>
#ifdef WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif
#include <map>
char *output_name = NULL, **input_names = NULL;
char *mask_name = NULL;
long ran2Seed;
long ran2initialSeed;
// first short is the label, second short is the number of images voting
// for that label.
typedef map<short, short> countMap;
map<short, short>::iterator iter;
short getMostPopular(countMap cMap){
short maxCount = 0, mostPopLabel = -1;
if (cMap.size() == 0){
// No votes to count, treat as background.
return 0;
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second > maxCount){
maxCount = iter->second;
mostPopLabel = iter->first;
}
}
return mostPopLabel;
}
bool isEquivocal(countMap cMap){
short maxCount = 0;
short numberWithMax = 0;
if (cMap.size() == 0){
// No votes to count, treat as background.
return false;
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second > maxCount){
maxCount = iter->second;
}
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second == maxCount){
++numberWithMax;
}
}
if (numberWithMax > 1){
return true;
} else {
return false;
}
}
short decideOnTie(countMap cMap){
short maxCount = 0;
short numberWithMax = 0;
int index, count;
short temp;
double val;
if (cMap.size() == 0){
// No votes to count, treat as background.
return false;
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second > maxCount){
maxCount = iter->second;
}
}
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second == maxCount){
++numberWithMax;
}
}
short *tiedLabels = new short[numberWithMax];
count = 0;
for (iter = cMap.begin(); iter != cMap.end(); ++iter){
if (iter->second == maxCount){
tiedLabels[count] = iter->first;
++count;
}
}
index = (int) floor( ran2(&ran2Seed) * count );
temp = tiedLabels[index];
delete tiedLabels;
return temp;
}
void usage()
{
cerr << " " << endl;
cerr << " Usage: combineLabels [output] [N] [input1] .. [inputN] <-options>" << endl;
cerr << " " << endl;
cerr << " Combine [N] label images into a consensus labelling using the vote rule." << endl;
cerr << " Labels for voxels where the vote is tied for are decided randomly." << endl;
cerr << " " << endl;
cerr << " The images [input1] .. [inputN] are assumed to contain labellings on the" << endl;
cerr << " same voxel grid. For each voxel, the modal label from the images is used " << endl;
cerr << " to generate a label in the output image." << endl;
cerr << " " << endl;
cerr << " Options:" << endl;
cerr << " -u [filename] Write out a volume showing the unanimous voxels." << endl;
cerr << " -pad [value] Padding value, default = -1." << endl;
cerr << " " << endl;
exit(1);
}
int main(int argc, char **argv)
{
int numberOfClassifiers, i, v, ok, voxels, contendedVoxelCount, contendedVoxelIndex, equivocalCount;
irtkGreyPixel *pIn, *pIn_0, *pOut;
irtkGreyImage input, output;
irtkGreyImage *input_0;
irtkByteImage mask;
irtkBytePixel *pMask;
int writeMask = false;
int pad = -1;
// Check command line
if (argc < 4){
usage();
}
output_name = argv[1];
argc--;
argv++;
numberOfClassifiers = atoi(argv[1]);
argc--;
argv++;
input_names = new char *[numberOfClassifiers];
for (i = 0; i < numberOfClassifiers; i++){
input_names[i] = argv[1];
argc--;
argv++;
}
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-u") == 0)){
argc--; argv++;
mask_name = argv[1];
writeMask = true;
argc--; argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-pad") == 0)){
argc--; argv++;
pad = atoi(argv[1]);
argc--; argv++;
ok = true;
}
if (ok == false){
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
// Mask has a value of 1 for all uncontended voxels.
mask.Read(input_names[0]);
voxels = mask.GetNumberOfVoxels();
// Reset mask so that all voxels are marked as unanimous.
pMask = mask.GetPointerToVoxels();
for (i = 0; i < voxels; ++i){
*pMask = 1;
++pMask;
}
input_0 = new irtkGreyImage(input_names[0]);
for (i = 1; i < numberOfClassifiers; ++i){
input.Read(input_names[i]);
pIn = input.GetPointerToVoxels();
pIn_0 = input_0->GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
for (v = 0; v < voxels; ++v){
if (*pIn != *pIn_0 && (*pIn > pad || *pIn_0 > pad) ){
*pMask = 0;
}
++pIn;
++pIn_0;
++pMask;
}
}
// Do we need to write out the `unanimask'?
if (writeMask == true && mask_name != NULL){
mask.Write(mask_name);
}
// free some memory.
delete input_0;
contendedVoxelCount = 0;
pMask = mask.GetPointerToVoxels();
for (i = 0; i < voxels; ++i){
if (*pMask == 0){
++contendedVoxelCount;
}
++pMask;
}
cout << "Number of contended voxels = " << contendedVoxelCount << " = ";
cout << 100.0 * contendedVoxelCount / ((double) voxels) << "%" << endl;
countMap *counts = new countMap[contendedVoxelCount];
for (i = 0; i < numberOfClassifiers; ++i){
input.Read(input_names[i]);
pIn = input.GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
contendedVoxelIndex = 0;
for (v = 0; v < voxels; ++v){
//Is the current voxel contended?
if (*pMask == 0){
if (*pIn > pad){
++counts[contendedVoxelIndex][*pIn];
}
++contendedVoxelIndex;
}
++pIn;
++pMask;
}
}
// Initialise output image using first input image, all inputs assumed
// same size etc..
output.Read(input_names[0]);
pOut = output.GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
contendedVoxelIndex = 0;
for (v = 0; v < voxels; ++v){
//Is the current voxel contentded?
if (*pMask == 0){
*pOut = getMostPopular(counts[contendedVoxelIndex]);
++contendedVoxelIndex;
}
++pOut;
++pMask;
}
// Get ready for random stuff.
time_t tv;
tv = time(NULL);
ran2Seed = tv;
ran2initialSeed = -1 * ran2Seed;
(void) ran2(&ran2initialSeed);
contendedVoxelIndex = 0;
equivocalCount = 0;
pOut = output.GetPointerToVoxels();
pMask = mask.GetPointerToVoxels();
for (v = 0; v < voxels; ++v){
//Is the current voxel contended?
if (*pMask == 0){
if (isEquivocal(counts[contendedVoxelIndex])){
++equivocalCount;
*pOut = decideOnTie(counts[contendedVoxelIndex]);
}
++contendedVoxelIndex;
}
++pOut;
++pMask;
}
cout << "Number of equivocal voxels = " << equivocalCount << " = ";
cout << 100.0 * equivocalCount / ((double) voxels) << "%" << endl;
output.Write(output_name);
delete [] counts;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fumorph.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:35:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_FU_MORPH_HXX
#define SD_FU_MORPH_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#include <math.h>
/*************************************************************************
|*
\************************************************************************/
class List;
class PolyPolygon3D;
class Polygon3D;
class Vector3D;
namespace sd {
class FuMorph
: public FuPoor
{
public:
TYPEINFO();
FuMorph (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuMorph (void) {}
private:
void ImpInsertPolygons(List& rPolyPolyList3D, BOOL bAttributeFade,
const SdrObject* pObj1, const SdrObject* pObj2);
PolyPolygon3D* ImpCreateMorphedPolygon(
const PolyPolygon3D& rPolyPolyStart,
const PolyPolygon3D& rPolyPolyEnd,
const double fMorphingFactor);
BOOL ImpMorphPolygons(
const PolyPolygon3D& rPolyPoly1, const PolyPolygon3D& rPolyPoly2,
const USHORT nSteps, List& rPolyPolyList3D);
void ImpAddPolys(PolyPolygon3D& rSmaller, const PolyPolygon3D& rBigger);
void ImpEqualizePolyPointCount(Polygon3D& rSmall, const Polygon3D& rBig);
sal_uInt16 ImpGetNearestIndex(const Polygon3D& rPoly, const Vector3D& rPos);
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS impressfunctions (1.3.38); FILE MERGED 2005/10/28 10:56:50 cl 1.3.38.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fumorph.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-12-14 17:13:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_FU_MORPH_HXX
#define SD_FU_MORPH_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#include <math.h>
/*************************************************************************
|*
\************************************************************************/
class List;
class PolyPolygon3D;
class Polygon3D;
class Vector3D;
namespace sd {
class FuMorph
: public FuPoor
{
public:
TYPEINFO();
static FunctionReference Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq );
virtual void DoExecute( SfxRequest& rReq );
private:
FuMorph (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
void ImpInsertPolygons(List& rPolyPolyList3D, BOOL bAttributeFade,
const SdrObject* pObj1, const SdrObject* pObj2);
PolyPolygon3D* ImpCreateMorphedPolygon(
const PolyPolygon3D& rPolyPolyStart,
const PolyPolygon3D& rPolyPolyEnd,
const double fMorphingFactor);
BOOL ImpMorphPolygons(
const PolyPolygon3D& rPolyPoly1, const PolyPolygon3D& rPolyPoly2,
const USHORT nSteps, List& rPolyPolyList3D);
void ImpAddPolys(PolyPolygon3D& rSmaller, const PolyPolygon3D& rBigger);
void ImpEqualizePolyPointCount(Polygon3D& rSmall, const Polygon3D& rBig);
sal_uInt16 ImpGetNearestIndex(const Polygon3D& rPoly, const Vector3D& rPos);
};
} // end of namespace sd
#endif
<|endoftext|> |
<commit_before>//===-- InstLoops.cpp ---------------------------------------- ---*- C++ -*--=//
// Pass to instrument loops
//
// At every backedge, insert a counter for that backedge and a call function
//===----------------------------------------------------------------------===//
#include "llvm/Reoptimizer/InstLoops.h"
#include "llvm/Support/CFG.h"
#include "llvm/Constants.h"
#include "llvm/iMemory.h"
#include "llvm/GlobalVariable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/iOther.h"
#include "llvm/iOperators.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/Pass.h"
//this is used to color vertices
//during DFS
enum Color{
WHITE,
GREY,
BLACK
};
struct InstLoops : public FunctionPass {
bool runOnFunction(Function &F);
};
static RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");
// createProfilePathsPass - Create a new pass to add path profiling
//
Pass *createInstLoopsPass() {
return new InstLoops();
}
//helper function to get back edges: it is called by
//the "getBackEdges" function below
void getBackEdgesVisit(BasicBlock *u,
std::map<BasicBlock *, Color > &color,
std::map<BasicBlock *, int > &d,
int &time, Value *threshold) {
color[u]=GREY;
time++;
d[u]=time;
for(BasicBlock::succ_iterator vl = succ_begin(u),
ve = succ_end(u); vl != ve; ++vl){
BasicBlock *BB = *vl;
if(color[BB]!=GREY && color[BB]!=BLACK){
getBackEdgesVisit(BB, color, d, time, threshold);
}
//now checking for d and f vals
if(color[BB]==GREY){
//so v is ancestor of u if time of u > time of v
if(d[u] >= d[BB]){
//insert a new basic block: modify terminator accordingly!
BasicBlock *newBB = new BasicBlock("", u->getParent());
BranchInst *ti = cast<BranchInst>(u->getTerminator());
unsigned char index = 1;
if(ti->getSuccessor(0) == BB){
index = 0;
}
assert(ti->getNumSuccessors() > index && "Not enough successors!");
ti->setSuccessor(index, newBB);
//insert global variable of type int
Constant *initializer = Constant::getNullValue(Type::IntTy);
GlobalVariable *countVar = new GlobalVariable(Type::IntTy, false, true,
initializer,
"loopCounter",
u->getParent()->getParent());
//load the variable
Instruction *ldInst = new LoadInst(countVar,"");
//increment
Instruction *addIn =
BinaryOperator::create(Instruction::Add, ldInst,
ConstantSInt::get(Type::IntTy,1), "");
//store
Instruction *stInst = new StoreInst(addIn, countVar);
Instruction *etr = new LoadInst(threshold, "threshold");
Instruction *cmpInst = new SetCondInst(Instruction::SetLE, etr,
addIn, "");
BasicBlock *callTrigger = new BasicBlock("", u->getParent());
//branch to calltrigger, or *vl
Instruction *newBr = new BranchInst(callTrigger, BB, cmpInst);
BasicBlock::InstListType < = newBB->getInstList();
lt.push_back(ldInst);
lt.push_back(addIn);
lt.push_back(stInst);
lt.push_back(etr);
lt.push_back(cmpInst);
lt.push_back(newBr);
//Now add instructions to the triggerCall BB
//now create a call function
//call llvm_first_trigger(int *x);
std::vector<const Type*> inCountArgs;
inCountArgs.push_back(PointerType::get(Type::IntTy));
const FunctionType *cFty = FunctionType::get(Type::VoidTy, inCountArgs,
false);
Function *inCountMth =
u->getParent()->getParent()->getOrInsertFunction("llvm_first_trigger", cFty);
assert(inCountMth && "Initialize method could not be inserted!");
std::vector<Value *> iniArgs;
iniArgs.push_back(countVar);
Instruction *call = new CallInst(inCountMth, iniArgs, "");
callTrigger->getInstList().push_back(call);
callTrigger->getInstList().push_back(new BranchInst(BB));
//now iterate over *vl, and set its Phi nodes right
for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end();
BB2Inst != BBend; ++BB2Inst){
if(PHINode *phiInst=dyn_cast<PHINode>(&*BB2Inst)){
int bbIndex = phiInst->getBasicBlockIndex(u);
if(bbIndex>=0){
phiInst->setIncomingBlock(bbIndex, newBB);
Value *val = phiInst->getIncomingValue((unsigned int)bbIndex);
phiInst->addIncoming(val, callTrigger);
}
}
}
}
}
}
color[u]=BLACK;//done with visiting the node and its neighbors
}
//getting the backedges in a graph
//Its a variation of DFS to get the backedges in the graph
//We get back edges by associating a time
//and a color with each vertex.
//The time of a vertex is the time when it was first visited
//The color of a vertex is initially WHITE,
//Changes to GREY when it is first visited,
//and changes to BLACK when ALL its neighbors
//have been visited
//So we have a back edge when we meet a successor of
//a node with smaller time, and GREY color
void getBackEdges(Function &F, Value *threshold){
std::map<BasicBlock *, Color > color;
std::map<BasicBlock *, int> d;
int time=0;
getBackEdgesVisit(F.begin(), color, d, time, threshold);
}
//Per function pass for inserting counters and call function
bool InstLoops::runOnFunction(Function &F){
static GlobalVariable *threshold = NULL;
static bool insertedThreshold = false;
if(!insertedThreshold){
threshold = new GlobalVariable(Type::IntTy, false, false, 0,
"reopt_threshold");
F.getParent()->getGlobalList().push_back(threshold);
insertedThreshold = true;
}
if(F.getName() == "main"){
//intialize threshold
std::vector<const Type*> initialize_args;
initialize_args.push_back(PointerType::get(Type::IntTy));
const FunctionType *Fty = FunctionType::get(Type::VoidTy, initialize_args,
false);
Function *initialMeth = F.getParent()->getOrInsertFunction("reoptimizerInitialize", Fty);
assert(initialMeth && "Initialize method could not be inserted!");
std::vector<Value *> trargs;
trargs.push_back(threshold);
new CallInst(initialMeth, trargs, "", F.begin()->begin());
}
assert(threshold && "GlobalVariable threshold not defined!");
if(F.isExternal()) {
return false;
}
getBackEdges(F, threshold);
return true;
}
<commit_msg>Fix typeo<commit_after>//===-- InstLoops.cpp ---------------------------------------- ---*- C++ -*--=//
// Pass to instrument loops
//
// At every backedge, insert a counter for that backedge and a call function
//===----------------------------------------------------------------------===//
#include "llvm/Reoptimizer/InstLoops.h"
#include "llvm/Support/CFG.h"
#include "llvm/Constants.h"
#include "llvm/iMemory.h"
#include "llvm/GlobalVariable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/iOther.h"
#include "llvm/iOperators.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Module.h"
#include "llvm/Function.h"
#include "llvm/Pass.h"
//this is used to color vertices
//during DFS
enum Color{
WHITE,
GREY,
BLACK
};
struct InstLoops : public FunctionPass {
bool runOnFunction(Function &F);
};
static RegisterOpt<InstLoops> X("instloops", "Instrument backedges for profiling");
// createInstLoopsPass - Create a new pass to add path profiling
//
Pass *createInstLoopsPass() {
return new InstLoops();
}
//helper function to get back edges: it is called by
//the "getBackEdges" function below
void getBackEdgesVisit(BasicBlock *u,
std::map<BasicBlock *, Color > &color,
std::map<BasicBlock *, int > &d,
int &time, Value *threshold) {
color[u]=GREY;
time++;
d[u]=time;
for(BasicBlock::succ_iterator vl = succ_begin(u),
ve = succ_end(u); vl != ve; ++vl){
BasicBlock *BB = *vl;
if(color[BB]!=GREY && color[BB]!=BLACK){
getBackEdgesVisit(BB, color, d, time, threshold);
}
//now checking for d and f vals
if(color[BB]==GREY){
//so v is ancestor of u if time of u > time of v
if(d[u] >= d[BB]){
//insert a new basic block: modify terminator accordingly!
BasicBlock *newBB = new BasicBlock("", u->getParent());
BranchInst *ti = cast<BranchInst>(u->getTerminator());
unsigned char index = 1;
if(ti->getSuccessor(0) == BB){
index = 0;
}
assert(ti->getNumSuccessors() > index && "Not enough successors!");
ti->setSuccessor(index, newBB);
//insert global variable of type int
Constant *initializer = Constant::getNullValue(Type::IntTy);
GlobalVariable *countVar = new GlobalVariable(Type::IntTy, false, true,
initializer,
"loopCounter",
u->getParent()->getParent());
//load the variable
Instruction *ldInst = new LoadInst(countVar,"");
//increment
Instruction *addIn =
BinaryOperator::create(Instruction::Add, ldInst,
ConstantSInt::get(Type::IntTy,1), "");
//store
Instruction *stInst = new StoreInst(addIn, countVar);
Instruction *etr = new LoadInst(threshold, "threshold");
Instruction *cmpInst = new SetCondInst(Instruction::SetLE, etr,
addIn, "");
BasicBlock *callTrigger = new BasicBlock("", u->getParent());
//branch to calltrigger, or *vl
Instruction *newBr = new BranchInst(callTrigger, BB, cmpInst);
BasicBlock::InstListType < = newBB->getInstList();
lt.push_back(ldInst);
lt.push_back(addIn);
lt.push_back(stInst);
lt.push_back(etr);
lt.push_back(cmpInst);
lt.push_back(newBr);
//Now add instructions to the triggerCall BB
//now create a call function
//call llvm_first_trigger(int *x);
std::vector<const Type*> inCountArgs;
inCountArgs.push_back(PointerType::get(Type::IntTy));
const FunctionType *cFty = FunctionType::get(Type::VoidTy, inCountArgs,
false);
Function *inCountMth =
u->getParent()->getParent()->getOrInsertFunction("llvm_first_trigger", cFty);
assert(inCountMth && "Initialize method could not be inserted!");
std::vector<Value *> iniArgs;
iniArgs.push_back(countVar);
Instruction *call = new CallInst(inCountMth, iniArgs, "");
callTrigger->getInstList().push_back(call);
callTrigger->getInstList().push_back(new BranchInst(BB));
//now iterate over *vl, and set its Phi nodes right
for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end();
BB2Inst != BBend; ++BB2Inst){
if(PHINode *phiInst=dyn_cast<PHINode>(&*BB2Inst)){
int bbIndex = phiInst->getBasicBlockIndex(u);
if(bbIndex>=0){
phiInst->setIncomingBlock(bbIndex, newBB);
Value *val = phiInst->getIncomingValue((unsigned int)bbIndex);
phiInst->addIncoming(val, callTrigger);
}
}
}
}
}
}
color[u]=BLACK;//done with visiting the node and its neighbors
}
//getting the backedges in a graph
//Its a variation of DFS to get the backedges in the graph
//We get back edges by associating a time
//and a color with each vertex.
//The time of a vertex is the time when it was first visited
//The color of a vertex is initially WHITE,
//Changes to GREY when it is first visited,
//and changes to BLACK when ALL its neighbors
//have been visited
//So we have a back edge when we meet a successor of
//a node with smaller time, and GREY color
void getBackEdges(Function &F, Value *threshold){
std::map<BasicBlock *, Color > color;
std::map<BasicBlock *, int> d;
int time=0;
getBackEdgesVisit(F.begin(), color, d, time, threshold);
}
//Per function pass for inserting counters and call function
bool InstLoops::runOnFunction(Function &F){
static GlobalVariable *threshold = NULL;
static bool insertedThreshold = false;
if(!insertedThreshold){
threshold = new GlobalVariable(Type::IntTy, false, false, 0,
"reopt_threshold");
F.getParent()->getGlobalList().push_back(threshold);
insertedThreshold = true;
}
if(F.getName() == "main"){
//intialize threshold
std::vector<const Type*> initialize_args;
initialize_args.push_back(PointerType::get(Type::IntTy));
const FunctionType *Fty = FunctionType::get(Type::VoidTy, initialize_args,
false);
Function *initialMeth = F.getParent()->getOrInsertFunction("reoptimizerInitialize", Fty);
assert(initialMeth && "Initialize method could not be inserted!");
std::vector<Value *> trargs;
trargs.push_back(threshold);
new CallInst(initialMeth, trargs, "", F.begin()->begin());
}
assert(threshold && "GlobalVariable threshold not defined!");
if(F.isExternal()) {
return false;
}
getBackEdges(F, threshold);
return true;
}
<|endoftext|> |
<commit_before>#include "digitanksentity.h"
#include <GL/glew.h>
#include <maths.h>
#include <mtrand.h>
#include <geometry.h>
#include <renderer/renderer.h>
#include <renderer/dissolver.h>
#include "digitanksgame.h"
#include "wreckage.h"
REGISTER_ENTITY(CDigitanksEntity);
NETVAR_TABLE_BEGIN(CDigitanksEntity);
NETVAR_TABLE_END();
SAVEDATA_TABLE_BEGIN(CDigitanksEntity);
SAVEDATA_DEFINE(CSaveData::DATA_COPYVECTOR, CEntityHandle<class CSupplyLine>, m_ahSupplyLinesIntercepted);
SAVEDATA_TABLE_END();
void CDigitanksEntity::Spawn()
{
BaseClass::Spawn();
m_bTakeDamage = true;
m_flTotalHealth = TotalHealth();
m_flHealth = m_flTotalHealth;
CalculateVisibility();
}
void CDigitanksEntity::Think()
{
BaseClass::Think();
if (!IsAlive() && GameServer()->GetGameTime() > m_flTimeKilled + 1.0f)
{
GameServer()->Delete(this);
if (DigitanksGame()->GetTerrain()->IsPointOverHole(GetOrigin()))
{
CWreckage* pWreckage = CreateWreckage();
if (pWreckage)
pWreckage->FellIntoHole();
}
else if (DigitanksGame()->GetGameType() == GAMETYPE_ARTILLERY)
{
switch (RandomInt(0, 8))
{
case 0:
case 6:
case 7:
case 8:
default:
{
CreateWreckage();
break;
}
case 1:
{
CProjectile* pProjectile = GameServer()->Create<CLargeShell>("CLargeShell");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 2:
{
CProjectile* pProjectile = GameServer()->Create<CAOEShell>("CAOEShell");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 3:
{
CProjectile* pProjectile = GameServer()->Create<CClusterBomb>("CClusterBomb");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 4:
{
CProjectile* pProjectile = GameServer()->Create<CEarthshaker>("CEarthshaker");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 5:
{
CProjectile* pProjectile = GameServer()->Create<CTractorBomb>("CTractorBomb");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
}
}
else
{
// Strategy mode
CreateWreckage();
}
}
}
CWreckage* CDigitanksEntity::CreateWreckage()
{
// Figure out what to do about structures later.
if (dynamic_cast<CDigitank*>(this) == NULL)
return NULL;
CWreckage* pWreckage = GameServer()->Create<CWreckage>("CWreckage");
pWreckage->SetOrigin(GetRenderOrigin());
pWreckage->SetAngles(GetRenderAngles());
pWreckage->SetModel(GetModel());
pWreckage->SetGravity(Vector(0, DigitanksGame()->GetGravity(), 0));
pWreckage->SetOldTeam(GetDigitanksTeam());
pWreckage->CalculateVisibility();
CDigitank* pTank = dynamic_cast<CDigitank*>(this);
if (pTank)
pWreckage->SetTurretModel(pTank->GetTurretModel());
bool bColorSwap = GetTeam() && (dynamic_cast<CDigitank*>(this));
if (bColorSwap)
pWreckage->SetColorSwap(GetTeam()->GetColor());
return pWreckage;
}
void CDigitanksEntity::StartTurn()
{
float flHealth = m_flHealth;
m_flHealth = Approach(m_flTotalHealth, m_flHealth, HealthRechargeRate());
if (flHealth - m_flHealth < 0)
DigitanksGame()->OnTakeDamage(this, NULL, NULL, flHealth - m_flHealth, true, false);
m_ahSupplyLinesIntercepted.clear();
}
void CDigitanksEntity::EndTurn()
{
InterceptSupplyLines();
}
void CDigitanksEntity::InterceptSupplyLines()
{
// Haha... no.
if (dynamic_cast<CSupplyLine*>(this))
return;
if (!GetTeam())
return;
for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
{
CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
if (!pEntity)
continue;
CSupplyLine* pSupplyLine = dynamic_cast<CSupplyLine*>(pEntity);
if (!pSupplyLine)
continue;
if (pSupplyLine->GetTeam() == GetTeam())
continue;
if (!pSupplyLine->GetTeam())
continue;
if (!pSupplyLine->GetSupplier() || !pSupplyLine->GetEntity())
continue;
Vector vecEntity = GetOrigin();
vecEntity.y = 0;
Vector vecSupplier = pSupplyLine->GetSupplier()->GetOrigin();
vecSupplier.y = 0;
Vector vecUnit = pSupplyLine->GetEntity()->GetOrigin();
vecUnit.y = 0;
if (DistanceToLineSegment(vecEntity, vecSupplier, vecUnit) > GetBoundingRadius()+4)
continue;
bool bFound = false;
for (size_t j = 0; j < m_ahSupplyLinesIntercepted.size(); j++)
{
if (pSupplyLine == m_ahSupplyLinesIntercepted[j])
{
bFound = true;
break;
}
}
if (!bFound)
{
pSupplyLine->Intercept(0.2f);
m_ahSupplyLinesIntercepted.push_back(pSupplyLine);
}
}
}
CDigitanksTeam* CDigitanksEntity::GetDigitanksTeam() const
{
return static_cast<CDigitanksTeam*>(BaseClass::GetTeam());
}
bool CDigitanksEntity::ShouldRender() const
{
return GetVisibility(DigitanksGame()->GetCurrentLocalDigitanksTeam()) > 0;
}
void CDigitanksEntity::RenderVisibleArea()
{
if (VisibleRange() == 0)
return;
CRenderingContext c(GameServer()->GetRenderer());
c.Translate(GetOrigin());
c.Scale(VisibleRange(), VisibleRange(), VisibleRange());
c.RenderSphere();
}
float CDigitanksEntity::GetVisibility(CDigitanksTeam* pTeam) const
{
CDigitanksGame* pGame = DigitanksGame();
float flConceal = 0.0f;
if (GetsConcealmentBonus())
{
if (pGame->GetTerrain()->GetBit(CTerrain::WorldToArraySpace(m_vecOrigin.Get().x), CTerrain::WorldToArraySpace(m_vecOrigin.Get().z), TB_TREE))
flConceal = 0.7f;
}
float flCloak = GetCloakConcealment();
if (flCloak > flConceal)
flConceal = flCloak;
if (HasLostConcealment())
flConceal = 0;
if (!pGame->ShouldRenderFogOfWar())
return 1 - flConceal;
if (!pTeam)
return 0;
if (pTeam == GetDigitanksTeam())
return 1 - flConceal/2;
float flVisibility = pTeam->GetEntityVisibility(GetHandle()) - flConceal;
if (flVisibility < 0)
return 0;
return flVisibility;
}
void CDigitanksEntity::CalculateVisibility()
{
for (size_t i = 0; i < DigitanksGame()->GetNumTeams(); i++)
DigitanksGame()->GetDigitanksTeam(i)->CalculateEntityVisibility(this);
}
float CDigitanksEntity::GetVisibility() const
{
CDigitanksGame* pGame = DigitanksGame();
if (!pGame)
return 0;
return GetVisibility(pGame->GetCurrentLocalDigitanksTeam());
}
float CDigitanksEntity::VisibleRange() const
{
// Don't use GetOrigin because CDigitank::GetOrigin() can be expensive and we really don't want what it does.
if (TreesReduceVisibility() && DigitanksGame()->GetTerrain()->IsPointInTrees(m_vecOrigin))
return BaseVisibleRange()/2;
return BaseVisibleRange();
}
void CDigitanksEntity::RenderAvailableArea(int iArea)
{
float flAvailableArea = AvailableArea(iArea);
if (flAvailableArea == 0)
return;
float flScoutScale = 1.0f;
// Scouts have very tall ones so we can see them underneath on the ground.
if (GetUnitType() == UNIT_SCOUT)
flScoutScale = 10;
if (dynamic_cast<CStructure*>(this) && DigitanksGame()->GetControlMode() == MODE_AIM)
flScoutScale = 10;
CRenderingContext c(GameServer()->GetRenderer());
c.Translate(GetOrigin());
c.Scale(flAvailableArea, flAvailableArea*flScoutScale, flAvailableArea);
c.RenderSphere();
}
void CDigitanksEntity::ModifyContext(CRenderingContext* pContext, bool bTransparent)
{
BaseClass::ModifyContext(pContext, bTransparent);
CDigitanksTeam* pTeam = DigitanksGame()->GetCurrentTeam();
float flVisibility = GetVisibility();
if (flVisibility < 1)
{
pContext->SetAlpha(flVisibility);
pContext->SetBlend(BLEND_ALPHA);
}
}
<commit_msg>Don't create wreckage on the client.<commit_after>#include "digitanksentity.h"
#include <GL/glew.h>
#include <maths.h>
#include <mtrand.h>
#include <geometry.h>
#include <renderer/renderer.h>
#include <renderer/dissolver.h>
#include "digitanksgame.h"
#include "wreckage.h"
REGISTER_ENTITY(CDigitanksEntity);
NETVAR_TABLE_BEGIN(CDigitanksEntity);
NETVAR_TABLE_END();
SAVEDATA_TABLE_BEGIN(CDigitanksEntity);
SAVEDATA_DEFINE(CSaveData::DATA_COPYVECTOR, CEntityHandle<class CSupplyLine>, m_ahSupplyLinesIntercepted);
SAVEDATA_TABLE_END();
void CDigitanksEntity::Spawn()
{
BaseClass::Spawn();
m_bTakeDamage = true;
m_flTotalHealth = TotalHealth();
m_flHealth = m_flTotalHealth;
CalculateVisibility();
}
void CDigitanksEntity::Think()
{
BaseClass::Think();
if (CNetwork::IsHost() && !IsAlive() && GameServer()->GetGameTime() > m_flTimeKilled + 1.0f)
{
GameServer()->Delete(this);
if (DigitanksGame()->GetTerrain()->IsPointOverHole(GetOrigin()))
{
CWreckage* pWreckage = CreateWreckage();
if (pWreckage)
pWreckage->FellIntoHole();
}
else if (DigitanksGame()->GetGameType() == GAMETYPE_ARTILLERY)
{
switch (RandomInt(0, 8))
{
case 0:
case 6:
case 7:
case 8:
default:
{
CreateWreckage();
break;
}
case 1:
{
CProjectile* pProjectile = GameServer()->Create<CLargeShell>("CLargeShell");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 2:
{
CProjectile* pProjectile = GameServer()->Create<CAOEShell>("CAOEShell");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 3:
{
CProjectile* pProjectile = GameServer()->Create<CClusterBomb>("CClusterBomb");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 4:
{
CProjectile* pProjectile = GameServer()->Create<CEarthshaker>("CEarthshaker");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
case 5:
{
CProjectile* pProjectile = GameServer()->Create<CTractorBomb>("CTractorBomb");
pProjectile->SetOwner(NULL);
pProjectile->SetOrigin(GetOrigin());
pProjectile->Explode();
break;
}
}
}
else
{
// Strategy mode
CreateWreckage();
}
}
}
CWreckage* CDigitanksEntity::CreateWreckage()
{
// Figure out what to do about structures later.
if (dynamic_cast<CDigitank*>(this) == NULL)
return NULL;
CWreckage* pWreckage = GameServer()->Create<CWreckage>("CWreckage");
pWreckage->SetOrigin(GetRenderOrigin());
pWreckage->SetAngles(GetRenderAngles());
pWreckage->SetModel(GetModel());
pWreckage->SetGravity(Vector(0, DigitanksGame()->GetGravity(), 0));
pWreckage->SetOldTeam(GetDigitanksTeam());
pWreckage->CalculateVisibility();
CDigitank* pTank = dynamic_cast<CDigitank*>(this);
if (pTank)
pWreckage->SetTurretModel(pTank->GetTurretModel());
bool bColorSwap = GetTeam() && (dynamic_cast<CDigitank*>(this));
if (bColorSwap)
pWreckage->SetColorSwap(GetTeam()->GetColor());
return pWreckage;
}
void CDigitanksEntity::StartTurn()
{
float flHealth = m_flHealth;
m_flHealth = Approach(m_flTotalHealth, m_flHealth, HealthRechargeRate());
if (flHealth - m_flHealth < 0)
DigitanksGame()->OnTakeDamage(this, NULL, NULL, flHealth - m_flHealth, true, false);
m_ahSupplyLinesIntercepted.clear();
}
void CDigitanksEntity::EndTurn()
{
InterceptSupplyLines();
}
void CDigitanksEntity::InterceptSupplyLines()
{
// Haha... no.
if (dynamic_cast<CSupplyLine*>(this))
return;
if (!GetTeam())
return;
for (size_t i = 0; i < GameServer()->GetMaxEntities(); i++)
{
CBaseEntity* pEntity = CBaseEntity::GetEntity(i);
if (!pEntity)
continue;
CSupplyLine* pSupplyLine = dynamic_cast<CSupplyLine*>(pEntity);
if (!pSupplyLine)
continue;
if (pSupplyLine->GetTeam() == GetTeam())
continue;
if (!pSupplyLine->GetTeam())
continue;
if (!pSupplyLine->GetSupplier() || !pSupplyLine->GetEntity())
continue;
Vector vecEntity = GetOrigin();
vecEntity.y = 0;
Vector vecSupplier = pSupplyLine->GetSupplier()->GetOrigin();
vecSupplier.y = 0;
Vector vecUnit = pSupplyLine->GetEntity()->GetOrigin();
vecUnit.y = 0;
if (DistanceToLineSegment(vecEntity, vecSupplier, vecUnit) > GetBoundingRadius()+4)
continue;
bool bFound = false;
for (size_t j = 0; j < m_ahSupplyLinesIntercepted.size(); j++)
{
if (pSupplyLine == m_ahSupplyLinesIntercepted[j])
{
bFound = true;
break;
}
}
if (!bFound)
{
pSupplyLine->Intercept(0.2f);
m_ahSupplyLinesIntercepted.push_back(pSupplyLine);
}
}
}
CDigitanksTeam* CDigitanksEntity::GetDigitanksTeam() const
{
return static_cast<CDigitanksTeam*>(BaseClass::GetTeam());
}
bool CDigitanksEntity::ShouldRender() const
{
return GetVisibility(DigitanksGame()->GetCurrentLocalDigitanksTeam()) > 0;
}
void CDigitanksEntity::RenderVisibleArea()
{
if (VisibleRange() == 0)
return;
CRenderingContext c(GameServer()->GetRenderer());
c.Translate(GetOrigin());
c.Scale(VisibleRange(), VisibleRange(), VisibleRange());
c.RenderSphere();
}
float CDigitanksEntity::GetVisibility(CDigitanksTeam* pTeam) const
{
CDigitanksGame* pGame = DigitanksGame();
CTerrain* pTerrain = pGame->GetTerrain();
float flConceal = 0.0f;
if (GetsConcealmentBonus() && pTerrain)
{
if (pTerrain->GetBit(CTerrain::WorldToArraySpace(m_vecOrigin.Get().x), CTerrain::WorldToArraySpace(m_vecOrigin.Get().z), TB_TREE))
flConceal = 0.7f;
}
float flCloak = GetCloakConcealment();
if (flCloak > flConceal)
flConceal = flCloak;
if (HasLostConcealment())
flConceal = 0;
if (!pGame->ShouldRenderFogOfWar())
return 1 - flConceal;
if (!pTeam)
return 0;
if (pTeam == GetDigitanksTeam())
return 1 - flConceal/2;
float flVisibility = pTeam->GetEntityVisibility(GetHandle()) - flConceal;
if (flVisibility < 0)
return 0;
return flVisibility;
}
void CDigitanksEntity::CalculateVisibility()
{
for (size_t i = 0; i < DigitanksGame()->GetNumTeams(); i++)
DigitanksGame()->GetDigitanksTeam(i)->CalculateEntityVisibility(this);
}
float CDigitanksEntity::GetVisibility() const
{
CDigitanksGame* pGame = DigitanksGame();
if (!pGame)
return 0;
return GetVisibility(pGame->GetCurrentLocalDigitanksTeam());
}
float CDigitanksEntity::VisibleRange() const
{
// Don't use GetOrigin because CDigitank::GetOrigin() can be expensive and we really don't want what it does.
if (TreesReduceVisibility() && DigitanksGame()->GetTerrain()->IsPointInTrees(m_vecOrigin))
return BaseVisibleRange()/2;
return BaseVisibleRange();
}
void CDigitanksEntity::RenderAvailableArea(int iArea)
{
float flAvailableArea = AvailableArea(iArea);
if (flAvailableArea == 0)
return;
float flScoutScale = 1.0f;
// Scouts have very tall ones so we can see them underneath on the ground.
if (GetUnitType() == UNIT_SCOUT)
flScoutScale = 10;
if (dynamic_cast<CStructure*>(this) && DigitanksGame()->GetControlMode() == MODE_AIM)
flScoutScale = 10;
CRenderingContext c(GameServer()->GetRenderer());
c.Translate(GetOrigin());
c.Scale(flAvailableArea, flAvailableArea*flScoutScale, flAvailableArea);
c.RenderSphere();
}
void CDigitanksEntity::ModifyContext(CRenderingContext* pContext, bool bTransparent)
{
BaseClass::ModifyContext(pContext, bTransparent);
CDigitanksTeam* pTeam = DigitanksGame()->GetCurrentTeam();
float flVisibility = GetVisibility();
if (flVisibility < 1)
{
pContext->SetAlpha(flVisibility);
pContext->SetBlend(BLEND_ALPHA);
}
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type
*
* @param x Primitive type such as int, double, long
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
int selectAction(PriorityQueue<int,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(std::time(NULL));
int action_forwards = FORWARD;
int action_backwards = BACKWARD;
int chosen_action = action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(action_forwards,0);
initiator_queue.enqueueWithPriority(action_backwards,0);
//create encoder
Encoder encoder;
encoder.Calibrate();
//create the state space
StateSpace space(100,50,initiator_queue);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
current_state.theta= M_PI * (encoder.GetAngle())/180;
current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
current_state.robot_state=static_cast<ROBOT_STATE>(chosen_action);
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
old_state=current_state;
chosen_action=selectAction(space[current_state]);
(chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
}
return 1;
}
/**
* @brief Analog to temperature variable in Boltzmann Distribution.
*
* @return current system time in milliseconds
*/
double temperature()
{
return static_cast<double>(std::time(NULL));
}
/**
* @brief Selects an action to perform based on probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @return integer corresponding to chosen action
*/
int selectAction(const PriorityQueue<int,double>& a_queue)
{
typedef PriorityQueue<int,double> PQ;
typedef std::vector< std::pair<int, double> > Vec_Pair;
typedef std::pair<int, double> Pair;
double sum= 0;
size_t i = 0;
size_t size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it1 < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand())/ RAND_MAX;
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return it->first;
}
return -1; //note that this line should never be reached
}
/**
* @brief Updates the utility (Q-value) of the system
*
* @param space Reference to StateSpace object
* @param new_state Reference to State instance giving the new system state
* @param old_state Reference to State instance giving the old system state
* @param alpha Learning rate of temporal difference learning algorithm
* @param gamma Discount factor applied to q-learning equation
*/
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
/**
* @brief Selects an action to perform based on probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @return integer corresponding to chosen action
*/
int selectActionAlt(const PriorityQueue<int, double>& a_queue) {
// queue to store action values
PriorityQueue<int, double> actionQueue(MAX);
double sum = 0.0;
// calculate partition function by iterating over action-values
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature());
}
// compute Boltzmann factors for action-values and enqueue to actionQueue
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
double priority = std::exp(iter.operator*().second / temperature()) / sum;
actionQueue.enqueueWithPriority(iter.operator*().first, priority);
}
// calculate cumulative probability distribution
for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
// change priority of it1->first data item in actionQueue to
// sum of priorities of it1 and it2 items
actionQueue.changePriority(it1->first, it1->second + it2->second);
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
<commit_msg>comments and casting<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type
*
* @param x Primitive type such as int, double, long
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
//function to calculate a temperature for the select action function as a function of time
double temperature();
//function to select next action
int selectAction(PriorityQueue<int,double>& a_queue);
//function to update a q value
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);
int main()
{
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try
{
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch(...)
{
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha=0.5;
//discount factor
const double gamma=0.5;
//seed rng
std::srand(static_cast<unsigned int>(std::time(NULL)));
int action_forwards = FORWARD;
int action_backwards = BACKWARD;
int chosen_action = action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int,double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(action_forwards,0);
initiator_queue.enqueueWithPriority(action_backwards,0);
//create encoder
Encoder encoder;
encoder.Calibrate();
//create the state space
StateSpace space(100,50,initiator_queue);
//state objects
State current_state(0,0,FORWARD);
State old_state(0,0,FORWARD);
while(true)
{
// set current state angle to angle received from encoder
// and set current state velocity to difference in new and
// old state angles over some time difference
current_state.theta= M_PI * (encoder.GetAngle())/180;
current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
current_state.robot_state=static_cast<ROBOT_STATE>(chosen_action);
// call updateQ function with state space, old and current states
// and learning rate, discount factor
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
// set old_state to current_state
old_state=current_state;
// determine chosen_action for current state
chosen_action=selectAction(space[current_state]);
// depending upon chosen action, call robot movement tools proxy with either
// swingForwards or swingBackwards commands.
(chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
}
return 1;
}
/**
* @brief Analog to temperature variable in Boltzmann Distribution.
*
* @return current system time in milliseconds
*/
double temperature()
{
return static_cast<double>(std::time(NULL));
}
/**
* @brief Selects an action to perform based on probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @return integer corresponding to chosen action
*/
int selectAction(const PriorityQueue<int,double>& a_queue)
{
typedef PriorityQueue<int,double> PQ;
typedef std::vector< std::pair<int, double> > Vec_Pair;
typedef std::pair<int, double> Pair;
double sum= 0;
size_t i = 0;
size_t size = a_queue.getSize();
Vec_Pair action_vec(size);
//Calculate partition function by iterating over action-values
for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
{
sum += std::exp((iter->second)/temperature());
}
//Calculate boltzmann factors for action-values
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
it->first = a_queue[i].first;
it->second = std::exp(a_queue[i].second /temperature()) / sum;
++i;
}
//calculate cumulative probability distribution
for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it1 < end; ++it1,++it2)
{
it1->second += it2->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand())/ RAND_MAX;
//select action based on probability
for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
{
//if RN falls within cumulative probability bin return the corresponding action
if(rand_num < it->second)return it->first;
}
return -1; //note that this line should never be reached
}
/**
* @brief Updates the utility (Q-value) of the system
*
* @param space Reference to StateSpace object
* @param new_state Reference to State instance giving the new system state
* @param old_state Reference to State instance giving the old system state
* @param alpha Learning rate of temporal difference learning algorithm
* @param gamma Discount factor applied to q-learning equation
*/
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)
{
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
/**
* @brief Selects an action to perform based on probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @return integer corresponding to chosen action
*/
int selectActionAlt(const PriorityQueue<int, double>& a_queue) {
// queue to store action values
PriorityQueue<int, double> actionQueue(MAX);
double sum = 0.0;
// calculate partition function by iterating over action-values
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature());
}
// compute Boltzmann factors for action-values and enqueue to actionQueue
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
double priority = std::exp(iter.operator*().second / temperature()) / sum;
actionQueue.enqueueWithPriority(iter.operator*().first, priority);
}
// calculate cumulative probability distribution
for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
// change priority of it1->first data item in actionQueue to
// sum of priorities of it1 and it2 items
actionQueue.changePriority(it1->first, it1->second + it2->second);
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __INSTRUCTIONSCHEDULER_HPP
#define __INSTRUCTIONSCHEDULER_HPP
#include <map>
#include <set>
#include <deque>
#include <mutex>
#include <bh.h>
#include "ResourceManager.hpp"
#include "SourceKernelCall.hpp"
class InstructionScheduler
{
private:
typedef std::map<bh_base*, BaseArray*> ArrayMap;
typedef std::map<bh_opcode, bh_extmethod_impl> FunctionMap;
typedef std::map<KernelID, Kernel> KernelMap;
typedef std::pair<KernelID, SourceKernelCall> KernelCall;
typedef std::deque<KernelCall> CallQueue;
typedef std::map<size_t, BaseArray*> ViewList;
std::mutex kernelMutex;
std::map<size_t,size_t> knownKernelID;
KernelMap kernelMap;
CallQueue callQueue;
ArrayMap arrayMap;
FunctionMap functionMap;
void compileAndRun(SourceKernelCall sourceKernel);
void build(KernelID id, const std::string source);
bh_error extmethod(bh_instruction* inst);
bh_error call_child(const bh_ir_kernel& kernel);
SourceKernelCall generateKernel(const bh_ir_kernel& kernel);
std::string generateFunctionBody(const bh_ir_kernel& kernel, const size_t kdims,
const std::vector<bh_index>& shape,
const std::vector<std::vector<size_t> >& dimOrders,
bool& float64, bool& complex, bool& integer, bool& random);
void sync(const std::set<bh_base*>& arrays);
void discard(const std::set<bh_base*>& arrays);
void beginDim(std::stringstream& source,
std::stringstream& indentss,
std::vector<std::string>& beforesource,
const size_t dims);
void endDim(std::stringstream& source,
std::stringstream& indentss,
std::vector<std::string>& beforesource,
std::set<bh_view>& save,
std::map<size_t,size_t>& incr_idx,
const std::vector<bh_index>& shape,
const size_t dims,
const size_t kdims,
const bh_index elements,
const bh_ir_kernel& kernel);
std::vector<std::vector<size_t> > genDimOrders(const std::map<bh_intp, bh_int64>& sweeps, const size_t ndim);
public:
InstructionScheduler() {}
void registerFunction(bh_opcode opcode, bh_extmethod_impl extmothod);
bh_error schedule(const bh_ir* bhir);
};
#endif
<commit_msg>cleanup<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __INSTRUCTIONSCHEDULER_HPP
#define __INSTRUCTIONSCHEDULER_HPP
#include <map>
#include <set>
#include <deque>
#include <mutex>
#include <bh.h>
#include "ResourceManager.hpp"
#include "SourceKernelCall.hpp"
class InstructionScheduler
{
private:
typedef std::map<bh_base*, BaseArray*> ArrayMap;
typedef std::map<bh_opcode, bh_extmethod_impl> FunctionMap;
typedef std::map<KernelID, Kernel> KernelMap;
typedef std::pair<KernelID, SourceKernelCall> KernelCall;
typedef std::deque<KernelCall> CallQueue;
std::mutex kernelMutex;
std::map<size_t,size_t> knownKernelID;
KernelMap kernelMap;
CallQueue callQueue;
ArrayMap arrayMap;
FunctionMap functionMap;
void compileAndRun(SourceKernelCall sourceKernel);
void build(KernelID id, const std::string source);
bh_error extmethod(bh_instruction* inst);
bh_error call_child(const bh_ir_kernel& kernel);
SourceKernelCall generateKernel(const bh_ir_kernel& kernel);
std::string generateFunctionBody(const bh_ir_kernel& kernel, const size_t kdims,
const std::vector<bh_index>& shape,
const std::vector<std::vector<size_t> >& dimOrders,
bool& float64, bool& complex, bool& integer, bool& random);
void sync(const std::set<bh_base*>& arrays);
void discard(const std::set<bh_base*>& arrays);
void beginDim(std::stringstream& source,
std::stringstream& indentss,
std::vector<std::string>& beforesource,
const size_t dims);
void endDim(std::stringstream& source,
std::stringstream& indentss,
std::vector<std::string>& beforesource,
std::set<bh_view>& save,
std::map<size_t,size_t>& incr_idx,
const std::vector<bh_index>& shape,
const size_t dims,
const size_t kdims,
const bh_index elements,
const bh_ir_kernel& kernel);
std::vector<std::vector<size_t> > genDimOrders(const std::map<bh_intp, bh_int64>& sweeps, const size_t ndim);
public:
InstructionScheduler() {}
void registerFunction(bh_opcode opcode, bh_extmethod_impl extmothod);
bh_error schedule(const bh_ir* bhir);
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_Network_InternetAddress_inl_
#define _Stroika_Foundation_IO_Network_InternetAddress_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../../Configuration/Endian.h"
#include "../../Memory/Bits.h"
namespace Stroika::Foundation::IO::Network {
/*
********************************************************************************
*********************** IO::Network::InternetAddress ***************************
********************************************************************************
*/
constexpr InternetAddress::InternetAddress ()
: fAddressFamily_{AddressFamily::UNKNOWN}
, fV4_{}
{
}
constexpr InternetAddress::InternetAddress (const in_addr_t& i)
: fAddressFamily_ (AddressFamily::V4)
#if qPlatform_POSIX
, fV4_
{
i
}
#elif qPlatform_Windows
, fV4_
{
in_addr
{
{
static_cast<uint8_t> (Memory::BitSubstring (i, 0, 8)),
static_cast<uint8_t> (Memory::BitSubstring (i, 8, 16)),
static_cast<uint8_t> (Memory::BitSubstring (i, 16, 24)),
static_cast<uint8_t> (Memory::BitSubstring (i, 24, 32))
}
}
}
#endif
{
#if qPlatform_Windows
Assert (fV4_.s_addr == i);
#endif
}
inline InternetAddress::InternetAddress (const in_addr_t& i, ByteOrder byteOrder)
: fAddressFamily_ (AddressFamily::V4)
#if qPlatform_POSIX
, fV4_
{
i
}
#endif
{
#if qPlatform_Windows
fV4_.s_addr = i;
#endif
if (byteOrder == ByteOrder::Host) {
fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro
}
}
inline constexpr InternetAddress::InternetAddress (const in_addr& i)
: fAddressFamily_{AddressFamily::V4}
, fV4_{i}
{
}
inline InternetAddress::InternetAddress (const in_addr& i, ByteOrder byteOrder)
: fAddressFamily_{AddressFamily::V4}
, fV4_{i}
{
if (byteOrder == ByteOrder::Host) {
fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro
}
}
constexpr InternetAddress::InternetAddress (byte octet1, byte octet2, byte octet3, byte octet4)
: InternetAddress (array<byte, 4>{octet1, octet2, octet3, octet4})
{
}
constexpr InternetAddress::InternetAddress (uint8_t octet1, uint8_t octet2, uint8_t octet3, uint8_t octet4)
: InternetAddress (array<uint8_t, 4>{octet1, octet2, octet3, octet4})
{
}
constexpr InternetAddress::InternetAddress (tuple<uint8_t, uint8_t, uint8_t, uint8_t> octets)
: InternetAddress (array<uint8_t, 4>{get<0> (octets), get<1> (octets), get<2> (octets), get<3> (octets)})
{
}
constexpr InternetAddress::InternetAddress (array<uint8_t, 4> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_4_uint_{octets}
{
}
constexpr InternetAddress::InternetAddress (array<byte, 4> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_4_byte_{octets}
{
}
constexpr InternetAddress::InternetAddress (const in6_addr& i)
: fAddressFamily_ (AddressFamily::V6)
, fV6_{i}
{
}
constexpr InternetAddress::InternetAddress (array<uint8_t, 16> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_16_uint_{octets}
{
}
constexpr InternetAddress::InternetAddress (array<byte, 16> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_16_byte_{octets}
{
}
template <typename ITERABLE_OF_UINT8OrByte, enable_if_t<Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, byte> or Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, uint8_t>>*>
inline InternetAddress::InternetAddress (ITERABLE_OF_UINT8OrByte octets, AddressFamily af)
: fAddressFamily_{af}
{
Require (af != AddressFamily::V4 or octets.size () == 4);
Require (af != AddressFamily::V6 or octets.size () == 16);
size_t i = 0;
for (auto b : octets) {
fArray_16_uint_[i++] = static_cast<uint8_t> (b);
}
}
constexpr bool InternetAddress::empty () const
{
return fAddressFamily_ == AddressFamily::UNKNOWN;
}
inline void InternetAddress::clear ()
{
fAddressFamily_ = AddressFamily::UNKNOWN;
}
constexpr InternetAddress::AddressFamily InternetAddress::GetAddressFamily () const
{
return fAddressFamily_;
}
constexpr optional<size_t> InternetAddress::GetAddressSize () const
{
switch (GetAddressFamily ()) {
case AddressFamily::V4:
return 4;
case AddressFamily::V6:
return 16;
default:
return nullopt;
}
}
template <>
String InternetAddress::As<String> () const;
#if qPlatform_POSIX
template <>
inline in_addr_t InternetAddress::As<in_addr_t> () const
{
Require (fAddressFamily_ == AddressFamily::V4);
return fV4_.s_addr;
}
#endif
template <>
constexpr in_addr InternetAddress::As<in_addr> () const
{
Require (fAddressFamily_ == AddressFamily::V4);
return fV4_;
}
template <>
constexpr array<uint8_t, 4> InternetAddress::As<array<uint8_t, 4>> () const
{
Require (GetAddressSize () == 4u);
return fArray_4_uint_;
}
template <>
constexpr array<byte, 4> InternetAddress::As<array<byte, 4>> () const
{
Require (GetAddressSize () == 4u);
return fArray_4_byte_;
}
template <>
constexpr array<uint8_t, 16> InternetAddress::As<array<uint8_t, 16>> () const
{
Require (GetAddressSize () == 16u);
return fArray_16_uint_;
}
template <>
constexpr array<byte, 16> InternetAddress::As<array<byte, 16>> () const
{
Require (GetAddressSize () == 16u);
return fArray_16_byte_;
}
template <>
inline vector<byte> InternetAddress::As<vector<byte>> () const
{
Require (GetAddressSize ().has_value ());
Assert (*GetAddressSize () <= 16);
return vector<byte>{fArray_16_byte_.begin (), fArray_16_byte_.begin () + *GetAddressSize ()};
}
template <>
inline vector<uint8_t> InternetAddress::As<vector<uint8_t>> () const
{
Require (GetAddressSize ().has_value ());
Assert (*GetAddressSize () <= 16);
return vector<uint8_t>{fArray_16_uint_.begin (), fArray_16_uint_.begin () + *GetAddressSize ()};
}
template <>
[[deprecated ("array<byte,4> works better so this is deprecated since Stroika v2.1d13")]] inline tuple<uint8_t, uint8_t, uint8_t, uint8_t> InternetAddress::As<tuple<uint8_t, uint8_t, uint8_t, uint8_t>> () const
{
Require (fAddressFamily_ == AddressFamily::V4);
switch (Configuration::GetEndianness ()) {
case Configuration::Endian::eLittleByte:
return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> (
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32)));
case Configuration::Endian::eBigByte:
return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> (
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8)));
default:
AssertNotImplemented ();
return tuple<uint8_t, uint8_t, uint8_t, uint8_t>{};
}
}
template <>
constexpr in6_addr InternetAddress::As<in6_addr> () const
{
Require (fAddressFamily_ == AddressFamily::V6);
return fV6_;
}
template <>
inline in_addr InternetAddress::As<in_addr> (ByteOrder byteOrder) const
{
Require (fAddressFamily_ == AddressFamily::V4);
if (byteOrder == ByteOrder::Network) {
return fV4_;
}
else {
in_addr tmp = fV4_;
tmp.s_addr = ntohl (tmp.s_addr);
return tmp;
}
}
/*
********************************************************************************
********************** InternetAddress::ThreeWayComparer ***********************
********************************************************************************
*/
constexpr int InternetAddress::ThreeWayComparer::operator() (const InternetAddress& lhs, const InternetAddress& rhs) const
{
if (int cmp = Common::ThreeWayCompare (lhs.fAddressFamily_, rhs.fAddressFamily_)) {
return cmp;
}
switch (lhs.fAddressFamily_) {
case AddressFamily::UNKNOWN: {
return 0;
} break;
case AddressFamily::V4: {
return Common::COMPARE_EQUAL (lhs.fArray_4_uint_.begin (), lhs.fArray_4_uint_.end (), rhs.fArray_4_uint_.begin ());
} break;
case AddressFamily::V6: {
return Common::COMPARE_EQUAL (lhs.fArray_16_uint_.begin (), lhs.fArray_16_uint_.end (), rhs.fArray_16_uint_.begin ());
} break;
}
AssertNotReached ();
return 0;
}
/*
********************************************************************************
************************* InternetAddress operators ****************************
********************************************************************************
*/
inline bool operator< (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) < 0;
}
inline bool operator<= (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) <= 0;
}
inline bool operator== (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) == 0;
}
inline bool operator!= (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) != 0;
}
inline bool operator>= (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) >= 0;
}
inline bool operator> (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) > 0;
}
namespace V4 {
constexpr InternetAddress kAddrAny{in_addr{}};
}
namespace V6 {
constexpr InternetAddress kAddrAny{in6_addr{}};
}
namespace V4 {
constexpr InternetAddress kLocalhost{0x7f, 0x0, 0x0, 0x1};
}
namespace V6 {
constexpr InternetAddress kLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}}};
}
namespace V6 {
constexpr InternetAddress kV4MappedLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1}}}};
}
}
#endif /*_Stroika_Foundation_IO_Network_InternetAddress_inl_*/
<commit_msg>disale AssertNotReached () in constexpr function and comment @todo to fix<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#ifndef _Stroika_Foundation_IO_Network_InternetAddress_inl_
#define _Stroika_Foundation_IO_Network_InternetAddress_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../../Configuration/Endian.h"
#include "../../Memory/Bits.h"
namespace Stroika::Foundation::IO::Network {
/*
********************************************************************************
*********************** IO::Network::InternetAddress ***************************
********************************************************************************
*/
constexpr InternetAddress::InternetAddress ()
: fAddressFamily_{AddressFamily::UNKNOWN}
, fV4_{}
{
}
constexpr InternetAddress::InternetAddress (const in_addr_t& i)
: fAddressFamily_ (AddressFamily::V4)
#if qPlatform_POSIX
, fV4_
{
i
}
#elif qPlatform_Windows
, fV4_
{
in_addr
{
{
static_cast<uint8_t> (Memory::BitSubstring (i, 0, 8)),
static_cast<uint8_t> (Memory::BitSubstring (i, 8, 16)),
static_cast<uint8_t> (Memory::BitSubstring (i, 16, 24)),
static_cast<uint8_t> (Memory::BitSubstring (i, 24, 32))
}
}
}
#endif
{
#if qPlatform_Windows
Assert (fV4_.s_addr == i);
#endif
}
inline InternetAddress::InternetAddress (const in_addr_t& i, ByteOrder byteOrder)
: fAddressFamily_ (AddressFamily::V4)
#if qPlatform_POSIX
, fV4_
{
i
}
#endif
{
#if qPlatform_Windows
fV4_.s_addr = i;
#endif
if (byteOrder == ByteOrder::Host) {
fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro
}
}
inline constexpr InternetAddress::InternetAddress (const in_addr& i)
: fAddressFamily_{AddressFamily::V4}
, fV4_{i}
{
}
inline InternetAddress::InternetAddress (const in_addr& i, ByteOrder byteOrder)
: fAddressFamily_{AddressFamily::V4}
, fV4_{i}
{
if (byteOrder == ByteOrder::Host) {
fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro
}
}
constexpr InternetAddress::InternetAddress (byte octet1, byte octet2, byte octet3, byte octet4)
: InternetAddress (array<byte, 4>{octet1, octet2, octet3, octet4})
{
}
constexpr InternetAddress::InternetAddress (uint8_t octet1, uint8_t octet2, uint8_t octet3, uint8_t octet4)
: InternetAddress (array<uint8_t, 4>{octet1, octet2, octet3, octet4})
{
}
constexpr InternetAddress::InternetAddress (tuple<uint8_t, uint8_t, uint8_t, uint8_t> octets)
: InternetAddress (array<uint8_t, 4>{get<0> (octets), get<1> (octets), get<2> (octets), get<3> (octets)})
{
}
constexpr InternetAddress::InternetAddress (array<uint8_t, 4> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_4_uint_{octets}
{
}
constexpr InternetAddress::InternetAddress (array<byte, 4> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_4_byte_{octets}
{
}
constexpr InternetAddress::InternetAddress (const in6_addr& i)
: fAddressFamily_ (AddressFamily::V6)
, fV6_{i}
{
}
constexpr InternetAddress::InternetAddress (array<uint8_t, 16> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_16_uint_{octets}
{
}
constexpr InternetAddress::InternetAddress (array<byte, 16> octets, AddressFamily af)
: fAddressFamily_{af}
, fArray_16_byte_{octets}
{
}
template <typename ITERABLE_OF_UINT8OrByte, enable_if_t<Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, byte> or Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, uint8_t>>*>
inline InternetAddress::InternetAddress (ITERABLE_OF_UINT8OrByte octets, AddressFamily af)
: fAddressFamily_{af}
{
Require (af != AddressFamily::V4 or octets.size () == 4);
Require (af != AddressFamily::V6 or octets.size () == 16);
size_t i = 0;
for (auto b : octets) {
fArray_16_uint_[i++] = static_cast<uint8_t> (b);
}
}
constexpr bool InternetAddress::empty () const
{
return fAddressFamily_ == AddressFamily::UNKNOWN;
}
inline void InternetAddress::clear ()
{
fAddressFamily_ = AddressFamily::UNKNOWN;
}
constexpr InternetAddress::AddressFamily InternetAddress::GetAddressFamily () const
{
return fAddressFamily_;
}
constexpr optional<size_t> InternetAddress::GetAddressSize () const
{
switch (GetAddressFamily ()) {
case AddressFamily::V4:
return 4;
case AddressFamily::V6:
return 16;
default:
return nullopt;
}
}
template <>
String InternetAddress::As<String> () const;
#if qPlatform_POSIX
template <>
inline in_addr_t InternetAddress::As<in_addr_t> () const
{
Require (fAddressFamily_ == AddressFamily::V4);
return fV4_.s_addr;
}
#endif
template <>
constexpr in_addr InternetAddress::As<in_addr> () const
{
Require (fAddressFamily_ == AddressFamily::V4);
return fV4_;
}
template <>
constexpr array<uint8_t, 4> InternetAddress::As<array<uint8_t, 4>> () const
{
Require (GetAddressSize () == 4u);
return fArray_4_uint_;
}
template <>
constexpr array<byte, 4> InternetAddress::As<array<byte, 4>> () const
{
Require (GetAddressSize () == 4u);
return fArray_4_byte_;
}
template <>
constexpr array<uint8_t, 16> InternetAddress::As<array<uint8_t, 16>> () const
{
Require (GetAddressSize () == 16u);
return fArray_16_uint_;
}
template <>
constexpr array<byte, 16> InternetAddress::As<array<byte, 16>> () const
{
Require (GetAddressSize () == 16u);
return fArray_16_byte_;
}
template <>
inline vector<byte> InternetAddress::As<vector<byte>> () const
{
Require (GetAddressSize ().has_value ());
Assert (*GetAddressSize () <= 16);
return vector<byte>{fArray_16_byte_.begin (), fArray_16_byte_.begin () + *GetAddressSize ()};
}
template <>
inline vector<uint8_t> InternetAddress::As<vector<uint8_t>> () const
{
Require (GetAddressSize ().has_value ());
Assert (*GetAddressSize () <= 16);
return vector<uint8_t>{fArray_16_uint_.begin (), fArray_16_uint_.begin () + *GetAddressSize ()};
}
template <>
[[deprecated ("array<byte,4> works better so this is deprecated since Stroika v2.1d13")]] inline tuple<uint8_t, uint8_t, uint8_t, uint8_t> InternetAddress::As<tuple<uint8_t, uint8_t, uint8_t, uint8_t>> () const
{
Require (fAddressFamily_ == AddressFamily::V4);
switch (Configuration::GetEndianness ()) {
case Configuration::Endian::eLittleByte:
return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> (
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32)));
case Configuration::Endian::eBigByte:
return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> (
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)),
static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8)));
default:
AssertNotImplemented ();
return tuple<uint8_t, uint8_t, uint8_t, uint8_t>{};
}
}
template <>
constexpr in6_addr InternetAddress::As<in6_addr> () const
{
Require (fAddressFamily_ == AddressFamily::V6);
return fV6_;
}
template <>
inline in_addr InternetAddress::As<in_addr> (ByteOrder byteOrder) const
{
Require (fAddressFamily_ == AddressFamily::V4);
if (byteOrder == ByteOrder::Network) {
return fV4_;
}
else {
in_addr tmp = fV4_;
tmp.s_addr = ntohl (tmp.s_addr);
return tmp;
}
}
/*
********************************************************************************
********************** InternetAddress::ThreeWayComparer ***********************
********************************************************************************
*/
constexpr int InternetAddress::ThreeWayComparer::operator() (const InternetAddress& lhs, const InternetAddress& rhs) const
{
if (int cmp = Common::ThreeWayCompare (lhs.fAddressFamily_, rhs.fAddressFamily_)) {
return cmp;
}
switch (lhs.fAddressFamily_) {
case AddressFamily::UNKNOWN: {
return 0;
} break;
case AddressFamily::V4: {
return Common::COMPARE_EQUAL (lhs.fArray_4_uint_.begin (), lhs.fArray_4_uint_.end (), rhs.fArray_4_uint_.begin ());
} break;
case AddressFamily::V6: {
return Common::COMPARE_EQUAL (lhs.fArray_16_uint_.begin (), lhs.fArray_16_uint_.end (), rhs.fArray_16_uint_.begin ());
} break;
}
//AssertNotReached (); @todo - this really should be an assertion failure, but tricky cuz constexpr function could fix with template)
return 0;
}
/*
********************************************************************************
************************* InternetAddress operators ****************************
********************************************************************************
*/
inline bool operator< (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) < 0;
}
inline bool operator<= (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) <= 0;
}
inline bool operator== (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) == 0;
}
inline bool operator!= (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) != 0;
}
inline bool operator>= (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) >= 0;
}
inline bool operator> (const InternetAddress& lhs, const InternetAddress& rhs)
{
return Common::ThreeWayCompare (lhs, rhs) > 0;
}
namespace V4 {
constexpr InternetAddress kAddrAny{in_addr{}};
}
namespace V6 {
constexpr InternetAddress kAddrAny{in6_addr{}};
}
namespace V4 {
constexpr InternetAddress kLocalhost{0x7f, 0x0, 0x0, 0x1};
}
namespace V6 {
constexpr InternetAddress kLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}}};
}
namespace V6 {
constexpr InternetAddress kV4MappedLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1}}}};
}
}
#endif /*_Stroika_Foundation_IO_Network_InternetAddress_inl_*/
<|endoftext|> |
<commit_before>
// Qt includes
#include <QApplication>
#include <QDebug>
#include <QList>
#include <QTimer>
// CTKVTK includes
#include "ctkVTKConnection.h"
// STD includes
#include <cstdlib>
#include <iostream>
// VTK includes
#include <vtkCallbackCommand.h>
#include <vtkCommand.h>
#include <vtkObject.h>
#include <vtkSmartPointer.h>
#include <vtkTimerLog.h>
void doit(vtkObject* vtkNotUsed(obj), unsigned long vtkNotUsed(event),
void* client_data, void* vtkNotUsed(param))
{
QTimer* t = reinterpret_cast<QTimer*>(client_data);
t->stop();
}
int ctkVTKConnectionTest1( int argc, char * argv [] )
{
QApplication app(argc, argv);
int objects = 1000;
int events = 100;
vtkObject* obj = vtkObject::New();
vtkObject* obj2 = vtkObject::New();
vtkObject* obj3 = vtkObject::New();
vtkObject* obj4 = vtkObject::New();
vtkObject* obj5 = vtkObject::New();
QObject* topObject = new QObject(0);
// It could be here any kind of Qt object, QTimer has a no op slot so use it
QTimer* slotObject = new QTimer(topObject);
for (int i = 0; i < objects; ++i)
{
ctkVTKConnection* connection = new ctkVTKConnection(topObject);
connection->observeDeletion(false);
connection->setup(obj, vtkCommand::ModifiedEvent,
slotObject, SLOT(stop()));
vtkCallbackCommand* callback = vtkCallbackCommand::New();
callback->SetClientData(slotObject);
callback->SetCallback(doit);
obj2->AddObserver(vtkCommand::ModifiedEvent, callback);
callback->Delete();
ctkVTKConnection* connection2 = new ctkVTKConnection(topObject);
connection2->observeDeletion(true);
connection2->setup(obj3, vtkCommand::ModifiedEvent,
slotObject, SLOT(stop()));
ctkVTKConnection* connection3 = new ctkVTKConnection(topObject);
connection3->observeDeletion(false);
connection3->setup(obj4, vtkCommand::ModifiedEvent,
new QTimer(topObject), SLOT(stop()));
ctkVTKConnection* connection4 = new ctkVTKConnection(topObject);
connection4->observeDeletion(true);
connection4->setup(obj5, vtkCommand::ModifiedEvent,
slotObject, SLOT(stop()));
}
vtkSmartPointer<vtkTimerLog> timerLog =
vtkSmartPointer<vtkTimerLog>::New();
timerLog->StartTimer();
for (int i = 0; i < events; ++i)
{
obj->Modified();
}
timerLog->StopTimer();
double t1 = timerLog->GetElapsedTime();
qDebug() << events << "events listened by" << objects << "objects (ctkVTKConnection): " << t1 << "seconds";
// Callback only
vtkSmartPointer<vtkTimerLog> timerLog2 =
vtkSmartPointer<vtkTimerLog>::New();
timerLog2->StartTimer();
for (int i = 0; i < events; ++i)
{
obj2->Modified();
}
timerLog2->StopTimer();
double t2 = timerLog2->GetElapsedTime();
qDebug() << events << "events listened by" << objects <<"objects (vtkCallbacks): " << t2 << "seconds";
double ratio = t1 / t2;
qDebug() << "ctkVTKConnection / vtkCallbacks: " << ratio;
vtkSmartPointer<vtkTimerLog> timerLog3 =
vtkSmartPointer<vtkTimerLog>::New();
timerLog3->StartTimer();
for (int i = 0; i < events; ++i)
{
obj3->Modified();
}
timerLog3->StopTimer();
double t3 = timerLog3->GetElapsedTime();
qDebug() << events << "events listened by" << objects << "objects (observed ctkVTKConnection): " << t3 << "seconds";
vtkSmartPointer<vtkTimerLog> timerLog4 =
vtkSmartPointer<vtkTimerLog>::New();
timerLog4->StartTimer();
for (int i = 0; i < events; ++i)
{
obj4->Modified();
}
timerLog4->StopTimer();
double t4 = timerLog4->GetElapsedTime();
qDebug() << events << "events listened by" << objects << "objects (ctkVTKConnection, 1-1): " << t4 << "seconds";
obj->Delete();
obj2->Delete();
obj3->Delete();
delete topObject;
obj4->Delete();
obj5->Delete();
// Ideally a ratio ~= 1. but the ratio can be more in Debug mode... up to 2.
if (ratio > 2.)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>BUG: Fix ctkVTKConnectionTest1 - Do not check for "ratio" if build in Debug<commit_after>
// Qt includes
#include <QApplication>
#include <QDebug>
#include <QList>
#include <QTimer>
// CTKVTK includes
#include "ctkVTKConnection.h"
// VTK includes
#include <vtkCallbackCommand.h>
#include <vtkCommand.h>
#include <vtkObject.h>
#include <vtkSmartPointer.h>
#include <vtkTimerLog.h>
// STD includes
#include <cstdlib>
#include <iostream>
//-----------------------------------------------------------------------------
void doit(vtkObject* vtkNotUsed(obj), unsigned long vtkNotUsed(event),
void* client_data, void* vtkNotUsed(param))
{
QTimer* t = reinterpret_cast<QTimer*>(client_data);
t->stop();
}
//-----------------------------------------------------------------------------
int ctkVTKConnectionTest1( int argc, char * argv [] )
{
QApplication app(argc, argv);
int objects = 1000;
int events = 100;
vtkObject* obj = vtkObject::New();
vtkObject* obj2 = vtkObject::New();
vtkObject* obj3 = vtkObject::New();
vtkObject* obj4 = vtkObject::New();
vtkObject* obj5 = vtkObject::New();
QObject* topObject = new QObject(0);
// It could be here any kind of Qt object, QTimer has a no op slot so use it
QTimer* slotObject = new QTimer(topObject);
for (int i = 0; i < objects; ++i)
{
ctkVTKConnection* connection = new ctkVTKConnection(topObject);
connection->observeDeletion(false);
connection->setup(obj, vtkCommand::ModifiedEvent,
slotObject, SLOT(stop()));
vtkCallbackCommand* callback = vtkCallbackCommand::New();
callback->SetClientData(slotObject);
callback->SetCallback(doit);
obj2->AddObserver(vtkCommand::ModifiedEvent, callback);
callback->Delete();
ctkVTKConnection* connection2 = new ctkVTKConnection(topObject);
connection2->observeDeletion(true);
connection2->setup(obj3, vtkCommand::ModifiedEvent,
slotObject, SLOT(stop()));
ctkVTKConnection* connection3 = new ctkVTKConnection(topObject);
connection3->observeDeletion(false);
connection3->setup(obj4, vtkCommand::ModifiedEvent,
new QTimer(topObject), SLOT(stop()));
ctkVTKConnection* connection4 = new ctkVTKConnection(topObject);
connection4->observeDeletion(true);
connection4->setup(obj5, vtkCommand::ModifiedEvent,
slotObject, SLOT(stop()));
}
vtkSmartPointer<vtkTimerLog> timerLog =
vtkSmartPointer<vtkTimerLog>::New();
timerLog->StartTimer();
for (int i = 0; i < events; ++i)
{
obj->Modified();
}
timerLog->StopTimer();
double t1 = timerLog->GetElapsedTime();
qDebug() << events << "events listened by" << objects << "objects (ctkVTKConnection): " << t1 << "seconds";
// Callback only
vtkSmartPointer<vtkTimerLog> timerLog2 =
vtkSmartPointer<vtkTimerLog>::New();
timerLog2->StartTimer();
for (int i = 0; i < events; ++i)
{
obj2->Modified();
}
timerLog2->StopTimer();
double t2 = timerLog2->GetElapsedTime();
qDebug() << events << "events listened by" << objects <<"objects (vtkCallbacks): " << t2 << "seconds";
double ratio = t1 / t2;
qDebug() << "ctkVTKConnection / vtkCallbacks: " << ratio;
vtkSmartPointer<vtkTimerLog> timerLog3 =
vtkSmartPointer<vtkTimerLog>::New();
timerLog3->StartTimer();
for (int i = 0; i < events; ++i)
{
obj3->Modified();
}
timerLog3->StopTimer();
double t3 = timerLog3->GetElapsedTime();
qDebug() << events << "events listened by" << objects << "objects (observed ctkVTKConnection): " << t3 << "seconds";
vtkSmartPointer<vtkTimerLog> timerLog4 =
vtkSmartPointer<vtkTimerLog>::New();
timerLog4->StartTimer();
for (int i = 0; i < events; ++i)
{
obj4->Modified();
}
timerLog4->StopTimer();
double t4 = timerLog4->GetElapsedTime();
qDebug() << events << "events listened by" << objects << "objects (ctkVTKConnection, 1-1): " << t4 << "seconds";
obj->Delete();
obj2->Delete();
obj3->Delete();
delete topObject;
obj4->Delete();
obj5->Delete();
#ifdef QT_NO_DEBUG // In Debug mode, the ratio can be over 2 !
// Ideally a ratio ~= 1.
if (ratio > 1.2)
{
return EXIT_FAILURE;
}
#endif
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// 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 author nor the names of other 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 "pch.h"
#include <core/sdk/IPlugin.h>
#include <core/sdk/IPlaybackRemote.h>
musik::core::sdk::IPlaybackService* playback;
static HHOOK hook = NULL;
LRESULT CALLBACK ShellProc(int code, WPARAM wParam, LPARAM lParam) {
if (code == HC_ACTION && playback) {
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
switch (p->vkCode) {
case VK_MEDIA_NEXT_TRACK:
playback->Next();
return 0;
case VK_MEDIA_PLAY_PAUSE:
playback->PauseOrResume();
return 0;
case VK_MEDIA_PREV_TRACK:
playback->Previous();
return 0;
case VK_MEDIA_STOP:
playback->Stop();
return 0;
}
bool ctrl = GetAsyncKeyState(VK_RCONTROL) & 0x8000;
bool alt = GetAsyncKeyState(VK_RMENU) & 0x8000;
//bool win = GetAsyncKeyState(VK_LWIN) & 0x8000;
if (ctrl && alt) {
switch (p->vkCode) {
case 'I':
case 'i':
playback->SetVolume(playback->GetVolume() + 0.05);
return 1;
case 'K':
case 'k':
playback->SetVolume(playback->GetVolume() - 0.05);
return 1;
case 'L':
case 'l':
playback->Next();
return 1;
case 'J':
case 'j':
playback->Previous();
return 1;
case 'M':
case 'm':
playback->Previous();
return 1;
}
}
}
}
return CallNextHookEx(nullptr, code, wParam, lParam);
}
BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) {
switch (reason) {
case DLL_PROCESS_ATTACH:
hook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) ShellProc, module, 0L);
break;
case DLL_PROCESS_DETACH:
UnhookWindowsHookEx(hook);
hook = nullptr;
break;
}
return TRUE;
}
class MMShellHook:
public musik::core::sdk::IPlugin,
public musik::core::sdk::IPlaybackRemote {
public:
void Destroy() {
}
const char* Name() {
return "win32globalhotkeys";
}
const char* Version() {
return "0.1";
}
const char* Author() {
return "clangen";
}
virtual void SetPlaybackService(musik::core::sdk::IPlaybackService* playback) {
::playback = playback;
}
virtual void OnTrackChanged(musik::core::sdk::ITrack* track) {
}
};
static MMShellHook plugin;
extern "C" __declspec(dllexport) musik::core::sdk::IPlugin* GetPlugin() {
return &plugin;
}
extern "C" __declspec(dllexport) musik::core::sdk::IPlaybackRemote* GetPlaybackRemote() {
return &plugin;
}<commit_msg>Fixed a small error in the win32 global hotkeys implementation... mute was not properly wired up.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// 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 author nor the names of other 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 "pch.h"
#include <core/sdk/IPlugin.h>
#include <core/sdk/IPlaybackRemote.h>
musik::core::sdk::IPlaybackService* playback;
static HHOOK hook = NULL;
LRESULT CALLBACK ShellProc(int code, WPARAM wParam, LPARAM lParam) {
if (code == HC_ACTION && playback) {
if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
switch (p->vkCode) {
case VK_MEDIA_NEXT_TRACK:
playback->Next();
return 0;
case VK_MEDIA_PLAY_PAUSE:
playback->PauseOrResume();
return 0;
case VK_MEDIA_PREV_TRACK:
playback->Previous();
return 0;
case VK_MEDIA_STOP:
playback->Stop();
return 0;
}
bool ctrl = GetAsyncKeyState(VK_RCONTROL) & 0x8000;
bool alt = GetAsyncKeyState(VK_RMENU) & 0x8000;
//bool win = GetAsyncKeyState(VK_LWIN) & 0x8000;
if (ctrl && alt) {
switch (p->vkCode) {
case 'I':
case 'i':
playback->SetVolume(playback->GetVolume() + 0.05);
return 1;
case 'K':
case 'k':
playback->SetVolume(playback->GetVolume() - 0.05);
return 1;
case 'L':
case 'l':
playback->Next();
return 1;
case 'J':
case 'j':
playback->Previous();
return 1;
case 'M':
case 'm':
playback->ToggleMute();
return 1;
}
}
}
}
return CallNextHookEx(nullptr, code, wParam, lParam);
}
BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) {
switch (reason) {
case DLL_PROCESS_ATTACH:
hook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC) ShellProc, module, 0L);
break;
case DLL_PROCESS_DETACH:
UnhookWindowsHookEx(hook);
hook = nullptr;
break;
}
return TRUE;
}
class MMShellHook:
public musik::core::sdk::IPlugin,
public musik::core::sdk::IPlaybackRemote {
public:
void Destroy() {
}
const char* Name() {
return "win32globalhotkeys";
}
const char* Version() {
return "0.1";
}
const char* Author() {
return "clangen";
}
virtual void SetPlaybackService(musik::core::sdk::IPlaybackService* playback) {
::playback = playback;
}
virtual void OnTrackChanged(musik::core::sdk::ITrack* track) {
}
};
static MMShellHook plugin;
extern "C" __declspec(dllexport) musik::core::sdk::IPlugin* GetPlugin() {
return &plugin;
}
extern "C" __declspec(dllexport) musik::core::sdk::IPlaybackRemote* GetPlaybackRemote() {
return &plugin;
}<|endoftext|> |
<commit_before>
#include "PhysicalOperators.h"
namespace srch2 {
namespace instantsearch {
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Union lists sorted by ID /////////////////////////////////////
UnionSortedByIDOperator::UnionSortedByIDOperator() {
//TODO
}
UnionSortedByIDOperator::~UnionSortedByIDOperator(){
//TODO
}
bool UnionSortedByIDOperator::open(QueryEvaluatorInternal * queryEvaluator, PhysicalPlanExecutionParameters & params){
this->queryEvaluator = queryEvaluator;
/*
* 1. open all children (no parameters known to pass as of now)
* 2. initialize nextRecordItems vector.
*/
for(unsigned childOffset = 0 ; childOffset != this->getPhysicalPlanOptimizationNode()->getChildrenCount() ; ++childOffset){
this->getPhysicalPlanOptimizationNode()->getChildAt(childOffset)->getExecutableNode()->open(queryEvaluator , params);
}
unsigned numberOfChildren = this->getPhysicalPlanOptimizationNode()->getChildrenCount();
for(unsigned childOffset = 0; childOffset < numberOfChildren; ++childOffset){
PhysicalPlanRecordItem * recordItem =
this->getPhysicalPlanOptimizationNode()->getChildAt(childOffset)->getExecutableNode()->getNext(params);
this->nextItemsFromChildren.push_back(recordItem);
}
listsHaveMoreRecordsInThem = true;
return true;
}
PhysicalPlanRecordItem * UnionSortedByIDOperator::getNext(const PhysicalPlanExecutionParameters & params) {
if(listsHaveMoreRecordsInThem == false){
return NULL;
}
/*
* 1. iterate on nextItemsFromChildren
* 2. find the min ID on top,
* 3. remove all top records that have the same ID as min ID
* 4. return the min ID (which has the most Score in ties)
*/
// find the min ID
unsigned numberOfChildren = this->getPhysicalPlanOptimizationNode()->getChildrenCount();
PhysicalPlanRecordItem * minIDRecord = NULL;
for(unsigned childOffset = 0; childOffset < numberOfChildren; ++childOffset){
PhysicalPlanRecordItem * recordItem = this->nextItemsFromChildren.at(childOffset);
if(recordItem == NULL){
continue;
}
if(minIDRecord == NULL){
minIDRecord = recordItem;
}else if((minIDRecord->getRecordId() > recordItem->getRecordId()) // find the 1. min ID and 2. max score
|| (minIDRecord->getRecordId() == recordItem->getRecordId() &&
minIDRecord->getRecordRuntimeScore() < recordItem->getRecordRuntimeScore())){
minIDRecord = recordItem;
}
}
if(minIDRecord == NULL){
return NULL;
}
// now remove all minID records from all lists
for(unsigned childOffset = 0; childOffset < numberOfChildren; ++childOffset){
if(this->nextItemsFromChildren.at(childOffset)->getRecordId() == minIDRecord->getRecordId()){
this->nextItemsFromChildren.at(childOffset) =
this->getPhysicalPlanOptimizationNode()->getChildAt(childOffset)->getExecutableNode()->getNext(params);
}
}
// and now return the minId record
return minIDRecord;
}
bool UnionSortedByIDOperator::close(PhysicalPlanExecutionParameters & params){
this->queryEvaluator = NULL;
this->listsHaveMoreRecordsInThem = true;
return true;
}
bool UnionSortedByIDOperator::verifyByRandomAccess(PhysicalPlanRandomAccessVerificationParameters & parameters) {
//TODO
}
// The cost of open of a child is considered only once in the cost computation
// of parent open function.
unsigned UnionSortedByIDOptimizationOperator::getCostOfOpen(const PhysicalPlanExecutionParameters & params){
//TODO
}
// The cost of getNext of a child is multiplied by the estimated number of calls to this function
// when the cost of parent is being calculated.
unsigned UnionSortedByIDOptimizationOperator::getCostOfGetNext(const PhysicalPlanExecutionParameters & params) {
//TODO
}
// the cost of close of a child is only considered once since each node's close function is only called once.
unsigned UnionSortedByIDOptimizationOperator::getCostOfClose(const PhysicalPlanExecutionParameters & params) {
//TODO
}
void UnionSortedByIDOptimizationOperator::getOutputProperties(IteratorProperties & prop){
prop.addProperty(PhysicalPlanIteratorProperty_SortById);
}
void UnionSortedByIDOptimizationOperator::getRequiredInputProperties(IteratorProperties & prop){
// the only requirement for input is to be sorted by ID
prop.addProperty(PhysicalPlanIteratorProperty_SortById);
}
PhysicalPlanNodeType UnionSortedByIDOptimizationOperator::getType() {
return PhysicalPlanNode_UnionSortedById;
}
bool UnionSortedByIDOptimizationOperator::validateChildren(){
for(unsigned i = 0 ; i < getChildrenCount() ; i++){
PhysicalPlanOptimizationNode * child = getChildAt(i);
PhysicalPlanNodeType childType = child->getType();
switch (childType) {
case PhysicalPlanNode_RandomAccessTerm:
case PhysicalPlanNode_RandomAccessAnd:
case PhysicalPlanNode_RandomAccessOr:
case PhysicalPlanNode_RandomAccessNot:
case PhysicalPlanNode_UnionLowestLevelTermVirtualList:
// this operator cannot have TVL as a child, TVL overhead is not needed for this operator
return false;
default:{
continue;
}
}
}
return true;
}
}
}
<commit_msg>A missed part in UnionSortedByIdOperator is added.<commit_after>
#include "PhysicalOperators.h"
namespace srch2 {
namespace instantsearch {
////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Union lists sorted by ID /////////////////////////////////////
UnionSortedByIDOperator::UnionSortedByIDOperator() {
//TODO
}
UnionSortedByIDOperator::~UnionSortedByIDOperator(){
//TODO
}
bool UnionSortedByIDOperator::open(QueryEvaluatorInternal * queryEvaluator, PhysicalPlanExecutionParameters & params){
this->queryEvaluator = queryEvaluator;
/*
* 1. open all children (no parameters known to pass as of now)
* 2. initialize nextRecordItems vector.
*/
for(unsigned childOffset = 0 ; childOffset != this->getPhysicalPlanOptimizationNode()->getChildrenCount() ; ++childOffset){
this->getPhysicalPlanOptimizationNode()->getChildAt(childOffset)->getExecutableNode()->open(queryEvaluator , params);
}
unsigned numberOfChildren = this->getPhysicalPlanOptimizationNode()->getChildrenCount();
for(unsigned childOffset = 0; childOffset < numberOfChildren; ++childOffset){
PhysicalPlanRecordItem * recordItem =
this->getPhysicalPlanOptimizationNode()->getChildAt(childOffset)->getExecutableNode()->getNext(params);
this->nextItemsFromChildren.push_back(recordItem);
}
listsHaveMoreRecordsInThem = true;
return true;
}
PhysicalPlanRecordItem * UnionSortedByIDOperator::getNext(const PhysicalPlanExecutionParameters & params) {
if(listsHaveMoreRecordsInThem == false){
return NULL;
}
/*
* 1. iterate on nextItemsFromChildren
* 2. find the min ID on top,
* 3. remove all top records that have the same ID as min ID
* 4. return the min ID (which has the most Score in ties)
*/
// find the min ID
unsigned numberOfChildren = this->getPhysicalPlanOptimizationNode()->getChildrenCount();
PhysicalPlanRecordItem * minIDRecord = NULL;
for(unsigned childOffset = 0; childOffset < numberOfChildren; ++childOffset){
PhysicalPlanRecordItem * recordItem = this->nextItemsFromChildren.at(childOffset);
if(recordItem == NULL){
continue;
}
if(minIDRecord == NULL){
minIDRecord = recordItem;
}else if((minIDRecord->getRecordId() > recordItem->getRecordId()) // find the 1. min ID and 2. max score
|| (minIDRecord->getRecordId() == recordItem->getRecordId() &&
minIDRecord->getRecordRuntimeScore() < recordItem->getRecordRuntimeScore())){
minIDRecord = recordItem;
}
}
if(minIDRecord == NULL){
return NULL;
}
// now remove all minID records from all lists
vector<float> runtimeScores;
vector<TrieNodePointer> recordKeywordMatchPrefixes;
vector<unsigned> recordKeywordMatchEditDistances;
vector<unsigned> recordKeywordMatchBitmaps;
vector<unsigned> positionIndexOffsets;
for(unsigned childOffset = 0; childOffset < numberOfChildren; ++childOffset){
if(this->nextItemsFromChildren.at(childOffset)->getRecordId() == minIDRecord->getRecordId()){
this->nextItemsFromChildren.at(childOffset)->getRecordMatchingPrefixes(recordKeywordMatchPrefixes);
this->nextItemsFromChildren.at(childOffset)->getRecordMatchEditDistances(recordKeywordMatchEditDistances);
this->nextItemsFromChildren.at(childOffset)->getRecordMatchAttributeBitmaps(recordKeywordMatchBitmaps);
this->nextItemsFromChildren.at(childOffset)->getPositionIndexOffsets(positionIndexOffsets);
// static score, not for now
// and remove it from this list by substituting it by the next one
this->nextItemsFromChildren.at(childOffset) =
this->getPhysicalPlanOptimizationNode()->getChildAt(childOffset)->getExecutableNode()->getNext(params);
}
}
// prepare the record and return it
minIDRecord->setRecordMatchingPrefixes(recordKeywordMatchPrefixes);
minIDRecord->setRecordMatchEditDistances(recordKeywordMatchEditDistances);
minIDRecord->setRecordMatchAttributeBitmaps(recordKeywordMatchBitmaps);
minIDRecord->setPositionIndexOffsets(positionIndexOffsets);
return minIDRecord;
}
bool UnionSortedByIDOperator::close(PhysicalPlanExecutionParameters & params){
this->queryEvaluator = NULL;
this->listsHaveMoreRecordsInThem = true;
return true;
}
bool UnionSortedByIDOperator::verifyByRandomAccess(PhysicalPlanRandomAccessVerificationParameters & parameters) {
//TODO
}
// The cost of open of a child is considered only once in the cost computation
// of parent open function.
unsigned UnionSortedByIDOptimizationOperator::getCostOfOpen(const PhysicalPlanExecutionParameters & params){
//TODO
}
// The cost of getNext of a child is multiplied by the estimated number of calls to this function
// when the cost of parent is being calculated.
unsigned UnionSortedByIDOptimizationOperator::getCostOfGetNext(const PhysicalPlanExecutionParameters & params) {
//TODO
}
// the cost of close of a child is only considered once since each node's close function is only called once.
unsigned UnionSortedByIDOptimizationOperator::getCostOfClose(const PhysicalPlanExecutionParameters & params) {
//TODO
}
void UnionSortedByIDOptimizationOperator::getOutputProperties(IteratorProperties & prop){
prop.addProperty(PhysicalPlanIteratorProperty_SortById);
}
void UnionSortedByIDOptimizationOperator::getRequiredInputProperties(IteratorProperties & prop){
// the only requirement for input is to be sorted by ID
prop.addProperty(PhysicalPlanIteratorProperty_SortById);
}
PhysicalPlanNodeType UnionSortedByIDOptimizationOperator::getType() {
return PhysicalPlanNode_UnionSortedById;
}
bool UnionSortedByIDOptimizationOperator::validateChildren(){
for(unsigned i = 0 ; i < getChildrenCount() ; i++){
PhysicalPlanOptimizationNode * child = getChildAt(i);
PhysicalPlanNodeType childType = child->getType();
switch (childType) {
case PhysicalPlanNode_RandomAccessTerm:
case PhysicalPlanNode_RandomAccessAnd:
case PhysicalPlanNode_RandomAccessOr:
case PhysicalPlanNode_RandomAccessNot:
case PhysicalPlanNode_UnionLowestLevelTermVirtualList:
// this operator cannot have TVL as a child, TVL overhead is not needed for this operator
return false;
default:{
continue;
}
}
}
return true;
}
}
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////
// //
// AddMyTaskCorPIDTOFQA //
// Author: Brennan Schaefer, Oak Ridge National Laboratory, 2016 //
// //
//////////////////////////////////////////////////////////////////////
class AliAnalysisDataContainer;
AliAnalysisTaskCorPIDTOFQA* AddMyTaskCorPIDTOFQA(TString name = "name")
{
// get the manager via the static access member. since it's static, you don't need
// an instance of the class to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":MyTask"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskCorPIDTOFQA* task = new AliAnalysisTaskCorPIDTOFQA(name.Data());
if(!task) return 0x0;
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task,1,mgr->CreateContainer("MyOutputContainer", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<commit_msg>adding multiple subwagons for systematic studies<commit_after>//////////////////////////////////////////////////////////////////////
// //
// AddMyTaskCorPIDTOFQA //
// Author: Brennan Schaefer, Oak Ridge National Laboratory, 2016 //
// //
//////////////////////////////////////////////////////////////////////
#include <stdlib.h>
class AliAnalysisDataContainer;
AliAnalysisTaskCorPIDTOFQA* AddMyTaskCorPIDTOFQA(TString name = "name")
{
// get the manager via the static access member. since it's static, you don't need
// an instance of the class to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
// fileName += ":MyTask"; // create a subfolder in the file
// now we create an instance of your task
// AliAnalysisTaskCorPIDTOFQA* task = new BSchaefer_devel::AliAnalysisTaskCorPIDTOFQA(name.Data());
AliAnalysisTaskCorPIDTOFQA* task = new AliAnalysisTaskCorPIDTOFQA(name.Data());
if(!task) return 0x0;
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
// if(run_mode == 0) mgr->ConnectInput(task ,0,mgr->GetCommonInputContainer());
// if(run_mode == 1) mgr->ConnectInput(task_PID,0,mgr->GetCommonInputContainer());
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
int run_mode = 0;
run_mode = atoi(name);
// cout<<endl<<endl<<endl<<run_mode<<endl<<endl<<endl;
if(run_mode == 0){ mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); }
if(run_mode == 1){ mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput_PID", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); }
if(run_mode == 2){ mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput_TPC", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); }
if(run_mode == 3){ mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput_nCl", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); }
if(run_mode == 4){ mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput_DCA", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); }
if(run_mode == 5){ mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput_sid", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); }
if(run_mode == 6){ mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput_glo", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); }
// mgr->ConnectOutput(task,1,mgr->CreateContainer("cOutput", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qaxwidgetpropertysheet.h"
#include "qdesigneraxwidget.h"
#include <QtDesigner/QDesignerMemberSheetExtension>
#include <QtDesigner/QDesignerFormWindowInterface>
#include <QtDesigner/QDesignerFormEditorInterface>
#include <QtDesigner/QDesignerPropertyEditorInterface>
#include <QtDesigner/QExtensionManager>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
static const char *geometryPropertyC = "geometry";
QT_BEGIN_NAMESPACE
const char *QAxWidgetPropertySheet::controlPropertyName = "control";
QAxWidgetPropertySheet::QAxWidgetPropertySheet(QDesignerAxWidget *object, QObject *parent) :
QDesignerPropertySheet(object, parent),
m_controlProperty(controlPropertyName),
m_propertyGroup(QStringLiteral("QAxWidget"))
{
if (!axWidget()->loaded()) { // For some obscure reason....
const int controlIndex = QDesignerPropertySheet::indexOf(m_controlProperty);
setPropertyGroup(controlIndex, m_propertyGroup);
}
}
bool QAxWidgetPropertySheet::isEnabled(int index) const
{
if (propertyName(index) == m_controlProperty)
return false;
return QDesignerPropertySheet::isEnabled(index);
}
bool QAxWidgetPropertySheet::dynamicPropertiesAllowed() const
{
return false;
}
QDesignerAxWidget *QAxWidgetPropertySheet::axWidget() const
{
return static_cast<QDesignerAxWidget*>(object());
}
// Reload as the meta object changes.
bool QAxWidgetPropertySheet::reset(int index)
{
const QString name = propertyName(index);
QMap<QString, QVariant>::iterator it = m_currentProperties.changedProperties.find(name);
if (it != m_currentProperties.changedProperties.end())
m_currentProperties.changedProperties.erase(it);
if (name != m_controlProperty)
return QDesignerPropertySheet::reset(index);
axWidget()->resetControl();
QTimer::singleShot(0, this, SLOT(updatePropertySheet()));
return true;
}
void QAxWidgetPropertySheet::setProperty(int index, const QVariant &value)
{
// take care of all changed properties
const QString name = propertyName(index);
m_currentProperties.changedProperties[name] = value;
if (name != m_controlProperty) {
QDesignerPropertySheet::setProperty(index, value);
return;
}
// Loading forms: Reload
if (name == m_controlProperty) {
const QString clsid = value.toString();
if (clsid.isEmpty() || !axWidget()->loadControl(clsid))
reset(index);
else
QTimer::singleShot(100, this, SLOT(updatePropertySheet()));
}
}
int QAxWidgetPropertySheet::indexOf(const QString &name) const
{
const int index = QDesignerPropertySheet::indexOf(name);
if (index != -1)
return index;
// Loading before recreation of sheet in timer slot: Add a fake property to store the value
const QVariant dummValue(0);
QAxWidgetPropertySheet *that = const_cast<QAxWidgetPropertySheet *>(this);
const int newIndex = that->createFakeProperty(name, dummValue);
that->setPropertyGroup(newIndex, m_propertyGroup);
return newIndex;
}
void QAxWidgetPropertySheet::updatePropertySheet()
{
// refresh the property sheet (we are deleting m_currentProperties)
struct SavedProperties tmp = m_currentProperties;
QDesignerAxWidget *axw = axWidget();
QDesignerFormWindowInterface *formWin = QDesignerFormWindowInterface::findFormWindow(axw);
Q_ASSERT(formWin != 0);
tmp.widget = axw;
tmp.clsid = axw->control();
// Delete the sheets as they cache the meta object and other information
delete this;
delete qt_extension<QDesignerMemberSheetExtension *>(formWin->core()->extensionManager(), axw);
reloadPropertySheet(tmp, formWin);
}
void QAxWidgetPropertySheet::reloadPropertySheet(const struct SavedProperties &properties, QDesignerFormWindowInterface *formWin)
{
QDesignerFormEditorInterface *core = formWin->core();
//Recreation of the property sheet
QDesignerPropertySheetExtension *sheet = qt_extension<QDesignerPropertySheetExtension *>(core->extensionManager(), properties.widget);
bool foundGeometry = false;
const QString geometryProperty = QLatin1String(geometryPropertyC);
const SavedProperties::NamePropertyMap::const_iterator cend = properties.changedProperties.constEnd();
for (SavedProperties::NamePropertyMap::const_iterator i = properties.changedProperties.constBegin(); i != cend; ++i) {
const QString name = i.key();
const int index = sheet->indexOf(name);
if (index == -1)
continue;
// filter out geometry as this will resize the control
// to is default size even if it is attached to an layout
// but set the changed flag to work around preview bug...
if (name == geometryProperty) {
sheet->setChanged(index, true);
foundGeometry = true;
continue;
}
if (name == QLatin1String(controlPropertyName)) {
sheet->setChanged(index, !i.value().toString().isEmpty());
continue;
}
sheet->setChanged(index, true);
sheet->setProperty(index, i.value());
}
if (!foundGeometry) // Make sure geometry is always changed in Designer
sheet->setChanged(sheet->indexOf(geometryProperty), true);
if (core->propertyEditor()->object() == properties.widget) {
formWin->clearSelection(true);
formWin->selectWidget(properties.widget);
}
}
QT_END_NAMESPACE
<commit_msg>ActiveQt Designer plugin: Load control string correctly.<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qaxwidgetpropertysheet.h"
#include "qdesigneraxwidget.h"
#include <QtDesigner/QDesignerMemberSheetExtension>
#include <QtDesigner/QDesignerFormWindowInterface>
#include <QtDesigner/QDesignerFormEditorInterface>
#include <QtDesigner/QDesignerPropertyEditorInterface>
#include <QtDesigner/QExtensionManager>
#include <private/qdesigner_utils_p.h>
#include <QtCore/QDebug>
#include <QtCore/QTimer>
static const char *geometryPropertyC = "geometry";
QT_BEGIN_NAMESPACE
const char *QAxWidgetPropertySheet::controlPropertyName = "control";
QAxWidgetPropertySheet::QAxWidgetPropertySheet(QDesignerAxWidget *object, QObject *parent) :
QDesignerPropertySheet(object, parent),
m_controlProperty(controlPropertyName),
m_propertyGroup(QStringLiteral("QAxWidget"))
{
if (!axWidget()->loaded()) { // For some obscure reason....
const int controlIndex = QDesignerPropertySheet::indexOf(m_controlProperty);
setPropertyGroup(controlIndex, m_propertyGroup);
}
}
bool QAxWidgetPropertySheet::isEnabled(int index) const
{
if (propertyName(index) == m_controlProperty)
return false;
return QDesignerPropertySheet::isEnabled(index);
}
bool QAxWidgetPropertySheet::dynamicPropertiesAllowed() const
{
return false;
}
QDesignerAxWidget *QAxWidgetPropertySheet::axWidget() const
{
return static_cast<QDesignerAxWidget*>(object());
}
// Reload as the meta object changes.
bool QAxWidgetPropertySheet::reset(int index)
{
const QString name = propertyName(index);
QMap<QString, QVariant>::iterator it = m_currentProperties.changedProperties.find(name);
if (it != m_currentProperties.changedProperties.end())
m_currentProperties.changedProperties.erase(it);
if (name != m_controlProperty)
return QDesignerPropertySheet::reset(index);
axWidget()->resetControl();
QTimer::singleShot(0, this, SLOT(updatePropertySheet()));
return true;
}
void QAxWidgetPropertySheet::setProperty(int index, const QVariant &value)
{
// take care of all changed properties
const QString name = propertyName(index);
m_currentProperties.changedProperties[name] = value;
if (name != m_controlProperty) {
QDesignerPropertySheet::setProperty(index, value);
return;
}
// Loading forms: Reload
if (name == m_controlProperty) {
const qdesigner_internal::PropertySheetStringValue sv = qvariant_cast<qdesigner_internal::PropertySheetStringValue>(value);
const QString clsid = sv.value();
if (clsid.isEmpty() || !axWidget()->loadControl(clsid))
reset(index);
else
QTimer::singleShot(100, this, SLOT(updatePropertySheet()));
}
}
int QAxWidgetPropertySheet::indexOf(const QString &name) const
{
const int index = QDesignerPropertySheet::indexOf(name);
if (index != -1)
return index;
// Loading before recreation of sheet in timer slot: Add a fake property to store the value
const QVariant dummValue(0);
QAxWidgetPropertySheet *that = const_cast<QAxWidgetPropertySheet *>(this);
const int newIndex = that->createFakeProperty(name, dummValue);
that->setPropertyGroup(newIndex, m_propertyGroup);
return newIndex;
}
void QAxWidgetPropertySheet::updatePropertySheet()
{
// refresh the property sheet (we are deleting m_currentProperties)
struct SavedProperties tmp = m_currentProperties;
QDesignerAxWidget *axw = axWidget();
QDesignerFormWindowInterface *formWin = QDesignerFormWindowInterface::findFormWindow(axw);
Q_ASSERT(formWin != 0);
tmp.widget = axw;
tmp.clsid = axw->control();
// Delete the sheets as they cache the meta object and other information
delete this;
delete qt_extension<QDesignerMemberSheetExtension *>(formWin->core()->extensionManager(), axw);
reloadPropertySheet(tmp, formWin);
}
void QAxWidgetPropertySheet::reloadPropertySheet(const struct SavedProperties &properties, QDesignerFormWindowInterface *formWin)
{
QDesignerFormEditorInterface *core = formWin->core();
//Recreation of the property sheet
QDesignerPropertySheetExtension *sheet = qt_extension<QDesignerPropertySheetExtension *>(core->extensionManager(), properties.widget);
bool foundGeometry = false;
const QString geometryProperty = QLatin1String(geometryPropertyC);
const SavedProperties::NamePropertyMap::const_iterator cend = properties.changedProperties.constEnd();
for (SavedProperties::NamePropertyMap::const_iterator i = properties.changedProperties.constBegin(); i != cend; ++i) {
const QString name = i.key();
const int index = sheet->indexOf(name);
if (index == -1)
continue;
// filter out geometry as this will resize the control
// to is default size even if it is attached to an layout
// but set the changed flag to work around preview bug...
if (name == geometryProperty) {
sheet->setChanged(index, true);
foundGeometry = true;
continue;
}
if (name == QLatin1String(controlPropertyName)) {
sheet->setChanged(index, !i.value().toString().isEmpty());
continue;
}
sheet->setChanged(index, true);
sheet->setProperty(index, i.value());
}
if (!foundGeometry) // Make sure geometry is always changed in Designer
sheet->setChanged(sheet->indexOf(geometryProperty), true);
if (core->propertyEditor()->object() == properties.widget) {
formWin->clearSelection(true);
formWin->selectWidget(properties.widget);
}
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#ifndef _SDD_HOM_EVALUATION_HH_
#define _SDD_HOM_EVALUATION_HH_
#include <cassert>
#include <iosfwd>
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/rewrite.hh"
#include "sdd/order/order.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Evaluate an homomorphism.
template <typename C>
struct evaluation
{
/// @brief Used by util::variant.
typedef SDD<C> result_type;
/// @brief Terminal |0| case.
///
/// It shall never be called as the |0| case is handled by the evaluation of
/// homomorphism::operator().
template <typename H>
SDD<C>
operator()( const H& h, const zero_terminal<C>&
, const SDD<C>&, context<C>&, const order<C>& o, const homomorphism<C>&)
const noexcept
{
assert(false);
__builtin_unreachable();
}
/// @brief Terminal |1| case.
template <typename H>
SDD<C>
operator()( const H& h, const one_terminal<C>&
, const SDD<C>& x, context<C>& cxt, const order<C>& o
, const homomorphism<C>&)
const
{
return h(cxt, o, x);
}
/// @brief Dispatch evaluation to the concrete homomorphism.
///
/// Implement a part of the automatic saturation: evaluation is propagated on successors
/// whenever possible.
template <typename H, typename Node>
SDD<C>
operator()( const H& h, const Node& node
, const SDD<C>& x, context<C>& cxt, const order<C>& o
, const homomorphism<C>& hom_proxy)
const
{
assert(not o.empty() && "Empty order.");
assert(o.variable() == node.variable() && "Different variables in order and SDD.");
if (h.skip(o))
{
// The evaluated homomorphism skips the current level. We can thus forward its application
// to the following levels.
dd::square_union<C, typename Node::valuation_type> su;
su.reserve(node.size());
for (const auto& arc : node)
{
SDD<C> new_successor = hom_proxy(cxt, o.next(), arc.successor());
if (not new_successor.empty())
{
su.add(new_successor, arc.valuation());
}
}
return {node.variable(), su(cxt.sdd_context())};
}
else
{
return h(cxt, o, x);
}
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Default traits for homomorphisms.
template <typename T>
struct homomorphism_traits
{
static constexpr bool should_cache = true;
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief The evaluation of an homomorphism in the cache.
template <typename C>
struct cached_homomorphism
{
/// @brief Needed by the cache.
typedef SDD<C> result_type;
/// @brief The current order position.
const order<C>& ord;
/// @brief The homomorphism to evaluate.
const homomorphism<C> hom;
/// @brief The homomorphism's operand.
const SDD<C> sdd;
/// @brief Constructor.
cached_homomorphism(const order<C>& o, const homomorphism<C>& h, const SDD<C>& s)
: ord(o)
, hom(h)
, sdd(s)
{
}
/// @brief Launch the evaluation.
SDD<C>
operator()(context<C>& cxt)
const
{
return apply_binary_visitor(evaluation<C>(), hom->data(), sdd->data(), sdd, cxt, ord, hom);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related cached_homomorphism
/// We don't need to compare orders as the SDD operands bring the same information.
template <typename C>
inline
bool
operator==(const cached_homomorphism<C>& lhs, const cached_homomorphism<C>& rhs)
noexcept
{
return lhs.hom == rhs.hom and lhs.sdd == rhs.sdd;
}
/// @internal
/// @related cached_homomorphism
template <typename C>
std::ostream&
operator<<(std::ostream& os, const cached_homomorphism<C>& ch)
{
return os << ch.hom;
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Used by the cache as a filter to know if an homomorphism should be cached.
template <typename C>
struct should_cache
{
/// @brief Needed by variant.
typedef bool result_type;
/// @brief Dispatch to each homomorphism's trait.
template <typename T>
constexpr bool
operator()(const T&)
const noexcept
{
return homomorphism_traits<T>::should_cache;
}
/// @brief Application of should_cache.
bool
operator()(const cached_homomorphism<C>& ch)
const noexcept
{
return apply_visitor(*this, ch.hom->data());
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::hom
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::cached_homomorphism
///
/// We don't need to hash order as the SDD operand brings the same information.
template <typename C>
struct hash<sdd::hom::cached_homomorphism<C>>
{
std::size_t
operator()(const sdd::hom::cached_homomorphism<C>& ch)
const noexcept
{
std::size_t seed = 0;
sdd::util::hash_combine(seed, ch.hom);
sdd::util::hash_combine(seed, ch.sdd);
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_EVALUATION_HH_
<commit_msg>Copy order in cached_homomorphism.<commit_after>#ifndef _SDD_HOM_EVALUATION_HH_
#define _SDD_HOM_EVALUATION_HH_
#include <cassert>
#include <iosfwd>
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/rewrite.hh"
#include "sdd/order/order.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Evaluate an homomorphism.
template <typename C>
struct evaluation
{
/// @brief Used by util::variant.
typedef SDD<C> result_type;
/// @brief Terminal |0| case.
///
/// It shall never be called as the |0| case is handled by the evaluation of
/// homomorphism::operator().
template <typename H>
SDD<C>
operator()( const H& h, const zero_terminal<C>&
, const SDD<C>&, context<C>&, const order<C>& o, const homomorphism<C>&)
const noexcept
{
assert(false);
__builtin_unreachable();
}
/// @brief Terminal |1| case.
template <typename H>
SDD<C>
operator()( const H& h, const one_terminal<C>&
, const SDD<C>& x, context<C>& cxt, const order<C>& o
, const homomorphism<C>&)
const
{
return h(cxt, o, x);
}
/// @brief Dispatch evaluation to the concrete homomorphism.
///
/// Implement a part of the automatic saturation: evaluation is propagated on successors
/// whenever possible.
template <typename H, typename Node>
SDD<C>
operator()( const H& h, const Node& node
, const SDD<C>& x, context<C>& cxt, const order<C>& o
, const homomorphism<C>& hom_proxy)
const
{
assert(not o.empty() && "Empty order.");
assert(o.variable() == node.variable() && "Different variables in order and SDD.");
if (h.skip(o))
{
// The evaluated homomorphism skips the current level. We can thus forward its application
// to the following levels.
dd::square_union<C, typename Node::valuation_type> su;
su.reserve(node.size());
for (const auto& arc : node)
{
SDD<C> new_successor = hom_proxy(cxt, o.next(), arc.successor());
if (not new_successor.empty())
{
su.add(new_successor, arc.valuation());
}
}
return {node.variable(), su(cxt.sdd_context())};
}
else
{
return h(cxt, o, x);
}
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Default traits for homomorphisms.
template <typename T>
struct homomorphism_traits
{
static constexpr bool should_cache = true;
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief The evaluation of an homomorphism in the cache.
template <typename C>
struct cached_homomorphism
{
/// @brief Needed by the cache.
typedef SDD<C> result_type;
/// @brief The current order position.
const order<C> ord;
/// @brief The homomorphism to evaluate.
const homomorphism<C> hom;
/// @brief The homomorphism's operand.
const SDD<C> sdd;
/// @brief Constructor.
cached_homomorphism(const order<C>& o, const homomorphism<C>& h, const SDD<C>& s)
: ord(o)
, hom(h)
, sdd(s)
{
}
/// @brief Launch the evaluation.
SDD<C>
operator()(context<C>& cxt)
const
{
return apply_binary_visitor(evaluation<C>(), hom->data(), sdd->data(), sdd, cxt, ord, hom);
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @related cached_homomorphism
/// We don't need to compare orders as the SDD operands bring the same information.
template <typename C>
inline
bool
operator==(const cached_homomorphism<C>& lhs, const cached_homomorphism<C>& rhs)
noexcept
{
return lhs.hom == rhs.hom and lhs.sdd == rhs.sdd;
}
/// @internal
/// @related cached_homomorphism
template <typename C>
std::ostream&
operator<<(std::ostream& os, const cached_homomorphism<C>& ch)
{
return os << ch.hom;
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Used by the cache as a filter to know if an homomorphism should be cached.
template <typename C>
struct should_cache
{
/// @brief Needed by variant.
typedef bool result_type;
/// @brief Dispatch to each homomorphism's trait.
template <typename T>
constexpr bool
operator()(const T&)
const noexcept
{
return homomorphism_traits<T>::should_cache;
}
/// @brief Application of should_cache.
bool
operator()(const cached_homomorphism<C>& ch)
const noexcept
{
return apply_visitor(*this, ch.hom->data());
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::hom
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::cached_homomorphism
///
/// We don't need to hash order as the SDD operand brings the same information.
template <typename C>
struct hash<sdd::hom::cached_homomorphism<C>>
{
std::size_t
operator()(const sdd::hom::cached_homomorphism<C>& ch)
const noexcept
{
std::size_t seed = 0;
sdd::util::hash_combine(seed, ch.hom);
sdd::util::hash_combine(seed, ch.sdd);
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_EVALUATION_HH_
<|endoftext|> |
<commit_before>// This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
/** sql.cc
Jeremy Barnes, 24 December 2014
Copyright (c) 2014 Datacratic Inc. All rights reserved.
sqlite plugin.
*/
#include "mldb/server/plugin_collection.h"
#include "mldb/server/dataset_collection.h"
#include "mldb/server/mldb_server.h"
#include "mldb/recoset_sqlite/sqlite3.h"
#include "mldb/recoset_sqlite/sqlite3pp.h"
#include "mldb/arch/timers.h"
using namespace std;
namespace MLDB {
void dumpQuery(sqlite3pp::database & db, const std::string & queryStr)
{
cerr << "dumping query " << queryStr << endl;
sqlite3pp::query query(db, queryStr.c_str());
Json::Value allRecords;
for (sqlite3pp::query::iterator i = query.begin(); i != query.end(); ++i) {
Json::Value record;
for (int j = 0; j < query.column_count(); ++j) {
const char * v = (*i).get<char const*>(j);
record[query.column_name(j)] = v ? Json::Value(v) : Json::Value();
}
allRecords.append(record);
}
cerr << allRecords;
}
Json::Value toJson(sqlite3_value * arg)
{
switch (sqlite3_value_type(arg)) {
case SQLITE_INTEGER:
return sqlite3_value_int64(arg);
case SQLITE_FLOAT:
return sqlite3_value_double(arg);
case SQLITE_NULL:
return Json::Value();
case SQLITE_TEXT: {
int len = sqlite3_value_bytes(arg);
auto bytes = sqlite3_value_text(arg);
return string(bytes, bytes + len);
}
case SQLITE_BLOB:
return "<<BLOB>>";
default:
throw MLDB::Exception("Unknown type for column");
}
}
CellValue toCell(sqlite3_value * arg)
{
switch (sqlite3_value_type(arg)) {
case SQLITE_INTEGER:
return (int64_t)sqlite3_value_int64(arg);
case SQLITE_FLOAT:
return sqlite3_value_double(arg);
case SQLITE_NULL:
return CellValue();
case SQLITE_TEXT: {
int len = sqlite3_value_bytes(arg);
auto bytes = sqlite3_value_text(arg);
return string(bytes, bytes + len);
}
default:
throw MLDB::Exception("Unknown type for column");
}
}
void dumpQueryArray(sqlite3pp::database & db, const std::string & queryStr)
{
Timer timer;
cerr << "dumping query " << queryStr << endl;
sqlite3pp::query query(db, queryStr.c_str());
Json::Value allRecords;
for (int j = 0; j < query.column_count(); ++j) {
allRecords[0][j] = query.column_name(j);
}
for (sqlite3pp::query::iterator i = query.begin(); i != query.end(); ++i) {
Json::Value record;
for (int j = 0; j < query.column_count(); ++j) {
switch ((*i).column_type(j)) {
case SQLITE_INTEGER:
record[j] = (*i).get<long long int>(j);
break;
case SQLITE_FLOAT:
record[j] = (*i).get<double>(j);
break;
case SQLITE_NULL:
break;
case SQLITE_TEXT:
record[j] = (*i).get<char const*>(j);;
break;
case SQLITE_BLOB:
record[j] = "<<BLOB>>";
break;
default:
throw MLDB::Exception("Unknown type for column");
}
}
allRecords.append(record);
}
cerr << "query executed in " << timer.elapsed() << endl;
cerr << allRecords;
}
void explainQuery(sqlite3pp::database & db, const std::string & queryStr)
{
dumpQuery(db, "EXPLAIN QUERY PLAN " + queryStr);
}
std::string sqlEscape(const std::string & val)
{
int numQuotes = 0;
for (char c: val) {
if (c == '\'')
++numQuotes;
if (c < ' ' || c >= 127)
throw MLDB::Exception("Non ASCII character in DB");
}
if (numQuotes == 0)
return val;
std::string result;
result.reserve(val.size() + numQuotes);
for (char c: val) {
if (c == '\'')
result += "\'\'";
else result += c;
}
return result;
}
int sqlite3_result_ascii(sqlite3_context* context, const std::string & str)
{
sqlite3_result_text(context, str.c_str(), str.length(), SQLITE_TRANSIENT);
return SQLITE_OK;
}
int sqlite3_result_utf8(sqlite3_context* context, const Utf8String & str)
{
sqlite3_result_text(context, str.rawData(), str.rawLength(), SQLITE_TRANSIENT);
return SQLITE_OK;
}
namespace {
enum {
TIMESTAMP_COLUMN = 0,
ISO_TIMESTAMP_COLUMN = 1,
ROW_HASH_COLUMN = 2,
ROW_NAME_COLUMN = 3,
NUM_FIXED_COLUMNS
};
} // file scope
static __thread MldbServer * currentMldb = nullptr;
struct BehaviourModule {
struct OurVtab: public sqlite3_vtab {
OurVtab(MldbServer * mldb)
: mldb(mldb)
{
}
MldbServer * mldb;
std::shared_ptr<Dataset> dataset;
std::vector<ColumnPath> columnNames;
std::vector<ColumnHash> columnHashes;
};
static int Create(sqlite3 * db, void *pAux, int argc, const char * const * argv,
sqlite3_vtab ** ppVTab, char ** err)
{
try {
cerr << "creating table" << endl;
cerr << "argc = " << argc << endl;
for (unsigned i = 0; i < argc; ++i)
cerr << " " << argv[i] << endl;
ExcAssert(currentMldb);
OurVtab * vtab;
*ppVTab = vtab = new OurVtab(currentMldb);
string datasetName = argv[2];
// Get the dataset
auto dataset = currentMldb->datasets->getExistingEntity(datasetName);
vtab->dataset = dataset;
string columnNameStr;
vector<ColumnPath> columnNames = dataset->getColumnNames();
vector<ColumnHash> columnHashes;
for (auto & columnName : columnNames) {
columnNameStr += ", '" + sqlEscape(columnName.toString()) + "'";
columnHashes.emplace_back(columnName);
}
vtab->columnNames = columnNames;
vtab->columnHashes = columnHashes;
string statement = "CREATE TABLE " + sqlEscape(datasetName) + " ('Timestamp', 'TimestampIso8601', 'RowHash', 'RowName'" + columnNameStr + ")";
cerr << "running statement " << statement << endl;
int res = sqlite3_declare_vtab(db, statement.c_str());
cerr << "res returned " << res << endl;
cerr << "error " << sqlite3_errmsg(db) << endl;
return res;
} catch (const std::exception & exc) {
*err = (char *)sqlite3_malloc(strlen(exc.what()) + 1);
strcpy(*err, exc.what());
return SQLITE_ERROR;
} MLDB_CATCH_ALL {
return SQLITE_ERROR;
}
}
static int Connect(sqlite3 * db, void *pAux, int argc, const char * const * argv,
sqlite3_vtab ** ppVTab, char **)
{
cerr << "connecting to table" << endl;
return SQLITE_OK;
}
static int BestIndex(sqlite3_vtab *pVTab, sqlite3_index_info* info)
{
OurVtab * vtab = static_cast<OurVtab *>(pVTab);
cerr << "BestIndex" << endl;
cerr << "info.nConstraint = " << info->nConstraint << endl;
cerr << "info.nOrderBy = " << info->nOrderBy << endl;
cerr << "info.aConstraintUsage = " << info->aConstraintUsage << endl;
Json::Value indexPlan;
for (unsigned i = 0; i < info->nConstraint; ++i) {
auto & constraint = info->aConstraint[i];
cerr << "constraint " << i
<< " column " << info->aConstraint[i].iColumn
<< " op " << (int)info->aConstraint[i].op
<< " usable " << (int)info->aConstraint[i].usable
<< endl;
if (!constraint.usable)
continue;
int col = -1;
if (constraint.iColumn >= NUM_FIXED_COLUMNS) {
col = constraint.iColumn - NUM_FIXED_COLUMNS;
cerr << "column is " << vtab->columnNames[col] << endl;
}
if (col == -1)
continue;
string constraintStr;
switch (constraint.op) {
case SQLITE_INDEX_CONSTRAINT_EQ:
constraintStr = "=="; break;
case SQLITE_INDEX_CONSTRAINT_GT:
constraintStr = ">"; break;
case SQLITE_INDEX_CONSTRAINT_LE:
constraintStr = "<="; break;
case SQLITE_INDEX_CONSTRAINT_LT:
constraintStr = "<"; break;
case SQLITE_INDEX_CONSTRAINT_GE:
constraintStr = ">="; break;
case SQLITE_INDEX_CONSTRAINT_MATCH:
constraintStr = "MATCHES"; break;
default:
throw MLDB::Exception("unknown constraint type");
}
cerr << "constraintStr = " << constraintStr << endl;
indexPlan[i]["cIdx"] = col;
indexPlan[i]["cName"] = vtab->columnNames[col].toString();
indexPlan[i]["op"] = constraintStr;
indexPlan[i]["arg"] = i;
// We can do this!
//constraintsOut += " " + vtab->columnNames[col].toString() + "," + constraintStr;
info->aConstraintUsage[i].argvIndex = i + 1;
// IN clauses can't be optimized without this
info->aConstraintUsage[i].omit = 1;
}
info->idxStr = sqlite3_mprintf("%s", indexPlan.toStringNoNewLine().c_str());
info->needToFreeIdxStr = true;
info->estimatedCost = indexPlan.isNull() ? 10000000 : 0; // TODO: something sensible
cerr << "bestIndex: plan " << indexPlan.toStringNoNewLine() << " cost "
<< info->estimatedCost << endl;
return SQLITE_OK;
}
static int Disconnect(sqlite3_vtab *pVTab)
{
delete static_cast<OurVtab *>(pVTab);
return SQLITE_OK;
}
static int Destroy(sqlite3_vtab *pVTab)
{
return Disconnect(pVTab);
}
static void Free(void *)
{
cerr << "destroying" << endl;
}
struct Cursor: public sqlite3_vtab_cursor {
OurVtab * vtab;
std::unique_ptr<MatrixEventIterator> it;
std::map<ColumnHash, CellValue> knownValues;
};
static int Open(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor)
{
cerr << "open" << endl;
OurVtab * vtab = static_cast<OurVtab *>(pVTab);
Cursor * cursor;
*ppCursor = cursor = new Cursor();
cursor->it = vtab->dataset->getMatrixView()->allEvents();
cursor->vtab = vtab;
return SQLITE_OK;
}
static int Close(sqlite3_vtab_cursor* vcursor)
{
Cursor * cursor = static_cast<Cursor *>(vcursor);
delete static_cast<Cursor *>(cursor);
return SQLITE_OK;
}
static int Filter(sqlite3_vtab_cursor* vcursor,
int idxNum,
const char *idxStr,
int argc, sqlite3_value **argv)
{
Cursor * cursor = static_cast<Cursor *>(vcursor);
OurVtab * vtab = cursor->vtab;
cerr << "filter" << endl;
cerr << "idxNum = " << idxNum << endl;
cerr << "idxStr = " << idxStr << endl;
cerr << "argc = " << argc << endl;
for (unsigned i = 0; i < argc; ++i) {
cerr << "arg " << argc << " = " << toJson(argv[i]);
}
Json::Value plan = Json::parse(idxStr);
if (plan.isNull()) {
cursor->it = vtab->dataset->getMatrixView()->allEvents();
return SQLITE_OK;
}
vector<pair<RowHash, Date> > events;
std::map<ColumnHash, CellValue> knownValues;
for (unsigned i = 0; i < plan.size(); ++i) {
const Json::Value & planVal = plan[i];
//int colIdx = planVal["cIdx"].asInt();
ColumnPath colName(planVal["cName"].asString());
int argNum = planVal["arg"].asInt();
string op = planVal["op"].asString();
CellValue arg = toCell(argv[argNum]);
knownValues[colName] = arg;
if (op != "==")
throw MLDB::Exception("non-equality not implemented");
cerr << "Filtering on " << colName << " " << op << " " << arg
<< endl;
auto clauseEvents = vtab->dataset->getColumnIndex()->rowsWithColumnValue(colName, arg);
std::sort(clauseEvents.begin(), clauseEvents.end());
if (i == 0)
events = std::move(clauseEvents);
else {
vector<pair<RowHash, Date> > intersectedEvents;
std::set_intersection(clauseEvents.begin(), clauseEvents.end(),
events.begin(), events.end(),
back_inserter(intersectedEvents));
events = std::move(intersectedEvents);
}
cerr << events.size() << " events matching after clause " << i << endl;
}
cursor->it = vtab->dataset->getMatrixView()->events(events);
cursor->knownValues = knownValues;
return SQLITE_OK;
}
static int Next(sqlite3_vtab_cursor* vcursor)
{
Cursor * cursor = static_cast<Cursor *>(vcursor);
//cerr << "next" << endl;
cursor->it->next();
return SQLITE_OK;
}
static int Eof(sqlite3_vtab_cursor* vcursor)
{
//cerr << "eof" << endl;
Cursor * cursor = static_cast<Cursor *>(vcursor);
return cursor->it->eof();
}
static int Column(sqlite3_vtab_cursor* vcursor,
sqlite3_context* context,
int colNum)
{
Cursor * cursor = static_cast<Cursor *>(vcursor);
//cerr << "column " << colNum << endl;
//cerr << "cursor->vtab->columnHashes.size() = "
// << cursor->vtab->columnHashes.size() << endl;
switch (colNum) {
case TIMESTAMP_COLUMN:
// timestamp column
sqlite3_result_double(context, cursor->it->timestamp().secondsSinceEpoch());
return SQLITE_OK;
case ISO_TIMESTAMP_COLUMN:
// timestamp utf column
return sqlite3_result_ascii(context, cursor->it->timestamp().printIso8601());
case ROW_HASH_COLUMN:
// row ID column
return sqlite3_result_ascii(context, cursor->it->rowName().toString());
case ROW_NAME_COLUMN:
// row ID column
return sqlite3_result_ascii(context, cursor->it->rowHash().toString());
default: {
ColumnHash column = cursor->vtab->columnHashes[colNum - NUM_FIXED_COLUMNS];
CellValue value;
// If this is part of a constraint, then we know it without
// needing to load the row
auto it = cursor->knownValues.find(column);
if (it != cursor->knownValues.end()) {
value = it->second;
}
else {
value = cursor->it->column(column);
}
switch (value.cellType()) {
case CellValue::EMPTY:
sqlite3_result_null(context);
return SQLITE_OK;
case CellValue::FLOAT:
sqlite3_result_double(context, value.toDouble());
return SQLITE_OK;
case CellValue::INTEGER:
sqlite3_result_int64(context, value.toInt());
return SQLITE_OK;
case CellValue::STRING:
return sqlite3_result_ascii(context, value.toString());
case CellValue::UTF8_STRING:
return sqlite3_result_result_utf8(context, value.toUtf8String());
default:
throw MLDB::Exception("unknown cell type");
}
}
}
return SQLITE_ERROR;
}
static int Rowid(sqlite3_vtab_cursor* vcursor, sqlite3_int64 *pRowid)
{
cerr << "rowid" << endl;
return SQLITE_ERROR;
}
static int Update(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *)
{
cerr << "update" << endl;
return SQLITE_ERROR;
}
static void implementFunc(sqlite3_context * context,
int arity,
sqlite3_value ** vals)
{
cerr << "implementing function with arity " << arity << endl;
}
static int FindFunction(sqlite3_vtab *pVtab, int nArg, const char *zName,
void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
void **ppArg)
{
cerr << "FindFunction " << zName << " arity " << nArg << endl;
*pxFunc = implementFunc;
return SQLITE_OK;
}
};
struct SqlitePlugin: public Plugin {
SqlitePlugin(ServicePeer * server,
PolyConfig config,
std::function<bool (const Json::Value & progress)> onProgress)
: Plugin(static_cast<MldbServer *>(server)),
db(":memory:")
{
init();
watchDatasets = this->server->datasets->watchElements("*", true, string("Sqlite Datasets Watch"));
watchDatasets.bind(std::bind(&SqlitePlugin::onNewDataset, this, std::placeholders::_1));
}
sqlite3pp::database db;
sqlite3_module module;
void init()
{
module = {
1, // version
&BehaviourModule::Create,
&BehaviourModule::Connect,
&BehaviourModule::BestIndex,
&BehaviourModule::Disconnect,
&BehaviourModule::Destroy,
&BehaviourModule::Open,
&BehaviourModule::Close,
&BehaviourModule::Filter,
&BehaviourModule::Next,
&BehaviourModule::Eof,
&BehaviourModule::Column,
&BehaviourModule::Rowid,
nullptr /* update */,
nullptr /* begin */,
nullptr /* sync */,
nullptr /* commit */,
nullptr /* rollback */,
&BehaviourModule::FindFunction,
nullptr /* rename */
};
int res = sqlite3_create_module_v2(db, "mldb", &module, nullptr,
&BehaviourModule::Free);
if (res != SQLITE_OK) {
throw sqlite3pp::database_error(db);
}
}
WatchT<DatasetCollection::ChildEvent> watchDatasets;
void onNewDataset(const DatasetCollection::ChildEvent & dataset)
{
cerr << "SQL got new dataset " << dataset.key << endl;
currentMldb = server;
sqlite3pp::command command(db, ("CREATE VIRTUAL TABLE " + sqlEscape(dataset.key) + " USING mldb()").c_str());
command.execute();
currentMldb = nullptr; // TODO: proper guard
string query = "SELECT * FROM " + dataset.key + " WHERE aircrafttype IN ('RV6', 'RV4') ORDER BY Timestamp LIMIT 10";
explainQuery(db, query);
dumpQueryArray(db, query);
//query = "SELECT status, COUNT(*) FROM " + dataset.key + " WHERE aircrafttype = 'A320' GROUP BY status";
//query = "SELECT aircrafttype, status, COUNT(*) FROM " + dataset.key + " WHERE status = 'Approach' OR status = 'Landing' GROUP BY aircrafttype, status ORDER BY count(*) DESC";
//query = "SELECT aircrafttype, COUNT(*) FROM " + dataset.key + " GROUP BY aircrafttype ORDER BY count(*) DESC";
//query = "SELECT DISTINCT aircrafttype FROM " + dataset.key;
//explainQuery(db, query);
//for (unsigned i = 0; i < 20; ++i)
// dumpQueryArray(db, query);
}
Any getStatus() const
{
return Any();
}
RestRequestRouter router;
virtual RestRequestMatchResult
handleRequest(RestConnection & connection,
const RestRequest & request,
RestRequestParsingContext & context) const
{
cerr << "SqlitePlugin handling request " << request << endl;
return router.processRequest(connection, request, context);
}
};
namespace {
PluginCollection::RegisterType<SqlitePlugin> regSqlite("sql");
} // file scope
} // namespace MLDB
<commit_msg>rm sql.cc<commit_after><|endoftext|> |
<commit_before>#include "PosixFileSystem.hpp"
#include "../File.hpp"
#include "../InputStream.hpp"
#include "../OutputStream.hpp"
#include "../EmptyFile.hpp"
#include "../PartFile.hpp"
#include "../Exception.hpp"
#include <limits>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
BEGIN_INANITY_PLATFORM
class PosixFile : public File
{
private:
void* data;
size_t size;
public:
PosixFile(void* data, size_t size)
: data(data), size(size) {}
~PosixFile()
{
munmap(data, size);
}
void* GetData() const
{
return data;
}
size_t GetSize() const
{
return size;
}
};
class PosixInputStream : public InputStream
{
private:
int fd;
public:
PosixInputStream(int fd) : fd(fd) {}
~PosixInputStream()
{
close(fd);
}
size_t Read(void* data, size_t size)
{
char* dataPtr = (char*)data;
size_t resultSize = 0;
while(size > 0)
{
ssize_t readSize = size;
if(readSize > std::numeric_limits<ssize_t>::max())
readSize = std::numeric_limits<ssize_t>::max();
readSize = read(fd, dataPtr, readSize);
if(readSize < 0)
THROW("Disk read error");
if(readSize == 0)
break;
resultSize += readSize;
size -= readSize;
dataPtr += readSize;
}
return resultSize;
}
size_t GetSize() const
{
struct stat st;
if(fstat(fd, &st) != 0)
THROW("Error getting size");
return st.st_size;
}
};
class PosixOutputStream : public OutputStream
{
private:
int fd;
public:
PosixOutputStream(int fd) : fd(fd) {}
~PosixOutputStream()
{
close(fd);
}
void Write(const void* data, size_t size)
{
const char* dataPtr = (const char*)data;
while(size > 0)
{
ssize_t written = write(fd, dataPtr, size);
if(written < 0)
THROW("Disk write error");
size -= written;
dataPtr += written;
}
}
};
PosixFileSystem::PosixFileSystem(const String& userFolderName)
{
// if the name is absolute
if(userFolderName.length() && userFolderName[0] == '/')
folderName = userFolderName;
// else it's relative
else
{
// get full path of current directory
char currentDirectory[1024];
if(!getcwd(currentDirectory, sizeof(currentDirectory)))
THROW_SECONDARY("Can't get current directory", Exception::SystemError());
folderName = currentDirectory;
// add specified user folder name
if(userFolderName.length())
{
// add '/' to the end
if(!folderName.length() || folderName[folderName.length() - 1] != '/')
folderName += '/';
folderName += userFolderName;
}
}
// add '/' to the end
if(!folderName.length() || folderName[folderName.length() - 1] != '/')
folderName += '/';
}
PosixFileSystem::PosixFileSystem()
{
//создать абсолютную файловую систему, то есть ничего не делать;
//folderName - пустая строка
}
String PosixFileSystem::GetFullName(String fileName) const
{
if(folderName.length())
{
if(!fileName.length() || fileName[0] != '/')
THROW("File name should begin with slash");
return folderName + fileName.substr(1);
}
else
return fileName;
}
size_t PosixFileSystem::GetFileSize(const String& fileName)
{
struct stat st;
if(stat(fileName.c_str(), &st) != 0)
THROW("Can't determine file size");
return st.st_size;
}
ptr<File> PosixFileSystem::LoadPartOfFile(const String& fileName, long long mappingStart, size_t mappingSize)
{
String name = GetFullName(fileName);
try
{
int fd = open(name.c_str(), O_RDONLY, 0);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
size_t size;
if(mappingSize)
size = mappingSize;
else
{
struct stat st;
if(fstat(fd, &st) < 0)
THROW_SECONDARY("Can't get file size", Exception::SystemError());
size = st.st_size;
}
if(!size)
return NEW(EmptyFile());
//получить размер страницы
static size_t pageSize = 0;
if(!pageSize)
pageSize = getpagesize();
//округлить начало проекции вниз на размер страницы
size_t realMappingStart = mappingStart & ~(pageSize - 1);
//вычислить реальный размер
size_t realMappingSize = size + (size_t)(mappingStart - realMappingStart);
//спроецировать файл с учетом этого сдвига
void* data = mmap(0, realMappingSize, PROT_READ, MAP_PRIVATE, fd, realMappingStart);
if(data == (caddr_t)-1)
THROW_SECONDARY("Can't map file", Exception::SystemError());
//если сдвиг был
if(realMappingStart < (unsigned long long)mappingStart)
//вернуть указатель на частичный файл, с учетом сдвига
return NEW(PartFile(NEW(PosixFile(data, realMappingSize)), (char*)data + (size_t)(mappingStart - realMappingStart), size));
//иначе сдвига не было, просто вернуть файл
return NEW(PosixFile(data, size));
}
catch(Exception* exception)
{
THROW_SECONDARY("Can't load file \"" + fileName + "\" as \"" + name + "\"", exception);
}
}
void PosixFileSystem::SaveFile(ptr<File> file, const String& fileName)
{
String name = GetFullName(fileName);
try
{
int fd = open(fileName.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
const char* data = (const char*)file->GetData();
size_t size = file->GetSize();
while(size > 0)
{
ssize_t written = write(fd, data, size);
if(written < 0)
{
ptr<Exception> exception = Exception::SystemError();
close(fd);
THROW_SECONDARY("Can't write file", exception);
}
size -= written;
data += written;
}
close(fd);
}
catch(Exception* exception)
{
THROW_SECONDARY(String("Can't save file \"") + fileName + "\" as \"" + name + "\"", exception);
}
}
ptr<InputStream> PosixFileSystem::LoadStream(const String& fileName)
{
String name = GetFullName(fileName);
try
{
int fd = open(name.c_str(), O_RDONLY, 0);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
return NEW(PosixInputStream(fd));
}
catch(Exception* exception)
{
THROW_SECONDARY(String("Can't load file \"") + fileName + "\" as \"" + name + "\" as stream", exception);
}
}
ptr<OutputStream> PosixFileSystem::SaveStream(const String& fileName)
{
String name = GetFullName(fileName);
try
{
int fd = open(fileName.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
return NEW(PosixOutputStream(fd));
}
catch(Exception* exception)
{
THROW_SECONDARY(String("Can't save file \"") + fileName + "\" as \"" + name + "\" as stream", exception);
}
}
void PosixFileSystem::GetDirectoryEntries(const String& directoryName, std::vector<String>& entries) const
{
String fullDirectoryName = GetFullName(directoryName);
DIR* dir = opendir(fullDirectoryName.c_str());
while(struct dirent* ent = readdir(dir))
{
if(errno)
{
ptr<Exception> exception = Exception::SystemError();
closedir(dir);
THROW_SECONDARY("Can't read dir", exception);
}
String fileTitle = ent->d_name;
String fullFileName = fullDirectoryName + fileTitle;
struct stat st;
if(stat(fullFileName.c_str(), &st) < 0)
{
ptr<Exception> exception = Exception::SystemError();
closedir(dir);
THROW_SECONDARY("Can't stat file " + fullFileName, exception);
}
// если файл скрыт (или ненужен: . или ..)
if(!fileTitle.length() || fileTitle[0] == '.')
// пропустить его
continue;
// если это каталог
if((st.st_mode & S_IFMT) == S_IFDIR)
// добавить слеш в конец
fileTitle += '/';
// добавить файл/каталог в результат
entries.push_back(directoryName + fileTitle);
}
closedir(dir);
}
ptr<File> PosixFileSystem::LoadFile(const String& fileName)
{
return LoadPartOfFile(fileName, 0, 0);
}
ptr<PosixFileSystem> PosixFileSystem::GetNativeFileSystem()
{
//этот метод сделан просто для лучшей понятности
return NEW(PosixFileSystem());
}
void PosixFileSystem::GetFileNames(std::vector<String>& fileNames) const
{
//только если файловая система не абсолютная
if(folderName.length())
GetAllDirectoryEntries("/", fileNames);
}
END_INANITY_PLATFORM
<commit_msg>fix PosixFileSystem issue with wrong filenames<commit_after>#include "PosixFileSystem.hpp"
#include "../File.hpp"
#include "../InputStream.hpp"
#include "../OutputStream.hpp"
#include "../EmptyFile.hpp"
#include "../PartFile.hpp"
#include "../Exception.hpp"
#include <limits>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
BEGIN_INANITY_PLATFORM
class PosixFile : public File
{
private:
void* data;
size_t size;
public:
PosixFile(void* data, size_t size)
: data(data), size(size) {}
~PosixFile()
{
munmap(data, size);
}
void* GetData() const
{
return data;
}
size_t GetSize() const
{
return size;
}
};
class PosixInputStream : public InputStream
{
private:
int fd;
public:
PosixInputStream(int fd) : fd(fd) {}
~PosixInputStream()
{
close(fd);
}
size_t Read(void* data, size_t size)
{
char* dataPtr = (char*)data;
size_t resultSize = 0;
while(size > 0)
{
ssize_t readSize = size;
if(readSize > std::numeric_limits<ssize_t>::max())
readSize = std::numeric_limits<ssize_t>::max();
readSize = read(fd, dataPtr, readSize);
if(readSize < 0)
THROW("Disk read error");
if(readSize == 0)
break;
resultSize += readSize;
size -= readSize;
dataPtr += readSize;
}
return resultSize;
}
size_t GetSize() const
{
struct stat st;
if(fstat(fd, &st) != 0)
THROW("Error getting size");
return st.st_size;
}
};
class PosixOutputStream : public OutputStream
{
private:
int fd;
public:
PosixOutputStream(int fd) : fd(fd) {}
~PosixOutputStream()
{
close(fd);
}
void Write(const void* data, size_t size)
{
const char* dataPtr = (const char*)data;
while(size > 0)
{
ssize_t written = write(fd, dataPtr, size);
if(written < 0)
THROW("Disk write error");
size -= written;
dataPtr += written;
}
}
};
PosixFileSystem::PosixFileSystem(const String& userFolderName)
{
// if the name is absolute
if(userFolderName.length() && userFolderName[0] == '/')
folderName = userFolderName;
// else it's relative
else
{
// get full path of current directory
char currentDirectory[1024];
if(!getcwd(currentDirectory, sizeof(currentDirectory)))
THROW_SECONDARY("Can't get current directory", Exception::SystemError());
folderName = currentDirectory;
// add specified user folder name
if(userFolderName.length())
{
// add '/' to the end
if(!folderName.length() || folderName[folderName.length() - 1] != '/')
folderName += '/';
folderName += userFolderName;
}
}
// add '/' to the end
if(!folderName.length() || folderName[folderName.length() - 1] != '/')
folderName += '/';
}
PosixFileSystem::PosixFileSystem()
{
//создать абсолютную файловую систему, то есть ничего не делать;
//folderName - пустая строка
}
String PosixFileSystem::GetFullName(String fileName) const
{
if(folderName.length())
{
if(!fileName.length() || fileName[0] != '/')
THROW("File name should begin with slash");
return folderName + fileName.substr(1);
}
else
return fileName;
}
size_t PosixFileSystem::GetFileSize(const String& fileName)
{
struct stat st;
if(stat(fileName.c_str(), &st) != 0)
THROW("Can't determine file size");
return st.st_size;
}
ptr<File> PosixFileSystem::LoadPartOfFile(const String& fileName, long long mappingStart, size_t mappingSize)
{
String name = GetFullName(fileName);
try
{
int fd = open(name.c_str(), O_RDONLY, 0);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
size_t size;
if(mappingSize)
size = mappingSize;
else
{
struct stat st;
if(fstat(fd, &st) < 0)
THROW_SECONDARY("Can't get file size", Exception::SystemError());
size = st.st_size;
}
if(!size)
return NEW(EmptyFile());
//получить размер страницы
static size_t pageSize = 0;
if(!pageSize)
pageSize = getpagesize();
//округлить начало проекции вниз на размер страницы
size_t realMappingStart = mappingStart & ~(pageSize - 1);
//вычислить реальный размер
size_t realMappingSize = size + (size_t)(mappingStart - realMappingStart);
//спроецировать файл с учетом этого сдвига
void* data = mmap(0, realMappingSize, PROT_READ, MAP_PRIVATE, fd, realMappingStart);
if(data == (caddr_t)-1)
THROW_SECONDARY("Can't map file", Exception::SystemError());
//если сдвиг был
if(realMappingStart < (unsigned long long)mappingStart)
//вернуть указатель на частичный файл, с учетом сдвига
return NEW(PartFile(NEW(PosixFile(data, realMappingSize)), (char*)data + (size_t)(mappingStart - realMappingStart), size));
//иначе сдвига не было, просто вернуть файл
return NEW(PosixFile(data, size));
}
catch(Exception* exception)
{
THROW_SECONDARY("Can't load file \"" + fileName + "\" as \"" + name + "\"", exception);
}
}
void PosixFileSystem::SaveFile(ptr<File> file, const String& fileName)
{
String name = GetFullName(fileName);
try
{
int fd = open(name.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
const char* data = (const char*)file->GetData();
size_t size = file->GetSize();
while(size > 0)
{
ssize_t written = write(fd, data, size);
if(written < 0)
{
ptr<Exception> exception = Exception::SystemError();
close(fd);
THROW_SECONDARY("Can't write file", exception);
}
size -= written;
data += written;
}
close(fd);
}
catch(Exception* exception)
{
THROW_SECONDARY(String("Can't save file \"") + fileName + "\" as \"" + name + "\"", exception);
}
}
ptr<InputStream> PosixFileSystem::LoadStream(const String& fileName)
{
String name = GetFullName(fileName);
try
{
int fd = open(name.c_str(), O_RDONLY, 0);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
return NEW(PosixInputStream(fd));
}
catch(Exception* exception)
{
THROW_SECONDARY(String("Can't load file \"") + fileName + "\" as \"" + name + "\" as stream", exception);
}
}
ptr<OutputStream> PosixFileSystem::SaveStream(const String& fileName)
{
String name = GetFullName(fileName);
try
{
int fd = open(name.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644);
if(fd < 0)
THROW_SECONDARY("Can't open file", Exception::SystemError());
return NEW(PosixOutputStream(fd));
}
catch(Exception* exception)
{
THROW_SECONDARY(String("Can't save file \"") + fileName + "\" as \"" + name + "\" as stream", exception);
}
}
void PosixFileSystem::GetDirectoryEntries(const String& directoryName, std::vector<String>& entries) const
{
String fullDirectoryName = GetFullName(directoryName);
DIR* dir = opendir(fullDirectoryName.c_str());
while(struct dirent* ent = readdir(dir))
{
if(errno)
{
ptr<Exception> exception = Exception::SystemError();
closedir(dir);
THROW_SECONDARY("Can't read dir", exception);
}
String fileTitle = ent->d_name;
String fullFileName = fullDirectoryName + fileTitle;
struct stat st;
if(stat(fullFileName.c_str(), &st) < 0)
{
ptr<Exception> exception = Exception::SystemError();
closedir(dir);
THROW_SECONDARY("Can't stat file " + fullFileName, exception);
}
// если файл скрыт (или ненужен: . или ..)
if(!fileTitle.length() || fileTitle[0] == '.')
// пропустить его
continue;
// если это каталог
if((st.st_mode & S_IFMT) == S_IFDIR)
// добавить слеш в конец
fileTitle += '/';
// добавить файл/каталог в результат
entries.push_back(directoryName + fileTitle);
}
closedir(dir);
}
ptr<File> PosixFileSystem::LoadFile(const String& fileName)
{
return LoadPartOfFile(fileName, 0, 0);
}
ptr<PosixFileSystem> PosixFileSystem::GetNativeFileSystem()
{
//этот метод сделан просто для лучшей понятности
return NEW(PosixFileSystem());
}
void PosixFileSystem::GetFileNames(std::vector<String>& fileNames) const
{
//только если файловая система не абсолютная
if(folderName.length())
GetAllDirectoryEntries("/", fileNames);
}
END_INANITY_PLATFORM
<|endoftext|> |
<commit_before>#include "stdafx.h"
#if defined(_WIN32_WCE)
#include <soundfile.h>
#endif
#include <common/RhodesApp.h>
#include <common/rhoparams.h>
#include "Alert.h"
#include "MainWindow.h"
#include "Vibrate.h"
extern "C" HWND getMainWnd();
/**
********************************************************************************
* CAlertDialog members.
********************************************************************************
*/
//TODO: smart alignment and win32
typedef CWinTraits <WS_CAPTION | WS_VISIBLE | WS_POPUP | DS_CENTER> CAlertDialogTraits;
CAlertDialog::CAlertDialog(Params *params)
{
m_title = params->m_title;
m_message = params->m_message;
m_callback = params->m_callback;
m_icon = params->m_icon;
int id = ID_ALERT_DLG_BUTTON_FIRST;
for (Hashtable<String, String>::iterator itr = params->m_buttons.begin(); itr != params->m_buttons.end(); ++itr)
m_buttons.addElement(CustomButton(itr->first, itr->second, id++));
}
CAlertDialog::~CAlertDialog()
{
}
void CAlertDialog::DoInitTemplate()
{
#ifdef OS_WINCE
int initialWidth = GetSystemMetrics(SM_CXSCREEN)/3;
int initialHeight = initialWidth/2;
m_Template.Create(false, convertToStringW(m_title).c_str(),
GetSystemMetrics(SM_CXSCREEN)/2 - initialWidth/2,
GetSystemMetrics(SM_CYSCREEN)/2 - initialHeight/2,
initialWidth,
initialHeight,
CAlertDialogTraits::GetWndStyle(0),
CAlertDialogTraits::GetWndExStyle(0));
#endif
}
void CAlertDialog::DoInitControls()
{
}
LRESULT CAlertDialog::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL&bHandled)
{
#ifdef OS_WINCE
int indent = 10;
unsigned int maxWidth = GetSystemMetrics(SM_CXSCREEN) - (indent * 2);
unsigned int maxHeight = GetSystemMetrics(SM_CYSCREEN) - (indent * 2);
unsigned int msgWidth = 0, msgHeight = 0;
CClientDC dc(m_hWnd);
TEXTMETRIC tm = {0};
POINT point = { 5, 5};
SIZE size = { 0, 0 };
unsigned int iconHeight = 42;
int iconId = MB_ICONWARNING;
HMODULE hGWES = LoadLibraryEx( L"gwes.exe", NULL, LOAD_LIBRARY_AS_DATAFILE );
HICON hIcon = LoadIcon(hGWES, MAKEINTRESOURCE(iconId));
if (hIcon == NULL) {
LOG(ERROR) + "Failed to load icon";
} else {
size.cx = iconHeight; size.cy = iconHeight;
m_iconCtrl.Create(m_hWnd, CRect(point, size), NULL, WS_CHILD | WS_VISIBLE);
if (m_iconCtrl.SetIcon(hIcon) == NULL)
LOG(INFO) + ": failed to set icon";
}
dc.GetTextMetrics(&tm);
if ((m_message.length() * tm.tmAveCharWidth) > maxWidth) {
msgWidth = maxWidth - indent - size.cy;
msgHeight = (((m_message.length() * tm.tmAveCharWidth * 2) / msgWidth))
* (tm.tmHeight + tm.tmExternalLeading + tm.tmInternalLeading);
RECT rect;
GetWindowRect(&rect);
MoveWindow(indent, rect.top, maxWidth, msgHeight + tm.tmHeight * 5);
point.x = size.cx; point.y = 5;
size.cx = msgWidth; size.cy = msgHeight;
} else {
point.x = size.cx + 4; point.y = 5;
msgWidth = m_message.length() * tm.tmAveCharWidth * 2;
msgHeight = (tm.tmHeight + tm.tmExternalLeading + tm.tmInternalLeading);
size.cx = msgWidth; size.cy = msgHeight;
}
m_messageCtrl.Create(m_hWnd, CRect(point, size), NULL, WS_CHILD | WS_VISIBLE);
m_messageCtrl.SetWindowText(convertToStringW(m_message).c_str());
int bntNum = m_buttons.size();
point.x = indent, point.y = msgHeight + 2;
if (iconHeight > msgHeight)
point.y = iconHeight + 6;
unsigned int btnWidth = 0, btnHeight = 0;
for (Vector<CustomButton>::iterator itr = m_buttons.begin(); itr != m_buttons.end(); ++itr) {
btnWidth = (itr->m_title.length() * tm.tmAveCharWidth * 2) + 6;
btnHeight = tm.tmHeight + 4;
size.cx = btnWidth; size.cy = btnHeight;
itr->Create(m_hWnd, CRect(point, size),
convertToStringW(itr->m_title).c_str(),
WS_CHILD | WS_VISIBLE, 0,
itr->m_numId);
point.x += btnWidth + 4;
}
#endif
return bHandled = FALSE;
}
bool CAlertDialog::findButton(int id, CustomButton &btn)
{
for (Vector<CustomButton>::iterator itr = m_buttons.begin(); itr != m_buttons.end(); ++itr) {
if (itr->m_numId == id) {
btn = *itr;
return true;
}
}
return false;
}
LRESULT CAlertDialog::OnAlertDialogButton (WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CustomButton cbtn;
if (findButton((int) wID, cbtn))
rho_rhodesapp_callPopupCallback(m_callback.c_str(), cbtn.m_strId.c_str(), cbtn.m_title.c_str());
else
LOG(ERROR) + "internal error";
EndDialog(wID);
return 0;
}
/**
********************************************************************************
* CAlert members.
********************************************************************************
*/
IMPLEMENT_LOGCLASS(CAlert, "Alert");
void CAlert::showPopup(CAlertDialog::Params *params)
{
HWND main_wnd = getMainWnd();
::PostMessage(main_wnd, WM_ALERT_SHOWPOPUP, 0, (LPARAM ) params);
}
#if defined(_WIN32_WCE)
void CAlert::vibrate()
{
CVibrate::getCVibrate().toggle();
}
void CAlert::playFile(String fileName)
{
rho::String path = RHODESAPP().getRhoRootPath() + "apps" + fileName;
HSOUND hSound;
rho::String::size_type pos = 0;
while ( (pos = path.find('/', pos)) != rho::String::npos ) {
path.replace( pos, 1, "\\");
pos++;
}
USES_CONVERSION;
//SndPlaySync(A2T(path.c_str()), SND_PLAY_IGNOREUSERSETTINGS);
HRESULT hr = SndOpen(A2T(path.c_str()), &hSound);
hr = SndPlayAsync (hSound, 0);
if (hr != S_OK) {
LOG(WARNING) + "OnAlertPlayFile: failed to play file";
}
WaitForSingleObject(hSound, INFINITE);
hr = SndClose(hSound);
SndStop(SND_SCOPE_PROCESS, NULL);
}
#endif //_WIN32_WCE
extern "C" void alert_show_popup(rho_param *p)
{
if (p->type == RHO_PARAM_STRING) {
CAlert::showPopup(new CAlertDialog::Params(String(p->v.string)));
} else if (p->type == RHO_PARAM_HASH) {
String title, message, callback, icon;
String btnId, btnTitle;
Hashtable<String, String> buttons;
for (int i = 0, lim = p->v.hash->size; i < lim; ++i) {
char *name = p->v.hash->name[i];
rho_param *value = p->v.hash->value[i];
if (strcasecmp(name, "title") == 0) {
if (value->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("'title' should be string");
continue;
}
title = value->v.string;
}
else if (strcasecmp(name, "message") == 0) {
if (value->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("'message' should be string");
continue;
}
message = value->v.string;
}
else if (strcasecmp(name, "callback") == 0) {
if (value->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("'callback' should be string");
continue;
}
callback = value->v.string;
}
else if (strcasecmp(name, "buttons") == 0) {
if (value->type != RHO_PARAM_ARRAY) {
RAWLOG_ERROR("'buttons' should be array");
continue;
}
for (int j = 0, limj = value->v.array->size; j < limj; ++j) {
rho_param *arrValue = value->v.array->value[j];
switch (arrValue->type) {
case RHO_PARAM_STRING:
btnId = arrValue->v.string;
btnTitle = arrValue->v.string;
break;
case RHO_PARAM_HASH:
for (int k = 0, limk = arrValue->v.hash->size; k < limk; ++k) {
char *sName = arrValue->v.hash->name[k];
rho_param *sValue = arrValue->v.hash->value[k];
if (sValue->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("Illegal type of button item's value");
continue;
}
if (strcasecmp(sName, "id") == 0)
btnId = sValue->v.string;
else if (strcasecmp(sName, "title") == 0)
btnTitle = sValue->v.string;
}
break;
default:
RAWLOG_ERROR("Illegal type of button item");
continue;
}
}
if (btnId == "" || btnTitle == "") {
RAWLOG_ERROR("Incomplete button item");
continue;
}
buttons.put(btnTitle, btnId);
}//buttons
}
CAlert::showPopup(new CAlertDialog::Params(title, message, icon, callback, buttons));
}
}
extern "C" void alert_vibrate(void*) {
#if defined(_WIN32_WCE)
CAlert::vibrate();
#endif
}
extern "C" void alert_play_file(char* file_name, ...) {
#if defined(_WIN32_WCE)
CAlert::playFile(file_name);
#endif
}
extern "C" void alert_hide_popup()
{
}<commit_msg>WM: fix icon in customized alerts.<commit_after>#include "stdafx.h"
#if defined(_WIN32_WCE)
#include <soundfile.h>
#endif
#include <common/RhodesApp.h>
#include <common/rhoparams.h>
#include "Alert.h"
#include "MainWindow.h"
#include "Vibrate.h"
extern "C" HWND getMainWnd();
/**
********************************************************************************
* CAlertDialog members.
********************************************************************************
*/
//TODO: smart alignment and win32
typedef CWinTraits <WS_CAPTION | WS_VISIBLE | WS_POPUP | DS_CENTER> CAlertDialogTraits;
CAlertDialog::CAlertDialog(Params *params)
{
m_title = params->m_title;
m_message = params->m_message;
m_callback = params->m_callback;
m_icon = params->m_icon;
int id = ID_ALERT_DLG_BUTTON_FIRST;
for (Hashtable<String, String>::iterator itr = params->m_buttons.begin(); itr != params->m_buttons.end(); ++itr)
m_buttons.addElement(CustomButton(itr->first, itr->second, id++));
}
CAlertDialog::~CAlertDialog()
{
}
void CAlertDialog::DoInitTemplate()
{
#ifdef OS_WINCE
int initialWidth = GetSystemMetrics(SM_CXSCREEN)/3;
int initialHeight = initialWidth/2;
m_Template.Create(false, convertToStringW(m_title).c_str(),
GetSystemMetrics(SM_CXSCREEN)/2 - initialWidth/2,
GetSystemMetrics(SM_CYSCREEN)/2 - initialHeight/2,
initialWidth,
initialHeight,
CAlertDialogTraits::GetWndStyle(0),
CAlertDialogTraits::GetWndExStyle(0));
#endif
}
void CAlertDialog::DoInitControls()
{
}
LRESULT CAlertDialog::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL&bHandled)
{
#ifdef OS_WINCE
int indent = 10;
unsigned int maxWidth = GetSystemMetrics(SM_CXSCREEN) - (indent * 2);
unsigned int maxHeight = GetSystemMetrics(SM_CYSCREEN) - (indent * 2);
unsigned int msgWidth = 0, msgHeight = 0;
CClientDC dc(m_hWnd);
TEXTMETRIC tm = {0};
POINT point = { 5, 5};
SIZE size = { 0, 0 };
unsigned int iconHeight = 42;
int iconId = 0;
/**
* Icon.
*/
if (m_icon == "alert")
iconId = MB_ICONWARNING;
else if (m_icon == "question")
iconId = MB_ICONQUESTION;
else if (m_icon == "info")
iconId = MB_ICONINFORMATION;
if (iconId != 0) {
HMODULE hGWES = LoadLibraryEx( L"gwes.exe", NULL, LOAD_LIBRARY_AS_DATAFILE );
HICON hIcon = LoadIcon(hGWES, MAKEINTRESOURCE(iconId));
if (hIcon == NULL) {
LOG(ERROR) + "Failed to load icon";
} else {
size.cx = iconHeight; size.cy = iconHeight;
m_iconCtrl.Create(m_hWnd, CRect(point, size), NULL, WS_CHILD | WS_VISIBLE | SS_ICON, 0);
if (m_iconCtrl.SetIcon(hIcon) == NULL)
LOG(INFO) + "Failed to set icon";
}
}
/**
* Message.
*/
dc.GetTextMetrics(&tm);
if ((m_message.length() * tm.tmAveCharWidth) > maxWidth) {
msgWidth = maxWidth - indent - size.cy;
msgHeight = (((m_message.length() * tm.tmAveCharWidth * 2) / msgWidth))
* (tm.tmHeight + tm.tmExternalLeading + tm.tmInternalLeading);
RECT rect;
GetWindowRect(&rect);
MoveWindow(indent, rect.top, maxWidth, msgHeight + tm.tmHeight * 5);
point.x = size.cx; point.y = 5;
size.cx = msgWidth; size.cy = msgHeight;
} else {
point.x = size.cx + 4; point.y = 5;
msgWidth = m_message.length() * tm.tmAveCharWidth * 2;
msgHeight = (tm.tmHeight + tm.tmExternalLeading + tm.tmInternalLeading);
size.cx = msgWidth; size.cy = msgHeight;
}
m_messageCtrl.Create(m_hWnd, CRect(point, size), NULL, WS_CHILD | WS_VISIBLE);
m_messageCtrl.SetWindowText(convertToStringW(m_message).c_str());
/**
* Buttons.
*/
int bntNum = m_buttons.size();
point.x = indent, point.y = iconHeight > msgHeight ? point.y = iconHeight + 6 : msgHeight + 2;
unsigned int btnWidth = 0, btnHeight = 0;
for (Vector<CustomButton>::iterator itr = m_buttons.begin(); itr != m_buttons.end(); ++itr) {
btnWidth = (itr->m_title.length() * tm.tmAveCharWidth * 2) + 6;
btnHeight = tm.tmHeight + 4;
size.cx = btnWidth; size.cy = btnHeight;
itr->Create(m_hWnd, CRect(point, size),
convertToStringW(itr->m_title).c_str(),
WS_CHILD | WS_VISIBLE, 0,
itr->m_numId);
point.x += btnWidth + 4;
}
#endif
return bHandled = FALSE;
}
bool CAlertDialog::findButton(int id, CustomButton &btn)
{
for (Vector<CustomButton>::iterator itr = m_buttons.begin(); itr != m_buttons.end(); ++itr) {
if (itr->m_numId == id) {
btn = *itr;
return true;
}
}
return false;
}
LRESULT CAlertDialog::OnAlertDialogButton (WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CustomButton cbtn;
if (findButton((int) wID, cbtn))
rho_rhodesapp_callPopupCallback(m_callback.c_str(), cbtn.m_strId.c_str(), cbtn.m_title.c_str());
else
LOG(ERROR) + "internal error";
EndDialog(wID);
return 0;
}
/**
********************************************************************************
* CAlert members.
********************************************************************************
*/
IMPLEMENT_LOGCLASS(CAlert, "Alert");
void CAlert::showPopup(CAlertDialog::Params *params)
{
HWND main_wnd = getMainWnd();
::PostMessage(main_wnd, WM_ALERT_SHOWPOPUP, 0, (LPARAM ) params);
}
#if defined(_WIN32_WCE)
void CAlert::vibrate()
{
CVibrate::getCVibrate().toggle();
}
void CAlert::playFile(String fileName)
{
rho::String path = RHODESAPP().getRhoRootPath() + "apps" + fileName;
HSOUND hSound;
rho::String::size_type pos = 0;
while ( (pos = path.find('/', pos)) != rho::String::npos ) {
path.replace( pos, 1, "\\");
pos++;
}
USES_CONVERSION;
//SndPlaySync(A2T(path.c_str()), SND_PLAY_IGNOREUSERSETTINGS);
HRESULT hr = SndOpen(A2T(path.c_str()), &hSound);
hr = SndPlayAsync (hSound, 0);
if (hr != S_OK) {
LOG(WARNING) + "OnAlertPlayFile: failed to play file";
}
WaitForSingleObject(hSound, INFINITE);
hr = SndClose(hSound);
SndStop(SND_SCOPE_PROCESS, NULL);
}
#endif //_WIN32_WCE
extern "C" void alert_show_popup(rho_param *p)
{
if (p->type == RHO_PARAM_STRING) {
CAlert::showPopup(new CAlertDialog::Params(String(p->v.string)));
} else if (p->type == RHO_PARAM_HASH) {
String title, message, callback, icon;
String btnId, btnTitle;
Hashtable<String, String> buttons;
for (int i = 0, lim = p->v.hash->size; i < lim; ++i) {
char *name = p->v.hash->name[i];
rho_param *value = p->v.hash->value[i];
if (strcasecmp(name, "title") == 0) {
if (value->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("'title' should be string");
continue;
}
title = value->v.string;
}
else if (strcasecmp(name, "message") == 0) {
if (value->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("'message' should be string");
continue;
}
message = value->v.string;
}
else if (strcasecmp(name, "callback") == 0) {
if (value->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("'callback' should be string");
continue;
}
callback = value->v.string;
} else if (strcasecmp(name, "icon") == 0) {
if (value->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("'title' should be string");
continue;
}
icon = value->v.string;
}
else if (strcasecmp(name, "buttons") == 0) {
if (value->type != RHO_PARAM_ARRAY) {
RAWLOG_ERROR("'buttons' should be array");
continue;
}
for (int j = 0, limj = value->v.array->size; j < limj; ++j) {
rho_param *arrValue = value->v.array->value[j];
switch (arrValue->type) {
case RHO_PARAM_STRING:
btnId = arrValue->v.string;
btnTitle = arrValue->v.string;
break;
case RHO_PARAM_HASH:
for (int k = 0, limk = arrValue->v.hash->size; k < limk; ++k) {
char *sName = arrValue->v.hash->name[k];
rho_param *sValue = arrValue->v.hash->value[k];
if (sValue->type != RHO_PARAM_STRING) {
RAWLOG_ERROR("Illegal type of button item's value");
continue;
}
if (strcasecmp(sName, "id") == 0)
btnId = sValue->v.string;
else if (strcasecmp(sName, "title") == 0)
btnTitle = sValue->v.string;
}
break;
default:
RAWLOG_ERROR("Illegal type of button item");
continue;
}
}
if (btnId == "" || btnTitle == "") {
RAWLOG_ERROR("Incomplete button item");
continue;
}
buttons.put(btnTitle, btnId);
}//buttons
}
CAlert::showPopup(new CAlertDialog::Params(title, message, icon, callback, buttons));
}
}
extern "C" void alert_vibrate(void*) {
#if defined(_WIN32_WCE)
CAlert::vibrate();
#endif
}
extern "C" void alert_play_file(char* file_name, ...) {
#if defined(_WIN32_WCE)
CAlert::playFile(file_name);
#endif
}
extern "C" void alert_hide_popup()
{
}<|endoftext|> |
<commit_before>/*
* 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.
*/
/* cacheurl.cc - Plugin to modify the URL used as a cache key for certain
* requests, without modifying the URL used for actually fetching data from
* the origin server.
*/
#include <stdio.h>
#include <string.h>
#include "ts/ts.h"
#include "ts/remap.h"
#include "ink_defs.h"
#include <memory>
#include <string>
#include <vector>
#ifdef HAVE_PCRE_PCRE_H
#include <pcre/pcre.h>
#else
#include <pcre.h>
#endif
#define TOKENCOUNT 10
#define OVECOUNT 30
#define PLUGIN_NAME "cacheurl"
struct regex_info {
pcre *re; /* Compiled regular expression */
int tokcount; /* Token count */
char *pattern; /* Pattern string */
char *replacement; /* Replacement string */
int *tokens; /* Array of $x token values */
int *tokenoffset; /* Array of $x token offsets */
};
struct pr_list {
std::vector<regex_info *> pr;
pr_list() {}
~pr_list()
{
for (std::vector<regex_info *>::iterator info = this->pr.begin(); info != this->pr.end(); ++info) {
TSfree((*info)->tokens);
TSfree((*info)->tokenoffset);
pcre_free((*info)->re);
TSfree(*info);
}
}
};
static int
regex_substitute(char **buf, char *str, regex_info *info)
{
int matchcount;
int ovector[OVECOUNT]; /* Locations of matches in regex */
int replacelen; /* length of replacement string */
int i;
int offset;
int prev;
/* Perform the regex matching */
matchcount = pcre_exec(info->re, NULL, str, strlen(str), 0, 0, ovector, OVECOUNT);
if (matchcount < 0) {
switch (matchcount) {
case PCRE_ERROR_NOMATCH:
break;
default:
TSError("[%s] Matching error: %d\n", PLUGIN_NAME, matchcount);
break;
}
return 0;
}
/* Verify the replacement has the right number of matching groups */
for (i = 0; i < info->tokcount; i++) {
if (info->tokens[i] >= matchcount) {
TSError("[%s] Invalid reference int replacement: $%d\n", PLUGIN_NAME, info->tokens[i]);
return 0;
}
}
/* malloc the replacement string */
replacelen = strlen(info->replacement);
replacelen -= info->tokcount * 2; /* Subtract $1, $2 etc... */
for (i = 0; i < info->tokcount; i++) {
replacelen += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
replacelen++; /* Null terminator */
*buf = (char *)TSmalloc(replacelen);
/* perform string replacement */
offset = 0; /* Where we are adding new data in the string */
prev = 0;
for (i = 0; i < info->tokcount; i++) {
memcpy(*buf + offset, info->replacement + prev, info->tokenoffset[i] - prev);
offset += (info->tokenoffset[i] - prev);
prev = info->tokenoffset[i] + 2;
memcpy(*buf + offset, str + ovector[info->tokens[i] * 2], ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
offset += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
memcpy(*buf + offset, info->replacement + prev, strlen(info->replacement) - prev);
offset += strlen(info->replacement) - prev;
(*buf)[offset] = 0; /* Null termination */
return 1;
}
static int
regex_compile(regex_info **buf, char *pattern, char *replacement)
{
const char *reerror; /* Error string from pcre */
int reerroffset; /* Offset where any pcre error occured */
int tokcount;
int *tokens = NULL;
int *tokenoffset = NULL;
int status = 1; /* Status (return value) of the function */
regex_info *info = (regex_info *)TSmalloc(sizeof(regex_info));
/* Precompile the regular expression */
info->re = pcre_compile(pattern, 0, &reerror, &reerroffset, NULL);
if (!info->re) {
TSError("[%s] Compilation of regex '%s' failed at char %d: %s\n", PLUGIN_NAME, pattern, reerroffset, reerror);
status = 0;
}
/* Precalculate the location of $X tokens in the replacement */
tokcount = 0;
if (status) {
tokens = (int *)TSmalloc(sizeof(int) * TOKENCOUNT);
tokenoffset = (int *)TSmalloc(sizeof(int) * TOKENCOUNT);
for (unsigned i = 0; i < strlen(replacement); i++) {
if (replacement[i] == '$') {
if (tokcount >= TOKENCOUNT) {
TSError("[%s] Error: too many tokens in replacement "
"string: %s\n",
PLUGIN_NAME, replacement);
status = 0;
break;
} else if (replacement[i + 1] < '0' || replacement[i + 1] > '9') {
TSError("[%s] Error: Invalid replacement token $%c in %s: should be $0 - $9\n", PLUGIN_NAME, replacement[i + 1],
replacement);
status = 0;
break;
} else {
/* Store the location of the replacement */
/* Convert '0' to 0 */
tokens[tokcount] = replacement[i + 1] - '0';
tokenoffset[tokcount] = i;
tokcount++;
/* Skip the next char */
i++;
}
}
}
}
if (status) {
/* Everything went OK */
info->tokcount = tokcount;
info->tokens = tokens;
info->tokenoffset = tokenoffset;
info->pattern = TSstrdup(pattern);
info->replacement = TSstrdup(replacement);
*buf = info;
} else {
/* Something went wrong, clean up */
TSfree(tokens);
TSfree(tokenoffset);
if (info->re)
pcre_free(info->re);
TSfree(info);
}
return status;
}
static pr_list *
load_config_file(const char *config_file)
{
char buffer[1024];
std::string path;
TSFile fh;
std::auto_ptr<pr_list> prl(new pr_list());
/* locations in a config file line, end of line, split start, split end */
char *eol, *spstart, *spend;
int lineno = 0;
int retval;
regex_info *info = 0;
if (config_file == NULL) {
/* Default config file of plugins/cacheurl.config */
path = TSPluginDirGet();
path += "/cacheurl.config";
} else if (*config_file != '/') {
// Relative paths are relative to the config directory
path = TSConfigDirGet();
path += "/";
path += config_file;
} else {
// Absolute path ...
path = config_file;
}
TSDebug(PLUGIN_NAME, "Opening config file: %s", path.c_str());
fh = TSfopen(path.c_str(), "r");
if (!fh) {
TSError("[%s] Unable to open %s. No patterns will be loaded\n", PLUGIN_NAME, path.c_str());
return NULL;
}
while (TSfgets(fh, buffer, sizeof(buffer) - 1)) {
lineno++;
if (*buffer == '#') {
/* # Comments, only at line beginning */
continue;
}
eol = strstr(buffer, "\n");
if (eol) {
*eol = 0; /* Terminate string at newline */
} else {
/* Malformed line - skip */
continue;
}
/* Split line into two parts based on whitespace */
/* Find first whitespace */
spstart = strstr(buffer, " ");
if (!spstart) {
spstart = strstr(buffer, "\t");
}
if (!spstart) {
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
TSfclose(fh);
return NULL;
}
/* Find part of the line after any whitespace */
spend = spstart + 1;
while (*spend == ' ' || *spend == '\t') {
spend++;
}
if (*spend == 0) {
/* We reached the end of the string without any non-whitepace */
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
TSfclose(fh);
return NULL;
}
*spstart = 0;
/* We have the pattern/replacement, now do precompilation.
* buffer is the first part of the line. spend is the second part just
* after the whitespace */
TSDebug(PLUGIN_NAME, "Adding pattern/replacement pair: '%s' -> '%s'", buffer, spend);
retval = regex_compile(&info, buffer, spend);
if (!retval) {
TSError("[%s] Error precompiling regex/replacement. Skipping.\n", PLUGIN_NAME);
TSfclose(fh);
return NULL;
}
prl->pr.push_back(info);
}
TSfclose(fh);
if (prl->pr.empty()) {
TSError("[%s] No regular expressions loaded.\n", PLUGIN_NAME);
}
TSDebug(PLUGIN_NAME, "loaded %u regexes", (unsigned)prl->pr.size());
return prl.release();
}
static int
rewrite_cacheurl(pr_list *prl, TSHttpTxn txnp)
{
int ok = 1;
char *newurl = 0;
int retval;
char *url;
int url_length;
url = TSHttpTxnEffectiveUrlStringGet(txnp, &url_length);
if (!url) {
TSError("[%s] couldn't retrieve request url\n", PLUGIN_NAME);
ok = 0;
}
if (ok) {
for (std::vector<regex_info *>::iterator info = prl->pr.begin(); info != prl->pr.end(); ++info) {
retval = regex_substitute(&newurl, url, *info);
if (retval) {
/* Successful match/substitution */
break;
}
}
if (newurl) {
TSDebug(PLUGIN_NAME, "Rewriting cache URL for %s to %s", url, newurl);
if (TSCacheUrlSet(txnp, newurl, strlen(newurl)) != TS_SUCCESS) {
TSError("[%s] Unable to modify cache url from "
"%s to %s\n",
PLUGIN_NAME, url, newurl);
ok = 0;
}
}
}
/* Clean up */
if (url)
TSfree(url);
if (newurl)
TSfree(newurl);
return ok;
}
static int
handle_hook(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = (TSHttpTxn)edata;
pr_list *prl;
int ok = 1;
prl = (pr_list *)TSContDataGet(contp);
switch (event) {
case TS_EVENT_HTTP_READ_REQUEST_HDR:
ok = rewrite_cacheurl(prl, txnp);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
break;
default:
TSAssert(!"Unexpected event");
ok = 0;
break;
}
return ok;
}
/* Generic error message function for errors in plugin initialization */
static void
initialization_error(const char *msg)
{
TSError("[%s] %s\n", PLUGIN_NAME, msg);
TSError("[%s] Unable to initialize plugin (disabled).\n", PLUGIN_NAME);
}
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size)
{
if (!api_info) {
strncpy(errbuf, "[tsremap_init] Invalid TSRemapInterface argument", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->size < sizeof(TSRemapInterface)) {
strncpy(errbuf, "[tsremap_init] Incorrect size of TSRemapInterface structure", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->tsremap_version < TSREMAP_VERSION) {
snprintf(errbuf, errbuf_size - 1, "[tsremap_init] Incorrect API version %ld.%ld", api_info->tsremap_version >> 16,
(api_info->tsremap_version & 0xffff));
return TS_ERROR;
}
TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized");
return TS_SUCCESS;
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf ATS_UNUSED, int errbuf_size ATS_UNUSED)
{
*ih = load_config_file(argc > 2 ? argv[2] : NULL);
return (NULL == *ih) ? TS_ERROR : TS_SUCCESS;
}
void
TSRemapDeleteInstance(void *ih)
{
pr_list *prl = (pr_list *)ih;
TSDebug(PLUGIN_NAME, "Deleting remap instance");
delete prl;
}
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri ATS_UNUSED)
{
int ok;
ok = rewrite_cacheurl((pr_list *)ih, rh);
if (ok) {
return TSREMAP_NO_REMAP;
} else {
return TSREMAP_ERROR;
}
}
void
TSPluginInit(int argc, const char *argv[])
{
TSPluginRegistrationInfo info;
TSCont contp;
pr_list *prl;
info.plugin_name = (char *)PLUGIN_NAME;
info.vendor_name = (char *)"Apache Software Foundation";
info.support_email = (char *)"[email protected]";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
initialization_error("Plugin registration failed.");
return;
}
prl = load_config_file(argc > 1 ? argv[1] : NULL);
if (prl) {
contp = TSContCreate((TSEventFunc)handle_hook, NULL);
/* Store the pattern replacement list in the continuation */
TSContDataSet(contp, prl);
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
}
}
<commit_msg>[TS-3531]: Ignore blank lines in the plugin config file<commit_after>/*
* 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.
*/
/* cacheurl.cc - Plugin to modify the URL used as a cache key for certain
* requests, without modifying the URL used for actually fetching data from
* the origin server.
*/
#include <stdio.h>
#include <string.h>
#include "ts/ts.h"
#include "ts/remap.h"
#include "ink_defs.h"
#include <memory>
#include <string>
#include <vector>
#ifdef HAVE_PCRE_PCRE_H
#include <pcre/pcre.h>
#else
#include <pcre.h>
#endif
#define TOKENCOUNT 10
#define OVECOUNT 30
#define PLUGIN_NAME "cacheurl"
struct regex_info {
pcre *re; /* Compiled regular expression */
int tokcount; /* Token count */
char *pattern; /* Pattern string */
char *replacement; /* Replacement string */
int *tokens; /* Array of $x token values */
int *tokenoffset; /* Array of $x token offsets */
};
struct pr_list {
std::vector<regex_info *> pr;
pr_list() {}
~pr_list()
{
for (std::vector<regex_info *>::iterator info = this->pr.begin(); info != this->pr.end(); ++info) {
TSfree((*info)->tokens);
TSfree((*info)->tokenoffset);
pcre_free((*info)->re);
TSfree(*info);
}
}
};
static int
regex_substitute(char **buf, char *str, regex_info *info)
{
int matchcount;
int ovector[OVECOUNT]; /* Locations of matches in regex */
int replacelen; /* length of replacement string */
int i;
int offset;
int prev;
/* Perform the regex matching */
matchcount = pcre_exec(info->re, NULL, str, strlen(str), 0, 0, ovector, OVECOUNT);
if (matchcount < 0) {
switch (matchcount) {
case PCRE_ERROR_NOMATCH:
break;
default:
TSError("[%s] Matching error: %d\n", PLUGIN_NAME, matchcount);
break;
}
return 0;
}
/* Verify the replacement has the right number of matching groups */
for (i = 0; i < info->tokcount; i++) {
if (info->tokens[i] >= matchcount) {
TSError("[%s] Invalid reference int replacement: $%d\n", PLUGIN_NAME, info->tokens[i]);
return 0;
}
}
/* malloc the replacement string */
replacelen = strlen(info->replacement);
replacelen -= info->tokcount * 2; /* Subtract $1, $2 etc... */
for (i = 0; i < info->tokcount; i++) {
replacelen += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
replacelen++; /* Null terminator */
*buf = (char *)TSmalloc(replacelen);
/* perform string replacement */
offset = 0; /* Where we are adding new data in the string */
prev = 0;
for (i = 0; i < info->tokcount; i++) {
memcpy(*buf + offset, info->replacement + prev, info->tokenoffset[i] - prev);
offset += (info->tokenoffset[i] - prev);
prev = info->tokenoffset[i] + 2;
memcpy(*buf + offset, str + ovector[info->tokens[i] * 2], ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
offset += (ovector[info->tokens[i] * 2 + 1] - ovector[info->tokens[i] * 2]);
}
memcpy(*buf + offset, info->replacement + prev, strlen(info->replacement) - prev);
offset += strlen(info->replacement) - prev;
(*buf)[offset] = 0; /* Null termination */
return 1;
}
static int
regex_compile(regex_info **buf, char *pattern, char *replacement)
{
const char *reerror; /* Error string from pcre */
int reerroffset; /* Offset where any pcre error occured */
int tokcount;
int *tokens = NULL;
int *tokenoffset = NULL;
int status = 1; /* Status (return value) of the function */
regex_info *info = (regex_info *)TSmalloc(sizeof(regex_info));
/* Precompile the regular expression */
info->re = pcre_compile(pattern, 0, &reerror, &reerroffset, NULL);
if (!info->re) {
TSError("[%s] Compilation of regex '%s' failed at char %d: %s\n", PLUGIN_NAME, pattern, reerroffset, reerror);
status = 0;
}
/* Precalculate the location of $X tokens in the replacement */
tokcount = 0;
if (status) {
tokens = (int *)TSmalloc(sizeof(int) * TOKENCOUNT);
tokenoffset = (int *)TSmalloc(sizeof(int) * TOKENCOUNT);
for (unsigned i = 0; i < strlen(replacement); i++) {
if (replacement[i] == '$') {
if (tokcount >= TOKENCOUNT) {
TSError("[%s] Error: too many tokens in replacement "
"string: %s\n",
PLUGIN_NAME, replacement);
status = 0;
break;
} else if (replacement[i + 1] < '0' || replacement[i + 1] > '9') {
TSError("[%s] Error: Invalid replacement token $%c in %s: should be $0 - $9\n", PLUGIN_NAME, replacement[i + 1],
replacement);
status = 0;
break;
} else {
/* Store the location of the replacement */
/* Convert '0' to 0 */
tokens[tokcount] = replacement[i + 1] - '0';
tokenoffset[tokcount] = i;
tokcount++;
/* Skip the next char */
i++;
}
}
}
}
if (status) {
/* Everything went OK */
info->tokcount = tokcount;
info->tokens = tokens;
info->tokenoffset = tokenoffset;
info->pattern = TSstrdup(pattern);
info->replacement = TSstrdup(replacement);
*buf = info;
} else {
/* Something went wrong, clean up */
TSfree(tokens);
TSfree(tokenoffset);
if (info->re)
pcre_free(info->re);
TSfree(info);
}
return status;
}
static pr_list *
load_config_file(const char *config_file)
{
char buffer[1024];
std::string path;
TSFile fh;
std::auto_ptr<pr_list> prl(new pr_list());
/* locations in a config file line, end of line, split start, split end */
char *eol, *spstart, *spend;
int lineno = 0;
int retval;
regex_info *info = 0;
if (config_file == NULL) {
/* Default config file of plugins/cacheurl.config */
path = TSPluginDirGet();
path += "/cacheurl.config";
} else if (*config_file != '/') {
// Relative paths are relative to the config directory
path = TSConfigDirGet();
path += "/";
path += config_file;
} else {
// Absolute path ...
path = config_file;
}
TSDebug(PLUGIN_NAME, "Opening config file: %s", path.c_str());
fh = TSfopen(path.c_str(), "r");
if (!fh) {
TSError("[%s] Unable to open %s. No patterns will be loaded\n", PLUGIN_NAME, path.c_str());
return NULL;
}
while (TSfgets(fh, buffer, sizeof(buffer) - 1)) {
lineno++;
// make sure line was not bigger than buffer
if ((eol = strchr(buffer, '\n')) == NULL && (eol = strstr(buffer, "\r\n")) == NULL) {
// Malformed line - skip
TSError("%s: config line too long, did not get a good line in cfg, skipping, line: %s", PLUGIN_NAME, buffer);
memset(buffer, 0, sizeof(buffer));
continue;
} else {
*eol = 0;
}
// make sure line has something useful on it
// or allow # Comments, only at line beginning
if (eol - buffer < 2 || buffer[0] == '#') {
memset(buffer, 0, sizeof(buffer));
continue;
}
/* Split line into two parts based on whitespace */
/* Find first whitespace */
spstart = strstr(buffer, " ");
if (!spstart) {
spstart = strstr(buffer, "\t");
}
if (!spstart) {
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
TSfclose(fh);
return NULL;
}
/* Find part of the line after any whitespace */
spend = spstart + 1;
while (*spend == ' ' || *spend == '\t') {
spend++;
}
if (*spend == 0) {
/* We reached the end of the string without any non-whitepace */
TSError("[%s] ERROR: Invalid format on line %d. Skipping\n", PLUGIN_NAME, lineno);
TSfclose(fh);
return NULL;
}
*spstart = 0;
/* We have the pattern/replacement, now do precompilation.
* buffer is the first part of the line. spend is the second part just
* after the whitespace */
TSDebug(PLUGIN_NAME, "Adding pattern/replacement pair: '%s' -> '%s'", buffer, spend);
retval = regex_compile(&info, buffer, spend);
if (!retval) {
TSError("[%s] Error precompiling regex/replacement. Skipping.\n", PLUGIN_NAME);
TSfclose(fh);
return NULL;
}
prl->pr.push_back(info);
}
TSfclose(fh);
if (prl->pr.empty()) {
TSError("[%s] No regular expressions loaded.\n", PLUGIN_NAME);
}
TSDebug(PLUGIN_NAME, "loaded %u regexes", (unsigned)prl->pr.size());
return prl.release();
}
static int
rewrite_cacheurl(pr_list *prl, TSHttpTxn txnp)
{
int ok = 1;
char *newurl = 0;
int retval;
char *url;
int url_length;
url = TSHttpTxnEffectiveUrlStringGet(txnp, &url_length);
if (!url) {
TSError("[%s] couldn't retrieve request url\n", PLUGIN_NAME);
ok = 0;
}
if (ok) {
for (std::vector<regex_info *>::iterator info = prl->pr.begin(); info != prl->pr.end(); ++info) {
retval = regex_substitute(&newurl, url, *info);
if (retval) {
/* Successful match/substitution */
break;
}
}
if (newurl) {
TSDebug(PLUGIN_NAME, "Rewriting cache URL for %s to %s", url, newurl);
if (TSCacheUrlSet(txnp, newurl, strlen(newurl)) != TS_SUCCESS) {
TSError("[%s] Unable to modify cache url from "
"%s to %s\n",
PLUGIN_NAME, url, newurl);
ok = 0;
}
}
}
/* Clean up */
if (url)
TSfree(url);
if (newurl)
TSfree(newurl);
return ok;
}
static int
handle_hook(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txnp = (TSHttpTxn)edata;
pr_list *prl;
int ok = 1;
prl = (pr_list *)TSContDataGet(contp);
switch (event) {
case TS_EVENT_HTTP_READ_REQUEST_HDR:
ok = rewrite_cacheurl(prl, txnp);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
break;
default:
TSAssert(!"Unexpected event");
ok = 0;
break;
}
return ok;
}
/* Generic error message function for errors in plugin initialization */
static void
initialization_error(const char *msg)
{
TSError("[%s] %s\n", PLUGIN_NAME, msg);
TSError("[%s] Unable to initialize plugin (disabled).\n", PLUGIN_NAME);
}
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size)
{
if (!api_info) {
strncpy(errbuf, "[tsremap_init] Invalid TSRemapInterface argument", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->size < sizeof(TSRemapInterface)) {
strncpy(errbuf, "[tsremap_init] Incorrect size of TSRemapInterface structure", errbuf_size - 1);
return TS_ERROR;
}
if (api_info->tsremap_version < TSREMAP_VERSION) {
snprintf(errbuf, errbuf_size - 1, "[tsremap_init] Incorrect API version %ld.%ld", api_info->tsremap_version >> 16,
(api_info->tsremap_version & 0xffff));
return TS_ERROR;
}
TSDebug(PLUGIN_NAME, "remap plugin is successfully initialized");
return TS_SUCCESS;
}
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf ATS_UNUSED, int errbuf_size ATS_UNUSED)
{
*ih = load_config_file(argc > 2 ? argv[2] : NULL);
return (NULL == *ih) ? TS_ERROR : TS_SUCCESS;
}
void
TSRemapDeleteInstance(void *ih)
{
pr_list *prl = (pr_list *)ih;
TSDebug(PLUGIN_NAME, "Deleting remap instance");
delete prl;
}
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri ATS_UNUSED)
{
int ok;
ok = rewrite_cacheurl((pr_list *)ih, rh);
if (ok) {
return TSREMAP_NO_REMAP;
} else {
return TSREMAP_ERROR;
}
}
void
TSPluginInit(int argc, const char *argv[])
{
TSPluginRegistrationInfo info;
TSCont contp;
pr_list *prl;
info.plugin_name = (char *)PLUGIN_NAME;
info.vendor_name = (char *)"Apache Software Foundation";
info.support_email = (char *)"[email protected]";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
TSDebug(PLUGIN_NAME, "ERROR, Plugin registration failed");
initialization_error("Plugin registration failed.");
return;
}
prl = load_config_file(argc > 1 ? argv[1] : NULL);
if (prl) {
contp = TSContCreate((TSEventFunc)handle_hook, NULL);
/* Store the pattern replacement list in the continuation */
TSContDataSet(contp, prl);
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
} else {
TSDebug(PLUGIN_NAME, "ERROR, Plugin config load failed.");
initialization_error("Plugin config load failed.");
return;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2000-2006 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/sysfunc.h"
#include "csutil/array.h"
#include "plugins/engine/3d/region.h"
#include "plugins/engine/3d/engine.h"
#include "iengine/sector.h"
#include "iengine/campos.h"
#include "iengine/texture.h"
#include "iengine/material.h"
#include "iengine/engine.h"
#include "iengine/mesh.h"
//---------------------------------------------------------------------------
csRegion::csRegion (csEngine *e)
: scfImplementationType (this), engine (e)
{
}
csRegion::~csRegion ()
{
Clear ();
}
// If you enable this then after deleting a region it will
// print out which objects were not removed and their ref count.
#define REGION_CHECK
void csRegion::DeleteAll ()
{
// First we need to copy the objects to a vector to avoid
// messing up the iterator while we are deleting them.
csArray<iObject*> copy (1024, 256);
csRef<iObjectIterator> iter = GetIterator ();
while (iter->HasNext ())
{
iObject *o = iter->Next ();
copy.Push (o);
}
size_t total = copy.GetSize ();
// Now we iterate over all objects in the 'copy' vector and
// delete them. This will release them as csObject children
// from this region parent.
size_t i;
#ifdef REGION_CHECK
struct rcStruct { csString n; csWeakRef<iBase> weakb; };
rcStruct* rc = new rcStruct[total];
#endif
// The first loop is the most general one where we just use
// engine->RemoveObject().
for (i = 0; i < copy.GetSize (); i++)
{
iBase* b = (iBase*)copy[i];
#ifdef REGION_CHECK
rc[i].weakb = b;
rc[i].n = copy[i]->GetName ();
#endif
if (engine->RemoveObject (b))
{
copy[i] = 0;
total--;
}
}
#ifdef REGION_CHECK
for (i = 0 ; i < copy.GetSize () ; i++)
if (rc[i].weakb != 0)
printf ("Not Deleted %p '%s' ref=%d\n",
(iBase*)rc[i].weakb, (const char*)rc[i].n,
rc[i].weakb->GetRefCount ());
fflush (stdout);
delete[] rc;
#endif
if (!total) return;
if (total > 0)
{
// Sanity check. There should be no more
// non-0 references in the copy array now.
for (i = 0; i < copy.GetSize (); i++)
if (copy[i])
{
iObject *o = copy[i];
engine->ReportBug ("There is still an object in the array after "
"deleting region contents!\nObject name is '%s'", o->GetName ());
}
CS_ASSERT (false);
}
}
bool csRegion::PrepareTextures ()
{
csRef<iObjectIterator> iter;
iTextureManager *txtmgr = engine->G3D->GetTextureManager ();
// First register all textures to the texture manager.
iter = GetIterator ();
while (iter->HasNext ())
{
csRef<iTextureWrapper> csth (scfQueryInterface<iTextureWrapper> (
iter->Next ()));
if (csth)
{
if (!csth->GetTextureHandle ()) csth->Register (txtmgr);
if (!csth->KeepImage ()) csth->SetImageFile (0);
}
}
return true;
}
bool csRegion::ShineLights ()
{
engine->ShineLights (this);
return true;
}
bool csRegion::Prepare ()
{
if (!PrepareTextures ()) return false;
if (!ShineLights ()) return false;
return true;
}
iObject *csRegion::QueryObject ()
{
return this;
}
void csRegion::Clear ()
{
ObjRemoveAll ();
}
iSector *csRegion::FindSector (const char *iName)
{
csRef<iSector> sector (CS_GET_NAMED_CHILD_OBJECT (
this, iSector, iName));
return sector; // DecRef is ok here.
}
iMeshWrapper *csRegion::FindMeshObject (const char *Name)
{
char const* p = strchr (Name, ':');
if (p)
{
char* cname = csStrNew (Name);
char* p2 = strchr (cname, ':');
*p2 = 0;
csRef<iMeshWrapper> m = CS_GET_NAMED_CHILD_OBJECT (
this, iMeshWrapper, cname);
delete[] cname;
if (m)
{
return m->FindChildByName (p+1);
}
return 0;
}
else
{
csRef<iMeshWrapper> m = CS_GET_NAMED_CHILD_OBJECT (
this, iMeshWrapper, Name);
return m; // DecRef is ok here.
}
}
iMeshFactoryWrapper *csRegion::FindMeshFactory (const char *iName)
{
csRef<iMeshFactoryWrapper> mf (CS_GET_NAMED_CHILD_OBJECT (
this, iMeshFactoryWrapper, iName));
return mf; // DecRef is ok here.
}
iTextureWrapper *csRegion::FindTexture (const char *iName)
{
csRef<iTextureWrapper> t (CS_GET_NAMED_CHILD_OBJECT (
this, iTextureWrapper, iName));
return t; // DecRef is ok here.
}
iMaterialWrapper *csRegion::FindMaterial (const char *iName)
{
csRef<iMaterialWrapper> m (CS_GET_NAMED_CHILD_OBJECT (
this, iMaterialWrapper, iName));
return m; // DecRef is ok here.
}
iCameraPosition *csRegion::FindCameraPosition (const char *iName)
{
csRef<iCameraPosition> cp (CS_GET_NAMED_CHILD_OBJECT (
this, iCameraPosition, iName));
return cp; // DecRef is ok here.
}
bool csRegion::IsInRegion (iObject *iobj)
{
return iobj->GetObjectParent () == this;
}
// ---------------------------------------------------------------------------
csRegionList::csRegionList ()
: scfImplementationType (this),
regionList (16, 16)
{
}
csRegionList::~csRegionList()
{
}
int csRegionList::GetCount () const
{
return (int)regionList.GetSize ();
}
iRegion *csRegionList::Get (int n) const
{
return regionList.Get (n);
}
int csRegionList::Add (iRegion *obj)
{
return (int)regionList.Push (obj);
}
bool csRegionList::Remove (iRegion *obj)
{
return regionList.Delete (obj);
}
bool csRegionList::Remove (int n)
{
return regionList.DeleteIndex (n);
}
void csRegionList::RemoveAll ()
{
regionList.DeleteAll ();
}
int csRegionList::Find (iRegion *obj) const
{
return (int)regionList.Find (obj);
}
iRegion *csRegionList::FindByName (const char *Name) const
{
return regionList.FindByName (Name);
}
<commit_msg>res made some VC warning fixes.<commit_after>/*
Copyright (C) 2000-2006 by Jorrit Tyberghein
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/sysfunc.h"
#include "csutil/array.h"
#include "plugins/engine/3d/region.h"
#include "plugins/engine/3d/engine.h"
#include "iengine/sector.h"
#include "iengine/campos.h"
#include "iengine/texture.h"
#include "iengine/material.h"
#include "iengine/engine.h"
#include "iengine/mesh.h"
//---------------------------------------------------------------------------
csRegion::csRegion (csEngine *e)
: scfImplementationType (this), engine (e)
{
}
csRegion::~csRegion ()
{
Clear ();
}
// If you enable this then after deleting a region it will
// print out which objects were not removed and their ref count.
#define REGION_CHECK
void csRegion::DeleteAll ()
{
// First we need to copy the objects to a vector to avoid
// messing up the iterator while we are deleting them.
csArray<iObject*> copy (1024, 256);
csRef<iObjectIterator> iter = GetIterator ();
while (iter->HasNext ())
{
iObject *o = iter->Next ();
copy.Push (o);
}
size_t total = copy.GetSize ();
// Now we iterate over all objects in the 'copy' vector and
// delete them. This will release them as csObject children
// from this region parent.
size_t i;
#ifdef REGION_CHECK
struct rcStruct { csString n; csWeakRef<iBase> weakb; };
rcStruct* rc = new rcStruct[total];
#endif
// The first loop is the most general one where we just use
// engine->RemoveObject().
for (i = 0; i < copy.GetSize (); i++)
{
iBase* b = (iBase*)copy[i];
#ifdef REGION_CHECK
rc[i].weakb = b;
rc[i].n = copy[i]->GetName ();
#endif
if (engine->RemoveObject (b))
{
copy[i] = 0;
total--;
}
}
#ifdef REGION_CHECK
for (i = 0 ; i < copy.GetSize () ; i++)
if (rc[i].weakb != 0)
printf ("Not Deleted %p '%s' ref=%d\n",
(iBase*)rc[i].weakb, (const char*)rc[i].n,
rc[i].weakb->GetRefCount ());
fflush (stdout);
delete[] rc;
#endif
if (!total) return;
if (total > 0)
{
// Sanity check. There should be no more
// non-0 references in the copy array now.
for (i = 0; i < copy.GetSize (); i++)
if (copy[i])
{
iObject *o = copy[i];
engine->ReportBug ("There is still an object in the array after "
"deleting region contents!\nObject name is '%s'", o->GetName ());
}
CS_ASSERT (false);
}
}
bool csRegion::PrepareTextures ()
{
csRef<iObjectIterator> iter;
iTextureManager *txtmgr = engine->G3D->GetTextureManager ();
// First register all textures to the texture manager.
iter = GetIterator ();
while (iter->HasNext ())
{
csRef<iTextureWrapper> csth (scfQueryInterface<iTextureWrapper> (
iter->Next ()));
if (csth)
{
if (!csth->GetTextureHandle ()) csth->Register (txtmgr);
if (!csth->KeepImage ()) csth->SetImageFile (0);
}
}
return true;
}
bool csRegion::ShineLights ()
{
engine->ShineLights (this);
return true;
}
bool csRegion::Prepare ()
{
if (!PrepareTextures ()) return false;
if (!ShineLights ()) return false;
return true;
}
iObject *csRegion::QueryObject ()
{
return this;
}
void csRegion::Clear ()
{
ObjRemoveAll ();
}
iSector *csRegion::FindSector (const char *iName)
{
csRef<iSector> sector (CS::GetNamedChildObject<iSector> (
this, iName));
return sector; // DecRef is ok here.
}
iMeshWrapper *csRegion::FindMeshObject (const char *Name)
{
char const* p = strchr (Name, ':');
if (p)
{
char* cname = csStrNew (Name);
char* p2 = strchr (cname, ':');
*p2 = 0;
csRef<iMeshWrapper> m = CS::GetNamedChildObject<iMeshWrapper> (
this, cname);
delete[] cname;
if (m)
{
return m->FindChildByName (p+1);
}
return 0;
}
else
{
csRef<iMeshWrapper> m = CS::GetNamedChildObject<iMeshWrapper> (
this, Name);
return m; // DecRef is ok here.
}
}
iMeshFactoryWrapper *csRegion::FindMeshFactory (const char *iName)
{
csRef<iMeshFactoryWrapper> mf (
CS::GetNamedChildObject<iMeshFactoryWrapper> (this, iName));
return mf; // DecRef is ok here.
}
iTextureWrapper *csRegion::FindTexture (const char *iName)
{
csRef<iTextureWrapper> t (CS::GetNamedChildObject<iTextureWrapper> (
this, iName));
return t; // DecRef is ok here.
}
iMaterialWrapper *csRegion::FindMaterial (const char *iName)
{
csRef<iMaterialWrapper> m (CS::GetNamedChildObject<iMaterialWrapper> (
this, iName));
return m; // DecRef is ok here.
}
iCameraPosition *csRegion::FindCameraPosition (const char *iName)
{
csRef<iCameraPosition> cp (CS::GetNamedChildObject<iCameraPosition> (
this, iName));
return cp; // DecRef is ok here.
}
bool csRegion::IsInRegion (iObject *iobj)
{
return iobj->GetObjectParent () == this;
}
// ---------------------------------------------------------------------------
csRegionList::csRegionList ()
: scfImplementationType (this),
regionList (16, 16)
{
}
csRegionList::~csRegionList()
{
}
int csRegionList::GetCount () const
{
return (int)regionList.GetSize ();
}
iRegion *csRegionList::Get (int n) const
{
return regionList.Get (n);
}
int csRegionList::Add (iRegion *obj)
{
return (int)regionList.Push (obj);
}
bool csRegionList::Remove (iRegion *obj)
{
return regionList.Delete (obj);
}
bool csRegionList::Remove (int n)
{
return regionList.DeleteIndex (n);
}
void csRegionList::RemoveAll ()
{
regionList.DeleteAll ();
}
int csRegionList::Find (iRegion *obj) const
{
return (int)regionList.Find (obj);
}
iRegion *csRegionList::FindByName (const char *Name) const
{
return regionList.FindByName (Name);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Arista Networks, Inc. All rights reserved.
// Arista Networks, Inc. Confidential and Proprietary.
#include "eos/class_map.h"
#include "eos/exception.h"
#include "impl.h"
namespace std {
size_t hash<eos::policy_map_action_t>::operator() (eos::policy_map_action_t
const & action) const {
// TODO: no op impl
return 0;
}
size_t hash<eos::policy_map_key_t>::operator() (eos::policy_map_key_t
const & key) const {
// TODO: no op impl
return 0;
}
}
namespace eos {
policy_map_handler::policy_map_handler(policy_map_mgr * mgr) :
base_handler<policy_map_mgr, policy_map_handler>(mgr) {
}
void
policy_map_handler::watch_policy_map(policy_map_key_t const & key,
bool interest) {
// TODO: no op impl.
}
void
policy_map_handler::watch_policy_map(policy_map_key_t const & key,
std::string const & name,
bool interest) {
// TODO: no op impl.
}
void
policy_map_handler::on_policy_map_sync_fail(policy_map_key_t const & key,
std::string const & message) {
// TODO: no op impl.
}
void
policy_map_handler::on_policy_map_sync(policy_map_key_t const & key) {
// TODO: no op impl.
}
void
policy_map_handler::on_policy_map_config_set(policy_map_key_t const & name) {
// TODO: no op impl.
}
class policy_map_mgr_impl : public policy_map_mgr {
public:
policy_map_mgr_impl() {
}
void resync_init() {
}
void resync_complete() {
}
bool exists(policy_map_key_t const & key) const {
return false;
}
policy_map_t policy_map(policy_map_key_t const & key) const {
return policy_map_t();
}
void policy_map_is(policy_map_t const & policy_map) {
}
void policy_map_del(policy_map_key_t const & key) {
}
policy_map_iter_t policy_map_iter(policy_feature_t) const {
policy_map_iter_t * nop = 0;
return *nop;
}
void policy_map_apply(policy_map_key_t const &, intf_id_t,
acl_direction_t, bool apply) {
}
void handleInputConfig(std::string const & name) const {
}
};
DEFINE_STUB_MGR_CTOR(policy_map_mgr)
}
<commit_msg>@13892585 EosSdk Policy Map: "ri" mount "pbr/input/pmap/config" and "pbr/input/intf/config"<commit_after>// Copyright (c) 2014 Arista Networks, Inc. All rights reserved.
// Arista Networks, Inc. Confidential and Proprietary.
#include "eos/class_map.h"
#include "eos/exception.h"
#include "impl.h"
namespace std {
size_t hash<eos::policy_map_action_t>::operator() (eos::policy_map_action_t
const & action) const {
// TODO: no op impl
return 0;
}
size_t hash<eos::policy_map_key_t>::operator() (eos::policy_map_key_t
const & key) const {
// TODO: no op impl
return 0;
}
}
namespace eos {
policy_map_handler::policy_map_handler(policy_map_mgr * mgr) :
base_handler<policy_map_mgr, policy_map_handler>(mgr) {
}
void
policy_map_handler::watch_policy_map(policy_map_key_t const & key,
bool interest) {
// TODO: no op impl.
}
void
policy_map_handler::watch_policy_map(policy_map_key_t const & key,
std::string const & name,
bool interest) {
// TODO: no op impl.
}
void
policy_map_handler::on_policy_map_sync_fail(policy_map_key_t const & key,
std::string const & message) {
// TODO: no op impl.
}
void
policy_map_handler::on_policy_map_sync(policy_map_key_t const & key) {
// TODO: no op impl.
}
void
policy_map_handler::on_policy_map_config_set(policy_map_key_t const & name) {
// TODO: no op impl.
}
class policy_map_mgr_impl : public policy_map_mgr {
public:
policy_map_mgr_impl() {
}
void resync_init() {
}
void resync_complete() {
}
bool exists(policy_map_key_t const & key) const {
return false;
}
policy_map_t policy_map(policy_map_key_t const & key) const {
return policy_map_t();
}
void policy_map_is(policy_map_t const & policy_map) {
}
void policy_map_del(policy_map_key_t const & key) {
}
policy_map_iter_t policy_map_iter(policy_feature_t) const {
policy_map_iter_t * nop = 0;
return *nop;
}
void policy_map_apply(policy_map_key_t const &, intf_id_t,
acl_direction_t, bool apply) {
}
};
DEFINE_STUB_MGR_CTOR(policy_map_mgr)
}
<|endoftext|> |
<commit_before>extern "C" {
#include <png.h>
}
#include <hx/CFFI.h>
#include <graphics/PNG.h>
#include <setjmp.h>
namespace lime {
static int id_data;
static int id_height;
static int id_width;
static bool init = false;
/*static void user_error_fn (png_structp png_ptr, png_const_charp error_msg) {
longjmp (png_ptr->jmpbuf, 1);
}
static void user_warning_fn (png_structp png_ptr, png_const_charp warning_msg) { }
static void user_read_data_fn (png_structp png_ptr, png_bytep data, png_size_t length) {
png_voidp buffer = png_get_io_ptr (png_ptr);
((ReadBuf *)buffer)->Read (data, length);
}
void user_write_data (png_structp png_ptr, png_bytep data, png_size_t length) {
QuickVec<unsigned char> *buffer = (QuickVec<unsigned char> *)png_get_io_ptr (png_ptr);
buffer->append ((unsigned char *)data, (int)length);
}
void user_flush_data (png_structp png_ptr) { }*/
void PNG::Decode (ByteArray bytes, value imageData) {
/*if (!init) {
id_data = val_id ("data");
id_height = val_id ("height");
id_width = val_id ("width");
init = true;
}
png_structp png_ptr;
png_infop info_ptr;
png_uint_32 width, height;
int bit_depth, color_type, interlace_type;
png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, user_error_fn, user_warning_fn);
if (png_ptr == NULL)
return;
info_ptr = png_create_info_struct (png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct (&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
return;
}
unsigned char* bytes[width * height * 4];
RenderTarget target;
if (setjmp (png_jmpbuf (png_ptr))) {
if (bytes) {
delete bytes;
}
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
return;
}
ReadBuf buffer (inData, inDataLen);
//if (inFile) {
//png_init_io (png_ptr, inFile);
//} else {
png_set_read_fn (png_ptr, (void *)&buffer, user_read_data_fn);
//}
png_read_info (png_ptr, info_ptr);
png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
bool has_alpha = (color_type == PNG_COLOR_TYPE_GRAY_ALPHA || color_type == PNG_COLOR_TYPE_RGB_ALPHA || png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS));
png_set_expand (png_ptr);
png_set_filler (png_ptr, 0xff, PNG_FILLER_AFTER);
png_set_palette_to_rgb (png_ptr);
png_set_gray_to_rgb (png_ptr);
if (bit_depth == 16)
png_set_strip_16 (png_ptr);
png_set_bgr (png_ptr);
//result = new ImageData ();
//result.width = width;
//result.height = height;
//result.data = uint8[width * height * 4];
png_read_png (png_ptr, (png_bytepp)&bytes);
png_read_end (png_ptr, info_ptr);
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
value object = (KeyEvent::eventObject ? KeyEvent::eventObject->get () : alloc_empty_object ());
alloc_field (object, id_code, alloc_int (event->code));
alloc_field (object, id_type, alloc_int (event->type));
alloc_field (imageData, id_width, alloc_int (width));
alloc_field (imageData, id_height, alloc_int (height));
alloc_field (imageData, id_data, alloc_int (bytes));
return result;*/
}
static bool Encode (ImageData *imageData, ByteArray *bytes) {
return true;
/*png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, user_error_fn, user_warning_fn);
if (!png_ptr)
return false;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
return false;
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr );
return false;
}
QuickVec<uint8> out_buffer;
png_set_write_fn(png_ptr, &out_buffer, user_write_data, user_flush_data);
int w = inSurface->Width();
int h = inSurface->Height();
int bit_depth = 8;
int color_type = (inSurface->Format()&pfHasAlpha) ?
PNG_COLOR_TYPE_RGB_ALPHA :
PNG_COLOR_TYPE_RGB;
png_set_IHDR(png_ptr, info_ptr, w, h,
bit_depth, color_type, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
bool do_alpha = color_type==PNG_COLOR_TYPE_RGBA;
{
QuickVec<uint8> row_data(w*4);
png_bytep row = &row_data[0];
for(int y=0;y<h;y++)
{
uint8 *buf = &row_data[0];
const uint8 *src = (const uint8 *)inSurface->Row(y);
for(int x=0;x<w;x++)
{
buf[0] = src[2];
buf[1] = src[1];
buf[2] = src[0];
src+=3;
buf+=3;
if (do_alpha)
*buf++ = *src;
src++;
}
png_write_rows(png_ptr, &row, 1);
}
}
png_write_end(png_ptr, NULL);
*outBytes = ByteArray(out_buffer);
return true;*/
}
}<commit_msg>Don't require png.h for the moment<commit_after>extern "C" {
//#include <png.h>
}
#include <hx/CFFI.h>
#include <graphics/PNG.h>
#include <setjmp.h>
namespace lime {
static int id_data;
static int id_height;
static int id_width;
static bool init = false;
/*static void user_error_fn (png_structp png_ptr, png_const_charp error_msg) {
longjmp (png_ptr->jmpbuf, 1);
}
static void user_warning_fn (png_structp png_ptr, png_const_charp warning_msg) { }
static void user_read_data_fn (png_structp png_ptr, png_bytep data, png_size_t length) {
png_voidp buffer = png_get_io_ptr (png_ptr);
((ReadBuf *)buffer)->Read (data, length);
}
void user_write_data (png_structp png_ptr, png_bytep data, png_size_t length) {
QuickVec<unsigned char> *buffer = (QuickVec<unsigned char> *)png_get_io_ptr (png_ptr);
buffer->append ((unsigned char *)data, (int)length);
}
void user_flush_data (png_structp png_ptr) { }*/
void PNG::Decode (ByteArray bytes, value imageData) {
/*if (!init) {
id_data = val_id ("data");
id_height = val_id ("height");
id_width = val_id ("width");
init = true;
}
png_structp png_ptr;
png_infop info_ptr;
png_uint_32 width, height;
int bit_depth, color_type, interlace_type;
png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, user_error_fn, user_warning_fn);
if (png_ptr == NULL)
return;
info_ptr = png_create_info_struct (png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct (&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
return;
}
unsigned char* bytes[width * height * 4];
RenderTarget target;
if (setjmp (png_jmpbuf (png_ptr))) {
if (bytes) {
delete bytes;
}
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
return;
}
ReadBuf buffer (inData, inDataLen);
//if (inFile) {
//png_init_io (png_ptr, inFile);
//} else {
png_set_read_fn (png_ptr, (void *)&buffer, user_read_data_fn);
//}
png_read_info (png_ptr, info_ptr);
png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
bool has_alpha = (color_type == PNG_COLOR_TYPE_GRAY_ALPHA || color_type == PNG_COLOR_TYPE_RGB_ALPHA || png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS));
png_set_expand (png_ptr);
png_set_filler (png_ptr, 0xff, PNG_FILLER_AFTER);
png_set_palette_to_rgb (png_ptr);
png_set_gray_to_rgb (png_ptr);
if (bit_depth == 16)
png_set_strip_16 (png_ptr);
png_set_bgr (png_ptr);
//result = new ImageData ();
//result.width = width;
//result.height = height;
//result.data = uint8[width * height * 4];
png_read_png (png_ptr, (png_bytepp)&bytes);
png_read_end (png_ptr, info_ptr);
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
value object = (KeyEvent::eventObject ? KeyEvent::eventObject->get () : alloc_empty_object ());
alloc_field (object, id_code, alloc_int (event->code));
alloc_field (object, id_type, alloc_int (event->type));
alloc_field (imageData, id_width, alloc_int (width));
alloc_field (imageData, id_height, alloc_int (height));
alloc_field (imageData, id_data, alloc_int (bytes));
return result;*/
}
static bool Encode (ImageData *imageData, ByteArray *bytes) {
return true;
/*png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, user_error_fn, user_warning_fn);
if (!png_ptr)
return false;
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr)
return false;
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_write_struct(&png_ptr, &info_ptr );
return false;
}
QuickVec<uint8> out_buffer;
png_set_write_fn(png_ptr, &out_buffer, user_write_data, user_flush_data);
int w = inSurface->Width();
int h = inSurface->Height();
int bit_depth = 8;
int color_type = (inSurface->Format()&pfHasAlpha) ?
PNG_COLOR_TYPE_RGB_ALPHA :
PNG_COLOR_TYPE_RGB;
png_set_IHDR(png_ptr, info_ptr, w, h,
bit_depth, color_type, PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_write_info(png_ptr, info_ptr);
bool do_alpha = color_type==PNG_COLOR_TYPE_RGBA;
{
QuickVec<uint8> row_data(w*4);
png_bytep row = &row_data[0];
for(int y=0;y<h;y++)
{
uint8 *buf = &row_data[0];
const uint8 *src = (const uint8 *)inSurface->Row(y);
for(int x=0;x<w;x++)
{
buf[0] = src[2];
buf[1] = src[1];
buf[2] = src[0];
src+=3;
buf+=3;
if (do_alpha)
*buf++ = *src;
src++;
}
png_write_rows(png_ptr, &row, 1);
}
}
png_write_end(png_ptr, NULL);
*outBytes = ByteArray(out_buffer);
return true;*/
}
}<|endoftext|> |
<commit_before>/*
* 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 <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <json/reader.h>
#include <json/writer.h>
#include <slog2.h>
// minizip
#include "unzip.h"
#include "state2json.h"
#include "extractzipfile_ndk.hpp"
#include "extractzipfile_js.hpp"
static void ExtractZipFileNDK_mkpath(char *path) {
size_t len = strlen(path);
// ensure path is a string
char last_char = path[len - 1];
path[len - 1] = '\0';
// mkdir() foreach except last folder
for (char *upto = path + 1; *upto; upto++) {
if (*upto == '/') {
*upto = '\0';
mkdir(path, 0x777);
*upto = '/';
}
}
// mkdir() last folder
mkdir(path, 0x777);
// restore input path
path[len - 1] = last_char;
}
namespace webworks {
ExtractZipFileNDK::ExtractZipFileNDK(ExtractZipFileJS *parent) {
m_pParent = parent;
}
ExtractZipFileNDK::~ExtractZipFileNDK() {
}
// ->extractFile
// Returns a json obejct with "result" set to int ret code
// ret code is < 0 on error.
// and "result_message" a description of the error or success
void ExtractZipFileNDK::extractFile(const std::string& callbackId, const std::string& inputString) {
#define extractReturn(x,y) \
do {retval["result"] = x; \
retval["result_message"] = y; \
m_pParent->NotifyEvent(callbackId + " " + writer.write(retval)); \
return;} while (0)
// Tune this and reduce mem usage
#define EZIPBUFSIZE 1024
#define MAX_FILENAME 1024
// Parse the arg string as JSON
Json::FastWriter writer;
Json::Reader reader;
Json::Value root;
Json::Value retval;
s2jInit(retval);
bool parse = reader.parse(inputString, root);
if (!parse) {
extractReturn(-1, "Cannot parse internal JSON object");
}
// -- Parse Input
// callbackToken
std::string requestedToken = root["callbackToken"].asString();
if (requestedToken == "")
requestedToken = root["zip"];
retval["callbackToken"] = requestedToken;
// destination
std::string dest_root = root["destination"].asString();
if (dest_root == "")
dest_root = "./";
if (dest_root[dest_root.size() - 1] != '/')
dest_root += "/";
// zip
std::string src_zip = root["zip"].asString();
if (src_zip == "")
extractReturn(-1, "zip argument must not be empty");
// tarBombProtection
// ensures everything is extracted into a single folder
bool prevent_tar_bomb = root["tarBombProtection"].asString() == "true";
if (prevent_tar_bomb) {
unsigned filename_start = 1 + src_zip.find_last_of("/");
unsigned filename_end = src_zip.find_last_of(".");
std::string filename = src_zip.substr(filename_start, filename_end);
dest_root += filename + "/";
}
// overwriteFiles
bool overwrite_files = !(root["overwriteFiles"].asString() == "false");
// -- Extract Zip
const char *zip_path = src_zip.c_str();
unzFile zipFile = unzOpen(zip_path);
if (zipFile == NULL)
extractReturn(-1, "Failed to open zip file.");
// get zip metadata
unz_global_info zipInfo;
if (unzGetGlobalInfo(zipFile, &zipInfo) != UNZ_OK) {
unzClose(zipFile);
extractReturn(-1, "Failed to parse zip metadata.");
}
// fixed size buf on stack, WATCH USAGE!
char fileBuffer[EZIPBUFSIZE];
// Ensure destination exists
ExtractZipFileNDK_mkpath(dest_root);
int filesExtracted = 0;
int files_skipped = 0;
for (int i = 0; i < zipInfo.number_entry; i++) {
s2jIncre("entries");
// single file metadata
unz_file_info fileInfo;
char filename[MAX_FILENAME + 1];
// get metadata on specific file
if (unzGetCurrentFileInfo(
zipFile,
&fileInfo,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0) != UNZ_OK) {
unzClose(zipFile);
extractReturn(-1, "Failed to parse a file's metadata.");
}
filename[MAX_FILENAME] = '\0'; // ensure string termination
s2jInsert("files", filename);
// Handle Directories
if (filename[strlen(filename) - 1] == '/') {
// Directory creation cannot lose data
// so we do not care if a dir already
// exists
ExtractZipFileNDK_mkpath((dest_root + filename).c_str(), 0x777);
s2jIncre("directories");
// Note: The zip format does store permissions
// except these are all in platform specific
// formats. I talked with the guy responsible
// for window's file navigator's zip lib.
// His stories have scared me into the thinking
// that providing a default permission is more
// user friendly than missing obscure edge cases
// which could leave files in "magical" states.
// Handle Files
} else {
// Note: This opens zipFile's "current" file
// "current" acts as an interator
if (unzOpenCurrentFile(zipFile) != UNZ_OK) {
unzClose(zipFile);
extractReturn(-1, "Failed to extract file");
}
// Open destination file in file system
std::string dest_file_path = dest_root + filename;
// Check for overwriting
if (!overwrite_files && access(dest_file_path.c_str(), F_OK) != -1) {
// file exists and we are not allowed to overwrite
s2jIncre("files_skipped");
} else {
FILE *destFile = fopen(dest_file_path.c_str(), "wb");
if (destFile == NULL) {
unzCloseCurrentFile(zipFile);
unzClose(zipFile);
extractReturn(-1, "Failed to open destination file");
}
// Ferry data into destination
int readResult = UNZ_OK; // is 0
do {
// Read
readResult = unzReadCurrentFile(zipFile, fileBuffer, EZIPBUFSIZE);
if (readResult < 0) {
unzCloseCurrentFile(zipFile);
unzClose(zipFile);
fclose(destFile);
extractReturn(-1, "Failed to read compressed file");
}
// Write
if (readResult > 0) {
int writeResult = fwrite(fileBuffer, readResult, 1, destFile);
if (writeResult != 1) {
// Note: we asked for the full buffer
// to be written at once, so the 1
// return value is not "true" but
// the number blocks writen
unzCloseCurrentFile(zipFile);
unzClose(zipFile);
fclose(destFile);
extractReturn(-1, "Failed to write to destination file");
}
}
} while (readResult > 0);
fclose(destFile);
filesExtracted++;
}
s2jIncre("files");
}
unzCloseCurrentFile(zipFile);
// Increment "current" file interator if any more files
unzGoToNextFile(zipFile);
}
unzClose(zipFile);
// Success!
extractReturn(filesExtracted, "Extraction successful.");
}
} /* namespace webworks */
<commit_msg>Add state logging to default builds<commit_after>/*
* 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 <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <json/reader.h>
#include <json/writer.h>
#include <slog2.h>
// minizip
#include "unzip.h"
#define S2J_ENABLED 1
#include "state2json.h"
#include "extractzipfile_ndk.hpp"
#include "extractzipfile_js.hpp"
static void ExtractZipFileNDK_mkpath(const char *path_raw) {
size_t len = strlen(path_raw);
// copy path so we can mangle it
char *path = (char *)malloc(len + 1);
snprintf(path, len + 1, "%s", path_raw);
char last_char = path[len - 1];
if (last_char == '/')
path[len - 1] = '\0';
// mkdir() foreach except last folder
for (char *upto = path + 1; *upto != '\0'; upto++) {
if (*upto == '/') {
*upto = '\0';
mkdir(path, 0x777);
*upto = '/';
}
}
// mkdir() last folder
mkdir(path, 0x777);
free(path);
}
namespace webworks {
ExtractZipFileNDK::ExtractZipFileNDK(ExtractZipFileJS *parent) {
m_pParent = parent;
}
ExtractZipFileNDK::~ExtractZipFileNDK() {
}
// ->extractFile
// Returns a json obejct with "result" set to int ret code
// ret code is < 0 on error.
// and "result_message" a description of the error or success
void ExtractZipFileNDK::extractFile(const std::string& callbackId, const std::string& inputString) {
#define extractReturn(x,y) \
do {retval["result"] = x; \
retval["result_message"] = y; \
m_pParent->NotifyEvent(callbackId + " " + writer.write(retval)); \
return;} while (0)
// Tune this and reduce mem usage
#define EZIPBUFSIZE 1024
#define MAX_FILENAME 1024
// Parse the arg string as JSON
Json::FastWriter writer;
Json::Reader reader;
Json::Value root;
Json::Value retval;
s2jInit(retval);
bool parse = reader.parse(inputString, root);
if (!parse) {
extractReturn(-1, "Cannot parse internal JSON object");
}
// -- Parse Input
// callbackToken
std::string requestedToken = root["callbackToken"].asString();
if (requestedToken == "")
requestedToken = root["zip"].asString();
retval["callbackToken"] = requestedToken;
// destination
std::string dest_root = root["destination"].asString();
if (dest_root == "")
dest_root = "./";
if (dest_root[dest_root.size() - 1] != '/')
dest_root += "/";
// zip
std::string src_zip = root["zip"].asString();
if (src_zip == "")
extractReturn(-1, "zip argument must not be empty");
// tarBombProtection
// ensures everything is extracted into a single folder
bool prevent_tar_bomb = root["tarBombProtection"].asString() == "true";
if (prevent_tar_bomb) {
unsigned filename_start = 1 + src_zip.find_last_of("/");
unsigned filename_end = src_zip.find_last_of(".");
std::string filename = src_zip.substr(filename_start, filename_end);
dest_root += filename + "/";
}
// overwriteFiles
bool overwrite_files = !(root["overwriteFiles"].asString() == "false");
// -- Extract Zip
const char *zip_path = src_zip.c_str();
unzFile zipFile = unzOpen(zip_path);
if (zipFile == NULL)
extractReturn(-1, "Failed to open zip file.");
// get zip metadata
unz_global_info zipInfo;
if (unzGetGlobalInfo(zipFile, &zipInfo) != UNZ_OK) {
unzClose(zipFile);
extractReturn(-1, "Failed to parse zip metadata.");
}
// fixed size buf on stack, WATCH USAGE!
char fileBuffer[EZIPBUFSIZE];
// Ensure destination exists
ExtractZipFileNDK_mkpath(dest_root.c_str());
int filesExtracted = 0;
int files_skipped = 0;
for (int i = 0; i < zipInfo.number_entry; i++) {
s2jIncre("entries");
// single file metadata
unz_file_info fileInfo;
char filename[MAX_FILENAME + 1];
// get metadata on specific file
if (unzGetCurrentFileInfo(
zipFile,
&fileInfo,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0) != UNZ_OK) {
unzClose(zipFile);
extractReturn(-1, "Failed to parse a file's metadata.");
}
filename[MAX_FILENAME] = '\0'; // ensure string termination
// Handle Directories
if (filename[strlen(filename) - 1] == '/') {
// Directory creation cannot lose data
// so we do not care if a dir already
// exists
ExtractZipFileNDK_mkpath((dest_root + filename).c_str());
s2jIncre("directories");
// Note: The zip format does store permissions
// except these are all in platform specific
// formats. I talked with the guy responsible
// for window's file navigator's zip lib.
// His stories have scared me into the thinking
// that providing a default permission is more
// user friendly than missing obscure edge cases
// which could leave files in "magical" states.
// Handle Files
} else {
// Note: This opens zipFile's "current" file
// "current" acts as an interator
if (unzOpenCurrentFile(zipFile) != UNZ_OK) {
unzClose(zipFile);
extractReturn(-1, "Failed to extract file");
}
// Open destination file in file system
std::string dest_file_path = dest_root + filename;
// Check for overwriting
if (!overwrite_files && access(dest_file_path.c_str(), F_OK) != -1) {
// file exists and we are not allowed to overwrite
s2jIncre("files_skipped");
} else {
FILE *destFile = fopen(dest_file_path.c_str(), "wb");
if (destFile == NULL) {
unzCloseCurrentFile(zipFile);
unzClose(zipFile);
extractReturn(-1, "Failed to open destination file");
}
// Ferry data into destination
int readResult = UNZ_OK; // is 0
do {
// Read
readResult = unzReadCurrentFile(zipFile, fileBuffer, EZIPBUFSIZE);
if (readResult < 0) {
unzCloseCurrentFile(zipFile);
unzClose(zipFile);
fclose(destFile);
extractReturn(-1, "Failed to read compressed file");
}
// Write
if (readResult > 0) {
int writeResult = fwrite(fileBuffer, readResult, 1, destFile);
if (writeResult != 1) {
// Note: we asked for the full buffer
// to be written at once, so the 1
// return value is not "true" but
// the number blocks writen
unzCloseCurrentFile(zipFile);
unzClose(zipFile);
fclose(destFile);
extractReturn(-1, "Failed to write to destination file");
}
}
} while (readResult > 0);
fclose(destFile);
filesExtracted++;
}
s2jIncre("files");
}
unzCloseCurrentFile(zipFile);
// Increment "current" file interator if any more files
unzGoToNextFile(zipFile);
}
unzClose(zipFile);
// Success!
extractReturn(filesExtracted, "Extraction successful.");
}
} /* namespace webworks */
<|endoftext|> |
<commit_before>/*
msncontact.cpp - MSN Contact
Copyright (c) 2002 Duncan Mac-Vicar Prett <[email protected]>
(c) 2002 Ryan Cumming <[email protected]>
(c) 2002 Martijn Klingens <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>
#include <kpopupmenu.h>
#include "kopete.h"
#include "kopetestdaction.h"
#include "msncontact.h"
#include "msnprotocol.h"
// Constructor for no-groups
MSNContact::MSNContact( QString &protocolId, const QString &msnId, const QString &displayName,
const QString &group, KopeteMetaContact *parent )
: KopeteContact( protocolId, parent )
{
initContact( msnId, displayName, group );
}
void MSNContact::initContact( const QString &msnId, const QString &displayName,
const QString &group )
{
m_actionRemove = 0L;
m_actionRemoveFromGroup = 0L;
m_actionChat = 0L;
m_actionInfo = 0L;
m_actionHistory = 0L;
m_actionMove = 0L;
m_actionCopy = 0L;
m_actionBlock = 0L;
m_status = MSNProtocol::FLN;
m_deleted = false;
m_allowed = false;
m_blocked = false;
historyDialog = 0L;
m_msnId = msnId;
if( !group.isEmpty() )
m_groups = group;
hasLocalGroup = false;
connect ( this, SIGNAL( chatToUser( QString ) ),
MSNProtocol::protocol(),
SLOT( slotStartChatSession( QString ) ) );
setDisplayName( displayName );
}
void MSNContact::showContextMenu(QPoint point, QString /*group*/)
{
KPopupMenu *popup = new KPopupMenu();
popup->insertTitle( i18n( "%1 (%2)" ).arg( displayName() ).arg( msnId() ) );
// Chat with user
if( !m_actionChat )
{
m_actionChat = KopeteStdAction::sendMessage(
this, SLOT( slotChatThisUser() ), this, "m_actionChat" );
}
m_actionChat->plug( popup );
popup->insertSeparator();
// View History
if( !m_actionHistory )
{
m_actionHistory = KopeteStdAction::viewHistory( this,
SLOT( slotViewHistory() ), this, "m_actionHistory" );
}
m_actionHistory->plug( popup );
popup->insertSeparator();
// Move Contact
if( !m_actionMove )
{
m_actionMove = KopeteStdAction::moveContact( this,
SLOT( slotMoveThisUser() ), this, "m_actionMove" );
}
m_actionMove->plug( popup );
// Copy Contact
if( !m_actionCopy )
{
m_actionCopy = new KListAction( i18n( "Copy Contact" ), "editcopy", 0,
this, SLOT( slotCopyThisUser() ), this, "m_actionCopy" );
}
m_actionCopy->setItems( MSNProtocol::protocol()->groups() );
m_actionCopy->plug( popup );
// Remove From Group
if( !m_actionRemoveFromGroup )
{
m_actionRemoveFromGroup = new KAction( i18n( "Remove From Group" ),
"edittrash", 0, this, SLOT( slotRemoveFromGroup() ),
this, "m_actionRemoveFromGroup" );
}
m_actionRemoveFromGroup->plug( popup );
// Remove Contact
if( !m_actionRemove )
{
m_actionRemove = KopeteStdAction::deleteContact( this,
SLOT( slotRemoveThisUser() ), this, "m_actionRemove" );
}
m_actionRemove->plug( popup );
popup->insertSeparator();
// Block/unblock Contact
delete m_actionBlock;
QString label = isBlocked() ?
i18n( "Unblock User" ) : i18n( "Block User" );
m_actionBlock = new KAction( label,
0, this, SLOT( slotBlockUser() ),
this, "m_actionBlock" );
m_actionBlock->plug( popup );
popup->exec( point );
delete popup;
}
void MSNContact::execute()
{
// ( new KopeteChatWindow( this, this, QString::null, 0 ) )->show(); // Debug, Martijn
emit chatToUser( m_msnId );
}
QString MSNContact::id() const
{
return m_msnId;
}
QString MSNContact::data() const
{
return m_msnId;
}
void MSNContact::slotChatThisUser()
{
return m_msnId;
}
void MSNContact::slotRemoveThisUser()
{
MSNProtocol::protocol()->removeContact( this );
// delete this;
}
void MSNContact::slotRemoveFromGroup()
{
// FIXME: This slot needs to know to remove from WHICH group!
// for now, remove from the first group...
MSNProtocol::protocol()->removeFromGroup( this, m_groups.first() );
}
void MSNContact::moveToGroup( const QString &from, const QString &to )
{
MSNProtocol::protocol()->moveContact( this, from, to );
}
void MSNContact::slotMoveThisUser()
{
// FIXME: originating group should also be provided!
if( m_actionMove )
{
//kdDebug() << "***** MOVE: Groups: " << m_groups.join( ", " ) << endl;
if( m_movingToGroup == m_actionMove->currentText() )
{
kdDebug() << "MSNContact::slotMoveThisUser: Suppressing second "
<< "slot invocation. Yes, I know this is ugly!" << endl;
}
else
moveToGroup( m_groups.first(), m_actionMove->currentText() );
}
}
void MSNContact::slotCopyThisUser()
{
if( m_actionCopy )
MSNProtocol::protocol()->copyContact( this, m_actionCopy->currentText() );
}
void MSNContact::slotBlockUser()
{
if( isBlocked() )
MSNProtocol::protocol()->contactUnBlock( m_msnId );
else
MSNProtocol::protocol()->slotBlockContact( m_msnId );
}
void MSNContact::slotViewHistory()
{
kdDebug() << "MSN Plugin: slotViewHistory()" << endl;
if (historyDialog != 0L)
{
historyDialog->raise();
}
else
{
historyDialog = new KopeteHistoryDialog(QString("msn_logs/%1.log").arg(m_msnId), displayName(), true, 50, 0, "MSNHistoryDialog");
connect ( historyDialog, SIGNAL(closing()), this, SLOT(slotCloseHistoryDialog()) );
connect ( historyDialog, SIGNAL(destroyed()), this, SLOT(slotHistoryDialogClosing()) );
}
}
void MSNContact::slotCloseHistoryDialog()
{
kdDebug() << "MSN Plugin: slotCloseHistoryDialog()" << endl;
delete historyDialog;
}
void MSNContact::slotHistoryDialogClosing()
{
kdDebug() << "MSN Plugin: slotHistoryDialogClosing()" << endl;
if (historyDialog != 0L)
{
historyDialog = 0L;
}
}
MSNContact::ContactStatus MSNContact::status() const
{
switch ( m_status )
{
case MSNProtocol::NLN: // Online
{
return Online;
break;
}
case MSNProtocol::BSY: // Busy
case MSNProtocol::IDL: // Idle
case MSNProtocol::AWY: // Away from computer
case MSNProtocol::PHN: // On the phone
case MSNProtocol::BRB: // Be right back
case MSNProtocol::LUN: // Out to lunch
{
return Away;
break;
}
default:
{
return Offline;
break;
}
}
}
QString MSNContact::statusText() const
{
switch ( m_status )
{
case MSNProtocol::BLO: // blocked
{
return i18n("Blocked");
break;
}
case MSNProtocol::NLN: // Online
{
return i18n("Online");
break;
}
case MSNProtocol::BSY: // Busy
{
return i18n("Busy");
break;
}
case MSNProtocol::IDL: // Idle
{
return i18n("Idle");
break;
}
case MSNProtocol::AWY: // Away from computer
{
return i18n("Away From Computer");
break;
}
case MSNProtocol::PHN: // On the phone
{
return i18n("On The Phone");
break;
}
case MSNProtocol::BRB: // Be right back
{
return i18n("Be Right Back");
break;
}
case MSNProtocol::LUN: // Out to lunch
{
return i18n("Out To Lunch");
break;
}
default:
{
return i18n("Offline");
}
}
}
QString MSNContact::statusIcon() const
{
switch ( m_status )
{
case MSNProtocol::NLN: // Online
{
return "msn_online";
break;
}
case MSNProtocol::BSY: // Busy
case MSNProtocol::PHN: // On the phone
{
return "msn_na";
break;
}
case MSNProtocol::IDL: // Idle
case MSNProtocol::AWY: // Away from computer
case MSNProtocol::BRB: // Be right back
case MSNProtocol::LUN: // Out to lunch
{
return "msn_away";
break;
}
default:
return "msn_offline";
}
}
int MSNContact::importance() const
{
switch ( m_status )
{
case MSNProtocol::BLO: // blocked
{
return 1;
break;
}
case MSNProtocol::NLN: // Online
{
return 20;
break;
}
case MSNProtocol::BSY: // Busy
{
return 13;
break;
}
case MSNProtocol::IDL: // Idle
{
return 15;
break;
}
case MSNProtocol::AWY: // Away from computer
{
return 10;
break;
}
case MSNProtocol::PHN: // On the phone
{
return 12;
break;
}
case MSNProtocol::BRB: // Be right back
{
return 14;
break;
}
case MSNProtocol::LUN: // Out to lunch
{
return 11;
break;
}
default:
{
return 0;
}
}
}
QString MSNContact::msnId() const
{
return m_msnId;
}
void MSNContact::setMsnId( const QString &id )
{
m_msnId = id;
}
MSNProtocol::Status MSNContact::msnStatus() const
{
return m_status;
}
void MSNContact::setMsnStatus( MSNProtocol::Status status )
{
if( m_status == status )
return;
kdDebug() << "MSNContact::setMsnStatus: Setting status for " << m_msnId <<
" to " << status << endl;
m_status = status;
emit statusChanged( this, MSNContact::status() );
}
bool MSNContact::isBlocked() const
{
return m_blocked;
}
void MSNContact::setBlocked( bool blocked )
{
if( m_blocked != blocked )
{
m_blocked = blocked;
emit statusChanged( this, MSNContact::status() );
}
}
bool MSNContact::isDeleted() const
{
return m_deleted;
}
void MSNContact::setDeleted( bool deleted )
{
m_deleted = deleted;
}
bool MSNContact::isAllowed() const
{
return m_allowed;
}
void MSNContact::setAllowed( bool allowed )
{
m_allowed = allowed;
}
QStringList MSNContact::groups()
{
return m_groups;
}
void MSNContact::addToGroup( const QString &group )
{
m_groups.append( group );
if( m_movingToGroup == group )
{
kopeteapp->contactList()->moveContact( this, m_movingFromGroup, group );
m_movingToGroup = QString::null;
m_movingFromGroup = QString::null;
}
}
void MSNContact::removeFromGroup( const QString &group )
{
m_groups.remove( group );
}
#include "msncontact.moc"
// vim: noet ts=4 sts=4 sw=4:
<commit_msg>void MSNContact::slotChatThisUser() { return m_msnId; }<commit_after>/*
msncontact.cpp - MSN Contact
Copyright (c) 2002 Duncan Mac-Vicar Prett <[email protected]>
(c) 2002 Ryan Cumming <[email protected]>
(c) 2002 Martijn Klingens <[email protected]>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>
#include <kpopupmenu.h>
#include "kopete.h"
#include "kopetestdaction.h"
#include "msncontact.h"
#include "msnprotocol.h"
// Constructor for no-groups
MSNContact::MSNContact( QString &protocolId, const QString &msnId, const QString &displayName,
const QString &group, KopeteMetaContact *parent )
: KopeteContact( protocolId, parent )
{
initContact( msnId, displayName, group );
}
void MSNContact::initContact( const QString &msnId, const QString &displayName,
const QString &group )
{
m_actionRemove = 0L;
m_actionRemoveFromGroup = 0L;
m_actionChat = 0L;
m_actionInfo = 0L;
m_actionHistory = 0L;
m_actionMove = 0L;
m_actionCopy = 0L;
m_actionBlock = 0L;
m_status = MSNProtocol::FLN;
m_deleted = false;
m_allowed = false;
m_blocked = false;
historyDialog = 0L;
m_msnId = msnId;
if( !group.isEmpty() )
m_groups = group;
hasLocalGroup = false;
connect ( this, SIGNAL( chatToUser( QString ) ),
MSNProtocol::protocol(),
SLOT( slotStartChatSession( QString ) ) );
setDisplayName( displayName );
}
void MSNContact::showContextMenu(QPoint point, QString /*group*/)
{
KPopupMenu *popup = new KPopupMenu();
popup->insertTitle( i18n( "%1 (%2)" ).arg( displayName() ).arg( msnId() ) );
// Chat with user
if( !m_actionChat )
{
m_actionChat = KopeteStdAction::sendMessage(
this, SLOT( slotChatThisUser() ), this, "m_actionChat" );
}
m_actionChat->plug( popup );
popup->insertSeparator();
// View History
if( !m_actionHistory )
{
m_actionHistory = KopeteStdAction::viewHistory( this,
SLOT( slotViewHistory() ), this, "m_actionHistory" );
}
m_actionHistory->plug( popup );
popup->insertSeparator();
// Move Contact
if( !m_actionMove )
{
m_actionMove = KopeteStdAction::moveContact( this,
SLOT( slotMoveThisUser() ), this, "m_actionMove" );
}
m_actionMove->plug( popup );
// Copy Contact
if( !m_actionCopy )
{
m_actionCopy = new KListAction( i18n( "Copy Contact" ), "editcopy", 0,
this, SLOT( slotCopyThisUser() ), this, "m_actionCopy" );
}
m_actionCopy->setItems( MSNProtocol::protocol()->groups() );
m_actionCopy->plug( popup );
// Remove From Group
if( !m_actionRemoveFromGroup )
{
m_actionRemoveFromGroup = new KAction( i18n( "Remove From Group" ),
"edittrash", 0, this, SLOT( slotRemoveFromGroup() ),
this, "m_actionRemoveFromGroup" );
}
m_actionRemoveFromGroup->plug( popup );
// Remove Contact
if( !m_actionRemove )
{
m_actionRemove = KopeteStdAction::deleteContact( this,
SLOT( slotRemoveThisUser() ), this, "m_actionRemove" );
}
m_actionRemove->plug( popup );
popup->insertSeparator();
// Block/unblock Contact
delete m_actionBlock;
QString label = isBlocked() ?
i18n( "Unblock User" ) : i18n( "Block User" );
m_actionBlock = new KAction( label,
0, this, SLOT( slotBlockUser() ),
this, "m_actionBlock" );
m_actionBlock->plug( popup );
popup->exec( point );
delete popup;
}
void MSNContact::execute()
{
// ( new KopeteChatWindow( this, this, QString::null, 0 ) )->show(); // Debug, Martijn
emit chatToUser( m_msnId );
}
QString MSNContact::id() const
{
return m_msnId;
}
QString MSNContact::data() const
{
return m_msnId;
}
void MSNContact::slotChatThisUser()
{
#warning "FIXME: what am I supposed to do"
//return m_msnId;
}
void MSNContact::slotRemoveThisUser()
{
MSNProtocol::protocol()->removeContact( this );
// delete this;
}
void MSNContact::slotRemoveFromGroup()
{
// FIXME: This slot needs to know to remove from WHICH group!
// for now, remove from the first group...
MSNProtocol::protocol()->removeFromGroup( this, m_groups.first() );
}
void MSNContact::moveToGroup( const QString &from, const QString &to )
{
MSNProtocol::protocol()->moveContact( this, from, to );
}
void MSNContact::slotMoveThisUser()
{
// FIXME: originating group should also be provided!
if( m_actionMove )
{
//kdDebug() << "***** MOVE: Groups: " << m_groups.join( ", " ) << endl;
if( m_movingToGroup == m_actionMove->currentText() )
{
kdDebug() << "MSNContact::slotMoveThisUser: Suppressing second "
<< "slot invocation. Yes, I know this is ugly!" << endl;
}
else
moveToGroup( m_groups.first(), m_actionMove->currentText() );
}
}
void MSNContact::slotCopyThisUser()
{
if( m_actionCopy )
MSNProtocol::protocol()->copyContact( this, m_actionCopy->currentText() );
}
void MSNContact::slotBlockUser()
{
if( isBlocked() )
MSNProtocol::protocol()->contactUnBlock( m_msnId );
else
MSNProtocol::protocol()->slotBlockContact( m_msnId );
}
void MSNContact::slotViewHistory()
{
kdDebug() << "MSN Plugin: slotViewHistory()" << endl;
if (historyDialog != 0L)
{
historyDialog->raise();
}
else
{
historyDialog = new KopeteHistoryDialog(QString("msn_logs/%1.log").arg(m_msnId), displayName(), true, 50, 0, "MSNHistoryDialog");
connect ( historyDialog, SIGNAL(closing()), this, SLOT(slotCloseHistoryDialog()) );
connect ( historyDialog, SIGNAL(destroyed()), this, SLOT(slotHistoryDialogClosing()) );
}
}
void MSNContact::slotCloseHistoryDialog()
{
kdDebug() << "MSN Plugin: slotCloseHistoryDialog()" << endl;
delete historyDialog;
}
void MSNContact::slotHistoryDialogClosing()
{
kdDebug() << "MSN Plugin: slotHistoryDialogClosing()" << endl;
if (historyDialog != 0L)
{
historyDialog = 0L;
}
}
MSNContact::ContactStatus MSNContact::status() const
{
switch ( m_status )
{
case MSNProtocol::NLN: // Online
{
return Online;
break;
}
case MSNProtocol::BSY: // Busy
case MSNProtocol::IDL: // Idle
case MSNProtocol::AWY: // Away from computer
case MSNProtocol::PHN: // On the phone
case MSNProtocol::BRB: // Be right back
case MSNProtocol::LUN: // Out to lunch
{
return Away;
break;
}
default:
{
return Offline;
break;
}
}
}
QString MSNContact::statusText() const
{
switch ( m_status )
{
case MSNProtocol::BLO: // blocked
{
return i18n("Blocked");
break;
}
case MSNProtocol::NLN: // Online
{
return i18n("Online");
break;
}
case MSNProtocol::BSY: // Busy
{
return i18n("Busy");
break;
}
case MSNProtocol::IDL: // Idle
{
return i18n("Idle");
break;
}
case MSNProtocol::AWY: // Away from computer
{
return i18n("Away From Computer");
break;
}
case MSNProtocol::PHN: // On the phone
{
return i18n("On The Phone");
break;
}
case MSNProtocol::BRB: // Be right back
{
return i18n("Be Right Back");
break;
}
case MSNProtocol::LUN: // Out to lunch
{
return i18n("Out To Lunch");
break;
}
default:
{
return i18n("Offline");
}
}
}
QString MSNContact::statusIcon() const
{
switch ( m_status )
{
case MSNProtocol::NLN: // Online
{
return "msn_online";
break;
}
case MSNProtocol::BSY: // Busy
case MSNProtocol::PHN: // On the phone
{
return "msn_na";
break;
}
case MSNProtocol::IDL: // Idle
case MSNProtocol::AWY: // Away from computer
case MSNProtocol::BRB: // Be right back
case MSNProtocol::LUN: // Out to lunch
{
return "msn_away";
break;
}
default:
return "msn_offline";
}
}
int MSNContact::importance() const
{
switch ( m_status )
{
case MSNProtocol::BLO: // blocked
{
return 1;
break;
}
case MSNProtocol::NLN: // Online
{
return 20;
break;
}
case MSNProtocol::BSY: // Busy
{
return 13;
break;
}
case MSNProtocol::IDL: // Idle
{
return 15;
break;
}
case MSNProtocol::AWY: // Away from computer
{
return 10;
break;
}
case MSNProtocol::PHN: // On the phone
{
return 12;
break;
}
case MSNProtocol::BRB: // Be right back
{
return 14;
break;
}
case MSNProtocol::LUN: // Out to lunch
{
return 11;
break;
}
default:
{
return 0;
}
}
}
QString MSNContact::msnId() const
{
return m_msnId;
}
void MSNContact::setMsnId( const QString &id )
{
m_msnId = id;
}
MSNProtocol::Status MSNContact::msnStatus() const
{
return m_status;
}
void MSNContact::setMsnStatus( MSNProtocol::Status status )
{
if( m_status == status )
return;
kdDebug() << "MSNContact::setMsnStatus: Setting status for " << m_msnId <<
" to " << status << endl;
m_status = status;
emit statusChanged( this, MSNContact::status() );
}
bool MSNContact::isBlocked() const
{
return m_blocked;
}
void MSNContact::setBlocked( bool blocked )
{
if( m_blocked != blocked )
{
m_blocked = blocked;
emit statusChanged( this, MSNContact::status() );
}
}
bool MSNContact::isDeleted() const
{
return m_deleted;
}
void MSNContact::setDeleted( bool deleted )
{
m_deleted = deleted;
}
bool MSNContact::isAllowed() const
{
return m_allowed;
}
void MSNContact::setAllowed( bool allowed )
{
m_allowed = allowed;
}
QStringList MSNContact::groups()
{
return m_groups;
}
void MSNContact::addToGroup( const QString &group )
{
m_groups.append( group );
if( m_movingToGroup == group )
{
kopeteapp->contactList()->moveContact( this, m_movingFromGroup, group );
m_movingToGroup = QString::null;
m_movingFromGroup = QString::null;
}
}
void MSNContact::removeFromGroup( const QString &group )
{
m_groups.remove( group );
}
#include "msncontact.moc"
// vim: noet ts=4 sts=4 sw=4:
<|endoftext|> |
<commit_before>/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2012-2013 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* 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.
*/
/*
* Sets given environment variables, dumps the entire environment to
* a given file (for diagnostics purposes), then execs the given command.
*
* This is a separate executable because it does quite
* some non-async-signal-safe stuff that we can't do after
* fork()ing from the Spawner and before exec()ing.
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string>
#include <Utils/Base64.h>
using namespace std;
using namespace Passenger;
extern "C" {
extern char **environ;
}
static void
changeWorkingDir(const char *dir) {
int ret = chdir(dir);
if (ret == 0) {
setenv("PWD", dir, 1);
} else {
int e = errno;
printf("!> Error\n");
printf("!> \n");
printf("Unable to change working directory to '%s': %s (errno=%d)\n",
dir, strerror(e), e);
fflush(stdout);
exit(1);
}
}
static void
setGivenEnvVars(const char *envvarsData) {
string envvars = Base64::decode(envvarsData);
const char *key = envvars.data();
const char *end = envvars.data() + envvars.size();
while (key < end) {
const char *keyEnd = (const char *) memchr(key, '\0', end - key);
if (keyEnd != NULL) {
const char *value = keyEnd + 1;
if (value < end) {
const char *valueEnd = (const char *) memchr(value, '\0', end - value);
if (valueEnd != NULL) {
setenv(key, value, 1);
key = valueEnd + 1;
} else {
break;
}
} else {
break;
}
} else {
break;
}
}
}
static void
dumpInformation() {
const char *c_dir;
if ((c_dir = getenv("PASSENGER_DEBUG_DIR")) == NULL) {
return;
}
FILE *f;
string dir = c_dir;
f = fopen((dir + "/envvars").c_str(), "w");
if (f != NULL) {
int i = 0;
while (environ[i] != NULL) {
fputs(environ[i], f);
putc('\n', f);
i++;
}
fclose(f);
}
f = fopen((dir + "/user_info").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("id", "id", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
f = fopen((dir + "/ulimit").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("ulimit", "ulimit", "-a", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
f = fopen((dir + "/ulimit").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("ulimit", "ulimit", "-a", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
#ifdef __linux__
// TODO: call helper-scripts/system-memory-stats.py
f = fopen((dir + "/sysmemory").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("free", "free", "-m", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
#endif
}
// Usage: SpawnPreparer <working directory> <envvars> <executable> <exec args...>
int
main(int argc, char *argv[]) {
if (argc < 5) {
fprintf(stderr, "Too few arguments.\n");
exit(1);
}
const char *workingDir = argv[1];
const char *envvars = argv[2];
const char *executable = argv[3];
char **execArgs = &argv[4];
changeWorkingDir(workingDir);
setGivenEnvVars(envvars);
dumpInformation();
// Print a newline just in case whatever executed us printed data
// without a newline. Otherwise the next process's "!> I have control"
// command will not be properly recognized.
// https://code.google.com/p/phusion-passenger/issues/detail?id=842#c16
printf("\n");
fflush(stdout);
execvp(executable, (char * const *) execArgs);
int e = errno;
fprintf(stderr, "*** ERROR ***: Cannot execute %s: %s (%d)\n",
executable, strerror(e), e);
return 1;
}
<commit_msg>SpawnPreparer.cpp should include stdlib.h for setenv(). Fixes issue #998<commit_after>/*
* Phusion Passenger - https://www.phusionpassenger.com/
* Copyright (c) 2012-2013 Phusion
*
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
*
* 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.
*/
/*
* Sets given environment variables, dumps the entire environment to
* a given file (for diagnostics purposes), then execs the given command.
*
* This is a separate executable because it does quite
* some non-async-signal-safe stuff that we can't do after
* fork()ing from the Spawner and before exec()ing.
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string>
#include <Utils/Base64.h>
using namespace std;
using namespace Passenger;
extern "C" {
extern char **environ;
}
static void
changeWorkingDir(const char *dir) {
int ret = chdir(dir);
if (ret == 0) {
setenv("PWD", dir, 1);
} else {
int e = errno;
printf("!> Error\n");
printf("!> \n");
printf("Unable to change working directory to '%s': %s (errno=%d)\n",
dir, strerror(e), e);
fflush(stdout);
exit(1);
}
}
static void
setGivenEnvVars(const char *envvarsData) {
string envvars = Base64::decode(envvarsData);
const char *key = envvars.data();
const char *end = envvars.data() + envvars.size();
while (key < end) {
const char *keyEnd = (const char *) memchr(key, '\0', end - key);
if (keyEnd != NULL) {
const char *value = keyEnd + 1;
if (value < end) {
const char *valueEnd = (const char *) memchr(value, '\0', end - value);
if (valueEnd != NULL) {
setenv(key, value, 1);
key = valueEnd + 1;
} else {
break;
}
} else {
break;
}
} else {
break;
}
}
}
static void
dumpInformation() {
const char *c_dir;
if ((c_dir = getenv("PASSENGER_DEBUG_DIR")) == NULL) {
return;
}
FILE *f;
string dir = c_dir;
f = fopen((dir + "/envvars").c_str(), "w");
if (f != NULL) {
int i = 0;
while (environ[i] != NULL) {
fputs(environ[i], f);
putc('\n', f);
i++;
}
fclose(f);
}
f = fopen((dir + "/user_info").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("id", "id", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
f = fopen((dir + "/ulimit").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("ulimit", "ulimit", "-a", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
f = fopen((dir + "/ulimit").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("ulimit", "ulimit", "-a", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
#ifdef __linux__
// TODO: call helper-scripts/system-memory-stats.py
f = fopen((dir + "/sysmemory").c_str(), "w");
if (f != NULL) {
pid_t pid = fork();
if (pid == 0) {
dup2(fileno(f), 1);
execlp("free", "free", "-m", (char *) 0);
_exit(1);
} else if (pid == -1) {
int e = errno;
fprintf(stderr, "Error: cannot fork a new process: %s (errno=%d)\n",
strerror(e), e);
} else {
waitpid(pid, NULL, 0);
}
fclose(f);
}
#endif
}
// Usage: SpawnPreparer <working directory> <envvars> <executable> <exec args...>
int
main(int argc, char *argv[]) {
if (argc < 5) {
fprintf(stderr, "Too few arguments.\n");
exit(1);
}
const char *workingDir = argv[1];
const char *envvars = argv[2];
const char *executable = argv[3];
char **execArgs = &argv[4];
changeWorkingDir(workingDir);
setGivenEnvVars(envvars);
dumpInformation();
// Print a newline just in case whatever executed us printed data
// without a newline. Otherwise the next process's "!> I have control"
// command will not be properly recognized.
// https://code.google.com/p/phusion-passenger/issues/detail?id=842#c16
printf("\n");
fflush(stdout);
execvp(executable, (char * const *) execArgs);
int e = errno;
fprintf(stderr, "*** ERROR ***: Cannot execute %s: %s (%d)\n",
executable, strerror(e), e);
return 1;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNarrowBandThresholdSegmentationLevelSetImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkNarrowBandThresholdSegmentationLevelSetImageFilter.h"
//#include "itkImageFileWriter.h"
//#include "itkRawImageIO.h"
#include "itkCastImageFilter.h"
#include "itkCommand.h"
#include "itkEventObject.h"
namespace NBTS {
typedef itk::Image<float, 3> ImageType;
typedef itk::Image<char, 3> SeedImageType;
const int V_WIDTH = 64;
const int V_HEIGHT = 64;
const int V_DEPTH = 64;
float sphere(float x, float y, float z)
{
float dis;
dis = (x - (float)V_WIDTH/2.0)*(x - (float)V_WIDTH/2.0)
/((0.2f*V_WIDTH)*(0.2f*V_WIDTH)) +
(y - (float)V_HEIGHT/2.0)*(y - (float)V_HEIGHT/2.0)
/((0.2f*V_HEIGHT)*(0.2f*V_HEIGHT)) +
(z - (float)V_DEPTH/2.0)*(z - (float)V_DEPTH/2.0)
/((0.2f*V_DEPTH)*(0.2f*V_DEPTH));
return(1.0f-dis);
}
void evaluate_function(itk::Image<char, 3> *im,
float (*f)(float, float, float) )
{
itk::Image<char, 3>::IndexType idx;
for(int z = 0; z < V_DEPTH; ++z)
{
idx[2] = z;
for (int y = 0; y < V_HEIGHT; ++y)
{
idx[1] = y;
for (int x = 0; x < V_WIDTH; ++x)
{
idx[0] = x;
if ( f((float)x,(float)y,(float)z) >= 0.0 )
{ im->SetPixel(idx, 1 ); }
else
{ im->SetPixel(idx, 0 ); }
}
}
}
}
} // end namespace
namespace itk {
class NBRMSCommand : public Command
{
public:
/** Smart pointer declaration methods */
typedef NBRMSCommand Self;
typedef Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
itkTypeMacro( NBRMSCommand, Command );
itkNewMacro(Self);
/** Standard Command virtual methods */
void Execute(Object *caller, const EventObject &)
{
std::cout <<
(dynamic_cast<NarrowBandLevelSetImageFilter< ::NBTS::SeedImageType,
::NBTS::ImageType> *>(caller))->GetSegmentationFunction()->GetPropagationWeight()
<< std::endl;
}
void Execute(const Object *, const EventObject &)
{
std::cout << "ack" << std::endl;
}
protected:
NBRMSCommand() {}
virtual ~NBRMSCommand() {}
};
}
int itkNarrowBandThresholdSegmentationLevelSetImageFilterTest(int, char * [] )
{
NBTS::ImageType::RegionType reg;
NBTS::ImageType::RegionType::SizeType sz;
NBTS::ImageType::RegionType::IndexType idx;
idx[0] = idx[1] = idx[2] = 0;
sz[0] = sz[1] = sz[2] = 64;
reg.SetSize(sz);
reg.SetIndex(idx);
NBTS::ImageType::Pointer inputImage = NBTS::ImageType::New();
NBTS::SeedImageType::Pointer seedImage = NBTS::SeedImageType::New();
inputImage->SetRegions(reg);
seedImage->SetRegions(reg);
inputImage->Allocate();
seedImage->Allocate();
// Starting surface is a sphere in the center of the image.
NBTS::evaluate_function(seedImage, NBTS::sphere);
// Target surface is a diamond
float val;
unsigned int i;
// NBTS::ImageType::IndexType idx;
for (idx[2] = 0; idx[2] < 64; idx[2]++)
for (idx[1] = 0; idx[1] < 64; idx[1]++)
for (idx[0] = 0; idx[0] < 64; idx[0]++)
{
val = 0;
for (i = 0; i < 3; ++i)
{
if (idx[i] < 32) val+=idx[i];
else val += 64 - idx[i];
}
inputImage->SetPixel(idx, val);
}
itk::NarrowBandThresholdSegmentationLevelSetImageFilter< ::NBTS::SeedImageType, ::NBTS::ImageType>::Pointer
filter = itk::NarrowBandThresholdSegmentationLevelSetImageFilter< ::NBTS::SeedImageType, ::NBTS::ImageType>::New();
filter->SetInput(seedImage);
filter->SetFeatureImage(inputImage);
filter->SetUpperThreshold(63);
filter->SetLowerThreshold(50);
filter->SetMaximumRMSError(0.04); //Does not have any effect
filter->SetMaximumIterations(10);
filter->ReverseExpansionDirectionOn(); // Change the default behavior of the speed
// function so that negative values result in
// surface growth.
itk::NBRMSCommand::Pointer c = itk::NBRMSCommand::New();
filter->AddObserver(itk::IterationEvent(), c);
filter->SetIsoSurfaceValue(0.5); //<--- IMPORTANT! Default is zero.
try {
filter->Update();
std::cout << "Done first trial" << std::endl;
// Repeat to make sure that the filter is reinitialized properly
filter->SetMaximumIterations(8);
filter->Update();
std::cout << "Done second trial" << std::endl;
//For Debugging
//typedef itk::ImageFileWriter< ::NBTS::ImageType> WriterType;
//WriterType::Pointer writer = WriterType::New();
//writer->SetInput( filter->GetOutput() );
//writer->SetFileName( "outputThreshold.mhd" );
//writer->Write();
//WriterType::Pointer writer3 = WriterType::New();
//writer3->SetInput(inputImage);
//writer3->SetFileName("inputThreshold.mhd");
//writer3->Write();
// typedef itk::ImageFileWriter< ::NBTS::SeedImageType> Writer2Type;
//Writer2Type::Pointer writer2 = Writer2Type::New();
//writer2->SetInput(seedImage);
//writer2->SetFileName("seedThreshold.mhd");
//writer2->Write();
// Write the output for debugging purposes
// itk::ImageFileWriter<NBTS::ImageType>::Pointer writer
// = itk::ImageFileWriter<NBTS::ImageType>::New();
// itk::RawImageIO<float, 3>::Pointer io = itk::RawImageIO<float, 3>::New();
// io->SetFileTypeToBinary();
// io->SetFileDimensionality(3);
// io->SetByteOrderToLittleEndian();
// writer->SetImageIO(io);
// itk::CastImageFilter<NBTS::SeedImageType, NBTS::ImageType>::Pointer
// caster = itk::CastImageFilter<NBTS::SeedImageType, NBTS::ImageType>::New();
// caster->SetInput(seedImage);
// caster->Update();
// writer->SetInput(caster->GetOutput());
// writer->SetInput(filter->GetSpeedImage());
// writer->SetInput(filter->GetFeatureImage());
// writer->SetInput(inputImage);
// writer->SetInput(filter->GetOutput());
// writer->SetFileName("output.raw");
// writer->Write();
}
catch (itk::ExceptionObject &e)
{
std::cerr << e << std::endl;
}
return 0;
}
<commit_msg>FIX: Test should return 1 if it caught an exception.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkNarrowBandThresholdSegmentationLevelSetImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "itkNarrowBandThresholdSegmentationLevelSetImageFilter.h"
//#include "itkImageFileWriter.h"
//#include "itkRawImageIO.h"
#include "itkCastImageFilter.h"
#include "itkCommand.h"
#include "itkEventObject.h"
namespace NBTS {
typedef itk::Image<float, 3> ImageType;
typedef itk::Image<char, 3> SeedImageType;
const int V_WIDTH = 64;
const int V_HEIGHT = 64;
const int V_DEPTH = 64;
float sphere(float x, float y, float z)
{
float dis;
dis = (x - (float)V_WIDTH/2.0)*(x - (float)V_WIDTH/2.0)
/((0.2f*V_WIDTH)*(0.2f*V_WIDTH)) +
(y - (float)V_HEIGHT/2.0)*(y - (float)V_HEIGHT/2.0)
/((0.2f*V_HEIGHT)*(0.2f*V_HEIGHT)) +
(z - (float)V_DEPTH/2.0)*(z - (float)V_DEPTH/2.0)
/((0.2f*V_DEPTH)*(0.2f*V_DEPTH));
return(1.0f-dis);
}
void evaluate_function(itk::Image<char, 3> *im,
float (*f)(float, float, float) )
{
itk::Image<char, 3>::IndexType idx;
for(int z = 0; z < V_DEPTH; ++z)
{
idx[2] = z;
for (int y = 0; y < V_HEIGHT; ++y)
{
idx[1] = y;
for (int x = 0; x < V_WIDTH; ++x)
{
idx[0] = x;
if ( f((float)x,(float)y,(float)z) >= 0.0 )
{ im->SetPixel(idx, 1 ); }
else
{ im->SetPixel(idx, 0 ); }
}
}
}
}
} // end namespace
namespace itk {
class NBRMSCommand : public Command
{
public:
/** Smart pointer declaration methods */
typedef NBRMSCommand Self;
typedef Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
itkTypeMacro( NBRMSCommand, Command );
itkNewMacro(Self);
/** Standard Command virtual methods */
void Execute(Object *caller, const EventObject &)
{
std::cout <<
(dynamic_cast<NarrowBandLevelSetImageFilter< ::NBTS::SeedImageType,
::NBTS::ImageType> *>(caller))->GetSegmentationFunction()->GetPropagationWeight()
<< std::endl;
}
void Execute(const Object *, const EventObject &)
{
std::cout << "ack" << std::endl;
}
protected:
NBRMSCommand() {}
virtual ~NBRMSCommand() {}
};
}
int itkNarrowBandThresholdSegmentationLevelSetImageFilterTest(int, char * [] )
{
NBTS::ImageType::RegionType reg;
NBTS::ImageType::RegionType::SizeType sz;
NBTS::ImageType::RegionType::IndexType idx;
idx[0] = idx[1] = idx[2] = 0;
sz[0] = sz[1] = sz[2] = 64;
reg.SetSize(sz);
reg.SetIndex(idx);
NBTS::ImageType::Pointer inputImage = NBTS::ImageType::New();
NBTS::SeedImageType::Pointer seedImage = NBTS::SeedImageType::New();
inputImage->SetRegions(reg);
seedImage->SetRegions(reg);
inputImage->Allocate();
seedImage->Allocate();
// Starting surface is a sphere in the center of the image.
NBTS::evaluate_function(seedImage, NBTS::sphere);
// Target surface is a diamond
float val;
unsigned int i;
// NBTS::ImageType::IndexType idx;
for (idx[2] = 0; idx[2] < 64; idx[2]++)
for (idx[1] = 0; idx[1] < 64; idx[1]++)
for (idx[0] = 0; idx[0] < 64; idx[0]++)
{
val = 0;
for (i = 0; i < 3; ++i)
{
if (idx[i] < 32) val+=idx[i];
else val += 64 - idx[i];
}
inputImage->SetPixel(idx, val);
}
itk::NarrowBandThresholdSegmentationLevelSetImageFilter< ::NBTS::SeedImageType, ::NBTS::ImageType>::Pointer
filter = itk::NarrowBandThresholdSegmentationLevelSetImageFilter< ::NBTS::SeedImageType, ::NBTS::ImageType>::New();
filter->SetInput(seedImage);
filter->SetFeatureImage(inputImage);
filter->SetUpperThreshold(63);
filter->SetLowerThreshold(50);
filter->SetMaximumRMSError(0.04); //Does not have any effect
filter->SetMaximumIterations(10);
filter->ReverseExpansionDirectionOn(); // Change the default behavior of the speed
// function so that negative values result in
// surface growth.
itk::NBRMSCommand::Pointer c = itk::NBRMSCommand::New();
filter->AddObserver(itk::IterationEvent(), c);
filter->SetIsoSurfaceValue(0.5); //<--- IMPORTANT! Default is zero.
try {
filter->Update();
std::cout << "Done first trial" << std::endl;
// Repeat to make sure that the filter is reinitialized properly
filter->SetMaximumIterations(8);
filter->Update();
std::cout << "Done second trial" << std::endl;
//For Debugging
//typedef itk::ImageFileWriter< ::NBTS::ImageType> WriterType;
//WriterType::Pointer writer = WriterType::New();
//writer->SetInput( filter->GetOutput() );
//writer->SetFileName( "outputThreshold.mhd" );
//writer->Write();
//WriterType::Pointer writer3 = WriterType::New();
//writer3->SetInput(inputImage);
//writer3->SetFileName("inputThreshold.mhd");
//writer3->Write();
// typedef itk::ImageFileWriter< ::NBTS::SeedImageType> Writer2Type;
//Writer2Type::Pointer writer2 = Writer2Type::New();
//writer2->SetInput(seedImage);
//writer2->SetFileName("seedThreshold.mhd");
//writer2->Write();
// Write the output for debugging purposes
// itk::ImageFileWriter<NBTS::ImageType>::Pointer writer
// = itk::ImageFileWriter<NBTS::ImageType>::New();
// itk::RawImageIO<float, 3>::Pointer io = itk::RawImageIO<float, 3>::New();
// io->SetFileTypeToBinary();
// io->SetFileDimensionality(3);
// io->SetByteOrderToLittleEndian();
// writer->SetImageIO(io);
// itk::CastImageFilter<NBTS::SeedImageType, NBTS::ImageType>::Pointer
// caster = itk::CastImageFilter<NBTS::SeedImageType, NBTS::ImageType>::New();
// caster->SetInput(seedImage);
// caster->Update();
// writer->SetInput(caster->GetOutput());
// writer->SetInput(filter->GetSpeedImage());
// writer->SetInput(filter->GetFeatureImage());
// writer->SetInput(inputImage);
// writer->SetInput(filter->GetOutput());
// writer->SetFileName("output.raw");
// writer->Write();
}
catch (itk::ExceptionObject &e)
{
std::cerr << e << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>[jnc_ct] fix: rename m_matchSwitchCaseId -> m_matchAcceptId<commit_after><|endoftext|> |
<commit_before><commit_msg>[MuLambdaES Mutation]: Fixed segfaults/memory leaks<commit_after><|endoftext|> |
<commit_before><commit_msg>Remove useless checks for webkit-min/max<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include "SofaConfiguration.h"
#include <qsizepolicy.h>
#ifdef SOFA_QT4
#include <QGroupBox>
#include <QToolBox>
#include <QSpacerItem>
#include <QPushButton>
#include <Q3Process>
#else
#include <qgroupbox.h>
#include <qtoolbox.h>
#include <qpushbutton.h>
#include <qprocess.h>
typedef QProcess Q3Process;
#endif
#include <map>
#include <algorithm>
#include <fstream>
namespace sofa
{
namespace gui
{
namespace qt
{
ConfigWidget::ConfigWidget(QWidget *parent, DEFINES &d):QWidget(parent), option(d)
{
setName(QString(option.name.c_str()));
layout=new QHBoxLayout(this);
check=new QCheckBox(QString(option.name.c_str()), this);
check->setChecked(option.value);
check->setMaximumSize(300,20);
layout->addWidget(check);
connect(check, SIGNAL(toggled(bool)), this, SLOT(updateValue(bool)));
}
void ConfigWidget::updateValue(bool b)
{
option.value=b;
emit(modified());
}
TextConfigWidget::TextConfigWidget(QWidget *parent, DEFINES &d):ConfigWidget(parent,d)
{
description=new QLineEdit(this);
description->setText(option.description.c_str());
description->setAlignment(Qt::AlignBottom | Qt::AlignLeft);
connect(description, SIGNAL(textChanged(const QString&)), this, SLOT(updateValue(const QString&)));
layout->addWidget(description);
}
void TextConfigWidget::updateValue(const QString &s)
{
option.description=s.ascii();
emit(modified());
}
OptionConfigWidget::OptionConfigWidget(QWidget *parent, DEFINES &d):ConfigWidget(parent,d)
{
description=new QLabel(this);
description->setText(option.description.c_str());
description->setAlignment(Qt::AlignBottom | Qt::AlignLeft);
layout->addWidget(description);
}
SofaConfiguration::SofaConfiguration(std::string p, std::vector< DEFINES >& config):QMainWindow(),path(p),data(config)
{
resize(800, 600);
QWidget *appli = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(appli);
QToolBox *global = new QToolBox(appli);
global->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
std::string currentCategory;
QWidget *page=NULL;
QVBoxLayout *pageLayout=NULL;
for (unsigned int i=0; i<config.size(); ++i)
{
if (currentCategory != config[i].category)
{
if (page)
{
pageLayout->addItem( new QSpacerItem(10,10,QSizePolicy::Expanding, QSizePolicy::Expanding));
}
currentCategory = config[i].category;
page = new QWidget(global);
global->addItem(page,QString(currentCategory.c_str()));
pageLayout=new QVBoxLayout(page);
}
ConfigWidget *o;
if (config[i].typeOption) o=new OptionConfigWidget(page, config[i]);
else o=new TextConfigWidget(page, config[i]);
pageLayout->addWidget(o);
options.push_back(o);
connect(o, SIGNAL(modified()), this, SLOT(updateOptions()));
}
if (page)
{
pageLayout->addItem( new QSpacerItem(10,10,QSizePolicy::Expanding, QSizePolicy::Expanding));
}
updateConditions();
QPushButton *button = new QPushButton(QString("Save and Update Configuration"),appli);
connect( button, SIGNAL(clicked()), this, SLOT(saveConfiguration()));
layout->addWidget(global);
#ifdef WIN32
projectVC = new QLineEdit(QString("ProjectVC8.bat"),appli);
layout->addWidget(projectVC);
#endif
layout->addWidget(button);
this->setCentralWidget(appli);
}
bool SofaConfiguration::getValue(CONDITION &c)
{
unsigned int i=0;
for (; i<options.size(); ++i)
{
if (options[i]->name() == c.option)
{
bool presence = options[i]->getValue();
if (c.presence && presence) return true;
if (!c.presence && !presence) return true;
return false;
}
}
return false;
}
void SofaConfiguration::updateOptions()
{
QWidget *option = (QWidget*)sender();
if (dynamic_cast<OptionConfigWidget*>(option))
optionsModified.insert(option);
updateConditions();
}
void SofaConfiguration::processCondition(QWidget *w, CONDITION &c)
{
switch(c.type)
{
case OPTION:
w->setEnabled(getValue(c));
break;
case ARCHI:
if (c.option == "win32")
{
if (c.presence)
{
#ifndef WIN32
w->hide();
#endif
}
else
{
#ifdef WIN32
w->hide();
#endif
}
}
else if (c.option == "unix")
{
if (c.presence)
{
#ifdef WIN32
w->hide();
#endif
}
else
{
#ifndef WIN32
w->hide();
#endif
}
}
break;
}
}
void SofaConfiguration::updateConditions()
{
for (unsigned int i=0; i<options.size(); ++i)
{
std::vector< CONDITION > &conditions=options[i]->option.conditions;
for (unsigned int c=0; c<conditions.size(); ++c)
{
processCondition(options[i],conditions[c]);
}
}
}
void SofaConfiguration::saveConfiguration()
{
std::ofstream out((path + std::string("/sofa-local.cfg")).c_str());
std::string currentCategory;
std::vector< CONDITION > currentConditions;
for (unsigned int i=0; i<options.size(); ++i)
{
DEFINES &option=options[i]->option;
bool differentConditions=false;
if (currentConditions.size() != option.conditions.size()) differentConditions=true;
else
{
for (unsigned int c=0; c<currentConditions.size() && !differentConditions; ++c)
{
if (currentConditions[c] != option.conditions[c]) differentConditions=true;
}
}
if (differentConditions)
{
for (unsigned int c=0; c<currentConditions.size(); ++c) out << "}\n";
currentConditions = option.conditions;
}
if (currentCategory != option.category)
{
if (!currentCategory.empty()) out << "\n\n";
currentCategory = option.category;
out << "########################################################################\n";
out << "# " << currentCategory << "\n";
out << "########################################################################\n";
}
if (differentConditions)
{
for (unsigned int c=0; c<currentConditions.size(); ++c)
{
if (!currentConditions[c].presence) out << "!";
switch( currentConditions[c].type)
{
case OPTION:
out << "contains(DEFINES," << currentConditions[c].option << "){\n";
break;
case ARCHI:
out << currentConditions[c].option << "{\n";
break;
}
}
}
if (option.typeOption)
{
std::string description=option.description;
for (unsigned int position=0; position<description.size(); ++position)
{
if (description[position] == '\n') description.insert(position+1, "# ");
}
out << "\n# Uncomment " << description << "\n";
if (!option.value) out << "# ";
out << "DEFINES += " << option.name << "\n";
}
else
{
if (!option.value) out << "# ";
out << option.name << " " << option.description << "\n";
}
}
for (unsigned int c=0; c<currentConditions.size(); ++c) out << "}\n";
out.close();
std::set< QWidget *>::iterator it;
if (!optionsModified.empty())
{
std::vector<QString> listDir;
listDir.push_back(QString("/applications"));
listDir.push_back(QString("/modules"));
listDir.push_back(QString("/framework"));
listDir.push_back(QString("/extlibs"));
std::set< QWidget *>::iterator it;
for (it=optionsModified.begin(); it!=optionsModified.end(); it++)
std::cout << "Touch file containing option \"" <<(*it)->name() << "\" ";
std::cout << "in [ ";
for (unsigned int i=0; i<listDir.size(); ++i)
std::cout << listDir[i].ascii() << " ";
std::cout << "]" << std::endl;
for (unsigned int i=0; i<listDir.size(); ++i)
{
std::cout << " Searching in " << listDir[i].ascii() << "\n";
processDirectory(listDir[i]);
}
QStringList argv;
#ifndef WIN32
#if SOFA_QT4
argv << QString("qmake-qt4");
#else
argv << QString("qmake");
#endif
#else
argv << QString(path.c_str()) + QString("/") + QString(projectVC->text());
#endif
Q3Process *p = new Q3Process(argv,this);
p->setCommunication(0);
p->setWorkingDirectory(QDir(QString(path.c_str())));
p->start();
optionsModified.clear();
}
}
void SofaConfiguration::processDirectory(const QString &dir)
{
QDir d(QString(path.c_str())+dir);
d.setFilter( QDir::Dirs | QDir::Hidden | QDir::NoSymLinks );
std::vector< QString > subDir;
const QFileInfoList &listDirectories =
#ifdef SOFA_QT4
d.entryInfoList();
for (int j = 0; j < listDirectories.size(); ++j)
{
QFileInfo fileInfo=listDirectories.at(j);
#else
*(d.entryInfoList());
QFileInfoListIterator it( listDirectories );
while ( (fi = itFile.current()) != 0 )
{
QFileInfo fileInfo=*(itFile.current());
#endif
subDir.push_back(fileInfo.fileName());
#ifndef SOFA_QT4
++itFile;
#endif
}
QStringList filters; filters << "*.cpp" << "*.h" << "*.inl";
d.setNameFilters(filters);
d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks );
std::vector< QString > filesInside;
const QFileInfoList &listFiles =
#ifdef SOFA_QT4
d.entryInfoList();
for (int j = 0; j < listFiles.size(); ++j)
{
QFileInfo fileInfo=listFiles.at(j);
#else
*(d.entryInfoList(filter));
QFileInfoListIterator it( listFiles );
while ( (fi = itFile.current()) != 0 )
{
QFileInfo fileInfo=*(itFile.current());
#endif
filesInside.push_back(fileInfo.fileName());
processFile(fileInfo);
#ifndef SOFA_QT4
++itFile;
#endif
}
for (unsigned int i=0; i<subDir.size(); ++i)
{
if (subDir[i].left(1) == QString(".")) continue;
if (subDir[i] == QString("OBJ")) continue;
QString nextDir=dir+QString("/")+subDir[i];
processDirectory(nextDir);
}
}
void SofaConfiguration::processFile(const QFileInfo &info)
{
std::fstream file;
file.open(info.absFilePath(), std::ios::in | std::ios::out);
std::string line;
while (std::getline(file, line))
{
std::set< QWidget *>::iterator it;
for (it=optionsModified.begin(); it!=optionsModified.end(); it++)
{
std::string option((*it)->name());
if (line.find(option.c_str()) != std::string::npos)
{
//Touch the file
file.seekg(0);
char space; file.get(space);
file.seekg(0);
file.put(space);
std::cout << " found in " << info.absFilePath().ascii() << std::endl;
return;
}
}
}
file.close();
}
}
}
}
<commit_msg>r4528/sofa-dev : FIX: compatibility QT3-4<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include "SofaConfiguration.h"
#include <qsizepolicy.h>
#ifdef SOFA_QT4
#include <QGroupBox>
#include <QToolBox>
#include <QSpacerItem>
#include <QPushButton>
#include <Q3Process>
#else
#include <qgroupbox.h>
#include <qtoolbox.h>
#include <qpushbutton.h>
#include <qprocess.h>
typedef QProcess Q3Process;
#endif
#include <map>
#include <algorithm>
#include <fstream>
namespace sofa
{
namespace gui
{
namespace qt
{
ConfigWidget::ConfigWidget(QWidget *parent, DEFINES &d):QWidget(parent), option(d)
{
setName(QString(option.name.c_str()));
layout=new QHBoxLayout(this);
check=new QCheckBox(QString(option.name.c_str()), this);
check->setChecked(option.value);
check->setMaximumSize(300,20);
layout->addWidget(check);
connect(check, SIGNAL(toggled(bool)), this, SLOT(updateValue(bool)));
}
void ConfigWidget::updateValue(bool b)
{
option.value=b;
emit(modified());
}
TextConfigWidget::TextConfigWidget(QWidget *parent, DEFINES &d):ConfigWidget(parent,d)
{
description=new QLineEdit(this);
description->setText(option.description.c_str());
description->setAlignment(Qt::AlignBottom | Qt::AlignLeft);
connect(description, SIGNAL(textChanged(const QString&)), this, SLOT(updateValue(const QString&)));
layout->addWidget(description);
}
void TextConfigWidget::updateValue(const QString &s)
{
option.description=s.ascii();
emit(modified());
}
OptionConfigWidget::OptionConfigWidget(QWidget *parent, DEFINES &d):ConfigWidget(parent,d)
{
description=new QLabel(this);
description->setText(option.description.c_str());
description->setAlignment(Qt::AlignBottom | Qt::AlignLeft);
layout->addWidget(description);
}
SofaConfiguration::SofaConfiguration(std::string p, std::vector< DEFINES >& config):QMainWindow(),path(p),data(config)
{
resize(800, 600);
QWidget *appli = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(appli);
QToolBox *global = new QToolBox(appli);
global->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
std::string currentCategory;
QWidget *page=NULL;
QVBoxLayout *pageLayout=NULL;
for (unsigned int i=0; i<config.size(); ++i)
{
if (currentCategory != config[i].category)
{
if (page)
{
pageLayout->addItem( new QSpacerItem(10,10,QSizePolicy::Expanding, QSizePolicy::Expanding));
}
currentCategory = config[i].category;
page = new QWidget(global);
global->addItem(page,QString(currentCategory.c_str()));
pageLayout=new QVBoxLayout(page);
}
ConfigWidget *o;
if (config[i].typeOption) o=new OptionConfigWidget(page, config[i]);
else o=new TextConfigWidget(page, config[i]);
pageLayout->addWidget(o);
options.push_back(o);
connect(o, SIGNAL(modified()), this, SLOT(updateOptions()));
}
if (page)
{
pageLayout->addItem( new QSpacerItem(10,10,QSizePolicy::Expanding, QSizePolicy::Expanding));
}
updateConditions();
QPushButton *button = new QPushButton(QString("Save and Update Configuration"),appli);
connect( button, SIGNAL(clicked()), this, SLOT(saveConfiguration()));
layout->addWidget(global);
#ifdef WIN32
projectVC = new QLineEdit(QString("ProjectVC8.bat"),appli);
layout->addWidget(projectVC);
#endif
layout->addWidget(button);
this->setCentralWidget(appli);
}
bool SofaConfiguration::getValue(CONDITION &c)
{
unsigned int i=0;
for (; i<options.size(); ++i)
{
if (options[i]->name() == c.option)
{
bool presence = options[i]->getValue();
if (c.presence && presence) return true;
if (!c.presence && !presence) return true;
return false;
}
}
return false;
}
void SofaConfiguration::updateOptions()
{
QWidget *option = (QWidget*)sender();
if (dynamic_cast<OptionConfigWidget*>(option))
optionsModified.insert(option);
updateConditions();
}
void SofaConfiguration::processCondition(QWidget *w, CONDITION &c)
{
switch(c.type)
{
case OPTION:
w->setEnabled(getValue(c));
break;
case ARCHI:
if (c.option == "win32")
{
if (c.presence)
{
#ifndef WIN32
w->hide();
#endif
}
else
{
#ifdef WIN32
w->hide();
#endif
}
}
else if (c.option == "unix")
{
if (c.presence)
{
#ifdef WIN32
w->hide();
#endif
}
else
{
#ifndef WIN32
w->hide();
#endif
}
}
break;
}
}
void SofaConfiguration::updateConditions()
{
for (unsigned int i=0; i<options.size(); ++i)
{
std::vector< CONDITION > &conditions=options[i]->option.conditions;
for (unsigned int c=0; c<conditions.size(); ++c)
{
processCondition(options[i],conditions[c]);
}
}
}
void SofaConfiguration::saveConfiguration()
{
std::ofstream out((path + std::string("/sofa-local.cfg")).c_str());
std::string currentCategory;
std::vector< CONDITION > currentConditions;
for (unsigned int i=0; i<options.size(); ++i)
{
DEFINES &option=options[i]->option;
bool differentConditions=false;
if (currentConditions.size() != option.conditions.size()) differentConditions=true;
else
{
for (unsigned int c=0; c<currentConditions.size() && !differentConditions; ++c)
{
if (currentConditions[c] != option.conditions[c]) differentConditions=true;
}
}
if (differentConditions)
{
for (unsigned int c=0; c<currentConditions.size(); ++c) out << "}\n";
currentConditions = option.conditions;
}
if (currentCategory != option.category)
{
if (!currentCategory.empty()) out << "\n\n";
currentCategory = option.category;
out << "########################################################################\n";
out << "# " << currentCategory << "\n";
out << "########################################################################\n";
}
if (differentConditions)
{
for (unsigned int c=0; c<currentConditions.size(); ++c)
{
if (!currentConditions[c].presence) out << "!";
switch( currentConditions[c].type)
{
case OPTION:
out << "contains(DEFINES," << currentConditions[c].option << "){\n";
break;
case ARCHI:
out << currentConditions[c].option << "{\n";
break;
}
}
}
if (option.typeOption)
{
std::string description=option.description;
for (unsigned int position=0; position<description.size(); ++position)
{
if (description[position] == '\n') description.insert(position+1, "# ");
}
out << "\n# Uncomment " << description << "\n";
if (!option.value) out << "# ";
out << "DEFINES += " << option.name << "\n";
}
else
{
if (!option.value) out << "# ";
out << option.name << " " << option.description << "\n";
}
}
for (unsigned int c=0; c<currentConditions.size(); ++c) out << "}\n";
out.close();
std::set< QWidget *>::iterator it;
if (!optionsModified.empty())
{
std::vector<QString> listDir;
listDir.push_back(QString("/applications"));
listDir.push_back(QString("/modules"));
listDir.push_back(QString("/framework"));
listDir.push_back(QString("/extlibs"));
std::set< QWidget *>::iterator it;
for (it=optionsModified.begin(); it!=optionsModified.end(); it++)
std::cout << "Touch file containing option \"" <<(*it)->name() << "\" ";
std::cout << "in [ ";
for (unsigned int i=0; i<listDir.size(); ++i)
std::cout << listDir[i].ascii() << " ";
std::cout << "]" << std::endl;
for (unsigned int i=0; i<listDir.size(); ++i)
{
std::cout << " Searching in " << listDir[i].ascii() << "\n";
processDirectory(listDir[i]);
}
QStringList argv;
#ifndef WIN32
#if SOFA_QT4
argv << QString("qmake-qt4");
#else
argv << QString("qmake");
#endif
#else
argv << QString(path.c_str()) + QString("/") + QString(projectVC->text());
#endif
Q3Process *p = new Q3Process(argv,this);
p->setCommunication(0);
p->setWorkingDirectory(QDir(QString(path.c_str())));
p->start();
optionsModified.clear();
}
}
void SofaConfiguration::processDirectory(const QString &dir)
{
QDir d(QString(path.c_str())+dir);
d.setFilter( QDir::Dirs | QDir::Hidden | QDir::NoSymLinks );
std::vector< QString > subDir;
const QFileInfoList &listDirectories =
#ifdef SOFA_QT4
d.entryInfoList();
QStringList filters; filters << "*.cpp" << "*.h" << "*.inl";
d.setNameFilters(filters);
for (int j = 0; j < listDirectories.size(); ++j)
{
QFileInfo fileInfo=listDirectories.at(j);
#else
*(d.entryInfoList());
QString filters="*.cpp *.h *.inl";
d.setNameFilter(filters);
QFileInfoListIterator itDir( listDirectories );
while ( (itDir.current()) != 0 )
{
QFileInfo fileInfo=*(itDir.current());
#endif
subDir.push_back(fileInfo.fileName());
#ifndef SOFA_QT4
++itDir;
#endif
}
d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks );
std::vector< QString > filesInside;
const QFileInfoList &listFiles =
#ifdef SOFA_QT4
d.entryInfoList();
for (int j = 0; j < listFiles.size(); ++j)
{
QFileInfo fileInfo=listFiles.at(j);
#else
*(d.entryInfoList());
QFileInfoListIterator itFile( listFiles );
while ( (itFile.current()) != 0 )
{
QFileInfo fileInfo=*(itFile.current());
#endif
filesInside.push_back(fileInfo.fileName());
processFile(fileInfo);
#ifndef SOFA_QT4
++itFile;
#endif
}
for (unsigned int i=0; i<subDir.size(); ++i)
{
if (subDir[i].left(1) == QString(".")) continue;
if (subDir[i] == QString("OBJ")) continue;
QString nextDir=dir+QString("/")+subDir[i];
processDirectory(nextDir);
}
}
void SofaConfiguration::processFile(const QFileInfo &info)
{
std::fstream file;
file.open(info.absFilePath(), std::ios::in | std::ios::out);
std::string line;
while (std::getline(file, line))
{
std::set< QWidget *>::iterator it;
for (it=optionsModified.begin(); it!=optionsModified.end(); it++)
{
std::string option((*it)->name());
if (line.find(option.c_str()) != std::string::npos)
{
//Touch the file
file.seekg(0);
char space; file.get(space);
file.seekg(0);
file.put(space);
std::cout << " found in " << info.absFilePath().ascii() << std::endl;
return;
}
}
}
file.close();
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>track param working correctly again with correct settings.dat<commit_after><|endoftext|> |
<commit_before><commit_msg>[core] Make sure {ADD,SUB}{P,S}{S,D} have a bypass delay<commit_after><|endoftext|> |
<commit_before>//
// Copyright 2017 Shivansh Rai
// 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 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.
//
// $FreeBSD$
#include <array>
#include <boost/thread.hpp>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unordered_set>
#include "generate_test.h"
#include "add_testcase.h"
#include "read_annotations.h"
std::pair<std::string, int>
generate_test::exec(const char* cmd)
{
const int bufsize = 128;
std::array<char, bufsize> buffer;
std::string usage_output;
FILE* pipe = popen(cmd, "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe))
if (std::fgets(buffer.data(), bufsize, pipe) != NULL)
usage_output += buffer.data();
}
catch(...) {
pclose(pipe);
throw "Unable to execute the command: " + std::string(cmd);
}
return std::make_pair<std::string, int>
((std::string)usage_output, WEXITSTATUS(pclose(pipe)));
}
void
generate_test::generate_test(std::string utility, std::string section)
{
std::list<utils::opt_rel*> ident_opt_list; // List of identified option relations.
std::vector<std::string> usage_messages; // Vector to store usage messages for comparison.
std::string command; // Command to be executed in shell.
std::string descr; // Testcase description.
std::string testcase_list; // List of testcases.
std::string testcase_buffer; // Buffer for (temporarily) holding testcase data.
std::string test_file; // atf-sh test name.
std::string util_with_section; // Section number appended to utility.
std::ofstream test_ofs; // Output stream for the atf-sh test.
std::ifstream license_ifs; // Input stream for license.
std::pair<std::string, int> output; // Return value type for `exec()`.
std::unordered_set<std::string> annot; // Hashset of utility specific annotations.
// Read annotations and populate hash set "annot".
annotations::read_annotations(utility, annot);
util_with_section = utility + '(' + section + ')';
utils::opt_def f_opts;
ident_opt_list = f_opts.check_opts(utility);
test_file = "generated_tests/" + utility + "_test.sh";
// Add license in the generated test scripts.
test_ofs.open(test_file, std::ios::out);
license_ifs.open("license", std::ios::in);
test_ofs << license_ifs.rdbuf();
license_ifs.close();
// If a known option was encountered (i.e. `ident_opt_list` is
// populated), produce a testcase to check the validity of the
// result of that option. If no known option was encountered,
// produce testcases to verify the correct (generated) usage
// message when using the supported options incorrectly.
// Add testcases for known options.
if (!ident_opt_list.empty()) {
for (const auto &i : ident_opt_list) {
command = utility + " -" + i->value + " 2>&1";
output = generate_test::exec(command.c_str());
if (!output.first.compare(0, 6, "usage:")) {
add_testcase::add_known_testcase(i->value, util_with_section,
descr, output.first, test_ofs);
}
else {
// A usage message was produced, i.e. we
// failed to guess the correct usage.
add_testcase::add_unknown_testcase(i->value, util_with_section, output.first,
output.second, testcase_buffer);
}
testcase_list.append("\tatf_add_test_case " + i->value + "_flag\n");
}
}
// Add testcases for the options whose usage is not known (yet).
if (!f_opts.opt_list.empty()) {
// For the purpose of adding a "$usage_output" variable,
// we choose the option which produces one.
// TODO Avoid double executions of an option, i.e. one while
// selecting usage message and another while generating testcase.
if (f_opts.opt_list.size() == 1) {
// Utility supports a single option, check if it produces a usage message.
command = utility + " -" + f_opts.opt_list.front() + " 2>&1";
output = generate_test::exec(command.c_str());
if (output.second)
test_ofs << "usage_output=\'" + output.first + "\'\n\n";
}
else {
// Utility supports multiple options. In case the usage message
// is consistent for atleast "two" options, we reduce duplication
// by assigning a variable "usage_output" in the test script.
for (const auto &i : f_opts.opt_list) {
command = utility + " -" + i + " 2>&1";
output = generate_test::exec(command.c_str());
if (output.second && usage_messages.size() < 3)
usage_messages.push_back(output.first);
}
for (int j = 0; j <= 3; j++) {
if (!(usage_messages[j]).compare(usage_messages[(j+1) % 3])) {
test_ofs << "usage_output=\'"
+ output.first.substr(0, 7 + utility.size())
+ "\'\n\n";
break;
}
}
}
// Execute the utility with supported options
// and add (+ve)/(-ve) testcases accordingly.
for (const auto &i : f_opts.opt_list) {
// If the option is annotated, skip it.
if (annot.find(i) != annot.end())
continue;
command = utility + " -" + i + " 2>&1";
output = generate_test::exec(command.c_str());
if (output.second) {
// Non-zero exit status was encountered.
add_testcase::add_unknown_testcase(i, util_with_section, output.first,
output.second, testcase_buffer);
}
else {
// EXIT_SUCCESS was encountered. Hence,
// the guessed usage was correct.
add_testcase::add_known_testcase(i, util_with_section, "",
output.first, test_ofs);
testcase_list.append(std::string("\tatf_add_test_case ")
+ i + "_flag\n");
}
}
testcase_list.append("\tatf_add_test_case invalid_usage\n");
test_ofs << std::string("atf_test_case invalid_usage\ninvalid_usage_head()\n")
+ "{\n\tatf_set \"descr\" \"Verify that an invalid usage "
+ "with a supported option produces a valid error message"
+ "\"\n}\n\ninvalid_usage_body()\n{";
test_ofs << testcase_buffer + "\n}\n\n";
}
// Add a testcase under "no_arguments" for
// running the utility without any arguments.
if (annot.find("*") == annot.end()) {
command = utility + " 2>&1";
output = generate_test::exec(command.c_str());
add_testcase::add_noargs_testcase(util_with_section, output, test_ofs);
testcase_list.append("\tatf_add_test_case no_arguments\n");
}
test_ofs << "atf_init_test_cases()\n{\n" + testcase_list + "}\n";
test_ofs.close();
}
int
main()
{
std::ifstream groff_list;
std::list<std::pair<std::string, std::string>> utility_list;
std::string test_file; // atf-sh test name.
std::string util_name; // Utility name.
struct stat buffer;
struct dirent *ent;
DIR *dir;
char answer; // User input to determine overwriting of test files.
int flag = 0;
// For testing (or generating tests for only selected utilities),
// the utility_list can be populated above during declaration.
if (utility_list.empty()) {
if ((dir = opendir("groff"))) {
while ((ent = readdir(dir))) {
util_name = ent->d_name;
utility_list.push_back(std::make_pair<std::string, std::string>
(util_name.substr(0, util_name.length() - 2),
util_name.substr(util_name.length() - 1, 1)));
}
closedir(dir);
}
else {
fprintf(stderr, "Could not open directory: groff/");
return EXIT_FAILURE;
}
}
for (const auto &util : utility_list) {
test_file = "generated_tests/" + util.first + "_test.sh";
// Check if the test file already exists. In
// case it does, confirm before proceeding.
if (!flag && !stat(test_file.c_str(), &buffer)) {
std::cout << "Test file(s) already exists. Overwrite? [y/n] ";
std::cin >> answer;
switch (answer) {
case 'n':
case 'N':
fprintf(stderr, "Stopping execution\n");
flag = 1;
break;
default:
// TODO capture newline character
flag = 1;
break;
}
}
std::cout << "Generating test for: " + util.first
+ '('+ util.second + ')' << " ...";
boost::thread api_caller(generate_test::generate_test, util.first, util.second);
if (api_caller.timed_join(boost::posix_time::seconds(1))) {
// API call returned withing 1 second.
std::cout << "Successful\n";
}
else {
// API call timed out.
std::cout << "Failed!\n";
}
}
return EXIT_SUCCESS;
}
<commit_msg>Fix out of bounds error<commit_after>//
// Copyright 2017 Shivansh Rai
// 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 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.
//
// $FreeBSD$
#include <array>
#include <boost/thread.hpp>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unordered_set>
#include "generate_test.h"
#include "add_testcase.h"
#include "read_annotations.h"
std::pair<std::string, int>
generate_test::exec(const char* cmd)
{
const int bufsize = 128;
std::array<char, bufsize> buffer;
std::string usage_output;
FILE* pipe = popen(cmd, "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe))
if (std::fgets(buffer.data(), bufsize, pipe) != NULL)
usage_output += buffer.data();
}
catch(...) {
pclose(pipe);
throw "Unable to execute the command: " + std::string(cmd);
}
return std::make_pair<std::string, int>
((std::string)usage_output, WEXITSTATUS(pclose(pipe)));
}
void
generate_test::generate_test(std::string utility, std::string section)
{
std::list<utils::opt_rel*> ident_opt_list; // List of identified option relations.
std::vector<std::string> usage_messages; // Vector to store usage messages for comparison.
std::string command; // Command to be executed in shell.
std::string descr; // Testcase description.
std::string testcase_list; // List of testcases.
std::string testcase_buffer; // Buffer for (temporarily) holding testcase data.
std::string test_file; // atf-sh test name.
std::string util_with_section; // Section number appended to utility.
std::ofstream test_ofs; // Output stream for the atf-sh test.
std::ifstream license_ifs; // Input stream for license.
std::pair<std::string, int> output; // Return value type for `exec()`.
std::unordered_set<std::string> annot; // Hashset of utility specific annotations.
int temp;
// Read annotations and populate hash set "annot".
annotations::read_annotations(utility, annot);
util_with_section = utility + '(' + section + ')';
utils::opt_def f_opts;
ident_opt_list = f_opts.check_opts(utility);
test_file = "generated_tests/" + utility + "_test.sh";
// Add license in the generated test scripts.
test_ofs.open(test_file, std::ios::out);
license_ifs.open("license", std::ios::in);
test_ofs << license_ifs.rdbuf();
license_ifs.close();
// If a known option was encountered (i.e. `ident_opt_list` is
// populated), produce a testcase to check the validity of the
// result of that option. If no known option was encountered,
// produce testcases to verify the correct (generated) usage
// message when using the supported options incorrectly.
// Add testcases for known options.
if (!ident_opt_list.empty()) {
for (const auto &i : ident_opt_list) {
command = utility + " -" + i->value + " 2>&1";
output = generate_test::exec(command.c_str());
if (!output.first.compare(0, 6, "usage:")) {
add_testcase::add_known_testcase(i->value, util_with_section,
descr, output.first, test_ofs);
}
else {
// A usage message was produced, i.e. we
// failed to guess the correct usage.
add_testcase::add_unknown_testcase(i->value, util_with_section, output.first,
output.second, testcase_buffer);
}
testcase_list.append("\tatf_add_test_case " + i->value + "_flag\n");
}
}
// Add testcases for the options whose usage is not known (yet).
if (!f_opts.opt_list.empty()) {
// For the purpose of adding a "$usage_output" variable,
// we choose the option which produces one.
// TODO Avoid double executions of an option, i.e. one while
// selecting usage message and another while generating testcase.
if (f_opts.opt_list.size() == 1) {
// Utility supports a single option, check if it produces a usage message.
command = utility + " -" + f_opts.opt_list.front() + " 2>&1";
output = generate_test::exec(command.c_str());
if (output.second)
test_ofs << "usage_output=\'" + output.first + "\'\n\n";
}
else {
// Utility supports multiple options. In case the usage message
// is consistent for atleast "two" options, we reduce duplication
// by assigning a variable "usage_output" in the test script.
for (const auto &i : f_opts.opt_list) {
command = utility + " -" + i + " 2>&1";
output = generate_test::exec(command.c_str());
if (output.second && usage_messages.size() < 3)
usage_messages.push_back(output.first);
}
temp = usage_messages.size();
for (int j = 0; j < temp; j++) {
if (!(usage_messages.at(j)).compare(usage_messages.at((j+1) % temp))) {
test_ofs << "usage_output=\'"
+ output.first.substr(0, 7 + utility.size())
+ "\'\n\n";
break;
}
}
}
// Execute the utility with supported options
// and add (+ve)/(-ve) testcases accordingly.
for (const auto &i : f_opts.opt_list) {
// If the option is annotated, skip it.
if (annot.find(i) != annot.end())
continue;
command = utility + " -" + i + " 2>&1";
output = generate_test::exec(command.c_str());
if (output.second) {
// Non-zero exit status was encountered.
add_testcase::add_unknown_testcase(i, util_with_section, output.first,
output.second, testcase_buffer);
}
else {
// EXIT_SUCCESS was encountered. Hence,
// the guessed usage was correct.
add_testcase::add_known_testcase(i, util_with_section, "",
output.first, test_ofs);
testcase_list.append(std::string("\tatf_add_test_case ")
+ i + "_flag\n");
}
}
testcase_list.append("\tatf_add_test_case invalid_usage\n");
test_ofs << std::string("atf_test_case invalid_usage\ninvalid_usage_head()\n")
+ "{\n\tatf_set \"descr\" \"Verify that an invalid usage "
+ "with a supported option produces a valid error message"
+ "\"\n}\n\ninvalid_usage_body()\n{";
test_ofs << testcase_buffer + "\n}\n\n";
}
// Add a testcase under "no_arguments" for
// running the utility without any arguments.
if (annot.find("*") == annot.end()) {
command = utility + " 2>&1";
output = generate_test::exec(command.c_str());
add_testcase::add_noargs_testcase(util_with_section, output, test_ofs);
testcase_list.append("\tatf_add_test_case no_arguments\n");
}
test_ofs << "atf_init_test_cases()\n{\n" + testcase_list + "}\n";
test_ofs.close();
}
int
main()
{
std::ifstream groff_list;
std::list<std::pair<std::string, std::string>> utility_list;
std::string test_file; // atf-sh test name.
std::string util_name; // Utility name.
struct stat buffer;
struct dirent *ent;
DIR *dir;
char answer; // User input to determine overwriting of test files.
int flag = 0;
// For testing (or generating tests for only selected utilities),
// the utility_list can be populated above during declaration.
if (utility_list.empty()) {
if ((dir = opendir("groff"))) {
while ((ent = readdir(dir))) {
util_name = ent->d_name;
utility_list.push_back(std::make_pair<std::string, std::string>
(util_name.substr(0, util_name.length() - 2),
util_name.substr(util_name.length() - 1, 1)));
}
closedir(dir);
}
else {
fprintf(stderr, "Could not open directory: groff/");
return EXIT_FAILURE;
}
}
for (const auto &util : utility_list) {
test_file = "generated_tests/" + util.first + "_test.sh";
// Check if the test file already exists. In
// case it does, confirm before proceeding.
if (!flag && !stat(test_file.c_str(), &buffer)) {
std::cout << "Test file(s) already exists. Overwrite? [y/n] ";
std::cin >> answer;
switch (answer) {
case 'n':
case 'N':
fprintf(stderr, "Stopping execution\n");
flag = 1;
break;
default:
// TODO capture newline character
flag = 1;
break;
}
}
std::cout << "Generating test for: " + util.first
+ '('+ util.second + ')' << " ...";
boost::thread api_caller(generate_test::generate_test, util.first, util.second);
if (api_caller.timed_join(boost::posix_time::seconds(1))) {
// API call returned within 1 second.
std::cout << "Successful\n";
}
else {
// API call timed out.
std::cout << "Failed!\n";
// Remove the incomplete test file.
remove(("generated_tests/" + util.first + "_test.sh").c_str());
}
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "CrashHandler.h"
#include "SkTypes.h"
#include <stdlib.h>
// Disable SetupCrashHandler() unless SK_CRASH_HANDLER is defined.
#ifndef SK_CRASH_HANDLER
void SetupCrashHandler() { }
#elif defined(GOOGLE3)
#include "base/process_state.h"
void SetupCrashHandler() { InstallSignalHandlers(); }
#else
#if defined(SK_BUILD_FOR_MAC)
// We only use local unwinding, so we can define this to select a faster implementation.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <cxxabi.h>
static void handler(int sig) {
unw_context_t context;
unw_getcontext(&context);
unw_cursor_t cursor;
unw_init_local(&cursor, &context);
SkDebugf("\nSignal %d:\n", sig);
while (unw_step(&cursor) > 0) {
static const size_t kMax = 256;
char mangled[kMax], demangled[kMax];
unw_word_t offset;
unw_get_proc_name(&cursor, mangled, kMax, &offset);
int ok;
size_t len = kMax;
abi::__cxa_demangle(mangled, demangled, &len, &ok);
SkDebugf("%s (+0x%zx)\n", ok == 0 ? demangled : mangled, (size_t)offset);
}
SkDebugf("\n");
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#elif defined(SK_BUILD_FOR_UNIX)
// We'd use libunwind here too, but it's a pain to get installed for
// both 32 and 64 bit on bots. Doesn't matter much: catchsegv is best anyway.
#include <execinfo.h>
static void handler(int sig) {
static const int kMax = 64;
void* stack[kMax];
const int count = backtrace(stack, kMax);
SkDebugf("\nSignal %d [%s]:\n", sig, strsignal(sig));
backtrace_symbols_fd(stack, count, 2/*stderr*/);
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#endif
#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX)
#include <signal.h>
void SetupCrashHandler() {
static const int kSignals[] = {
SIGABRT,
SIGBUS,
SIGFPE,
SIGILL,
SIGSEGV,
};
for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) {
// Register our signal handler unless something's already done so (e.g. catchsegv).
void (*prev)(int) = signal(kSignals[i], handler);
if (prev != SIG_DFL) {
signal(kSignals[i], prev);
}
}
}
#elif defined(SK_CRASH_HANDLER) && defined(SK_BUILD_FOR_WIN)
#include <DbgHelp.h>
static const struct {
const char* name;
int code;
} kExceptions[] = {
#define _(E) {#E, E}
_(EXCEPTION_ACCESS_VIOLATION),
_(EXCEPTION_BREAKPOINT),
_(EXCEPTION_INT_DIVIDE_BY_ZERO),
_(EXCEPTION_STACK_OVERFLOW),
// TODO: more?
#undef _
};
static LONG WINAPI handler(EXCEPTION_POINTERS* e) {
const DWORD code = e->ExceptionRecord->ExceptionCode;
SkDebugf("\nCaught exception %u", code);
for (size_t i = 0; i < SK_ARRAY_COUNT(kExceptions); i++) {
if (kExceptions[i].code == code) {
SkDebugf(" %s", kExceptions[i].name);
}
}
SkDebugf("\n");
// We need to run SymInitialize before doing any of the stack walking below.
HANDLE hProcess = GetCurrentProcess();
SymInitialize(hProcess, 0, true);
STACKFRAME64 frame;
sk_bzero(&frame, sizeof(frame));
// Start frame off from the frame that triggered the exception.
CONTEXT* c = e->ContextRecord;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
#if defined(_X86_)
frame.AddrPC.Offset = c->Eip;
frame.AddrStack.Offset = c->Esp;
frame.AddrFrame.Offset = c->Ebp;
const DWORD machineType = IMAGE_FILE_MACHINE_I386;
#elif defined(_AMD64_)
frame.AddrPC.Offset = c->Rip;
frame.AddrStack.Offset = c->Rsp;
frame.AddrFrame.Offset = c->Rbp;
const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
#endif
while (StackWalk64(machineType,
GetCurrentProcess(),
GetCurrentThread(),
&frame,
c,
nullptr,
SymFunctionTableAccess64,
SymGetModuleBase64,
nullptr)) {
// Buffer to store symbol name in.
static const int kMaxNameLength = 1024;
uint8_t buffer[sizeof(IMAGEHLP_SYMBOL64) + kMaxNameLength];
sk_bzero(buffer, sizeof(buffer));
// We have to place IMAGEHLP_SYMBOL64 at the front, and fill in
// how much space it can use.
IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(&buffer);
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = kMaxNameLength - 1;
// Translate the current PC into a symbol and byte offset from the symbol.
DWORD64 offset;
SymGetSymFromAddr64(hProcess, frame.AddrPC.Offset, &offset, symbol);
SkDebugf("%s +%x\n", symbol->Name, offset);
}
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_exit(1);
// The compiler wants us to return something. This is what we'd do
// if we didn't _exit().
return EXCEPTION_EXECUTE_HANDLER;
}
void SetupCrashHandler() {
SetUnhandledExceptionFilter(handler);
}
#else // We asked for SK_CRASH_HANDLER, but it's not Mac, Linux, or Windows. Sorry!
void SetupCrashHandler() { }
#endif
#endif // SK_CRASH_HANDLER
<commit_msg>Don't convert DWORD to int.<commit_after>/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "CrashHandler.h"
#include "SkTypes.h"
#include <stdlib.h>
// Disable SetupCrashHandler() unless SK_CRASH_HANDLER is defined.
#ifndef SK_CRASH_HANDLER
void SetupCrashHandler() { }
#elif defined(GOOGLE3)
#include "base/process_state.h"
void SetupCrashHandler() { InstallSignalHandlers(); }
#else
#if defined(SK_BUILD_FOR_MAC)
// We only use local unwinding, so we can define this to select a faster implementation.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <cxxabi.h>
static void handler(int sig) {
unw_context_t context;
unw_getcontext(&context);
unw_cursor_t cursor;
unw_init_local(&cursor, &context);
SkDebugf("\nSignal %d:\n", sig);
while (unw_step(&cursor) > 0) {
static const size_t kMax = 256;
char mangled[kMax], demangled[kMax];
unw_word_t offset;
unw_get_proc_name(&cursor, mangled, kMax, &offset);
int ok;
size_t len = kMax;
abi::__cxa_demangle(mangled, demangled, &len, &ok);
SkDebugf("%s (+0x%zx)\n", ok == 0 ? demangled : mangled, (size_t)offset);
}
SkDebugf("\n");
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#elif defined(SK_BUILD_FOR_UNIX)
// We'd use libunwind here too, but it's a pain to get installed for
// both 32 and 64 bit on bots. Doesn't matter much: catchsegv is best anyway.
#include <execinfo.h>
static void handler(int sig) {
static const int kMax = 64;
void* stack[kMax];
const int count = backtrace(stack, kMax);
SkDebugf("\nSignal %d [%s]:\n", sig, strsignal(sig));
backtrace_symbols_fd(stack, count, 2/*stderr*/);
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#endif
#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_UNIX)
#include <signal.h>
void SetupCrashHandler() {
static const int kSignals[] = {
SIGABRT,
SIGBUS,
SIGFPE,
SIGILL,
SIGSEGV,
};
for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) {
// Register our signal handler unless something's already done so (e.g. catchsegv).
void (*prev)(int) = signal(kSignals[i], handler);
if (prev != SIG_DFL) {
signal(kSignals[i], prev);
}
}
}
#elif defined(SK_CRASH_HANDLER) && defined(SK_BUILD_FOR_WIN)
#include <DbgHelp.h>
static const struct {
const char* name;
const DWORD code;
} kExceptions[] = {
#define _(E) {#E, E}
_(EXCEPTION_ACCESS_VIOLATION),
_(EXCEPTION_BREAKPOINT),
_(EXCEPTION_INT_DIVIDE_BY_ZERO),
_(EXCEPTION_STACK_OVERFLOW),
// TODO: more?
#undef _
};
static LONG WINAPI handler(EXCEPTION_POINTERS* e) {
const DWORD code = e->ExceptionRecord->ExceptionCode;
SkDebugf("\nCaught exception %u", code);
for (size_t i = 0; i < SK_ARRAY_COUNT(kExceptions); i++) {
if (kExceptions[i].code == code) {
SkDebugf(" %s", kExceptions[i].name);
}
}
SkDebugf("\n");
// We need to run SymInitialize before doing any of the stack walking below.
HANDLE hProcess = GetCurrentProcess();
SymInitialize(hProcess, 0, true);
STACKFRAME64 frame;
sk_bzero(&frame, sizeof(frame));
// Start frame off from the frame that triggered the exception.
CONTEXT* c = e->ContextRecord;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
#if defined(_X86_)
frame.AddrPC.Offset = c->Eip;
frame.AddrStack.Offset = c->Esp;
frame.AddrFrame.Offset = c->Ebp;
const DWORD machineType = IMAGE_FILE_MACHINE_I386;
#elif defined(_AMD64_)
frame.AddrPC.Offset = c->Rip;
frame.AddrStack.Offset = c->Rsp;
frame.AddrFrame.Offset = c->Rbp;
const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
#endif
while (StackWalk64(machineType,
GetCurrentProcess(),
GetCurrentThread(),
&frame,
c,
nullptr,
SymFunctionTableAccess64,
SymGetModuleBase64,
nullptr)) {
// Buffer to store symbol name in.
static const int kMaxNameLength = 1024;
uint8_t buffer[sizeof(IMAGEHLP_SYMBOL64) + kMaxNameLength];
sk_bzero(buffer, sizeof(buffer));
// We have to place IMAGEHLP_SYMBOL64 at the front, and fill in
// how much space it can use.
IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(&buffer);
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = kMaxNameLength - 1;
// Translate the current PC into a symbol and byte offset from the symbol.
DWORD64 offset;
SymGetSymFromAddr64(hProcess, frame.AddrPC.Offset, &offset, symbol);
SkDebugf("%s +%x\n", symbol->Name, offset);
}
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_exit(1);
// The compiler wants us to return something. This is what we'd do
// if we didn't _exit().
return EXCEPTION_EXECUTE_HANDLER;
}
void SetupCrashHandler() {
SetUnhandledExceptionFilter(handler);
}
#else // We asked for SK_CRASH_HANDLER, but it's not Mac, Linux, or Windows. Sorry!
void SetupCrashHandler() { }
#endif
#endif // SK_CRASH_HANDLER
<|endoftext|> |
<commit_before>#include "LotsOfLinesApp.h"
#include <QFileDialog>
#include <QCheckBox>
#include <QMessageBox>
#include <QTableView>
#include <QtConcurrent/qtconcurrentrun.h>
#include <qfuture.h>
#include "LoadDataDialog.h"
#include "PreferencesDialog.h"
#include "DataTableModel.h"
#include <LotsOfLines/RenderingSystem.hpp>
#include <LotsOfLines/IVisualizationMethod.hpp>
//Custom checkbox for selecting visualization methods.
class VisualizationTypeCheckbox : public QCheckBox
{
public:
VisualizationTypeCheckbox(const QString& text, QWidget* parent, LotsOfLines::E_VISUALIZATION_TYPE type)
:QCheckBox(text, parent),
m_visualizationType(type)
{}
LotsOfLines::E_VISUALIZATION_TYPE getVisualizationType() { return m_visualizationType; }
private:
LotsOfLines::E_VISUALIZATION_TYPE m_visualizationType;
};
LotsOfLinesApp::LotsOfLinesApp(QWidget *parent)
:QMainWindow(parent),
m_dataSet(nullptr)
{
ui.setupUi(this);
//Setup rendering window
auto rendererWidget = new VisualizationRendererWidget(this);
//m_renderingSystem = m_rendererWidget->getRenderingSystem();
//ui.centralLayout->addWidget(m_rendererWidget);
//Populate visualization type selection menu
LotsOfLines::VisualizationMethodList visualizationMethods;
rendererWidget->getRenderingSystem()->getVisualizationMethods(visualizationMethods);
for (auto method : visualizationMethods)
{
VisualizationTypeCheckbox* methodCheckbox = new VisualizationTypeCheckbox(QString::fromStdString(method->getTypeName()), ui.visualizationTypeArea, method->getType());
connect(methodCheckbox, SIGNAL(stateChanged(int)), this, SLOT(onVisualizationChecked(int)));
ui.visualizationTypeLayout->addWidget(methodCheckbox);
}
delete rendererWidget;
//Setup dock widgets
ui.menuView->addAction(ui.sidebarDockWidget->toggleViewAction());
ui.menuView->addAction(ui.dataTableDock->toggleViewAction());
//Connect signals and slots
connect(ui.actionLoad, SIGNAL(triggered()), this, SLOT(onLoadFile()));
connect(ui.actionPreferences, SIGNAL(triggered()), this, SLOT(onOpenPreferences()));
}
void LotsOfLinesApp::loadFile(const QString& filename, const LotsOfLines::LoadOptions& options)
{
//Load data set through DataModel module with QtConcurrent
QFuture<std::shared_ptr<LotsOfLines::DataSet>> dataSet = QtConcurrent::run(this->m_dataModel, &LotsOfLines::DataModel::loadData, filename.toStdString(), options);
//This will keep GUI active but does slow load down. Needs work
while (!dataSet.isFinished()) {
QCoreApplication::processEvents();
//Potentially get progress here
}
//Set dataset to QtConcurrent run result
m_dataSet = dataSet.result();
if (m_dataSet == nullptr)
{
QMessageBox::warning(this, "Failed to load", "There was an error loading the data file.");
}
//Pass data along to rendering system
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->setDataSet(m_dataSet);
renderingSystem->redraw();
}
reloadDataTable();
}
void LotsOfLinesApp::reloadDataTable()
{
//Delete all tabs
for (unsigned int i = 0; i < ui.dataClassTabs->count(); ++i)
{
QWidget* tab = ui.dataClassTabs->widget(i);
delete tab;
}
ui.dataClassTabs->clear();
//Generate new tabs for each data class
for (auto dataClass : m_dataSet->getClasses())
{
QTableView* dataTable = new QTableView(ui.dataClassTabs);
dataTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
dataTable->setModel(new DataTableModel(m_dataSet, dataClass));
dataTable->setSelectionMode(QAbstractItemView::NoSelection);
ui.dataClassTabs->addTab(dataTable, QString::fromStdString(dataClass));
}
}
void LotsOfLinesApp::onLoadFile()
{
//Get file path of data to load
QString file = QFileDialog::getOpenFileName(this, "Select data file");
if (file.isNull())
{
return;
}
//Show data loading options
LoadDataDialog dlg(this, file);
if (dlg.exec() == QDialog::Accepted)
{
LotsOfLines::LoadOptions options = dlg.getLoadOptions();
loadFile(file, options);
}
}
void LotsOfLinesApp::onOpenPreferences()
{
PreferencesDialog dlg(this);
dlg.exec();
}
void LotsOfLinesApp::onVisualizationChecked(int state)
{
VisualizationTypeCheckbox* checkbox = (VisualizationTypeCheckbox*)sender();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = checkbox->getVisualizationType();
if (state)
{
//Init callback will be called by the rendering widget after OpenGL loads
auto initCallback = [this, visualizationType](LotsOfLines::RenderingSystem* renderingSystem)
{
//Set visualization type and dataset now that OpenGL is initialized
renderingSystem->setDataSet(m_dataSet);
renderingSystem->setVisualizationType(visualizationType);
renderingSystem->redraw();
//Add options editor widget for visualization method
OptionEditorWidget* editorWidget = new OptionEditorWidget(
QString::fromStdString(renderingSystem->getCurrentVisualizationMethod()->getTypeName()),
renderingSystem->getVisualizationOptions(),
ui.optionsScrollArea
);
m_optionEditorWidgets[visualizationType] = editorWidget;
ui.optionsScrollLayout->addWidget(editorWidget);
//Connect option editing signal so that the visualization can be redrawn when options are changed
connect(editorWidget, SIGNAL(optionChanged(const std::string&)), this, SLOT(onVisualizationOptionsChanged(const std::string&)));
};
//Create widget for screen section and use init callback to set parameters
VisualizationRendererWidget* rendererWidget = new VisualizationRendererWidget(this, initCallback);
m_rendererWidgets[checkbox->getVisualizationType()] = rendererWidget;
reorderSplitScreens();
}
else
{
//Remove visualization type from splitscreen display
m_rendererWidgets.erase(visualizationType);
reorderSplitScreens();
//Remove editor widget
auto optionEditorWidget = m_optionEditorWidgets.find(visualizationType);
if (optionEditorWidget != m_optionEditorWidgets.end())
{
ui.optionsScrollLayout->removeWidget(optionEditorWidget->second);
delete optionEditorWidget->second;
m_optionEditorWidgets.erase(optionEditorWidget);
}
}
}
void LotsOfLinesApp::onVisualizationOptionsChanged(const std::string& name)
{
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->redraw();
}
}
void LotsOfLinesApp::reorderSplitScreens()
{
//Clear layout
while (ui.centralLayout->count() > 0)
{
QLayoutItem* rendererLayoutItem = ui.centralLayout->itemAt(0);
VisualizationRendererWidget* renderWidget = (VisualizationRendererWidget*)rendererLayoutItem->widget();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = renderWidget->getRenderingSystem()->getCurrentVisualizationMethod()->getType();
ui.centralLayout->removeItem(rendererLayoutItem);
//If the visualization method has been disabled, then delete the rendering widget.
if (m_rendererWidgets.find(visualizationType) == m_rendererWidgets.end())
{
delete renderWidget;
}
}
//Assign based on index
unsigned int idx = 0;
for (auto widget : m_rendererWidgets)
{
unsigned int row = idx / 2;
unsigned int col = idx % 2;
ui.centralLayout->addWidget(widget.second, row, col);
idx++;
}
}<commit_msg>Simple progressbar marquee style<commit_after>#include "LotsOfLinesApp.h"
#include <QFileDialog>
#include <QCheckBox>
#include <QMessageBox>
#include <QTableView>
#include <QtConcurrent/qtconcurrentrun.h>
#include <QtWidgets/qprogressdialog.h>
#include <qfuturewatcher.h>
#include <qfuture.h>
#include "LoadDataDialog.h"
#include "PreferencesDialog.h"
#include "DataTableModel.h"
#include <LotsOfLines/RenderingSystem.hpp>
#include <LotsOfLines/IVisualizationMethod.hpp>
//Custom checkbox for selecting visualization methods.
class VisualizationTypeCheckbox : public QCheckBox
{
public:
VisualizationTypeCheckbox(const QString& text, QWidget* parent, LotsOfLines::E_VISUALIZATION_TYPE type)
:QCheckBox(text, parent),
m_visualizationType(type)
{}
LotsOfLines::E_VISUALIZATION_TYPE getVisualizationType() { return m_visualizationType; }
private:
LotsOfLines::E_VISUALIZATION_TYPE m_visualizationType;
};
LotsOfLinesApp::LotsOfLinesApp(QWidget *parent)
:QMainWindow(parent),
m_dataSet(nullptr)
{
ui.setupUi(this);
//Setup rendering window
auto rendererWidget = new VisualizationRendererWidget(this);
//m_renderingSystem = m_rendererWidget->getRenderingSystem();
//ui.centralLayout->addWidget(m_rendererWidget);
//Populate visualization type selection menu
LotsOfLines::VisualizationMethodList visualizationMethods;
rendererWidget->getRenderingSystem()->getVisualizationMethods(visualizationMethods);
for (auto method : visualizationMethods)
{
VisualizationTypeCheckbox* methodCheckbox = new VisualizationTypeCheckbox(QString::fromStdString(method->getTypeName()), ui.visualizationTypeArea, method->getType());
connect(methodCheckbox, SIGNAL(stateChanged(int)), this, SLOT(onVisualizationChecked(int)));
ui.visualizationTypeLayout->addWidget(methodCheckbox);
}
delete rendererWidget;
//Setup dock widgets
ui.menuView->addAction(ui.sidebarDockWidget->toggleViewAction());
ui.menuView->addAction(ui.dataTableDock->toggleViewAction());
//Connect signals and slots
connect(ui.actionLoad, SIGNAL(triggered()), this, SLOT(onLoadFile()));
connect(ui.actionPreferences, SIGNAL(triggered()), this, SLOT(onOpenPreferences()));
}
void LotsOfLinesApp::loadFile(const QString& filename, const LotsOfLines::LoadOptions& options)
{
QProgressDialog dialog;
dialog.setLabelText("Please wait while loading file...");
dialog.setMaximum(0); // Marquee style
QFutureWatcher<std::shared_ptr<LotsOfLines::DataSet>> future;
QObject::connect(&future, SIGNAL(finished()), &dialog, SLOT(reset()));
QObject::connect(&dialog, SIGNAL(canceled()), &future, SLOT(cancel()));
//Load data set through DataModel module with QtConcurrent
future.setFuture(QtConcurrent::run(this->m_dataModel, &LotsOfLines::DataModel::loadData, filename.toStdString(), options));
dialog.exec();
while (!future.future().isFinished()) {
QCoreApplication::processEvents();
if (future.future().isCanceled()) return;
}
//Set dataset to QtConcurrent run result
m_dataSet = future.future().result();
if (m_dataSet == nullptr)
{
QMessageBox::warning(this, "Failed to load", "There was an error loading the data file.");
}
//Pass data along to rendering system
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->setDataSet(m_dataSet);
renderingSystem->redraw();
}
reloadDataTable();
}
void LotsOfLinesApp::reloadDataTable()
{
//Delete all tabs
for (unsigned int i = 0; i < ui.dataClassTabs->count(); ++i)
{
QWidget* tab = ui.dataClassTabs->widget(i);
delete tab;
}
ui.dataClassTabs->clear();
//Generate new tabs for each data class
for (auto dataClass : m_dataSet->getClasses())
{
QTableView* dataTable = new QTableView(ui.dataClassTabs);
dataTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
dataTable->setModel(new DataTableModel(m_dataSet, dataClass));
dataTable->setSelectionMode(QAbstractItemView::NoSelection);
ui.dataClassTabs->addTab(dataTable, QString::fromStdString(dataClass));
}
}
void LotsOfLinesApp::onLoadFile()
{
//Get file path of data to load
QString file = QFileDialog::getOpenFileName(this, "Select data file");
if (file.isNull())
{
return;
}
//Show data loading options
LoadDataDialog dlg(this, file);
if (dlg.exec() == QDialog::Accepted)
{
LotsOfLines::LoadOptions options = dlg.getLoadOptions();
loadFile(file, options);
}
}
void LotsOfLinesApp::onOpenPreferences()
{
PreferencesDialog dlg(this);
dlg.exec();
}
void LotsOfLinesApp::onVisualizationChecked(int state)
{
VisualizationTypeCheckbox* checkbox = (VisualizationTypeCheckbox*)sender();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = checkbox->getVisualizationType();
if (state)
{
//Init callback will be called by the rendering widget after OpenGL loads
auto initCallback = [this, visualizationType](LotsOfLines::RenderingSystem* renderingSystem)
{
//Set visualization type and dataset now that OpenGL is initialized
renderingSystem->setDataSet(m_dataSet);
renderingSystem->setVisualizationType(visualizationType);
renderingSystem->redraw();
//Add options editor widget for visualization method
OptionEditorWidget* editorWidget = new OptionEditorWidget(
QString::fromStdString(renderingSystem->getCurrentVisualizationMethod()->getTypeName()),
renderingSystem->getVisualizationOptions(),
ui.optionsScrollArea
);
m_optionEditorWidgets[visualizationType] = editorWidget;
ui.optionsScrollLayout->addWidget(editorWidget);
//Connect option editing signal so that the visualization can be redrawn when options are changed
connect(editorWidget, SIGNAL(optionChanged(const std::string&)), this, SLOT(onVisualizationOptionsChanged(const std::string&)));
};
//Create widget for screen section and use init callback to set parameters
VisualizationRendererWidget* rendererWidget = new VisualizationRendererWidget(this, initCallback);
m_rendererWidgets[checkbox->getVisualizationType()] = rendererWidget;
reorderSplitScreens();
}
else
{
//Remove visualization type from splitscreen display
m_rendererWidgets.erase(visualizationType);
reorderSplitScreens();
//Remove editor widget
auto optionEditorWidget = m_optionEditorWidgets.find(visualizationType);
if (optionEditorWidget != m_optionEditorWidgets.end())
{
ui.optionsScrollLayout->removeWidget(optionEditorWidget->second);
delete optionEditorWidget->second;
m_optionEditorWidgets.erase(optionEditorWidget);
}
}
}
void LotsOfLinesApp::onVisualizationOptionsChanged(const std::string& name)
{
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->redraw();
}
}
void LotsOfLinesApp::reorderSplitScreens()
{
//Clear layout
while (ui.centralLayout->count() > 0)
{
QLayoutItem* rendererLayoutItem = ui.centralLayout->itemAt(0);
VisualizationRendererWidget* renderWidget = (VisualizationRendererWidget*)rendererLayoutItem->widget();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = renderWidget->getRenderingSystem()->getCurrentVisualizationMethod()->getType();
ui.centralLayout->removeItem(rendererLayoutItem);
//If the visualization method has been disabled, then delete the rendering widget.
if (m_rendererWidgets.find(visualizationType) == m_rendererWidgets.end())
{
delete renderWidget;
}
}
//Assign based on index
unsigned int idx = 0;
for (auto widget : m_rendererWidgets)
{
unsigned int row = idx / 2;
unsigned int col = idx % 2;
ui.centralLayout->addWidget(widget.second, row, col);
idx++;
}
}<|endoftext|> |
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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.
=========================================================================*/
#ifndef __itktubeSingleValuedCostFunctionImageSource_hxx
#define __itktubeSingleValuedCostFunctionImageSource_hxx
#include "itktubeSingleValuedCostFunctionImageSource.h"
#include <itkImageRegionIteratorWithIndex.h>
#include <itkProgressReporter.h>
namespace itk
{
namespace tube
{
template< class TCostFunction, unsigned int VNumberOfParameters >
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SingleValuedCostFunctionImageSource():
m_ParametersLowerBound( NumberOfParameters ),
m_ParametersUpperBound( NumberOfParameters ),
m_ParametersStep( NumberOfParameters )
{
this->m_ParametersLowerBound.Fill( 0.0 );
this->m_ParametersUpperBound.Fill( 10.0 );
this->m_ParametersStep.Fill( 1.0 );
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersLowerBound( const ParametersType & lowerBound )
{
const SizeValueType lowerBoundSize = lowerBound.GetSize();
if( lowerBoundSize != NumberOfParameters )
{
itkExceptionMacro( << "The ParametersLowerBound size: " << lowerBoundSize
<< " does not equal the expected number of parameters: " << NumberOfParameters
<< std::endl );
}
for( SizeValueType ii = 0; ii < lowerBoundSize; ++ii )
{
if( this->m_ParametersLowerBound[ii] != lowerBound[ii] )
{
this->m_ParametersLowerBound = lowerBound;
this->Modified();
break;
}
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersLowerBound() const
{
return this->m_ParametersLowerBound;
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersUpperBound( const ParametersType & upperBound )
{
const SizeValueType upperBoundSize = upperBound.GetSize();
if( upperBoundSize != NumberOfParameters )
{
itkExceptionMacro( << "The ParametersUpperBound size: " << upperBoundSize
<< " does not equal the expected number of parameters: " << NumberOfParameters
<< std::endl );
}
for( SizeValueType ii = 0; ii < upperBoundSize; ++ii )
{
if( this->m_ParametersUpperBound[ii] != upperBound[ii] )
{
this->m_ParametersUpperBound = upperBound;
this->Modified();
break;
}
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersUpperBound() const
{
return this->m_ParametersUpperBound;
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersStep( const ParametersType & step )
{
const SizeValueType stepSize = step.GetSize();
if( stepSize != NumberOfParameters )
{
itkExceptionMacro( << "The ParametersStep size: " << stepSize
<< " does not equal the expected number of parameters: " << NumberOfParameters
<< std::endl );
}
for( SizeValueType ii = 0; ii < stepSize; ++ii )
{
if( this->m_ParametersStep[ii] != step[ii] )
{
this->m_ParametersStep = step;
this->Modified();
break;
}
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersStep() const
{
return this->m_ParametersStep;
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
OutputImageType * outputImage = this->GetOutput();
typename OutputImageType::IndexType index;
index.Fill( 0 );
typename OutputImageType::SizeType size;
typename OutputImageType::PointType origin;
typename OutputImageType::SpacingType spacing;
for( unsigned int ii = 0; ii < NumberOfParameters; ++ii )
{
origin[ii] = this->m_ParametersLowerBound[ii];
spacing[ii] = this->m_ParametersStep[ii];
size[ii] = static_cast< SizeValueType >( (this->m_ParametersUpperBound[ii] - this->m_ParametersLowerBound[ii]) /
this->m_ParametersStep[ii] ) + 1;
}
typename OutputImageType::RegionType region;
region.SetIndex( index );
region.SetSize( size );
outputImage->SetLargestPossibleRegion( region );
outputImage->SetSpacing( spacing );
outputImage->SetOrigin( origin );
typename OutputImageType::DirectionType direction;
direction.SetIdentity();
outputImage->SetDirection( direction );
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::BeforeThreadedGenerateData()
{
if( this->m_CostFunction.IsNull() )
{
itkExceptionMacro( << "Cost function must be assigned!" );
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )
{
OutputImageType * outputImage = this->GetOutput(0);
ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );
typedef ImageRegionIteratorWithIndex< OutputImageType > ImageIteratorType;
ImageIteratorType imageIt( outputImage, outputRegionForThread );
for( imageIt.GoToBegin(); !imageIt.IsAtEnd(); ++imageIt )
{
const typename OutputImageType::IndexType index = imageIt.GetIndex();
typename OutputImageType::PointType point;
outputImage->TransformIndexToPhysicalPoint( index, point );
ParametersType parameters( NumberOfParameters );
parameters.SetData( point.GetDataPointer() );
const MeasureType measure = this->m_CostFunction->GetValue( parameters );
imageIt.Set( measure );
progress.CompletedPixel();
}
}
} // End namespace tube
} // End namespace itk
#endif // End !defined(__itktubeSingleValuedCostFunctionImageSource_hxx)
<commit_msg>ENH: Output cast in SingleValuedCostFunctionImageSource.<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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.
=========================================================================*/
#ifndef __itktubeSingleValuedCostFunctionImageSource_hxx
#define __itktubeSingleValuedCostFunctionImageSource_hxx
#include "itktubeSingleValuedCostFunctionImageSource.h"
#include <itkImageRegionIteratorWithIndex.h>
#include <itkProgressReporter.h>
namespace itk
{
namespace tube
{
template< class TCostFunction, unsigned int VNumberOfParameters >
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SingleValuedCostFunctionImageSource():
m_ParametersLowerBound( NumberOfParameters ),
m_ParametersUpperBound( NumberOfParameters ),
m_ParametersStep( NumberOfParameters )
{
this->m_ParametersLowerBound.Fill( 0.0 );
this->m_ParametersUpperBound.Fill( 10.0 );
this->m_ParametersStep.Fill( 1.0 );
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersLowerBound( const ParametersType & lowerBound )
{
const SizeValueType lowerBoundSize = lowerBound.GetSize();
if( lowerBoundSize != NumberOfParameters )
{
itkExceptionMacro( << "The ParametersLowerBound size: " << lowerBoundSize
<< " does not equal the expected number of parameters: " << NumberOfParameters
<< std::endl );
}
for( SizeValueType ii = 0; ii < lowerBoundSize; ++ii )
{
if( this->m_ParametersLowerBound[ii] != lowerBound[ii] )
{
this->m_ParametersLowerBound = lowerBound;
this->Modified();
break;
}
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersLowerBound() const
{
return this->m_ParametersLowerBound;
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersUpperBound( const ParametersType & upperBound )
{
const SizeValueType upperBoundSize = upperBound.GetSize();
if( upperBoundSize != NumberOfParameters )
{
itkExceptionMacro( << "The ParametersUpperBound size: " << upperBoundSize
<< " does not equal the expected number of parameters: " << NumberOfParameters
<< std::endl );
}
for( SizeValueType ii = 0; ii < upperBoundSize; ++ii )
{
if( this->m_ParametersUpperBound[ii] != upperBound[ii] )
{
this->m_ParametersUpperBound = upperBound;
this->Modified();
break;
}
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersUpperBound() const
{
return this->m_ParametersUpperBound;
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::SetParametersStep( const ParametersType & step )
{
const SizeValueType stepSize = step.GetSize();
if( stepSize != NumberOfParameters )
{
itkExceptionMacro( << "The ParametersStep size: " << stepSize
<< " does not equal the expected number of parameters: " << NumberOfParameters
<< std::endl );
}
for( SizeValueType ii = 0; ii < stepSize; ++ii )
{
if( this->m_ParametersStep[ii] != step[ii] )
{
this->m_ParametersStep = step;
this->Modified();
break;
}
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
typename SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >::ParametersType
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GetParametersStep() const
{
return this->m_ParametersStep;
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
OutputImageType * outputImage = this->GetOutput();
typename OutputImageType::IndexType index;
index.Fill( 0 );
typename OutputImageType::SizeType size;
typename OutputImageType::PointType origin;
typename OutputImageType::SpacingType spacing;
for( unsigned int ii = 0; ii < NumberOfParameters; ++ii )
{
origin[ii] = this->m_ParametersLowerBound[ii];
spacing[ii] = this->m_ParametersStep[ii];
size[ii] = static_cast< SizeValueType >( (this->m_ParametersUpperBound[ii] - this->m_ParametersLowerBound[ii]) /
this->m_ParametersStep[ii] ) + 1;
}
typename OutputImageType::RegionType region;
region.SetIndex( index );
region.SetSize( size );
outputImage->SetLargestPossibleRegion( region );
outputImage->SetSpacing( spacing );
outputImage->SetOrigin( origin );
typename OutputImageType::DirectionType direction;
direction.SetIdentity();
outputImage->SetDirection( direction );
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::BeforeThreadedGenerateData()
{
if( this->m_CostFunction.IsNull() )
{
itkExceptionMacro( << "Cost function must be assigned!" );
}
}
template< class TCostFunction, unsigned int VNumberOfParameters >
void
SingleValuedCostFunctionImageSource< TCostFunction, VNumberOfParameters >
::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId )
{
OutputImageType * outputImage = this->GetOutput(0);
ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() );
typedef ImageRegionIteratorWithIndex< OutputImageType > ImageIteratorType;
ImageIteratorType imageIt( outputImage, outputRegionForThread );
for( imageIt.GoToBegin(); !imageIt.IsAtEnd(); ++imageIt )
{
const typename OutputImageType::IndexType index = imageIt.GetIndex();
typename OutputImageType::PointType point;
outputImage->TransformIndexToPhysicalPoint( index, point );
ParametersType parameters( NumberOfParameters );
parameters.SetData( point.GetDataPointer() );
const MeasureType measure = this->m_CostFunction->GetValue( parameters );
imageIt.Set( static_cast< typename OutputImageType::PixelType >( measure ) );
progress.CompletedPixel();
}
}
} // End namespace tube
} // End namespace itk
#endif // End !defined(__itktubeSingleValuedCostFunctionImageSource_hxx)
<|endoftext|> |
<commit_before>/*
*
* XMLFileReporter.cpp
*
* Copyright 2000 Lotus Development Corporation. All rights reserved.
* This software is subject to the Lotus Software Agreement, Restricted
* Rights for U.S. government users and applicable export regulations.
*/
#include <stdlib.h>
#include "XMLFileReporter.hpp"
#include "PlatformSupport/XalanUnicode.hpp"
const XalanDOMString XMLFileReporter::OPT_FILENAME("filename");
const XalanDOMString XMLFileReporter::ELEM_RESULTSFILE("resultsfile");
const XalanDOMString XMLFileReporter::ELEM_TESTFILE("testfile");
const XalanDOMString XMLFileReporter::ELEM_FILERESULT("fileresult");
const XalanDOMString XMLFileReporter::ELEM_TESTCASE("testcase");
const XalanDOMString XMLFileReporter::ELEM_CASERESULT("caseresult");
const XalanDOMString XMLFileReporter::ELEM_CHECKRESULT("checkresult");
const XalanDOMString XMLFileReporter::ELEM_STATISTIC("statistic");
const XalanDOMString XMLFileReporter::ELEM_LONGVAL("longval");
const XalanDOMString XMLFileReporter::ELEM_DOUBLEVAL("doubleval");
const XalanDOMString XMLFileReporter::ELEM_MESSAGE("message");
const XalanDOMString XMLFileReporter::ELEM_ARBITRARY("arbitrary");
const XalanDOMString XMLFileReporter::ELEM_HASHTABLE("hashtable");
const XalanDOMString XMLFileReporter::ELEM_HASHITEM("hashitem");
const XalanDOMString XMLFileReporter::ATTR_LEVEL("level");
const XalanDOMString XMLFileReporter::ATTR_DESC("desc");
const XalanDOMString XMLFileReporter::ATTR_TIME("time");
const XalanDOMString XMLFileReporter::ATTR_RESULT("result");
const XalanDOMString XMLFileReporter::ATTR_KEY("key");
const XalanDOMString XMLFileReporter::ATTR_FILENAME = XMLFileReporter::OPT_FILENAME;
const XalanDOMString XMLFileReporter::TESTCASEINIT_HDR("<" + ELEM_TESTCASE + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::TESTCASECLOSE_HDR("<" + ELEM_CASERESULT + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::MESSAGE_HDR("<" + ELEM_MESSAGE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::STATISTIC_HDR("<" + ELEM_STATISTIC + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::ARBITRARY_HDR("<" + ELEM_ARBITRARY + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHTABLE_HDR("<" + ELEM_HASHTABLE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHITEM_HDR(" <" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"");
const XalanDOMString XMLFileReporter::CHECKPASS_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "PASS" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKAMBG_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "AMBG" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKERRR_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "ERRR" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKFAIL_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "FAIL" + "\" " + ATTR_DESC + "=\"");
XMLFileReporter::XMLFileReporter():
m_anyOutput(false),
m_fileName(""),
m_fileHandle(0),
m_ready(false),
m_error(false),
m_flushOnCaseClose(true)
{
}
XMLFileReporter::XMLFileReporter(const XalanDOMString& fileName):
m_anyOutput(false),
m_fileName(fileName),
m_fileHandle(0),
m_ready(false),
m_error(false),
m_flushOnCaseClose(true)
{
m_ready = initialize();
}
XMLFileReporter::XMLFileReporter(const char* fileName):
m_anyOutput(false),
m_fileName(XalanDOMString(fileName)),
m_fileHandle(0),
m_ready(false),
m_error(false),
m_flushOnCaseClose(true)
{
m_ready = initialize();
}
bool
XMLFileReporter::initialize()
{
if (length(m_fileName) == 0)
{
// We don't have a valid file, so bail
m_error = true;
m_ready = false;
fprintf(stderr, "XMLFileReporter.initialize() ERROR: file name is blank");
return(false);
}
// Create a file and ensure it has a place to live
m_fileHandle = fopen(&m_fileName.transcode().front(), "w");
if (m_fileHandle == 0)
{
// Couldn't create or find the directory for the file to live in, so bail
m_error = true;
m_ready = false;
fprintf(stderr, "XMLFileReporter.initialize() ERROR: unble to open file, %s", m_fileName);
return(false);
}
m_ready = true;
startResultsFile();
// fprintf(stderr, "DEBUG:XMLFileReporter.initialize() complete with " + fileName);
return m_ready;
}
bool
XMLFileReporter::getFlushOnCaseClose()
{
return(m_flushOnCaseClose);
}
const XalanDOMString&
XMLFileReporter::getFileName() const
{
return(m_fileName);
}
void
XMLFileReporter::setFileName(const XalanDOMString& fileName)
{
m_fileName = fileName;
}
bool
XMLFileReporter::checkError()
{
// Ensure our underlying reporter, if one, is still OK
if (m_fileHandle == 0)
{
m_error = true;
}
return(m_error);
}
bool
XMLFileReporter::isReady()
{
// Ensure our underlying reporter, if one, is still OK
if (m_fileHandle == 0)
{
// NEEDSWORK: should we set m_ready = false in this case?
// errors in the PrintStream are not necessarily fatal
m_error = true;
m_ready = false;
}
return(m_ready);
}
void
XMLFileReporter::flush()
{
if (isReady())
{
fflush(m_fileHandle);
}
}
void
XMLFileReporter::close()
{
fflush(m_fileHandle);
if (isReady())
{
if (m_fileHandle != 0)
{
closeResultsFile();
fclose(m_fileHandle);
}
}
m_ready = false;
}
void
XMLFileReporter::logTestFileInit(const XalanDOMString& msg)
{
if (isReady())
{
printToFile("<" + ELEM_TESTFILE
+ " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\">");
}
}
void
XMLFileReporter::logTestFileClose(const XalanDOMString& msg, const XalanDOMString& result)
{
if (isReady())
{
printToFile("<" + ELEM_FILERESULT
+ " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\"/>");
printToFile("</" + ELEM_TESTFILE + ">");
}
flush();
}
void
XMLFileReporter::logTestCaseInit(const XalanDOMString& msg)
{
if (isReady())
{
printToFile(TESTCASEINIT_HDR + escapestring(msg) + "\">");
}
}
void
XMLFileReporter::logTestCaseClose(const XalanDOMString& msg, const XalanDOMString& result)
{
if (isReady())
{
printToFile(TESTCASECLOSE_HDR + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\"/>");
printToFile("</" + ELEM_TESTCASE + ">");
}
if (getFlushOnCaseClose())
{
flush();
}
}
void
XMLFileReporter::logMessage(int level, const XalanDOMString& msg)
{
char tmp[20];
sprintf(tmp, "%d", level);
if (isReady())
{
printToFile(MESSAGE_HDR + tmp + "\">");
printToFile(escapestring(msg));
printToFile("</" + ELEM_MESSAGE +">");
}
}
void
XMLFileReporter::logElement(int level, const XalanDOMString& element, Hashtable attrs,const XalanDOMString& msg)
{
if (isReady()
&& (element.empty() == 0)
&& (attrs.empty() == 0)
)
{
char tmp[20];
sprintf(tmp, "%d", level);
printToFile("<" + escapestring(element) + " " + ATTR_LEVEL + "=\""
+ tmp + "\"");
Hashtable::iterator theEnd = attrs.end();
for(Hashtable::iterator i = attrs.begin(); i != theEnd; ++i)
{
printToFile((*i).first + "=\""
+ (*i).second + "\"");
}
printToFile(XalanDOMString(">"));
if (msg.empty() != 0)
printToFile(escapestring(msg));
printToFile("</" + escapestring(element) + ">");
}
}
void
XMLFileReporter::logStatistic (int level, long lVal, double dVal, const XalanDOMString& msg)
{
char tmp[20];
if (isReady())
{
sprintf(tmp, "%d", level);
printToFile(STATISTIC_HDR + tmp + "\" " + ATTR_DESC + "=\"" + escapestring(msg) + "\">");
sprintf(tmp, "%d", lVal);
printToFile("<" + ELEM_LONGVAL + ">" + tmp + "</" + ELEM_LONGVAL + ">");
sprintf(tmp, "%d", dVal);
printToFile("<" + ELEM_DOUBLEVAL + ">" + tmp + "</" + ELEM_DOUBLEVAL + ">");
printToFile("</" + ELEM_STATISTIC + ">");
}
}
void
XMLFileReporter::logArbitraryMessage (int level, const XalanDOMString& msg)
{
char tmp[20];
sprintf(tmp, "%d", level);
if (isReady())
{
printToFile(ARBITRARY_HDR + tmp + "\">");
printToFile(escapestring(msg));
printToFile("</" + ELEM_ARBITRARY +">");
}
}
/*
void logHashtable (int level, Hashtable hash, XalanDOMString msg)
{
if (isReady())
{
printToFile(HASHTABLE_HDR + level + "\" " + ATTR_DESC + "=\"" + msg + "\">");
if (hash == null)
{
printToFile("<" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"null\">");
printToFile("</" + ELEM_HASHITEM + ">");
}
try
{
for (Enumeration enum = hash.keys(); enum.hasMoreElements();)
{
Object key = enum.nextElement();
// Ensure we'll have clean output by pre-fetching value before outputting anything
XalanDOMString value = hash.get(key).tostring();
printToFile(HASHITEM_HDR + key.tostring() + "\">");
printToFile(value);
printToFile("</" + ELEM_HASHITEM + ">");
}
}
catch (Exception e)
{
// No-op: should ensure we have clean output
}
printToFile("</" + ELEM_HASHTABLE +">");
}
}
*/
void
XMLFileReporter::logCheckPass(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKPASS_HDR + escapestring(comment) + "\"/>");
}
}
void
XMLFileReporter::logCheckAmbiguous(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKAMBG_HDR + escapestring(comment) + "\"/>");
}
}
void
XMLFileReporter::logCheckFail(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKFAIL_HDR + escapestring(comment) + "\"/>");
}
}
void
XMLFileReporter::logCheckErr(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKERRR_HDR + escapestring(comment) + "\"/>");
}
}
static const XalanDOMChar theLessThanString[] =
{
XalanUnicode::charAmpersand,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_t,
XalanUnicode::charSemicolon,
0
};
static const XalanDOMChar theGreaterThanString[] =
{
XalanUnicode::charAmpersand,
XalanUnicode::charLetter_g,
XalanUnicode::charLetter_t,
XalanUnicode::charSemicolon,
0
};
XalanDOMString
XMLFileReporter::escapestring(const XalanDOMString& s)
{
XalanDOMString sb;
const unsigned int length = s.length();
for (unsigned int i = 0; i < length; i++)
{
const XalanDOMChar ch = charAt(s, i);
if (XalanUnicode::charLessThanSign == ch)
{
append(sb, theLessThanString);
}
else if (XalanUnicode::charGreaterThanSign == ch)
{
append(sb, theGreaterThanString);
}
// Note: Skipping escaping of UTF-16 surrogates and & ampersands, since
// I don't think we'll be outputting them or they won't affect our output
else
{
append(sb, ch);
}
}
return sb;
}
bool
XMLFileReporter::startResultsFile()
{
if (isReady())
{
// Write out XML header and root test result element
printToFile(XalanDOMString("<?xml version=\"1.0\"?>"));
// Note: this tag is closed in our .close() method, which the caller had better call!
printToFile("<" + ELEM_RESULTSFILE + " " + ATTR_FILENAME + "=\"" + m_fileName + "\">");
return true;
}
else
{
return false;
}
}
bool
XMLFileReporter::closeResultsFile()
{
if (isReady())
{
printToFile("</" + ELEM_RESULTSFILE + ">");
return true;
}
else
return false;
}
bool
XMLFileReporter::printToFile(const XalanDOMString& output)
{
if (isReady())
{
fprintf(m_fileHandle, &output.transcode().front());
fprintf(m_fileHandle, "\n");
return true;
}
else
return false;
}
XalanDOMString
XMLFileReporter::getDateTimeString()
{
struct tm *tmNow;
time_t time_tNow;
time(&time_tNow);
tmNow = localtime(&time_tNow);
const char* const theTime = asctime(tmNow);
return XalanDOMString(theTime, strlen(theTime) - 1);
}
<commit_msg>Removed Level attribute from logElement method<commit_after>/*
*
* XMLFileReporter.cpp
*
* Copyright 2000 Lotus Development Corporation. All rights reserved.
* This software is subject to the Lotus Software Agreement, Restricted
* Rights for U.S. government users and applicable export regulations.
*/
#include <stdlib.h>
#include "XMLFileReporter.hpp"
#include "PlatformSupport/XalanUnicode.hpp"
const XalanDOMString XMLFileReporter::OPT_FILENAME("filename");
const XalanDOMString XMLFileReporter::ELEM_RESULTSFILE("resultsfile");
const XalanDOMString XMLFileReporter::ELEM_TESTFILE("testfile");
const XalanDOMString XMLFileReporter::ELEM_FILERESULT("fileresult");
const XalanDOMString XMLFileReporter::ELEM_TESTCASE("testcase");
const XalanDOMString XMLFileReporter::ELEM_CASERESULT("caseresult");
const XalanDOMString XMLFileReporter::ELEM_CHECKRESULT("checkresult");
const XalanDOMString XMLFileReporter::ELEM_STATISTIC("statistic");
const XalanDOMString XMLFileReporter::ELEM_LONGVAL("longval");
const XalanDOMString XMLFileReporter::ELEM_DOUBLEVAL("doubleval");
const XalanDOMString XMLFileReporter::ELEM_MESSAGE("message");
const XalanDOMString XMLFileReporter::ELEM_ARBITRARY("arbitrary");
const XalanDOMString XMLFileReporter::ELEM_HASHTABLE("hashtable");
const XalanDOMString XMLFileReporter::ELEM_HASHITEM("hashitem");
const XalanDOMString XMLFileReporter::ATTR_LEVEL("level");
const XalanDOMString XMLFileReporter::ATTR_DESC("desc");
const XalanDOMString XMLFileReporter::ATTR_TIME("time");
const XalanDOMString XMLFileReporter::ATTR_RESULT("result");
const XalanDOMString XMLFileReporter::ATTR_KEY("key");
const XalanDOMString XMLFileReporter::ATTR_FILENAME = XMLFileReporter::OPT_FILENAME;
const XalanDOMString XMLFileReporter::TESTCASEINIT_HDR("<" + ELEM_TESTCASE + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::TESTCASECLOSE_HDR("<" + ELEM_CASERESULT + " " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::MESSAGE_HDR("<" + ELEM_MESSAGE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::STATISTIC_HDR("<" + ELEM_STATISTIC + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::ARBITRARY_HDR("<" + ELEM_ARBITRARY + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHTABLE_HDR("<" + ELEM_HASHTABLE + " " + ATTR_LEVEL + "=\"");
const XalanDOMString XMLFileReporter::HASHITEM_HDR(" <" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"");
const XalanDOMString XMLFileReporter::CHECKPASS_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "PASS" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKAMBG_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "AMBG" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKERRR_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "ERRR" + "\" " + ATTR_DESC + "=\"");
const XalanDOMString XMLFileReporter::CHECKFAIL_HDR("<" + ELEM_CHECKRESULT + " " + ATTR_RESULT + "=\"" + "FAIL" + "\" " + ATTR_DESC + "=\"");
XMLFileReporter::XMLFileReporter():
m_anyOutput(false),
m_fileName(""),
m_fileHandle(0),
m_ready(false),
m_error(false),
m_flushOnCaseClose(true)
{
}
XMLFileReporter::XMLFileReporter(const XalanDOMString& fileName):
m_anyOutput(false),
m_fileName(fileName),
m_fileHandle(0),
m_ready(false),
m_error(false),
m_flushOnCaseClose(true)
{
m_ready = initialize();
}
XMLFileReporter::XMLFileReporter(const char* fileName):
m_anyOutput(false),
m_fileName(XalanDOMString(fileName)),
m_fileHandle(0),
m_ready(false),
m_error(false),
m_flushOnCaseClose(true)
{
m_ready = initialize();
}
bool
XMLFileReporter::initialize()
{
if (length(m_fileName) == 0)
{
// We don't have a valid file, so bail
m_error = true;
m_ready = false;
fprintf(stderr, "XMLFileReporter.initialize() ERROR: file name is blank");
return(false);
}
// Create a file and ensure it has a place to live
m_fileHandle = fopen(&m_fileName.transcode().front(), "w");
if (m_fileHandle == 0)
{
// Couldn't create or find the directory for the file to live in, so bail
m_error = true;
m_ready = false;
fprintf(stderr, "XMLFileReporter.initialize() ERROR: unble to open file, %s", m_fileName);
return(false);
}
m_ready = true;
startResultsFile();
// fprintf(stderr, "DEBUG:XMLFileReporter.initialize() complete with " + fileName);
return m_ready;
}
bool
XMLFileReporter::getFlushOnCaseClose()
{
return(m_flushOnCaseClose);
}
const XalanDOMString&
XMLFileReporter::getFileName() const
{
return(m_fileName);
}
void
XMLFileReporter::setFileName(const XalanDOMString& fileName)
{
m_fileName = fileName;
}
bool
XMLFileReporter::checkError()
{
// Ensure our underlying reporter, if one, is still OK
if (m_fileHandle == 0)
{
m_error = true;
}
return(m_error);
}
bool
XMLFileReporter::isReady()
{
// Ensure our underlying reporter, if one, is still OK
if (m_fileHandle == 0)
{
// NEEDSWORK: should we set m_ready = false in this case?
// errors in the PrintStream are not necessarily fatal
m_error = true;
m_ready = false;
}
return(m_ready);
}
void
XMLFileReporter::flush()
{
if (isReady())
{
fflush(m_fileHandle);
}
}
void
XMLFileReporter::close()
{
fflush(m_fileHandle);
if (isReady())
{
if (m_fileHandle != 0)
{
closeResultsFile();
fclose(m_fileHandle);
}
}
m_ready = false;
}
void
XMLFileReporter::logTestFileInit(const XalanDOMString& msg)
{
if (isReady())
{
printToFile("<" + ELEM_TESTFILE
+ " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\">");
}
}
void
XMLFileReporter::logTestFileClose(const XalanDOMString& msg, const XalanDOMString& result)
{
if (isReady())
{
printToFile("<" + ELEM_FILERESULT
+ " " + ATTR_DESC + "=\"" + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\" " + ATTR_TIME + "=\"" + getDateTimeString() + "\"/>");
printToFile("</" + ELEM_TESTFILE + ">");
}
flush();
}
void
XMLFileReporter::logTestCaseInit(const XalanDOMString& msg)
{
if (isReady())
{
printToFile(TESTCASEINIT_HDR + escapestring(msg) + "\">");
}
}
void
XMLFileReporter::logTestCaseClose(const XalanDOMString& msg, const XalanDOMString& result)
{
if (isReady())
{
printToFile(TESTCASECLOSE_HDR + escapestring(msg) + "\" " + ATTR_RESULT + "=\"" + result + "\"/>");
printToFile("</" + ELEM_TESTCASE + ">");
}
if (getFlushOnCaseClose())
{
flush();
}
}
void
XMLFileReporter::logMessage(int level, const XalanDOMString& msg)
{
char tmp[20];
sprintf(tmp, "%d", level);
if (isReady())
{
printToFile(MESSAGE_HDR + tmp + "\">");
printToFile(escapestring(msg));
printToFile("</" + ELEM_MESSAGE +">");
}
}
void
XMLFileReporter::logElement(int level, const XalanDOMString& element, Hashtable attrs,const XalanDOMString& msg)
{
if (isReady()
&& (element.empty() == 0)
&& (attrs.empty() == 0)
)
{
char tmp[20];
sprintf(tmp, "%d", level);
//
// Took out this level attribute cuz we don't use it.
// printToFile("<" + escapestring(element) + " " + ATTR_LEVEL + "=\""
// + tmp + "\"");
printToFile("<" + escapestring(element) + " ");
Hashtable::iterator theEnd = attrs.end();
for(Hashtable::iterator i = attrs.begin(); i != theEnd; ++i)
{
printToFile((*i).first + "=\""
+ (*i).second + "\"");
}
printToFile(XalanDOMString(">"));
if (msg.empty() != 0)
printToFile(escapestring(msg));
printToFile("</" + escapestring(element) + ">");
}
}
void
XMLFileReporter::logStatistic (int level, long lVal, double dVal, const XalanDOMString& msg)
{
char tmp[20];
if (isReady())
{
sprintf(tmp, "%d", level);
printToFile(STATISTIC_HDR + tmp + "\" " + ATTR_DESC + "=\"" + escapestring(msg) + "\">");
sprintf(tmp, "%d", lVal);
printToFile("<" + ELEM_LONGVAL + ">" + tmp + "</" + ELEM_LONGVAL + ">");
sprintf(tmp, "%d", dVal);
printToFile("<" + ELEM_DOUBLEVAL + ">" + tmp + "</" + ELEM_DOUBLEVAL + ">");
printToFile("</" + ELEM_STATISTIC + ">");
}
}
void
XMLFileReporter::logArbitraryMessage (int level, const XalanDOMString& msg)
{
char tmp[20];
sprintf(tmp, "%d", level);
if (isReady())
{
printToFile(ARBITRARY_HDR + tmp + "\">");
printToFile(escapestring(msg));
printToFile("</" + ELEM_ARBITRARY +">");
}
}
/*
void logHashtable (int level, Hashtable hash, XalanDOMString msg)
{
if (isReady())
{
printToFile(HASHTABLE_HDR + level + "\" " + ATTR_DESC + "=\"" + msg + "\">");
if (hash == null)
{
printToFile("<" + ELEM_HASHITEM + " " + ATTR_KEY + "=\"null\">");
printToFile("</" + ELEM_HASHITEM + ">");
}
try
{
for (Enumeration enum = hash.keys(); enum.hasMoreElements();)
{
Object key = enum.nextElement();
// Ensure we'll have clean output by pre-fetching value before outputting anything
XalanDOMString value = hash.get(key).tostring();
printToFile(HASHITEM_HDR + key.tostring() + "\">");
printToFile(value);
printToFile("</" + ELEM_HASHITEM + ">");
}
}
catch (Exception e)
{
// No-op: should ensure we have clean output
}
printToFile("</" + ELEM_HASHTABLE +">");
}
}
*/
void
XMLFileReporter::logCheckPass(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKPASS_HDR + escapestring(comment) + "\"/>");
}
}
void
XMLFileReporter::logCheckAmbiguous(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKAMBG_HDR + escapestring(comment) + "\"/>");
}
}
void
XMLFileReporter::logCheckFail(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKFAIL_HDR + escapestring(comment) + "\"/>");
}
}
void
XMLFileReporter::logCheckErr(const XalanDOMString& comment)
{
if (isReady())
{
printToFile(CHECKERRR_HDR + escapestring(comment) + "\"/>");
}
}
static const XalanDOMChar theLessThanString[] =
{
XalanUnicode::charAmpersand,
XalanUnicode::charLetter_l,
XalanUnicode::charLetter_t,
XalanUnicode::charSemicolon,
0
};
static const XalanDOMChar theGreaterThanString[] =
{
XalanUnicode::charAmpersand,
XalanUnicode::charLetter_g,
XalanUnicode::charLetter_t,
XalanUnicode::charSemicolon,
0
};
XalanDOMString
XMLFileReporter::escapestring(const XalanDOMString& s)
{
XalanDOMString sb;
const unsigned int length = s.length();
for (unsigned int i = 0; i < length; i++)
{
const XalanDOMChar ch = charAt(s, i);
if (XalanUnicode::charLessThanSign == ch)
{
append(sb, theLessThanString);
}
else if (XalanUnicode::charGreaterThanSign == ch)
{
append(sb, theGreaterThanString);
}
// Note: Skipping escaping of UTF-16 surrogates and & ampersands, since
// I don't think we'll be outputting them or they won't affect our output
else
{
append(sb, ch);
}
}
return sb;
}
bool
XMLFileReporter::startResultsFile()
{
if (isReady())
{
// Write out XML header and root test result element
printToFile(XalanDOMString("<?xml version=\"1.0\"?>"));
// Note: this tag is closed in our .close() method, which the caller had better call!
printToFile("<" + ELEM_RESULTSFILE + " " + ATTR_FILENAME + "=\"" + m_fileName + "\">");
return true;
}
else
{
return false;
}
}
bool
XMLFileReporter::closeResultsFile()
{
if (isReady())
{
printToFile("</" + ELEM_RESULTSFILE + ">");
return true;
}
else
return false;
}
bool
XMLFileReporter::printToFile(const XalanDOMString& output)
{
if (isReady())
{
fprintf(m_fileHandle, &output.transcode().front());
fprintf(m_fileHandle, "\n");
return true;
}
else
return false;
}
XalanDOMString
XMLFileReporter::getDateTimeString()
{
struct tm *tmNow;
time_t time_tNow;
time(&time_tNow);
tmNow = localtime(&time_tNow);
const char* const theTime = asctime(tmNow);
return XalanDOMString(theTime, strlen(theTime) - 1);
}
<|endoftext|> |
<commit_before>/*
* 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.
*/
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif
#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>
#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"
XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)
/**
* Processor interface options
*/
struct ProcessorOptions
{
XalanNode* initOptions;
XalanNode* compileOptions;
XalanNode* parseOptions;
XalanNode* resultOptions;
XalanNode* transformOptions;
ProcessorOptions() :
initOptions(0),
compileOptions(0),
parseOptions(0),
resultOptions(0),
transformOptions(0)
{
}
};
/**
* Test case
*/
class TestCase
{
public:
TestCase();
TestCase(const TestCase& theRhs);
XalanDOMString stylesheet;
XalanDOMString inputDocument;
XalanDOMString resultDocument;
XalanDOMString resultDirectory;
XalanDOMString goldResult;
long numIterations;
long minTimeToExecute;
bool verifyResult;
XalanDOMString inputMode;
typedef XalanMap<XalanDOMString, ProcessorOptions> ProcessorOptionsMap;
ProcessorOptionsMap processorOptions;
};
typedef TestCase TestCaseType;
typedef XalanVector<TestCaseType> TestCasesType;
/**
* Test harness
*/
template <class Processor>
class TestHarness
{
public:
typedef typename Processor::CompiledStylesheetType CompiledStylesheetType;
typedef typename Processor::ParsedInputSourceType ParsedInputSourceType;
typedef typename Processor::ResultTargetType ResultTargetType;
typedef typename XalanXMLFileReporter::Hashtable TestAttributesType;
TestHarness();
void init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger);
void terminate();
void executeTestCase(const TestCaseType& testCase);
void executeTestCases(const TestCasesType& testCases);
protected:
Processor m_processor;
XalanFileUtility* m_fileUtility;
XalanXMLFileReporter* m_reporter;
Logger* m_logger;
};
template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
TestCasesType::const_iterator testCaseIter = testCases.begin();
while (testCaseIter != testCases.end())
{
executeTestCase(*testCaseIter);
++testCaseIter;
}
}
template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));
try {
CompiledStylesheetType compiledStylesheet;
ParsedInputSourceType parsedInputSource;
ResultTargetType resultTarget;
static const ProcessorOptions defaultProcessor;
TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());
const ProcessorOptions& processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;
m_fileUtility->checkAndCreateDir(testCase.resultDirectory);
Timer timeCompile;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.stylesheet, buffer);
istrstream compilerStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream compilerStream;
fileToStream(testCase.stylesheet, compilerStream);
#endif
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
compilerStream,
processor.compileOptions);
timeCompile.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
testCase.stylesheet,
processor.compileOptions);
timeCompile.stop();
}
else
{
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for stylesheet: "
<< testCase.stylesheet
<< endl;
}
m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);
long numIterations = 0;
long totalParseInputTime = 0;
long minParseInputTime = LONG_MAX;
long maxParseInputTime = 0 ;
long totalTransformTime = 0;
long minTransformTime = LONG_MAX;
long maxTransformTime = 0;
Timer timeTotalRun;
timeTotalRun.start();
while (numIterations < testCase.numIterations
&& timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
{
Timer timeInput;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.inputDocument, buffer);
istrstream inputStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream inputStream;
fileToStream(testCase.inputDocument, inputStream);
#endif
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
inputStream,
processor.parseOptions);
timeInput.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
testCase.inputDocument,
processor.parseOptions);
timeInput.stop();
}
else
{
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for input document: "
<< testCase.inputDocument
<< endl;
}
totalParseInputTime += timeInput.getElapsedTime();
minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;
resultTarget = m_processor.createResultTarget(
testCase.resultDocument,
processor.resultOptions);
Timer timeTransform;
timeTransform.start();
m_processor.transform(
compiledStylesheet,
parsedInputSource,
resultTarget);
timeTransform.stop();
totalTransformTime += timeTransform.getElapsedTime();
minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;
++numIterations;
}
timeTotalRun.stop();
m_processor.releaseStylesheet(compiledStylesheet);
m_processor.releaseInputSource(parsedInputSource);
m_processor.releaseResultTarget(resultTarget);
if (true == testCase.verifyResult)
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
if (checkFileExists(testCase.resultDocument))
{
if (checkFileExists(testCase.goldResult))
{
if (m_fileUtility->compareSerializedResults(
testCase.resultDocument,
testCase.goldResult))
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
}
m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));
}
catch (XalanDOMString exception)
{
m_logger->error()
<< "Error encountered during transformation: "
<< testCase.stylesheet.c_str()
<< ", error: "
<< exception.c_str()
<< endl;
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
}
m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}
template <class Processor>
TestHarness<Processor>::TestHarness()
{
}
template <class Processor>
void
TestHarness<Processor>::init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger)
{
m_processor.init();
m_fileUtility = &fileUtility;
m_reporter = &reporter;
m_logger = &logger;
}
template <class Processor>
void
TestHarness<Processor>::terminate()
{
m_processor.terminate();
}
#endif // TESTHARNESS_HEADER_GUARD_1357924680
<commit_msg>Patch for Jira issue XALANC-660.<commit_after>/*
* 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.
*/
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif
#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>
#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"
XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)
/**
* Processor interface options
*/
struct ProcessorOptions
{
XalanNode* initOptions;
XalanNode* compileOptions;
XalanNode* parseOptions;
XalanNode* resultOptions;
XalanNode* transformOptions;
ProcessorOptions() :
initOptions(0),
compileOptions(0),
parseOptions(0),
resultOptions(0),
transformOptions(0)
{
}
};
/**
* Test case
*/
class TestCase
{
public:
TestCase();
TestCase(const TestCase& theRhs);
XalanDOMString stylesheet;
XalanDOMString inputDocument;
XalanDOMString resultDocument;
XalanDOMString resultDirectory;
XalanDOMString goldResult;
long numIterations;
long minTimeToExecute;
bool verifyResult;
XalanDOMString inputMode;
typedef XalanMap<XalanDOMString, ProcessorOptions> ProcessorOptionsMap;
ProcessorOptionsMap processorOptions;
};
typedef TestCase TestCaseType;
typedef XalanVector<TestCaseType> TestCasesType;
/**
* Test harness
*/
template <class Processor>
class TestHarness
{
public:
typedef typename Processor::CompiledStylesheetType CompiledStylesheetType;
typedef typename Processor::ParsedInputSourceType ParsedInputSourceType;
typedef typename Processor::ResultTargetType ResultTargetType;
typedef typename XalanXMLFileReporter::Hashtable TestAttributesType;
TestHarness();
void init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger);
void terminate();
void executeTestCase(const TestCaseType& testCase);
void executeTestCases(const TestCasesType& testCases);
protected:
Processor m_processor;
XalanFileUtility* m_fileUtility;
XalanXMLFileReporter* m_reporter;
Logger* m_logger;
};
template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
TestCasesType::const_iterator testCaseIter = testCases.begin();
while (testCaseIter != testCases.end())
{
executeTestCase(*testCaseIter);
++testCaseIter;
}
}
template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));
try {
CompiledStylesheetType compiledStylesheet;
ParsedInputSourceType parsedInputSource;
ResultTargetType resultTarget;
static const ProcessorOptions defaultProcessor;
TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());
const ProcessorOptions& processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;
m_fileUtility->checkAndCreateDir(testCase.resultDirectory);
Timer timeCompile;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.stylesheet, buffer);
istrstream compilerStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream compilerStream;
fileToStream(testCase.stylesheet, compilerStream);
#endif
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
compilerStream,
processor.compileOptions);
timeCompile.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
testCase.stylesheet,
processor.compileOptions);
timeCompile.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for stylesheet: "
<< testCase.stylesheet
<< endl;
}
m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);
long numIterations = 0;
long totalParseInputTime = 0;
long minParseInputTime = LONG_MAX;
long maxParseInputTime = 0 ;
long totalTransformTime = 0;
long minTransformTime = LONG_MAX;
long maxTransformTime = 0;
Timer timeTotalRun;
timeTotalRun.start();
while (numIterations < testCase.numIterations
&& timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
{
Timer timeInput;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.inputDocument, buffer);
istrstream inputStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream inputStream;
fileToStream(testCase.inputDocument, inputStream);
#endif
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
inputStream,
processor.parseOptions);
timeInput.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
testCase.inputDocument,
processor.parseOptions);
timeInput.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for input document: "
<< testCase.inputDocument
<< endl;
}
totalParseInputTime += timeInput.getElapsedTime();
minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;
resultTarget = m_processor.createResultTarget(
testCase.resultDocument,
processor.resultOptions);
Timer timeTransform;
timeTransform.start();
m_processor.transform(
compiledStylesheet,
parsedInputSource,
resultTarget);
timeTransform.stop();
totalTransformTime += timeTransform.getElapsedTime();
minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;
++numIterations;
}
timeTotalRun.stop();
m_processor.releaseStylesheet(compiledStylesheet);
m_processor.releaseInputSource(parsedInputSource);
m_processor.releaseResultTarget(resultTarget);
if (true == testCase.verifyResult)
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
if (checkFileExists(testCase.resultDocument))
{
if (checkFileExists(testCase.goldResult))
{
if (m_fileUtility->compareSerializedResults(
testCase.resultDocument,
testCase.goldResult))
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
}
m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));
}
catch (const XalanDOMString& exception)
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Error encountered during transformation: "
<< testCase.stylesheet.c_str()
<< ", error: "
<< exception.c_str()
<< endl;
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
}
m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}
template <class Processor>
TestHarness<Processor>::TestHarness()
{
}
template <class Processor>
void
TestHarness<Processor>::init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger)
{
m_processor.init();
m_fileUtility = &fileUtility;
m_reporter = &reporter;
m_logger = &logger;
}
template <class Processor>
void
TestHarness<Processor>::terminate()
{
m_processor.terminate();
}
#endif // TESTHARNESS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Transceiver.h"
#include "radioDevice.h"
#include "DummyLoad.h"
#include <time.h>
#include <signal.h>
#include <GSMCommon.h>
#include <Logger.h>
#include <Configuration.h>
#ifdef RESAMPLE
#define DEVICERATE 400e3
#else
#define DEVICERATE 1625e3/6
#endif
using namespace std;
ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");
volatile bool gbShutdown = false;
static void ctrlCHandler(int signo)
{
cout << "Received shutdown signal" << endl;;
gbShutdown = true;
}
int main(int argc, char *argv[])
{
std::string deviceArgs;
if (argc == 3)
{
deviceArgs = std::string(argv[2]);
}
else
{
deviceArgs = "";
}
if ( signal( SIGINT, ctrlCHandler ) == SIG_ERR )
{
cerr << "Couldn't install signal handler for SIGINT" << endl;
exit(1);
}
if ( signal( SIGTERM, ctrlCHandler ) == SIG_ERR )
{
cerr << "Couldn't install signal handler for SIGTERM" << endl;
exit(1);
}
// Configure logger.
gLogInit("transceiver",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);
int numARFCN=1;
LOG(NOTICE) << "starting transceiver with " << numARFCN << " ARFCNs (argc=" << argc << ")";
srandom(time(NULL));
int mOversamplingRate = numARFCN/2 + numARFCN;
RadioDevice *usrp = RadioDevice::make(DEVICERATE * SAMPSPERSYM);
if (!usrp->open(deviceArgs)) {
LOG(ALERT) << "Transceiver exiting..." << std::endl;
return EXIT_FAILURE;
}
RadioInterface* radio = new RadioInterface(usrp,3,SAMPSPERSYM,mOversamplingRate,false);
Transceiver *trx = new Transceiver(5700,"127.0.0.1",SAMPSPERSYM,GSM::Time(3,0),radio);
trx->receiveFIFO(radio->receiveFIFO());
/*
signalVector *gsmPulse = generateGSMPulse(2,1);
BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[0]),normalBurstSeg);
signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
signalVector totalBurst1(*modBurst,*modBurst9);
signalVector totalBurst2(*modBurst,*modBurst);
signalVector totalBurst(totalBurst1,totalBurst2);
scaleVector(totalBurst,usrp->fullScaleInputValue());
double beaconFreq = -1.0*(numARFCN-1)*200e3;
signalVector finalVec(625*mOversamplingRate);
for (int j = 0; j < numARFCN; j++) {
signalVector *frequencyShifter = new signalVector(625*mOversamplingRate);
frequencyShifter->fill(1.0);
frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
signalVector *interpVec = polyphaseResampleVector(totalBurst,mOversamplingRate,1,interpolationFilter);
multVector(*interpVec,*frequencyShifter);
addVector(finalVec,*interpVec);
}
signalVector::iterator itr = finalVec.begin();
short finalVecShort[2*finalVec.size()];
short *shortItr = finalVecShort;
while (itr < finalVec.end()) {
*shortItr++ = (short) (itr->real());
*shortItr++ = (short) (itr->imag());
itr++;
}
usrp->loadBurst(finalVecShort,finalVec.size());
*/
trx->start();
//int i = 0;
while(!gbShutdown) { sleep(1); }//i++; if (i==60) break;}
cout << "Shutting down transceiver..." << endl;
// trx->stop();
delete trx;
// delete radio;
}
<commit_msg>Transceiver52M: Read IP address and port to bind to from a configuration instead of hardcoding them.<commit_after>/*
* Copyright 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright 2010 Kestrel Signal Processing, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Transceiver.h"
#include "radioDevice.h"
#include "DummyLoad.h"
#include <time.h>
#include <signal.h>
#include <GSMCommon.h>
#include <Logger.h>
#include <Configuration.h>
#ifdef RESAMPLE
#define DEVICERATE 400e3
#else
#define DEVICERATE 1625e3/6
#endif
using namespace std;
ConfigurationTable gConfig("/etc/OpenBTS/OpenBTS.db");
volatile bool gbShutdown = false;
static void ctrlCHandler(int signo)
{
cout << "Received shutdown signal" << endl;;
gbShutdown = true;
}
int main(int argc, char *argv[])
{
std::string deviceArgs;
if (argc == 3)
{
deviceArgs = std::string(argv[2]);
}
else
{
deviceArgs = "";
}
if ( signal( SIGINT, ctrlCHandler ) == SIG_ERR )
{
cerr << "Couldn't install signal handler for SIGINT" << endl;
exit(1);
}
if ( signal( SIGTERM, ctrlCHandler ) == SIG_ERR )
{
cerr << "Couldn't install signal handler for SIGTERM" << endl;
exit(1);
}
// Configure logger.
gLogInit("transceiver",gConfig.getStr("Log.Level").c_str(),LOG_LOCAL7);
int numARFCN=1;
LOG(NOTICE) << "starting transceiver with " << numARFCN << " ARFCNs (argc=" << argc << ")";
srandom(time(NULL));
int mOversamplingRate = numARFCN/2 + numARFCN;
RadioDevice *usrp = RadioDevice::make(DEVICERATE * SAMPSPERSYM);
if (!usrp->open(deviceArgs)) {
LOG(ALERT) << "Transceiver exiting..." << std::endl;
return EXIT_FAILURE;
}
RadioInterface* radio = new RadioInterface(usrp,3,SAMPSPERSYM,mOversamplingRate,false);
Transceiver *trx = new Transceiver(gConfig.getNum("TRX.Port"),gConfig.getStr("TRX.IP").c_str(),SAMPSPERSYM,GSM::Time(3,0),radio);
trx->receiveFIFO(radio->receiveFIFO());
/*
signalVector *gsmPulse = generateGSMPulse(2,1);
BitVector normalBurstSeg = "0000101010100111110010101010010110101110011000111001101010000";
BitVector normalBurst(BitVector(normalBurstSeg,gTrainingSequence[0]),normalBurstSeg);
signalVector *modBurst = modulateBurst(normalBurst,*gsmPulse,8,1);
signalVector *modBurst9 = modulateBurst(normalBurst,*gsmPulse,9,1);
signalVector *interpolationFilter = createLPF(0.6/mOversamplingRate,6*mOversamplingRate,1);
signalVector totalBurst1(*modBurst,*modBurst9);
signalVector totalBurst2(*modBurst,*modBurst);
signalVector totalBurst(totalBurst1,totalBurst2);
scaleVector(totalBurst,usrp->fullScaleInputValue());
double beaconFreq = -1.0*(numARFCN-1)*200e3;
signalVector finalVec(625*mOversamplingRate);
for (int j = 0; j < numARFCN; j++) {
signalVector *frequencyShifter = new signalVector(625*mOversamplingRate);
frequencyShifter->fill(1.0);
frequencyShift(frequencyShifter,frequencyShifter,2.0*M_PI*(beaconFreq+j*400e3)/(1625.0e3/6.0*mOversamplingRate));
signalVector *interpVec = polyphaseResampleVector(totalBurst,mOversamplingRate,1,interpolationFilter);
multVector(*interpVec,*frequencyShifter);
addVector(finalVec,*interpVec);
}
signalVector::iterator itr = finalVec.begin();
short finalVecShort[2*finalVec.size()];
short *shortItr = finalVecShort;
while (itr < finalVec.end()) {
*shortItr++ = (short) (itr->real());
*shortItr++ = (short) (itr->imag());
itr++;
}
usrp->loadBurst(finalVecShort,finalVec.size());
*/
trx->start();
//int i = 0;
while(!gbShutdown) { sleep(1); }//i++; if (i==60) break;}
cout << "Shutting down transceiver..." << endl;
// trx->stop();
delete trx;
// delete radio;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* standardpanel.cpp : The "standard" playlist panel : just a treeview
****************************************************************************
* Copyright (C) 2000-2005 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "playlist_model.hpp"
#include "components/playlist/panels.hpp"
#include "util/customwidgets.hpp"
#include <vlc_intf_strings.h>
#include <QTreeView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QModelIndexList>
#include <QToolBar>
#include <QLabel>
#include <QSpacerItem>
#include <QMenu>
#include <assert.h>
StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent,
intf_thread_t *_p_intf,
playlist_t *p_playlist,
playlist_item_t *p_root ):
PLPanel( _parent, _p_intf )
{
model = new PLModel( p_playlist, p_intf, p_root, -1, this );
/* Create and configure the QTreeView */
view = new QVLCTreeView( 0 );
view->setModel(model);
view->setIconSize( QSize(20,20) );
view->setAlternatingRowColors( true );
view->setAnimated( true );
view->setSortingEnabled( true );
view->setSelectionMode( QAbstractItemView::ExtendedSelection );
view->setDragEnabled( true );
view->setAcceptDrops( true );
view->setDropIndicatorShown( true );
view->setAutoScroll( true );
view->header()->resizeSection( 0, 230 );
view->header()->resizeSection( 1, 170 );
view->header()->setSortIndicatorShown( true );
view->header()->setClickable( true );
view->header()->setContextMenuPolicy( Qt::CustomContextMenu );
CONNECT( view, activated( const QModelIndex& ) ,
model,activateItem( const QModelIndex& ) );
CONNECT( view, rightClicked( QModelIndex , QPoint ),
this, doPopup( QModelIndex, QPoint ) );
CONNECT( model, dataChanged( const QModelIndex&, const QModelIndex& ),
this, handleExpansion( const QModelIndex& ) );
CONNECT( view->header(), customContextMenuRequested( const QPoint & ),
this, popupSelectColumn( QPoint ) );
currentRootId = -1;
CONNECT( parent, rootChanged(int), this, setCurrentRootId( int ) );
QVBoxLayout *layout = new QVBoxLayout();
layout->setSpacing( 0 ); layout->setMargin( 0 );
/* Buttons configuration */
QHBoxLayout *buttons = new QHBoxLayout();
addButton = new QPushButton( QIcon( ":/pixmaps/playlist_add.png" ), "", this );
addButton->setMaximumWidth( 25 );
BUTTONACT( addButton, popupAdd() );
buttons->addWidget( addButton );
randomButton = new QPushButton( this );
if( model->hasRandom() )
{
randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_on.png" ));
randomButton->setToolTip( qtr( I_PL_RANDOM ));
}
else
{
randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_off.png" ) );
randomButton->setToolTip( qtr( I_PL_NORANDOM ));
}
BUTTONACT( randomButton, toggleRandom() );
buttons->addWidget( randomButton );
QSpacerItem *spacer = new QSpacerItem( 10, 20 );
buttons->addItem( spacer );
repeatButton = new QPushButton( this );
if( model->hasRepeat() )
{
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
repeatButton->setToolTip( qtr( I_PL_REPEAT ));
}
else if( model->hasLoop() )
{
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
repeatButton->setToolTip( qtr( I_PL_LOOP ));
}
else
{
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
}
BUTTONACT( repeatButton, toggleRepeat() );
buttons->addWidget( repeatButton );
QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " );
buttons->addWidget( filter );
searchLine = new ClickLineEdit( qtr(I_PL_FILTER), 0 );
CONNECT( searchLine, textChanged(QString), this, search(QString));
buttons->addWidget( searchLine ); filter->setBuddy( searchLine );
QPushButton *clear = new QPushButton( qfu( "CL") );
clear->setMaximumWidth( 30 );
clear->setToolTip( qtr( "Clear" ));
BUTTONACT( clear, clearFilter() );
buttons->addWidget( clear );
layout->addWidget( view );
layout->addLayout( buttons );
// layout->addWidget( bar );
setLayout( layout );
}
void StandardPLPanel::toggleRepeat()
{
if( model->hasRepeat() )
{
model->setRepeat( false ); model->setLoop( true );
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
repeatButton->setToolTip( qtr( I_PL_LOOP ));
}
else if( model->hasLoop() )
{
model->setRepeat( false ) ; model->setLoop( false );
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
}
else
{
model->setRepeat( true );
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
repeatButton->setToolTip( qtr( I_PL_REPEAT ));
}
}
void StandardPLPanel::toggleRandom()
{
bool prev = model->hasRandom();
model->setRandom( !prev );
randomButton->setIcon( prev ?
QIcon( ":/pixmaps/playlist_shuffle_off.png" ) :
QIcon( ":/pixmaps/playlist_shuffle_on.png" ) );
randomButton->setToolTip( prev ? qtr( I_PL_NORANDOM ) : qtr(I_PL_RANDOM ) );
}
void StandardPLPanel::handleExpansion( const QModelIndex &index )
{
if( model->isCurrent( index ) )
view->scrollTo( index, QAbstractItemView::EnsureVisible );
}
void StandardPLPanel::setCurrentRootId( int _new )
{
currentRootId = _new;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDPL) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDML) );
}
else
addButton->setEnabled( false );
}
void StandardPLPanel::popupAdd()
{
QMenu popup;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simplePLAppendDialog()));
popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT(PLAppendDialog()) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simpleMLAppendDialog()));
popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT( MLAppendDialog() ) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
}
popup.exec( QCursor::pos() );
}
void StandardPLPanel::popupSelectColumn( QPoint )
{
ContextUpdateMapper = new QSignalMapper(this);
QMenu selectColMenu;
#define ADD_META_ACTION( meta ) { \
QAction* option = selectColMenu.addAction( qfu(VLC_META_##meta) ); \
option->setCheckable( true ); \
option->setChecked( model->shownFlags() & VLC_META_ENGINE_##meta ); \
ContextUpdateMapper->setMapping( option, VLC_META_ENGINE_##meta ); \
CONNECT( option, triggered(), ContextUpdateMapper, map() ); \
}
CONNECT( ContextUpdateMapper, mapped( int ), model, viewchanged( int ) );
ADD_META_ACTION( TITLE );
ADD_META_ACTION( ARTIST );
ADD_META_ACTION( DURATION );
ADD_META_ACTION( COLLECTION );
ADD_META_ACTION( GENRE );
ADD_META_ACTION( SEQ_NUM );
ADD_META_ACTION( RATING );
ADD_META_ACTION( DESCRIPTION );
#undef ADD_META_ACTION
selectColMenu.exec( QCursor::pos() );
}
void StandardPLPanel::clearFilter()
{
searchLine->setText( "" );
}
void StandardPLPanel::search( QString searchText )
{
model->search( searchText );
}
void StandardPLPanel::doPopup( QModelIndex index, QPoint point )
{
if( !index.isValid() ) return;
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->popup( index, point, list );
}
void StandardPLPanel::setRoot( int i_root_id )
{
playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id,
VLC_TRUE );
assert( p_item );
p_item = playlist_GetPreferredNode( THEPL, p_item );
assert( p_item );
model->rebuild( p_item );
}
void StandardPLPanel::removeItem( int i_id )
{
model->removeItem( i_id );
}
void StandardPLPanel::keyPressEvent( QKeyEvent *e )
{
switch( e->key() )
{
case Qt::Key_Back:
case Qt::Key_Delete:
deleteSelection();
break;
}
}
void StandardPLPanel::deleteSelection()
{
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->doDelete( list );
}
StandardPLPanel::~StandardPLPanel()
{}
<commit_msg>Qt4 - small cosmetic for the playlist.<commit_after>/*****************************************************************************
* standardpanel.cpp : The "standard" playlist panel : just a treeview
****************************************************************************
* Copyright (C) 2000-2005 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "playlist_model.hpp"
#include "components/playlist/panels.hpp"
#include "util/customwidgets.hpp"
#include <vlc_intf_strings.h>
#include <QTreeView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QModelIndexList>
#include <QToolBar>
#include <QLabel>
#include <QSpacerItem>
#include <QMenu>
#include <assert.h>
StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent,
intf_thread_t *_p_intf,
playlist_t *p_playlist,
playlist_item_t *p_root ):
PLPanel( _parent, _p_intf )
{
model = new PLModel( p_playlist, p_intf, p_root, -1, this );
QVBoxLayout *layout = new QVBoxLayout();
layout->setSpacing( 0 ); layout->setMargin( 0 );
/* Create and configure the QTreeView */
view = new QVLCTreeView( 0 );
view->setModel(model);
view->setIconSize( QSize( 20, 20 ) );
view->setAlternatingRowColors( true );
view->setAnimated( true );
view->setSortingEnabled( true );
view->setSelectionMode( QAbstractItemView::ExtendedSelection );
view->setDragEnabled( true );
view->setAcceptDrops( true );
view->setDropIndicatorShown( true );
view->setAutoScroll( true );
view->header()->resizeSection( 0, 230 );
view->header()->resizeSection( 1, 80 );
view->header()->setSortIndicatorShown( true );
view->header()->setClickable( true );
view->header()->setContextMenuPolicy( Qt::CustomContextMenu );
CONNECT( view, activated( const QModelIndex& ) ,
model,activateItem( const QModelIndex& ) );
CONNECT( view, rightClicked( QModelIndex , QPoint ),
this, doPopup( QModelIndex, QPoint ) );
CONNECT( model, dataChanged( const QModelIndex&, const QModelIndex& ),
this, handleExpansion( const QModelIndex& ) );
CONNECT( view->header(), customContextMenuRequested( const QPoint & ),
this, popupSelectColumn( QPoint ) );
currentRootId = -1;
CONNECT( parent, rootChanged( int ), this, setCurrentRootId( int ) );
/* Buttons configuration */
QHBoxLayout *buttons = new QHBoxLayout;
addButton = new QPushButton( QIcon( ":/pixmaps/playlist_add.png" ), "", this );
addButton->setMaximumWidth( 25 );
BUTTONACT( addButton, popupAdd() );
buttons->addWidget( addButton );
randomButton = new QPushButton( this );
if( model->hasRandom() )
{
randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_on.png" ));
randomButton->setToolTip( qtr( I_PL_RANDOM ));
}
else
{
randomButton->setIcon( QIcon( ":/pixmaps/playlist_shuffle_off.png" ) );
randomButton->setToolTip( qtr( I_PL_NORANDOM ));
}
BUTTONACT( randomButton, toggleRandom() );
buttons->addWidget( randomButton );
QSpacerItem *spacer = new QSpacerItem( 10, 20 );
buttons->addItem( spacer );
repeatButton = new QPushButton( this );
if( model->hasRepeat() )
{
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
repeatButton->setToolTip( qtr( I_PL_REPEAT ));
}
else if( model->hasLoop() )
{
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
repeatButton->setToolTip( qtr( I_PL_LOOP ));
}
else
{
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
}
BUTTONACT( repeatButton, toggleRepeat() );
buttons->addWidget( repeatButton );
QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " );
buttons->addWidget( filter );
searchLine = new ClickLineEdit( qtr(I_PL_FILTER), 0 );
CONNECT( searchLine, textChanged(QString), this, search(QString));
buttons->addWidget( searchLine ); filter->setBuddy( searchLine );
QPushButton *clear = new QPushButton( qfu( "CL") );
clear->setMaximumWidth( 30 );
clear->setToolTip( qtr( "Clear" ));
BUTTONACT( clear, clearFilter() );
buttons->addWidget( clear );
layout->addWidget( view );
layout->addLayout( buttons );
// layout->addWidget( bar );
setLayout( layout );
}
void StandardPLPanel::toggleRepeat()
{
if( model->hasRepeat() )
{
model->setRepeat( false ); model->setLoop( true );
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_all.png" ) );
repeatButton->setToolTip( qtr( I_PL_LOOP ));
}
else if( model->hasLoop() )
{
model->setRepeat( false ) ; model->setLoop( false );
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_off.png" ) );
repeatButton->setToolTip( qtr( I_PL_NOREPEAT ));
}
else
{
model->setRepeat( true );
repeatButton->setIcon( QIcon( ":/pixmaps/playlist_repeat_one.png" ) );
repeatButton->setToolTip( qtr( I_PL_REPEAT ));
}
}
void StandardPLPanel::toggleRandom()
{
bool prev = model->hasRandom();
model->setRandom( !prev );
randomButton->setIcon( prev ?
QIcon( ":/pixmaps/playlist_shuffle_off.png" ) :
QIcon( ":/pixmaps/playlist_shuffle_on.png" ) );
randomButton->setToolTip( prev ? qtr( I_PL_NORANDOM ) : qtr(I_PL_RANDOM ) );
}
void StandardPLPanel::handleExpansion( const QModelIndex &index )
{
if( model->isCurrent( index ) )
view->scrollTo( index, QAbstractItemView::EnsureVisible );
}
void StandardPLPanel::setCurrentRootId( int _new )
{
currentRootId = _new;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDPL) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDML) );
}
else
addButton->setEnabled( false );
}
void StandardPLPanel::popupAdd()
{
QMenu popup;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simplePLAppendDialog()));
popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT(PLAppendDialog()) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT(simpleMLAppendDialog()));
popup.addAction( qtr(I_PL_ADVADD), THEDP, SLOT( MLAppendDialog() ) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
}
popup.exec( QCursor::pos() );
}
void StandardPLPanel::popupSelectColumn( QPoint )
{
ContextUpdateMapper = new QSignalMapper(this);
QMenu selectColMenu;
#define ADD_META_ACTION( meta ) { \
QAction* option = selectColMenu.addAction( qfu(VLC_META_##meta) ); \
option->setCheckable( true ); \
option->setChecked( model->shownFlags() & VLC_META_ENGINE_##meta ); \
ContextUpdateMapper->setMapping( option, VLC_META_ENGINE_##meta ); \
CONNECT( option, triggered(), ContextUpdateMapper, map() ); \
}
CONNECT( ContextUpdateMapper, mapped( int ), model, viewchanged( int ) );
ADD_META_ACTION( TITLE );
ADD_META_ACTION( ARTIST );
ADD_META_ACTION( DURATION );
ADD_META_ACTION( COLLECTION );
ADD_META_ACTION( GENRE );
ADD_META_ACTION( SEQ_NUM );
ADD_META_ACTION( RATING );
ADD_META_ACTION( DESCRIPTION );
#undef ADD_META_ACTION
selectColMenu.exec( QCursor::pos() );
}
void StandardPLPanel::clearFilter()
{
searchLine->setText( "" );
}
void StandardPLPanel::search( QString searchText )
{
model->search( searchText );
}
void StandardPLPanel::doPopup( QModelIndex index, QPoint point )
{
if( !index.isValid() ) return;
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->popup( index, point, list );
}
void StandardPLPanel::setRoot( int i_root_id )
{
playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id,
VLC_TRUE );
assert( p_item );
p_item = playlist_GetPreferredNode( THEPL, p_item );
assert( p_item );
model->rebuild( p_item );
}
void StandardPLPanel::removeItem( int i_id )
{
model->removeItem( i_id );
}
void StandardPLPanel::keyPressEvent( QKeyEvent *e )
{
switch( e->key() )
{
case Qt::Key_Back:
case Qt::Key_Delete:
deleteSelection();
break;
}
}
void StandardPLPanel::deleteSelection()
{
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->doDelete( list );
}
StandardPLPanel::~StandardPLPanel()
{}
<|endoftext|> |
<commit_before><commit_msg>Fix crash on engine shutdown in gerstner scene<commit_after><|endoftext|> |
<commit_before>/*!
* \file painter_image_brush_shader.cpp
* \brief file painter_image_brush_shader.cpp
*
* Copyright 2019 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#include <iostream>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/painter/shader/painter_image_brush_shader.hpp>
#include <fastuidraw/painter/painter_packed_value_pool.hpp>
#include <private/util_private_ostream.hpp>
namespace
{
class PainterImageBrushShaderPrivate
{
public:
typedef fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> shader_ref;
shader_ref m_parent_shader;
fastuidraw::vecN<shader_ref, fastuidraw::PainterImageBrushShader::number_sub_shaders> m_sub_shaders;
};
}
/////////////////////////////////////////////
// fastuidraw::PainterImageBrushShader methods
fastuidraw::PainterImageBrushShader::
PainterImageBrushShader(const reference_counted_ptr<PainterBrushShader> &parent_shader)
{
PainterImageBrushShaderPrivate *d;
m_d = d = FASTUIDRAWnew PainterImageBrushShaderPrivate();
d->m_parent_shader = parent_shader;
for (unsigned int i = 0; i < number_sub_shaders; ++i)
{
d->m_sub_shaders[i] = FASTUIDRAWnew PainterBrushShader(parent_shader, i);
}
}
fastuidraw::PainterImageBrushShader::
~PainterImageBrushShader()
{
PainterImageBrushShaderPrivate *d;
d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
FASTUIDRAWdelete(d);
}
uint32_t
fastuidraw::PainterImageBrushShader::
sub_shader_id(const Image *image,
enum filter_t image_filter,
enum mipmap_t mip_mapping)
{
uint32_t return_value(0u);
if (image)
{
uint32_t filter_bits, type_bits, mip_bits, format_bits;
filter_bits = pack_bits(filter_bit0, filter_num_bits, image_filter);
mip_bits = pack_bits(mipmap_bit0, mipmap_num_bits,
(mip_mapping == apply_mipmapping) ?
image->number_mipmap_levels() - 1u: 0u);
type_bits = pack_bits(type_bit0, type_num_bits, image->type());
format_bits = pack_bits(format_bit0, format_num_bits, image->format());
return_value = filter_bits | mip_bits | type_bits | format_bits;
}
return return_value;
}
const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader>&
fastuidraw::PainterImageBrushShader::
sub_shader(const Image *image,
enum filter_t image_filter,
enum mipmap_t mip_mapping) const
{
PainterImageBrushShaderPrivate *d;
d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
return d->m_sub_shaders[sub_shader_id(image, image_filter, mip_mapping)];
}
fastuidraw::c_array<const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> >
fastuidraw::PainterImageBrushShader::
sub_shaders(void) const
{
PainterImageBrushShaderPrivate *d;
d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
return d->m_sub_shaders;
}
fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
const reference_counted_ptr<const Image> &image,
uvec2 xy, uvec2 wh,
enum filter_t image_filter,
enum mipmap_t mip_mapping) const
{
PainterDataValue<PainterBrushShaderData> packed_data;
PainterImageBrushShaderData data;
data.sub_image(image, xy, wh);
packed_data = pool.create_packed_value(data);
return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}
fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
const reference_counted_ptr<const Image> &image,
enum filter_t image_filter,
enum mipmap_t mip_mapping) const
{
PainterDataValue<PainterBrushShaderData> packed_data;
PainterImageBrushShaderData data;
data.image(image);
packed_data = pool.create_packed_value(data);
return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}
////////////////////////////////////////////////
// fastuidraw::PainterImageBrushShaderData methods
fastuidraw::PainterImageBrushShaderData::
PainterImageBrushShaderData(void)
{
reference_counted_ptr<const Image> null_image;
image(null_image);
}
unsigned int
fastuidraw::PainterImageBrushShaderData::
data_size(void) const
{
return FASTUIDRAW_NUMBER_BLOCK4_NEEDED(shader_data_size);
}
void
fastuidraw::PainterImageBrushShaderData::
save_resources(c_array<reference_counted_ptr<const resource_base> > dst) const
{
if (m_image)
{
dst[0] = m_image;
}
}
unsigned int
fastuidraw::PainterImageBrushShaderData::
number_resources(void) const
{
return (m_image) ? 1 : 0;
}
fastuidraw::c_array<const fastuidraw::reference_counted_ptr<const fastuidraw::Image> >
fastuidraw::PainterImageBrushShaderData::
bind_images(void) const
{
unsigned int sz;
const reference_counted_ptr<const Image> *im;
sz = (m_image && m_image->type() == Image::context_texture2d) ? 1 : 0;
im = (sz != 0) ? &m_image : nullptr;
return c_array<const reference_counted_ptr<const Image> >(im, sz);
}
void
fastuidraw::PainterImageBrushShaderData::
image(const reference_counted_ptr<const Image> &im)
{
sub_image(im, uvec2(0, 0),
(im) ? uvec2(im->dimensions()) : uvec2(0, 0));
}
void
fastuidraw::PainterImageBrushShaderData::
sub_image(const reference_counted_ptr<const Image> &im,
uvec2 xy, uvec2 wh)
{
m_image = im;
m_image_xy = xy;
m_image_wh = wh;
}
void
fastuidraw::PainterImageBrushShaderData::
pack_data(c_array<vecN<generic_data, 4> > pdst) const
{
c_array<generic_data> dst;
dst = pdst.flatten_array();
if (m_image)
{
dst[start_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_xy.x())
| pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_xy.y());
dst[size_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_wh.x())
| pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_wh.y());
switch (m_image->type())
{
case Image::on_atlas:
{
uvec3 loc(m_image->master_index_tile());
uint32_t lookups(m_image->number_index_lookups());
dst[atlas_location_xyz_offset].u = pack_bits(atlas_location_x_bit0, atlas_location_x_num_bits, loc.x())
| pack_bits(atlas_location_y_bit0, atlas_location_y_num_bits, loc.y())
| pack_bits(atlas_location_z_bit0, atlas_location_z_num_bits, loc.z());
dst[number_lookups_offset].u = lookups;
}
break;
case Image::bindless_texture2d:
{
uint64_t v, hi, low;
v = m_image->bindless_handle();
hi = uint64_unpack_bits(32, 32, v);
low = uint64_unpack_bits(0, 32, v);
dst[bindless_handle_hi_offset].u = hi;
dst[bindless_handle_low_offset].u = low;
}
break;
default:
break;
}
}
else
{
generic_data zero;
zero.u = 0u;
std::fill(dst.begin(), dst.end(), zero);
}
}
<commit_msg>fastuidraw/painter/shader/painter_image_brush_shader: remove unneeded includes<commit_after>/*!
* \file painter_image_brush_shader.cpp
* \brief file painter_image_brush_shader.cpp
*
* Copyright 2019 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/painter/shader/painter_image_brush_shader.hpp>
#include <fastuidraw/painter/painter_packed_value_pool.hpp>
namespace
{
class PainterImageBrushShaderPrivate
{
public:
typedef fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> shader_ref;
shader_ref m_parent_shader;
fastuidraw::vecN<shader_ref, fastuidraw::PainterImageBrushShader::number_sub_shaders> m_sub_shaders;
};
}
/////////////////////////////////////////////
// fastuidraw::PainterImageBrushShader methods
fastuidraw::PainterImageBrushShader::
PainterImageBrushShader(const reference_counted_ptr<PainterBrushShader> &parent_shader)
{
PainterImageBrushShaderPrivate *d;
m_d = d = FASTUIDRAWnew PainterImageBrushShaderPrivate();
d->m_parent_shader = parent_shader;
for (unsigned int i = 0; i < number_sub_shaders; ++i)
{
d->m_sub_shaders[i] = FASTUIDRAWnew PainterBrushShader(parent_shader, i);
}
}
fastuidraw::PainterImageBrushShader::
~PainterImageBrushShader()
{
PainterImageBrushShaderPrivate *d;
d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
FASTUIDRAWdelete(d);
}
uint32_t
fastuidraw::PainterImageBrushShader::
sub_shader_id(const Image *image,
enum filter_t image_filter,
enum mipmap_t mip_mapping)
{
uint32_t return_value(0u);
if (image)
{
uint32_t filter_bits, type_bits, mip_bits, format_bits;
filter_bits = pack_bits(filter_bit0, filter_num_bits, image_filter);
mip_bits = pack_bits(mipmap_bit0, mipmap_num_bits,
(mip_mapping == apply_mipmapping) ?
image->number_mipmap_levels() - 1u: 0u);
type_bits = pack_bits(type_bit0, type_num_bits, image->type());
format_bits = pack_bits(format_bit0, format_num_bits, image->format());
return_value = filter_bits | mip_bits | type_bits | format_bits;
}
return return_value;
}
const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader>&
fastuidraw::PainterImageBrushShader::
sub_shader(const Image *image,
enum filter_t image_filter,
enum mipmap_t mip_mapping) const
{
PainterImageBrushShaderPrivate *d;
d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
return d->m_sub_shaders[sub_shader_id(image, image_filter, mip_mapping)];
}
fastuidraw::c_array<const fastuidraw::reference_counted_ptr<fastuidraw::PainterBrushShader> >
fastuidraw::PainterImageBrushShader::
sub_shaders(void) const
{
PainterImageBrushShaderPrivate *d;
d = static_cast<PainterImageBrushShaderPrivate*>(m_d);
return d->m_sub_shaders;
}
fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
const reference_counted_ptr<const Image> &image,
uvec2 xy, uvec2 wh,
enum filter_t image_filter,
enum mipmap_t mip_mapping) const
{
PainterDataValue<PainterBrushShaderData> packed_data;
PainterImageBrushShaderData data;
data.sub_image(image, xy, wh);
packed_data = pool.create_packed_value(data);
return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}
fastuidraw::PainterCustomBrush
fastuidraw::PainterImageBrushShader::
create_brush(PainterPackedValuePool &pool,
const reference_counted_ptr<const Image> &image,
enum filter_t image_filter,
enum mipmap_t mip_mapping) const
{
PainterDataValue<PainterBrushShaderData> packed_data;
PainterImageBrushShaderData data;
data.image(image);
packed_data = pool.create_packed_value(data);
return PainterCustomBrush(packed_data, sub_shader(image.get(), image_filter, mip_mapping).get());
}
////////////////////////////////////////////////
// fastuidraw::PainterImageBrushShaderData methods
fastuidraw::PainterImageBrushShaderData::
PainterImageBrushShaderData(void)
{
reference_counted_ptr<const Image> null_image;
image(null_image);
}
unsigned int
fastuidraw::PainterImageBrushShaderData::
data_size(void) const
{
return FASTUIDRAW_NUMBER_BLOCK4_NEEDED(shader_data_size);
}
void
fastuidraw::PainterImageBrushShaderData::
save_resources(c_array<reference_counted_ptr<const resource_base> > dst) const
{
if (m_image)
{
dst[0] = m_image;
}
}
unsigned int
fastuidraw::PainterImageBrushShaderData::
number_resources(void) const
{
return (m_image) ? 1 : 0;
}
fastuidraw::c_array<const fastuidraw::reference_counted_ptr<const fastuidraw::Image> >
fastuidraw::PainterImageBrushShaderData::
bind_images(void) const
{
unsigned int sz;
const reference_counted_ptr<const Image> *im;
sz = (m_image && m_image->type() == Image::context_texture2d) ? 1 : 0;
im = (sz != 0) ? &m_image : nullptr;
return c_array<const reference_counted_ptr<const Image> >(im, sz);
}
void
fastuidraw::PainterImageBrushShaderData::
image(const reference_counted_ptr<const Image> &im)
{
sub_image(im, uvec2(0, 0),
(im) ? uvec2(im->dimensions()) : uvec2(0, 0));
}
void
fastuidraw::PainterImageBrushShaderData::
sub_image(const reference_counted_ptr<const Image> &im,
uvec2 xy, uvec2 wh)
{
m_image = im;
m_image_xy = xy;
m_image_wh = wh;
}
void
fastuidraw::PainterImageBrushShaderData::
pack_data(c_array<vecN<generic_data, 4> > pdst) const
{
c_array<generic_data> dst;
dst = pdst.flatten_array();
if (m_image)
{
dst[start_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_xy.x())
| pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_xy.y());
dst[size_xy_offset].u = pack_bits(uvec2_x_bit0, uvec2_x_num_bits, m_image_wh.x())
| pack_bits(uvec2_y_bit0, uvec2_y_num_bits, m_image_wh.y());
switch (m_image->type())
{
case Image::on_atlas:
{
uvec3 loc(m_image->master_index_tile());
uint32_t lookups(m_image->number_index_lookups());
dst[atlas_location_xyz_offset].u = pack_bits(atlas_location_x_bit0, atlas_location_x_num_bits, loc.x())
| pack_bits(atlas_location_y_bit0, atlas_location_y_num_bits, loc.y())
| pack_bits(atlas_location_z_bit0, atlas_location_z_num_bits, loc.z());
dst[number_lookups_offset].u = lookups;
}
break;
case Image::bindless_texture2d:
{
uint64_t v, hi, low;
v = m_image->bindless_handle();
hi = uint64_unpack_bits(32, 32, v);
low = uint64_unpack_bits(0, 32, v);
dst[bindless_handle_hi_offset].u = hi;
dst[bindless_handle_low_offset].u = low;
}
break;
default:
break;
}
}
else
{
generic_data zero;
zero.u = 0u;
std::fill(dst.begin(), dst.end(), zero);
}
}
<|endoftext|> |
<commit_before>//=============================================================================
// ■ tile.cpp
//-----------------------------------------------------------------------------
// 3D模型:Tile
//=============================================================================
#include "tile.hpp"
namespace VM76 {
Tiles::Tiles(int tid) {
int x = tid % 16;
int y = tid / 16;
float T = 1.0f / 16.0f;
float S = 0.0f;
float xs = x * T;
float ys = y * T;
vtx[0] = new Vertex[4] {
{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, -1.0}},
{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, -1.0}},
{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, -1.0}},
{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, -1.0}},
};
vtx[1] = new Vertex[4] {
{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, 1.0}},
{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, 1.0}},
{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, 1.0}},
{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, 1.0}},
};
vtx[2] = new Vertex[4] {
{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 1.0, 0.0}},
{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 1.0, 0.0}},
{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 1.0, 0.0}},
{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 1.0, 0.0}},
};
vtx[3] = new Vertex[4] {
{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, -1.0, 0.0}},
{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, -1.0, 0.0}},
{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, -1.0, 0.0}},
{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, -1.0, 0.0}},
};
vtx[4] = new Vertex[4] {
{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{-1.0, 0.0, 0.0}},
{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{-1.0, 0.0, 0.0}},
{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{-1.0, 0.0, 0.0}},
{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{-1.0, 0.0, 0.0}},
};
vtx[5] = new Vertex[4] {
{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{1.0, 0.0, 0.0}},
{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{1.0, 0.0, 0.0}},
{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{1.0, 0.0, 0.0}},
{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{1.0, 0.0, 0.0}},
};
itx[0] = new GLuint[6] {0,1,3, 1,2,3};
itx[1] = new GLuint[6] {3,1,0, 3,2,1};
itx[2] = new GLuint[6] {0,1,3, 1,2,3};
itx[3] = new GLuint[6] {3,1,0, 3,2,1};
itx[4] = new GLuint[6] {0,1,3, 1,2,3};
itx[5] = new GLuint[6] {3,1,0, 3,2,1};
// Prepare an empty space
for (int i = 0; i < 6; i++) {
mat[i] = new glm::mat4[4096];
for (int x = 0; x < 4096; x++) mat[i][x] = glm::mat4(1.0);
obj[i] = new GDrawable();
obj[i]->data.vtx_c = 4;
obj[i]->data.ind_c = 2 * 3;
obj[i]->data.vertices = vtx[i];
obj[i]->data.indices = itx[i];
obj[i]->data.tri_mesh_count = 2;
// Reserve 512 spaces
obj[i]->data.mat_c = 4096;
obj[i]->data.mat = (GLuint*) &mat[0];
obj[i]->fbind();
// Draw none for default
obj[i]->data.mat_c = 0;
}
}
void Tiles::update_instance(int c1, int c2, int c3, int c4, int c5, int c6) {
obj[0]->data.mat_c = c1;
obj[0]->data.mat = (GLuint*) mat[0];
obj[0]->update_instance();
obj[1]->data.mat_c = c2;
obj[1]->data.mat = (GLuint*) mat[1];
obj[1]->update_instance();
obj[2]->data.mat_c = c3;
obj[2]->data.mat = (GLuint*) mat[2];
obj[2]->update_instance();
obj[3]->data.mat_c = c4;
obj[3]->data.mat = (GLuint*) mat[3];
obj[3]->update_instance();
obj[4]->data.mat_c = c5;
obj[4]->data.mat = (GLuint*) mat[4];
obj[4]->update_instance();
obj[5]->data.mat_c = c6;
obj[5]->data.mat = (GLuint*) mat[5];
obj[5]->update_instance();
}
void Tiles::render() {
for (int i = 0; i < 6; i++)
if (obj[i]->data.mat_c) obj[i]->draw();
}
void Tiles::dispose() {
for (int i = 0; i < 6; i++) {
VMDE_Dispose(obj[i]);
xefree(vtx[i]); xefree(itx[i]);
}
}
}
<commit_msg>FIX SAD BUG<commit_after>//=============================================================================
// ■ tile.cpp
//-----------------------------------------------------------------------------
// 3D模型:Tile
//=============================================================================
#include "tile.hpp"
namespace VM76 {
Tiles::Tiles(int tid) {
int x = tid % 16;
int y = tid / 16;
float T = 1.0f / 16.0f;
float S = 0.0f;
float xs = x * T;
float ys = y * T;
vtx[0] = new Vertex[4] {
{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, -1.0}},
{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, -1.0}},
{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, -1.0}},
{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, -1.0}},
};
vtx[1] = new Vertex[4] {
{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 0.0, 1.0}},
{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 0.0, 1.0}},
{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 0.0, 1.0}},
{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 0.0, 1.0}},
};
vtx[2] = new Vertex[4] {
{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, 1.0, 0.0}},
{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, 1.0, 0.0}},
{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, 1.0, 0.0}},
{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, 1.0, 0.0}},
};
vtx[3] = new Vertex[4] {
{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{0.0, -1.0, 0.0}},
{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{0.0, -1.0, 0.0}},
{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{0.0, -1.0, 0.0}},
{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{0.0, -1.0, 0.0}},
};
vtx[4] = new Vertex[4] {
{{0.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{-1.0, 0.0, 0.0}},
{{0.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{-1.0, 0.0, 0.0}},
{{0.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{-1.0, 0.0, 0.0}},
{{0.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{-1.0, 0.0, 0.0}},
};
vtx[5] = new Vertex[4] {
{{1.0, 0.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + T},{1.0, 0.0, 0.0}},
{{1.0, 0.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + T},{1.0, 0.0, 0.0}},
{{1.0, 1.0, 1.0},{1.0, 1.0, 1.0, 1.0},{xs + T, ys + S},{1.0, 0.0, 0.0}},
{{1.0, 1.0, 0.0},{1.0, 1.0, 1.0, 1.0},{xs + S, ys + S},{1.0, 0.0, 0.0}},
};
itx[0] = new GLuint[6] {0,1,3, 1,2,3};
itx[1] = new GLuint[6] {3,1,0, 3,2,1};
itx[2] = new GLuint[6] {0,1,3, 1,2,3};
itx[3] = new GLuint[6] {3,1,0, 3,2,1};
itx[4] = new GLuint[6] {0,1,3, 1,2,3};
itx[5] = new GLuint[6] {3,1,0, 3,2,1};
// Prepare an empty space
for (int i = 0; i < 6; i++) {
mat[i] = new glm::mat4[4096];
for (int x = 0; x < 4096; x++) mat[i][x] = glm::mat4(1.0);
obj[i] = new GDrawable();
obj[i]->data.vtx_c = 4;
obj[i]->data.ind_c = 2 * 3;
obj[i]->data.vertices = vtx[i];
obj[i]->data.indices = itx[i];
// Reserve 512 spaces
obj[i]->data.mat_c = 4096;
obj[i]->data.mat = (GLuint*) &mat[i][0];
obj[i]->fbind();
// Draw none for default
obj[i]->data.mat_c = 0;
}
}
void Tiles::update_instance(int c1, int c2, int c3, int c4, int c5, int c6) {
obj[0]->data.mat_c = c1;
obj[0]->data.mat = (GLuint*) mat[0];
obj[0]->update_instance();
obj[1]->data.mat_c = c2;
obj[1]->data.mat = (GLuint*) mat[1];
obj[1]->update_instance();
obj[2]->data.mat_c = c3;
obj[2]->data.mat = (GLuint*) mat[2];
obj[2]->update_instance();
obj[3]->data.mat_c = c4;
obj[3]->data.mat = (GLuint*) mat[3];
obj[3]->update_instance();
obj[4]->data.mat_c = c5;
obj[4]->data.mat = (GLuint*) mat[4];
obj[4]->update_instance();
obj[5]->data.mat_c = c6;
obj[5]->data.mat = (GLuint*) mat[5];
obj[5]->update_instance();
}
void Tiles::render() {
for (int i = 0; i < 6; i++)
if (obj[i]->data.mat_c) obj[i]->draw();
}
void Tiles::dispose() {
for (int i = 0; i < 6; i++) {
VMDE_Dispose(obj[i]);
xefree(vtx[i]); xefree(itx[i]);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "base/compiler_specific.h"
#include "GenericWorkerTask.h"
#include "KURL.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "WorkerContext.h"
#include "WorkerThread.h"
#include <wtf/Threading.h>
#undef LOG
#include "base/logging.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webworkerclient.h"
#include "webkit/glue/webworker_impl.h"
#if ENABLE(WORKERS)
WebWorker* WebWorker::Create(WebWorkerClient* client) {
return new WebWorkerImpl(client);
}
// This function is called on the main thread to force to initialize some static
// values used in WebKit before any worker thread is started. This is because in
// our worker processs, we do not run any WebKit code in main thread and thus
// when multiple workers try to start at the same time, we might hit crash due
// to contention for initializing static values.
void InitializeWebKitStaticValues() {
static bool initialized = false;
if (!initialized) {
initialized= true;
WTF::RefPtr<WebCore::SecurityOrigin> origin =
WebCore::SecurityOrigin::create(WebCore::KURL());
origin.release();
}
}
WebWorkerImpl::WebWorkerImpl(WebWorkerClient* client) : client_(client) {
InitializeWebKitStaticValues();
}
WebWorkerImpl::~WebWorkerImpl() {
}
void WebWorkerImpl::PostMessageToWorkerContextTask(
WebCore::ScriptExecutionContext* context,
WebWorkerImpl* this_ptr,
const WebCore::String& message) {
DCHECK(context->isWorkerContext());
WebCore::WorkerContext* worker_context =
static_cast<WebCore::WorkerContext*>(context);
worker_context->dispatchMessage(message);
this_ptr->client_->ConfirmMessageFromWorkerObject(
worker_context->hasPendingActivity());
}
void WebWorkerImpl::StartWorkerContext(const GURL& script_url,
const string16& user_agent,
const string16& source_code) {
worker_thread_ = WebCore::WorkerThread::create(
webkit_glue::GURLToKURL(script_url),
webkit_glue::String16ToString(user_agent),
webkit_glue::String16ToString(source_code),
this);
// Worker initialization means a pending activity.
reportPendingActivity(true);
worker_thread_->start();
}
void WebWorkerImpl::TerminateWorkerContext() {
worker_thread_->stop();
}
void WebWorkerImpl::PostMessageToWorkerContext(const string16& message) {
worker_thread_->runLoop().postTask(WebCore::createCallbackTask(
&PostMessageToWorkerContextTask,
this,
webkit_glue::String16ToString(message)));
}
void WebWorkerImpl::WorkerObjectDestroyed() {
}
void WebWorkerImpl::postMessageToWorkerObject(const WebCore::String& message) {
client_->PostMessageToWorkerObject(webkit_glue::StringToString16(message));
}
void WebWorkerImpl::postExceptionToWorkerObject(
const WebCore::String& errorMessage,
int lineNumber,
const WebCore::String& sourceURL) {
client_->PostExceptionToWorkerObject(
webkit_glue::StringToString16(errorMessage),
lineNumber,
webkit_glue::StringToString16(sourceURL));
}
void WebWorkerImpl::postConsoleMessageToWorkerObject(
WebCore::MessageDestination destination,
WebCore::MessageSource source,
WebCore::MessageLevel level,
const WebCore::String& message,
int lineNumber,
const WebCore::String& sourceURL) {
client_->PostConsoleMessageToWorkerObject(
destination,
source,
level,
webkit_glue::StringToString16(message),
lineNumber,
webkit_glue::StringToString16(sourceURL));
}
void WebWorkerImpl::confirmMessageFromWorkerObject(bool hasPendingActivity) {
client_->ConfirmMessageFromWorkerObject(hasPendingActivity);
}
void WebWorkerImpl::reportPendingActivity(bool hasPendingActivity) {
client_->ReportPendingActivity(hasPendingActivity);
}
void WebWorkerImpl::workerContextDestroyed() {
client_->WorkerContextDestroyed();
// The lifetime of this proxy is controlled by the worker context.
delete this;
}
#else
WebWorker* WebWorker::Create(WebWorkerClient* client) {
return NULL;
}
#endif
<commit_msg>Pass a URL with valid protocol to SecurityOrigin::create in order to follow the code path to do static value initializations for worker process. Review URL: http://codereview.chromium.org/66063<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "base/compiler_specific.h"
#include "GenericWorkerTask.h"
#include "KURL.h"
#include "ScriptExecutionContext.h"
#include "SecurityOrigin.h"
#include "WorkerContext.h"
#include "WorkerThread.h"
#include <wtf/Threading.h>
#undef LOG
#include "base/logging.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webworkerclient.h"
#include "webkit/glue/webworker_impl.h"
#if ENABLE(WORKERS)
WebWorker* WebWorker::Create(WebWorkerClient* client) {
return new WebWorkerImpl(client);
}
// This function is called on the main thread to force to initialize some static
// values used in WebKit before any worker thread is started. This is because in
// our worker processs, we do not run any WebKit code in main thread and thus
// when multiple workers try to start at the same time, we might hit crash due
// to contention for initializing static values.
void InitializeWebKitStaticValues() {
static bool initialized = false;
if (!initialized) {
initialized= true;
// Note that we have to pass a URL with valid protocol in order to follow
// the path to do static value initializations.
WTF::RefPtr<WebCore::SecurityOrigin> origin =
WebCore::SecurityOrigin::create(WebCore::KURL("http://localhost"));
origin.release();
}
}
WebWorkerImpl::WebWorkerImpl(WebWorkerClient* client) : client_(client) {
InitializeWebKitStaticValues();
}
WebWorkerImpl::~WebWorkerImpl() {
}
void WebWorkerImpl::PostMessageToWorkerContextTask(
WebCore::ScriptExecutionContext* context,
WebWorkerImpl* this_ptr,
const WebCore::String& message) {
DCHECK(context->isWorkerContext());
WebCore::WorkerContext* worker_context =
static_cast<WebCore::WorkerContext*>(context);
worker_context->dispatchMessage(message);
this_ptr->client_->ConfirmMessageFromWorkerObject(
worker_context->hasPendingActivity());
}
void WebWorkerImpl::StartWorkerContext(const GURL& script_url,
const string16& user_agent,
const string16& source_code) {
worker_thread_ = WebCore::WorkerThread::create(
webkit_glue::GURLToKURL(script_url),
webkit_glue::String16ToString(user_agent),
webkit_glue::String16ToString(source_code),
this);
// Worker initialization means a pending activity.
reportPendingActivity(true);
worker_thread_->start();
}
void WebWorkerImpl::TerminateWorkerContext() {
worker_thread_->stop();
}
void WebWorkerImpl::PostMessageToWorkerContext(const string16& message) {
worker_thread_->runLoop().postTask(WebCore::createCallbackTask(
&PostMessageToWorkerContextTask,
this,
webkit_glue::String16ToString(message)));
}
void WebWorkerImpl::WorkerObjectDestroyed() {
}
void WebWorkerImpl::postMessageToWorkerObject(const WebCore::String& message) {
client_->PostMessageToWorkerObject(webkit_glue::StringToString16(message));
}
void WebWorkerImpl::postExceptionToWorkerObject(
const WebCore::String& errorMessage,
int lineNumber,
const WebCore::String& sourceURL) {
client_->PostExceptionToWorkerObject(
webkit_glue::StringToString16(errorMessage),
lineNumber,
webkit_glue::StringToString16(sourceURL));
}
void WebWorkerImpl::postConsoleMessageToWorkerObject(
WebCore::MessageDestination destination,
WebCore::MessageSource source,
WebCore::MessageLevel level,
const WebCore::String& message,
int lineNumber,
const WebCore::String& sourceURL) {
client_->PostConsoleMessageToWorkerObject(
destination,
source,
level,
webkit_glue::StringToString16(message),
lineNumber,
webkit_glue::StringToString16(sourceURL));
}
void WebWorkerImpl::confirmMessageFromWorkerObject(bool hasPendingActivity) {
client_->ConfirmMessageFromWorkerObject(hasPendingActivity);
}
void WebWorkerImpl::reportPendingActivity(bool hasPendingActivity) {
client_->ReportPendingActivity(hasPendingActivity);
}
void WebWorkerImpl::workerContextDestroyed() {
client_->WorkerContextDestroyed();
// The lifetime of this proxy is controlled by the worker context.
delete this;
}
#else
WebWorker* WebWorker::Create(WebWorkerClient* client) {
return NULL;
}
#endif
<|endoftext|> |
<commit_before>#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <fj_tool/fapp.h>
#include <fjcoll.h>
#include "pearson-3d.h"
int T_MAX;
int T_MONITOR;
int mpi_my_rank;
const double PI=3.14159265358979323846;
float frand() {
return rand() / float(RAND_MAX);
}
double wctime() {
struct timeval tv;
gettimeofday(&tv,NULL);
return (double)tv.tv_sec + (double)tv.tv_usec*1e-6;
}
void init() {
double wx = frand() * 2 * PI;
double wy = frand() * 2 * PI;
double wz = frand() * 2 * PI;
for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
double k = (2*PI) / 128;
double x = k * (navi.offset_x + ix);
double y = k * (navi.offset_y + iy);
double z = k * (navi.offset_z + iz);
U[ix][iy][iz] = 1.0;
V[ix][iy][iz] = 0.0;
if (abs(cos(x+0.1*y+wx) * cos(y+0.1*z+wy) * cos(z+0.1*x+wz)) > 0.1) {
U[ix][iy][iz] = 0.5;
V[ix][iy][iz] = 0.25;
}
}
}
}
}
void write_monitor() {
printf("#%d: t = %d\n", mpi_my_rank, navi.time_step);
char fn[256];
sprintf(fn, "out/monitor-%06d-%d.txt", navi.time_step, mpi_my_rank);
FILE *fp = fopen(fn,"wb");
int global_position[6];
global_position[0] = navi.offset_x + navi.lower_x;
global_position[1] = navi.offset_y + navi.lower_y;
global_position[2] = navi.offset_z + navi.lower_z;
global_position[3] = navi.upper_x - navi.lower_x;
global_position[4] = navi.upper_y - navi.lower_y;
global_position[5] = navi.upper_z - navi.lower_z;
fwrite(global_position, sizeof(int), 6, fp);
int x_size = navi.upper_x - navi.lower_x;
int y_size = navi.upper_y - navi.lower_y;
int z_size = navi.upper_z - navi.lower_z;
{
const int y=navi.lower_y + y_size/2;
for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
}
{
const int x=navi.lower_x + x_size/2;
for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
}
fclose(fp);
}
int main (int argc, char **argv) {
MPI_Init(&argc, &argv);
Formura_Init(&navi, MPI_COMM_WORLD);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank);
srand(time(NULL)+mpi_my_rank*65537);
if (argc <= 1) {
T_MAX=8192;
}else{
sscanf(argv[1], "%d", &T_MAX);
}
if (argc <= 2) {
T_MONITOR=8192;
}else{
sscanf(argv[2], "%d", &T_MONITOR);
}
init();
double t_begin = wctime(), t_end;
int last_monitor_t = -T_MONITOR;
for(;;){
double t = wctime();
bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR;
if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) {
printf("%d step @ %lf sec\n", navi.time_step, t-t_begin);
}
if(monitor_flag) {
write_monitor();
}
if(monitor_flag) {
last_monitor_t += T_MONITOR;
}
if (navi.time_step >= T_MAX) break;
if (navi.time_step == 0) {
t_begin = wctime();
start_collection("main");
}
Formura_Forward(&navi); // navi.time_step increases
MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization
if (navi.time_step >= T_MAX) {
t_end = wctime();
stop_collection("main");
}
}
printf("wct = %lf sec\n",t_end - t_begin);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
}
<commit_msg>Rewrite seeding for pearson-3d<commit_after>#include <algorithm>
#include <map>
#include <math.h>
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <fj_tool/fapp.h>
#include <fjcoll.h>
#include "pearson-3d.h"
int T_MAX;
int T_MONITOR;
int mpi_my_rank;
const double PI=3.14159265358979323846;
float frand() {
return rand() / float(RAND_MAX);
}
double wctime() {
struct timeval tv;
gettimeofday(&tv,NULL);
return (double)tv.tv_sec + (double)tv.tv_usec*1e-6;
}
/*
void init() {
for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
double k = (2*PI) / 128;
double x = k * (navi.offset_x + ix);
double y = k * (navi.offset_y + iy);
double z = k * (navi.offset_z + iz);
U[ix][iy][iz] = 1.0;
V[ix][iy][iz] = 0.0;
if (abs(cos(x+0.1*y+wx) * cos(y+0.1*z+wy) * cos(z+0.1*x+wz)) > 0.1) {
if (frand() < 0.5) {
U[ix][iy][iz] = 0.5;
V[ix][iy][iz] = 0.25;
}
}
}
}
}*/
typedef pair<int,<int,int> > Key;
void init() {
map<Key ,double> seeds;
for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) {
for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) {
for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) {
Key k (ix%16, pair<int,int>(iy%16, iz%16));
U[ix][iy][iz] = 1.0;
V[ix][iy][iz] = 0.0;
double s = seeds[k];
if (s==0) {
s = frand();
seeds[k]=s;
}
if (s < 0.25) {
U[ix][iy][iz] = 0.5;
V[ix][iy][iz] = 0.25;
}
}
}
}
}
void write_monitor() {
printf("#%d: t = %d\n", mpi_my_rank, navi.time_step);
char fn[256];
sprintf(fn, "out/monitor-%06d-%d.txt", navi.time_step, mpi_my_rank);
FILE *fp = fopen(fn,"wb");
int global_position[6];
global_position[0] = navi.offset_x + navi.lower_x;
global_position[1] = navi.offset_y + navi.lower_y;
global_position[2] = navi.offset_z + navi.lower_z;
global_position[3] = navi.upper_x - navi.lower_x;
global_position[4] = navi.upper_y - navi.lower_y;
global_position[5] = navi.upper_z - navi.lower_z;
fwrite(global_position, sizeof(int), 6, fp);
int x_size = navi.upper_x - navi.lower_x;
int y_size = navi.upper_y - navi.lower_y;
int z_size = navi.upper_z - navi.lower_z;
{
const int y=navi.lower_y + y_size/2;
for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
}
{
const int x=navi.lower_x + x_size/2;
for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp);
for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp);
}
fclose(fp);
}
int main (int argc, char **argv) {
MPI_Init(&argc, &argv);
Formura_Init(&navi, MPI_COMM_WORLD);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank);
srand(time(NULL)+mpi_my_rank*65537);
if (argc <= 1) {
T_MAX=8192;
}else{
sscanf(argv[1], "%d", &T_MAX);
}
if (argc <= 2) {
T_MONITOR=8192;
}else{
sscanf(argv[2], "%d", &T_MONITOR);
}
init();
double t_begin = wctime(), t_end;
int last_monitor_t = -T_MONITOR;
for(;;){
double t = wctime();
bool monitor_flag = navi.time_step >= last_monitor_t + T_MONITOR;
if(monitor_flag || navi.time_step <= 3 * T_MONITOR ) {
printf("%d step @ %lf sec\n", navi.time_step, t-t_begin);
}
if(monitor_flag) {
write_monitor();
}
if(monitor_flag) {
last_monitor_t += T_MONITOR;
}
if (navi.time_step >= T_MAX) break;
if (navi.time_step == 0) {
t_begin = wctime();
start_collection("main");
}
Formura_Forward(&navi); // navi.time_step increases
MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization
if (navi.time_step >= T_MAX) {
t_end = wctime();
stop_collection("main");
}
}
printf("wct = %lf sec\n",t_end - t_begin);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.