text stringlengths 54 60.6k |
|---|
<commit_before>/**
* @copyright
* ====================================================================
* Copyright (c) 2008 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file RevpropTable.cpp
* @brief Implementation of the class RevpropTable
*/
#include "RevpropTable.h"
#include "Pool.h"
#include "JNIUtil.h"
#include "JNIStringHolder.h"
#include <apr_tables.h>
#include <apr_strings.h>
#include <apr_hash.h>
#include "svn_path.h"
#include <iostream>
RevpropTable::~RevpropTable()
{
if (m_revpropTable != NULL)
JNIUtil::getEnv()->DeleteLocalRef(m_revpropTable);
}
const apr_hash_t *RevpropTable::hash(const Pool &pool)
{
if (m_revprops.size() == 0)
return NULL;
apr_hash_t *revprop_table = apr_hash_make(pool.pool());
std::map<std::string, std::string>::const_iterator it;
for (it = m_revprops.begin(); it != m_revprops.end(); ++it)
{
const char *propname = apr_pstrdup(pool.pool(), it->first.c_str());
if (!svn_prop_name_is_valid(propname))
{
const char *msg = apr_psprintf(pool.pool(),
"Invalid property name: '%s'",
propname);
JNIUtil::throwNativeException(JAVA_PACKAGE "/ClientException", msg,
NULL, SVN_ERR_CLIENT_PROPERTY_NAME);
return NULL;
}
svn_string_t *propval = svn_string_create(it->second.c_str(),
pool.pool());
apr_hash_set(revprop_table, propname, APR_HASH_KEY_STRING, propval);
}
return revprop_table;
}
RevpropTable::RevpropTable(jobject jrevpropTable)
{
m_revpropTable = jrevpropTable;
if (jrevpropTable != NULL)
{
static jmethodID keySet = 0, toArray = 0, get = 0;
JNIEnv *env = JNIUtil::getEnv();
jclass mapClazz = env->FindClass("java/util/Map");
if (keySet == 0)
{
keySet = env->GetMethodID(mapClazz, "keySet",
"()Ljava/util/Set;");
if (JNIUtil::isExceptionThrown())
return;
}
jobject jkeySet = env->CallObjectMethod(jrevpropTable, keySet);
if (JNIUtil::isExceptionThrown())
return;
jclass setClazz = env->FindClass("java/util/Set");
if (toArray == 0)
{
toArray = env->GetMethodID(setClazz, "toArray",
"()[Ljava/lang/Object;");
if (JNIUtil::isExceptionThrown())
return;
}
jobjectArray jkeyArray = (jobjectArray) env->CallObjectMethod(jkeySet,
toArray);
if (JNIUtil::isExceptionThrown())
return;
if (get == 0)
{
get = env->GetMethodID(mapClazz, "get",
"(Ljava/lang/Object;)Ljava/lang/Object;");
if (JNIUtil::isExceptionThrown())
return;
}
jint arraySize = env->GetArrayLength(jkeyArray);
if (JNIUtil::isExceptionThrown())
return;
for (int i = 0; i < arraySize; ++i)
{
jobject jpropname = env->GetObjectArrayElement(jkeyArray, i);
if (JNIUtil::isExceptionThrown())
return;
JNIStringHolder propname((jstring)jpropname);
if (JNIUtil::isExceptionThrown())
return;
jobject jpropval = env->CallObjectMethod(jrevpropTable, get,
jpropname);
if (JNIUtil::isExceptionThrown())
return;
JNIStringHolder propval((jstring)jpropval);
if (JNIUtil::isExceptionThrown())
return;
m_revprops[std::string((const char *)propname)]
= std::string((const char *)propval);
JNIUtil::getEnv()->DeleteLocalRef(jpropname);
if (JNIUtil::isExceptionThrown())
return;
JNIUtil::getEnv()->DeleteLocalRef(jpropval);
if (JNIUtil::isExceptionThrown())
return;
}
JNIUtil::getEnv()->DeleteLocalRef(jkeySet);
if (JNIUtil::isExceptionThrown())
return;
JNIUtil::getEnv()->DeleteLocalRef(jkeyArray);
if (JNIUtil::isExceptionThrown())
return;
}
}
<commit_msg>JavaHL: Fix the build after r35424.<commit_after>/**
* @copyright
* ====================================================================
* Copyright (c) 2008 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file RevpropTable.cpp
* @brief Implementation of the class RevpropTable
*/
#include "RevpropTable.h"
#include "Pool.h"
#include "JNIUtil.h"
#include "JNIStringHolder.h"
#include <apr_tables.h>
#include <apr_strings.h>
#include <apr_hash.h>
#include "svn_path.h"
#include "svn_props.h"
#include <iostream>
RevpropTable::~RevpropTable()
{
if (m_revpropTable != NULL)
JNIUtil::getEnv()->DeleteLocalRef(m_revpropTable);
}
const apr_hash_t *RevpropTable::hash(const Pool &pool)
{
if (m_revprops.size() == 0)
return NULL;
apr_hash_t *revprop_table = apr_hash_make(pool.pool());
std::map<std::string, std::string>::const_iterator it;
for (it = m_revprops.begin(); it != m_revprops.end(); ++it)
{
const char *propname = apr_pstrdup(pool.pool(), it->first.c_str());
if (!svn_prop_name_is_valid(propname))
{
const char *msg = apr_psprintf(pool.pool(),
"Invalid property name: '%s'",
propname);
JNIUtil::throwNativeException(JAVA_PACKAGE "/ClientException", msg,
NULL, SVN_ERR_CLIENT_PROPERTY_NAME);
return NULL;
}
svn_string_t *propval = svn_string_create(it->second.c_str(),
pool.pool());
apr_hash_set(revprop_table, propname, APR_HASH_KEY_STRING, propval);
}
return revprop_table;
}
RevpropTable::RevpropTable(jobject jrevpropTable)
{
m_revpropTable = jrevpropTable;
if (jrevpropTable != NULL)
{
static jmethodID keySet = 0, toArray = 0, get = 0;
JNIEnv *env = JNIUtil::getEnv();
jclass mapClazz = env->FindClass("java/util/Map");
if (keySet == 0)
{
keySet = env->GetMethodID(mapClazz, "keySet",
"()Ljava/util/Set;");
if (JNIUtil::isExceptionThrown())
return;
}
jobject jkeySet = env->CallObjectMethod(jrevpropTable, keySet);
if (JNIUtil::isExceptionThrown())
return;
jclass setClazz = env->FindClass("java/util/Set");
if (toArray == 0)
{
toArray = env->GetMethodID(setClazz, "toArray",
"()[Ljava/lang/Object;");
if (JNIUtil::isExceptionThrown())
return;
}
jobjectArray jkeyArray = (jobjectArray) env->CallObjectMethod(jkeySet,
toArray);
if (JNIUtil::isExceptionThrown())
return;
if (get == 0)
{
get = env->GetMethodID(mapClazz, "get",
"(Ljava/lang/Object;)Ljava/lang/Object;");
if (JNIUtil::isExceptionThrown())
return;
}
jint arraySize = env->GetArrayLength(jkeyArray);
if (JNIUtil::isExceptionThrown())
return;
for (int i = 0; i < arraySize; ++i)
{
jobject jpropname = env->GetObjectArrayElement(jkeyArray, i);
if (JNIUtil::isExceptionThrown())
return;
JNIStringHolder propname((jstring)jpropname);
if (JNIUtil::isExceptionThrown())
return;
jobject jpropval = env->CallObjectMethod(jrevpropTable, get,
jpropname);
if (JNIUtil::isExceptionThrown())
return;
JNIStringHolder propval((jstring)jpropval);
if (JNIUtil::isExceptionThrown())
return;
m_revprops[std::string((const char *)propname)]
= std::string((const char *)propval);
JNIUtil::getEnv()->DeleteLocalRef(jpropname);
if (JNIUtil::isExceptionThrown())
return;
JNIUtil::getEnv()->DeleteLocalRef(jpropval);
if (JNIUtil::isExceptionThrown())
return;
}
JNIUtil::getEnv()->DeleteLocalRef(jkeySet);
if (JNIUtil::isExceptionThrown())
return;
JNIUtil::getEnv()->DeleteLocalRef(jkeyArray);
if (JNIUtil::isExceptionThrown())
return;
}
}
<|endoftext|> |
<commit_before>/**
* @defgroup pwglf_forward_trains_util Utilities for Train setups
*
* @ingroup pwglf_forward_trains
*/
/**
* @file OutputUtilities.C
* @author Christian Holm Christensen <cholm@master.hehi.nbi.dk>
* @date Tue Oct 16 17:55:32 2012
*
* @brief Special output handling
*
* @ingroup pwglf_forward_trains_util
*/
#ifndef TREEOUTPUTHELPER_C
#define TREEOUTPUTHELPER_C
#ifndef __CINT__
# include <TString.h>
# include <TError.h>
# include <AliAnalysisManager.h>
# include <AliAnalysisDataContainer.h>
# include <AliVEventHandler.h>
// Below for finding free port number
# ifdef R__UNIX
# include <sys/types.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/ip.h>
# include <unistd/ip.h>
# endif
#else
class TString;
#endif
// ===================================================================
/**
* Special output handling - data sets and remote storage
*
* @ingroup pwglf_forward_trains_util
*/
struct OutputUtilities
{
/**
* Register output data set
*
* @param dsname Data set name
*
* @return true on success
*/
static Bool_t RegisterDataset(const TString& dsname)
{
// Get the manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
// If we are asked to make a data-set, get the output handler and
// common output container.
AliVEventHandler* handler = mgr->GetOutputEventHandler();
if (!handler) return true;
// Get the container
AliAnalysisDataContainer* cont = mgr->GetCommonOutputContainer();
if (!cont) {
Warning("OutputUtilities::RegisterDataset",
"No common output container defined");
return false;
}
// Make the name
TString nme(dsname);
if (nme.IsNull()) nme = mgr->GetName();
if (nme.IsNull()) {
Error("OutputUtilities::RegisterDataset", "No data set name specified");
return false;
}
// Flag for data-set creation
cont->SetRegisterDataset(true);
handler->SetOutputFileName(nme);
// cont->SetFileName(nme);
TString base(handler->GetOutputFileName());
base.ReplaceAll(".root","");
Info("OutputUtilities::RegisterDataset",
"Will register tree output AODs (%s%s) as dataset",
base.Data(), cont->GetTitle());
return true;
}
/**
* Get the name of the registered data set
*
*
* @return Name of the registered data set
*/
static TString RegisteredDataset()
{
TString ret;
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
AliVEventHandler* oh = mgr->GetOutputEventHandler();
if (!oh) {
Warning("OutputUtilities::GetOutputDataSet",
"No outout event handler defined");
return ret;
}
AliAnalysisDataContainer* co = mgr->GetCommonOutputContainer();
if (!co) {
Warning("OutputUtilities::GetOutputDataSet",
"No common output container defined");
return ret;
}
if (!co->IsRegisterDataset()) {
Info("OutputUtilities::GetOutputDataSet",
"Common output is not registered as dataset");
return ret;
}
ret = oh->GetOutputFileName();
// ret.ReplaceAll("TTree", "");
ret.ReplaceAll(".root", "");
// ret.Append(co->GetTitle());
return ret;
}
static Int_t FindPort()
{
#ifdef R_UNIX
int sd = socket(AF_INET,SOCK_STREAM,0);
if (sd < 0) {
Warning("FindPort", "Failed to make socket");
return -1;
}
// Binding to port 0 will give us back a free port. The kernel
// does not reuse port numbers immediately
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = 0;
int bd = bind(sd, (struct sockaddr*)&addr, sizeof(addr));
if (bd != 0) {
Warning("FindPort", "Failed to bind socket to port 0");
close(sd);
return -1;
}
// Get the address on the bound socket
struct sockaddr_in radd;
socklen_t ladd = sizeof(radd);
int nr = getsockname(sd, (struct sockaddr*)&radd, &ladd);
if (nr != 0) {
Warning("FindPort", "Failed get socket port");
close(sd);
return -1;
}
int port = radd.sin_port;
close (sd);
return port;
#else
Warning("FindPort", "don't know how to do that on your system");
return -1;
#endif
}
/**
* Start a unique XRootd server and return it's access URL
*
* @param url On return, the access url
*
* @return true if successful, false otherwise
*/
static Bool_t StartXrootd(TString& url)
{
url = "";
Int_t port = FindPort();
if (port < 0) return false;
// Get host, current directory, and user name for unique name
TString host(gSystem->HostName());
TString dir(gSystem->WorkingDirectory());
TString name(gSystem->UserInfo()->fUser.Data());
// Form the command line. Note, we put the PID file one level up,
// so we know where to look for it. Otherwise it would be put in a
// sub-directory based on the name of the server. Since we later
// on don't know the name of the server we wouldn't now where to
// look for the PID file
TString exec;
exec.Form("xrootd -p %d -l xrd.log -s ../xrd.pid -b -n %s %s",
port, name.Data(), dir.Data());
Info("StartXrootd", "Starting XRootD to serve %s on port %d",
dir.Data(), port);
Info("StartXrootd", exec.Data());
int ret = gSystem->Exec(exec);
if (ret != 0) {
Warning("StartXrootd", "Failed to start XRootd server");
return false;
}
// Form the access URL
url = Form("root://%s@%s:%d/%s",
name.Data(), host.Data(), port, dir.Data());
Info("StartXrootd", "Access URL is \"%s\"", url.Data());
return true;
}
/**
* Stop a previously started Xrootd server
*
* @return true if stopped, false otherwise
*/
static Bool_t StopXrootd()
{
std::ifstream pidFile("xrd.pid");
if (!pidFile) return false;
TString s; s.ReadFile(pidFile);
pidFile.close();
gSystem->Unlink("xrd.pid");
if (s.IsNull()) return false;
Info("StopXrootd", "Stopping XRootd server (pid: %s)", s.Data());
return gSystem->Exec(Form("kill -9 %s", s.Data())) == 0;
}
/**
* Register special putput storage
*
* @param url Url (root://host/full_path)
*
* @return true on success
*/
static Bool_t RegisterStorage(const TString& url)
{
if (url.IsNull()) {
Error("OutputUtilities::RegisterStorage", "No storage URI specified");
return false;
}
// Get the manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
// Get the container
AliAnalysisDataContainer* cont = mgr->GetCommonOutputContainer();
if (!cont) {
Warning("OutputUtilities::RegisterStorage",
"No common output container defined");
return false;
}
TString u(url);
if (u.EqualTo("auto")) {
if (!StartXrootd(u)) {
Warning("OutputUtilities::RegisterStorage",
"Couldn't start the XRootD server");
return false;
}
}
cont->SetSpecialOutput();
mgr->SetSpecialOutputLocation(u);
return true;
}
};
#endif
//
// EOF
//
<commit_msg>Fixed a problem<commit_after>/**
* @defgroup pwglf_forward_trains_util Utilities for Train setups
*
* @ingroup pwglf_forward_trains
*/
/**
* @file OutputUtilities.C
* @author Christian Holm Christensen <cholm@master.hehi.nbi.dk>
* @date Tue Oct 16 17:55:32 2012
*
* @brief Special output handling
*
* @ingroup pwglf_forward_trains_util
*/
#ifndef TREEOUTPUTHELPER_C
#define TREEOUTPUTHELPER_C
#ifndef __CINT__
# include <TString.h>
# include <TError.h>
# include <AliAnalysisManager.h>
# include <AliAnalysisDataContainer.h>
# include <AliVEventHandler.h>
// Below for finding free port number
# ifdef R__UNIX
# include <sys/types.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netinet/ip.h>
# include <unistd.h>
# endif
#else
class TString;
#endif
// ===================================================================
/**
* Special output handling - data sets and remote storage
*
* @ingroup pwglf_forward_trains_util
*/
struct OutputUtilities
{
/**
* Register output data set
*
* @param dsname Data set name
*
* @return true on success
*/
static Bool_t RegisterDataset(const TString& dsname)
{
// Get the manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
// If we are asked to make a data-set, get the output handler and
// common output container.
AliVEventHandler* handler = mgr->GetOutputEventHandler();
if (!handler) return true;
// Get the container
AliAnalysisDataContainer* cont = mgr->GetCommonOutputContainer();
if (!cont) {
Warning("OutputUtilities::RegisterDataset",
"No common output container defined");
return false;
}
// Make the name
TString nme(dsname);
if (nme.IsNull()) nme = mgr->GetName();
if (nme.IsNull()) {
Error("OutputUtilities::RegisterDataset", "No data set name specified");
return false;
}
// Flag for data-set creation
cont->SetRegisterDataset(true);
handler->SetOutputFileName(nme);
// cont->SetFileName(nme);
TString base(handler->GetOutputFileName());
base.ReplaceAll(".root","");
Info("OutputUtilities::RegisterDataset",
"Will register tree output AODs (%s%s) as dataset",
base.Data(), cont->GetTitle());
return true;
}
/**
* Get the name of the registered data set
*
*
* @return Name of the registered data set
*/
static TString RegisteredDataset()
{
TString ret;
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
AliVEventHandler* oh = mgr->GetOutputEventHandler();
if (!oh) {
Warning("OutputUtilities::GetOutputDataSet",
"No outout event handler defined");
return ret;
}
AliAnalysisDataContainer* co = mgr->GetCommonOutputContainer();
if (!co) {
Warning("OutputUtilities::GetOutputDataSet",
"No common output container defined");
return ret;
}
if (!co->IsRegisterDataset()) {
Info("OutputUtilities::GetOutputDataSet",
"Common output is not registered as dataset");
return ret;
}
ret = oh->GetOutputFileName();
// ret.ReplaceAll("TTree", "");
ret.ReplaceAll(".root", "");
// ret.Append(co->GetTitle());
return ret;
}
static Int_t FindPort()
{
#ifdef R_UNIX
int sd = socket(AF_INET,SOCK_STREAM,0);
if (sd < 0) {
Warning("FindPort", "Failed to make socket");
return -1;
}
// Binding to port 0 will give us back a free port. The kernel
// does not reuse port numbers immediately
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = 0;
int bd = bind(sd, (struct sockaddr*)&addr, sizeof(addr));
if (bd != 0) {
Warning("FindPort", "Failed to bind socket to port 0");
close(sd);
return -1;
}
// Get the address on the bound socket
struct sockaddr_in radd;
socklen_t ladd = sizeof(radd);
int nr = getsockname(sd, (struct sockaddr*)&radd, &ladd);
if (nr != 0) {
Warning("FindPort", "Failed get socket port");
close(sd);
return -1;
}
int port = radd.sin_port;
close (sd);
return port;
#else
Warning("FindPort", "don't know how to do that on your system");
return -1;
#endif
}
/**
* Start a unique XRootd server and return it's access URL
*
* @param url On return, the access url
*
* @return true if successful, false otherwise
*/
static Bool_t StartXrootd(TString& url)
{
url = "";
Int_t port = FindPort();
if (port < 0) return false;
// Get host, current directory, and user name for unique name
TString host(gSystem->HostName());
TString dir(gSystem->WorkingDirectory());
TString name(gSystem->GetUserInfo()->fUser.Data());
// Form the command line. Note, we put the PID file one level up,
// so we know where to look for it. Otherwise it would be put in a
// sub-directory based on the name of the server. Since we later
// on don't know the name of the server we wouldn't now where to
// look for the PID file
TString exec;
exec.Form("xrootd -p %d -l xrd.log -s ../xrd.pid -b -n %s %s",
port, name.Data(), dir.Data());
Info("StartXrootd", "Starting XRootD to serve %s on port %d",
dir.Data(), port);
Info("StartXrootd", exec.Data());
int ret = gSystem->Exec(exec);
if (ret != 0) {
Warning("StartXrootd", "Failed to start XRootd server");
return false;
}
// Form the access URL
url = Form("root://%s@%s:%d/%s",
name.Data(), host.Data(), port, dir.Data());
Info("StartXrootd", "Access URL is \"%s\"", url.Data());
return true;
}
/**
* Stop a previously started Xrootd server
*
* @return true if stopped, false otherwise
*/
static Bool_t StopXrootd()
{
std::ifstream pidFile("xrd.pid");
if (!pidFile) return false;
TString s; s.ReadFile(pidFile);
pidFile.close();
gSystem->Unlink("xrd.pid");
if (s.IsNull()) return false;
Info("StopXrootd", "Stopping XRootd server (pid: %s)", s.Data());
return gSystem->Exec(Form("kill -9 %s", s.Data())) == 0;
}
/**
* Register special putput storage
*
* @param url Url (root://host/full_path)
*
* @return true on success
*/
static Bool_t RegisterStorage(const TString& url)
{
if (url.IsNull()) {
Error("OutputUtilities::RegisterStorage", "No storage URI specified");
return false;
}
// Get the manager
AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();
// Get the container
AliAnalysisDataContainer* cont = mgr->GetCommonOutputContainer();
if (!cont) {
Warning("OutputUtilities::RegisterStorage",
"No common output container defined");
return false;
}
TString u(url);
if (u.EqualTo("auto")) {
if (!StartXrootd(u)) {
Warning("OutputUtilities::RegisterStorage",
"Couldn't start the XRootD server");
return false;
}
}
cont->SetSpecialOutput();
mgr->SetSpecialOutputLocation(u);
return true;
}
};
#endif
//
// EOF
//
<|endoftext|> |
<commit_before>void CreateResCalib(int run=245231
,Long64_t tmin=0
,Long64_t tmax= 9999999999
,const char * resList="lst.txt"
)
{
gROOT->ProcessLine(".L /home/shahoian/tpcCalib/vClass/AliTPCDcalibRes.cxx+g");
AliTPCDcalibRes* clb = new AliTPCDcalibRes(run, tmin, tmax, resList);
clb->SetOCDBPath("local:///cvmfs/alice.cern.ch/calibration/data/2015/OCDB");
clb->ProcessFromDeltaTrees();
clb->Save();
}
void postProcResCalib(int run=245231
,Long64_t tmin=0
,Long64_t tmax= 9999999999
)
{
gROOT->ProcessLine(".L /home/shahoian/tpcCalib/vClass/AliTPCDcalibRes.cxx+g");
AliTPCDcalibRes* clb = new AliTPCDcalibRes(run, tmin, tmax);
clb->SetOCDBPath("local:///cvmfs/alice.cern.ch/calibration/data/2015/OCDB");
clb->ProcessFromStatTree();
clb->Save();
}
<commit_msg>no need to compile the source code<commit_after>void CreateResCalib(int run=245231
,Long64_t tmin=0
,Long64_t tmax= 9999999999
,const char * resList="lst.txt"
)
{
AliTPCDcalibRes* clb = new AliTPCDcalibRes(run, tmin, tmax, resList);
clb->SetOCDBPath("local:///cvmfs/alice.cern.ch/calibration/data/2015/OCDB");
clb->ProcessFromDeltaTrees();
clb->Save();
}
void postProcResCalib(int run=245231
,Long64_t tmin=0
,Long64_t tmax= 9999999999
)
{
AliTPCDcalibRes* clb = new AliTPCDcalibRes(run, tmin, tmax);
clb->SetOCDBPath("local:///cvmfs/alice.cern.ch/calibration/data/2015/OCDB");
clb->ProcessFromStatTree();
clb->Save();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(OS_WIN)
#include <windows.h>
#endif
#include "content/common/gpu/gpu_channel.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "content/common/child_process.h"
#include "content/common/gpu/gpu_channel_manager.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_surface.h"
#if defined(OS_POSIX)
#include "ipc/ipc_channel_posix.h"
#endif
namespace {
// The first time polling a fence, delay some extra time to allow other
// stubs to process some work, or else the timing of the fences could
// allow a pattern of alternating fast and slow frames to occur.
const int64 kHandleMoreWorkPeriodMs = 2;
const int64 kHandleMoreWorkPeriodBusyMs = 1;
}
GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
renderer_process_(base::kNullProcessHandle),
renderer_pid_(base::kNullProcessId),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
GpuChannel::~GpuChannel() {
#if defined(OS_WIN)
if (renderer_process_)
CloseHandle(renderer_process_);
#endif
}
bool GpuChannel::OnMessageReceived(const IPC::Message& message) {
if (log_messages_) {
DVLOG(1) << "received message @" << &message << " on channel @" << this
<< " with type " << message.type();
}
// Control messages are not deferred and can be handled out of order with
// respect to routed ones.
if (message.routing_id() == MSG_ROUTING_CONTROL)
return OnControlMessageReceived(message);
if (message.type() == GpuCommandBufferMsg_GetStateFast::ID) {
if (processed_get_state_fast_) {
// Require a non-GetStateFast message in between two GetStateFast
// messages, to ensure progress is made.
std::deque<IPC::Message*>::iterator point = deferred_messages_.begin();
while (point != deferred_messages_.end() &&
(*point)->type() == GpuCommandBufferMsg_GetStateFast::ID) {
++point;
}
if (point != deferred_messages_.end()) {
++point;
}
deferred_messages_.insert(point, new IPC::Message(message));
} else {
// Move GetStateFast commands to the head of the queue, so the renderer
// doesn't have to wait any longer than necessary.
deferred_messages_.push_front(new IPC::Message(message));
}
} else {
deferred_messages_.push_back(new IPC::Message(message));
}
OnScheduled();
return true;
}
void GpuChannel::OnChannelError() {
gpu_channel_manager_->RemoveChannel(client_id_);
}
void GpuChannel::OnChannelConnected(int32 peer_pid) {
renderer_pid_ = peer_pid;
}
bool GpuChannel::Send(IPC::Message* message) {
// The GPU process must never send a synchronous IPC message to the renderer
// process. This could result in deadlock.
DCHECK(!message->is_sync());
if (log_messages_) {
DVLOG(1) << "sending message @" << message << " on channel @" << this
<< " with type " << message->type();
}
if (!channel_.get()) {
delete message;
return false;
}
return channel_->Send(message);
}
void GpuChannel::AppendAllCommandBufferStubs(
std::vector<GpuCommandBufferStubBase*>& stubs) {
for (StubMap::Iterator<GpuCommandBufferStub> it(&stubs_);
!it.IsAtEnd(); it.Advance()) {
stubs.push_back(it.GetCurrentValue());
}
}
void GpuChannel::OnScheduled() {
if (handle_messages_scheduled_)
return;
// Post a task to handle any deferred messages. The deferred message queue is
// not emptied here, which ensures that OnMessageReceived will continue to
// defer newly received messages until the ones in the queue have all been
// handled by HandleMessage. HandleMessage is invoked as a
// task to prevent reentrancy.
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&GpuChannel::HandleMessage, weak_factory_.GetWeakPtr()));
handle_messages_scheduled_ = true;
}
void GpuChannel::LoseAllContexts() {
gpu_channel_manager_->LoseAllContexts();
}
void GpuChannel::DestroySoon() {
MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&GpuChannel::OnDestroy, this));
}
void GpuChannel::OnDestroy() {
TRACE_EVENT0("gpu", "GpuChannel::OnDestroy");
gpu_channel_manager_->RemoveChannel(client_id_);
}
void GpuChannel::CreateViewCommandBuffer(
const gfx::GLSurfaceHandle& window,
int32 surface_id,
const GPUCreateCommandBufferConfig& init_params,
int32* route_id) {
*route_id = MSG_ROUTING_NONE;
content::GetContentClient()->SetActiveURL(init_params.active_url);
#if defined(ENABLE_GPU)
WillCreateCommandBuffer(init_params.gpu_preference);
GpuCommandBufferStub* share_group = stubs_.Lookup(init_params.share_group_id);
*route_id = GenerateRouteID();
scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub(
this,
share_group,
window,
gfx::Size(),
disallowed_features_,
init_params.allowed_extensions,
init_params.attribs,
init_params.gpu_preference,
*route_id,
surface_id,
watchdog_,
software_));
router_.AddRoute(*route_id, stub.get());
stubs_.AddWithID(stub.release(), *route_id);
#endif // ENABLE_GPU
}
GpuCommandBufferStub* GpuChannel::LookupCommandBuffer(int32 route_id) {
return stubs_.Lookup(route_id);
}
bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) {
// Always use IPC_MESSAGE_HANDLER_DELAY_REPLY for synchronous message handlers
// here. This is so the reply can be delayed if the scheduler is unscheduled.
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg)
IPC_MESSAGE_HANDLER(GpuChannelMsg_Initialize, OnInitialize)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer,
OnCreateOffscreenCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer,
OnDestroyCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur,
OnWillGpuSwitchOccur)
IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled) << msg.type();
return handled;
}
void GpuChannel::HandleMessage() {
handle_messages_scheduled_ = false;
if (!deferred_messages_.empty()) {
IPC::Message* m = deferred_messages_.front();
GpuCommandBufferStub* stub = stubs_.Lookup(m->routing_id());
if (stub && !stub->IsScheduled()) {
if (m->type() == GpuCommandBufferMsg_Echo::ID) {
stub->DelayEcho(m);
deferred_messages_.pop_front();
if (!deferred_messages_.empty())
OnScheduled();
}
return;
}
scoped_ptr<IPC::Message> message(m);
deferred_messages_.pop_front();
processed_get_state_fast_ =
(message->type() == GpuCommandBufferMsg_GetStateFast::ID);
// Handle deferred control messages.
if (!router_.RouteMessage(*message)) {
// Respond to sync messages even if router failed to route.
if (message->is_sync()) {
IPC::Message* reply = IPC::SyncMessage::GenerateReply(&*message);
reply->set_reply_error();
Send(reply);
}
} else {
// If the command buffer becomes unscheduled as a result of handling the
// message but still has more commands to process, synthesize an IPC
// message to flush that command buffer.
if (stub) {
if (stub->HasUnprocessedCommands()) {
deferred_messages_.push_front(new GpuCommandBufferMsg_Rescheduled(
stub->route_id()));
}
ScheduleDelayedWork(stub, kHandleMoreWorkPeriodMs);
}
}
}
if (!deferred_messages_.empty()) {
OnScheduled();
}
}
void GpuChannel::PollWork(int route_id) {
GpuCommandBufferStub* stub = stubs_.Lookup(route_id);
if (stub) {
stub->PollWork();
ScheduleDelayedWork(stub, kHandleMoreWorkPeriodBusyMs);
}
}
void GpuChannel::ScheduleDelayedWork(GpuCommandBufferStub *stub,
int64 delay) {
if (stub->HasMoreWork()) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&GpuChannel::PollWork,
weak_factory_.GetWeakPtr(),
stub->route_id()),
base::TimeDelta::FromMilliseconds(delay));
}
}
int GpuChannel::GenerateRouteID() {
static int last_id = 0;
return ++last_id;
}
void GpuChannel::AddRoute(int32 route_id, IPC::Channel::Listener* listener) {
router_.AddRoute(route_id, listener);
}
void GpuChannel::RemoveRoute(int32 route_id) {
router_.RemoveRoute(route_id);
}
bool GpuChannel::ShouldPreferDiscreteGpu() const {
return num_contexts_preferring_discrete_gpu_ > 0;
}
void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) {
// Initialize should only happen once.
DCHECK(!renderer_process_);
// Verify that the renderer has passed its own process handle.
if (base::GetProcId(renderer_process) == renderer_pid_)
renderer_process_ = renderer_process;
}
void GpuChannel::OnCreateOffscreenCommandBuffer(
const gfx::Size& size,
const GPUCreateCommandBufferConfig& init_params,
IPC::Message* reply_message) {
int32 route_id = MSG_ROUTING_NONE;
content::GetContentClient()->SetActiveURL(init_params.active_url);
#if defined(ENABLE_GPU)
WillCreateCommandBuffer(init_params.gpu_preference);
GpuCommandBufferStub* share_group = stubs_.Lookup(init_params.share_group_id);
route_id = GenerateRouteID();
scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub(
this,
share_group,
gfx::GLSurfaceHandle(),
size,
disallowed_features_,
init_params.allowed_extensions,
init_params.attribs,
init_params.gpu_preference,
route_id,
0, watchdog_,
software_));
router_.AddRoute(route_id, stub.get());
stubs_.AddWithID(stub.release(), route_id);
TRACE_EVENT1("gpu", "GpuChannel::OnCreateOffscreenCommandBuffer",
"route_id", route_id);
#endif
GpuChannelMsg_CreateOffscreenCommandBuffer::WriteReplyParams(
reply_message,
route_id);
Send(reply_message);
}
void GpuChannel::OnDestroyCommandBuffer(int32 route_id,
IPC::Message* reply_message) {
#if defined(ENABLE_GPU)
TRACE_EVENT1("gpu", "GpuChannel::OnDestroyCommandBuffer",
"route_id", route_id);
if (router_.ResolveRoute(route_id)) {
GpuCommandBufferStub* stub = stubs_.Lookup(route_id);
bool need_reschedule = (stub && !stub->IsScheduled());
gfx::GpuPreference gpu_preference =
stub ? stub->gpu_preference() : gfx::PreferIntegratedGpu;
router_.RemoveRoute(route_id);
stubs_.Remove(route_id);
// In case the renderer is currently blocked waiting for a sync reply from
// the stub, we need to make sure to reschedule the GpuChannel here.
if (need_reschedule)
OnScheduled();
DidDestroyCommandBuffer(gpu_preference);
}
#endif
if (reply_message)
Send(reply_message);
}
void GpuChannel::OnWillGpuSwitchOccur(bool is_creating_context,
gfx::GpuPreference gpu_preference,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuChannel::OnWillGpuSwitchOccur");
bool will_switch_occur = false;
if (gpu_preference == gfx::PreferDiscreteGpu &&
gfx::GLContext::SupportsDualGpus()) {
if (is_creating_context) {
will_switch_occur = !num_contexts_preferring_discrete_gpu_;
} else {
will_switch_occur = (num_contexts_preferring_discrete_gpu_ == 1);
}
}
GpuChannelMsg_WillGpuSwitchOccur::WriteReplyParams(
reply_message,
will_switch_occur);
Send(reply_message);
}
void GpuChannel::OnCloseChannel() {
gpu_channel_manager_->RemoveChannel(client_id_);
// At this point "this" is deleted!
}
bool GpuChannel::Init(base::MessageLoopProxy* io_message_loop,
base::WaitableEvent* shutdown_event) {
DCHECK(!channel_.get());
// Map renderer ID to a (single) channel to that process.
channel_.reset(new IPC::SyncChannel(
channel_id_,
IPC::Channel::MODE_SERVER,
this,
io_message_loop,
false,
shutdown_event));
return true;
}
void GpuChannel::WillCreateCommandBuffer(gfx::GpuPreference gpu_preference) {
if (gpu_preference == gfx::PreferDiscreteGpu)
++num_contexts_preferring_discrete_gpu_;
}
void GpuChannel::DidDestroyCommandBuffer(gfx::GpuPreference gpu_preference) {
if (gpu_preference == gfx::PreferDiscreteGpu)
--num_contexts_preferring_discrete_gpu_;
DCHECK_GE(num_contexts_preferring_discrete_gpu_, 0);
}
std::string GpuChannel::GetChannelName() {
return channel_id_;
}
#if defined(OS_POSIX)
int GpuChannel::TakeRendererFileDescriptor() {
if (!channel_.get()) {
NOTREACHED();
return -1;
}
return channel_->TakeClientFileDescriptor();
}
#endif // defined(OS_POSIX)
<commit_msg>Only synthesize a reschedule message when descheduled.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if defined(OS_WIN)
#include <windows.h>
#endif
#include "content/common/gpu/gpu_channel.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "content/common/child_process.h"
#include "content/common/gpu/gpu_channel_manager.h"
#include "content/common/gpu/gpu_messages.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_surface.h"
#if defined(OS_POSIX)
#include "ipc/ipc_channel_posix.h"
#endif
namespace {
// The first time polling a fence, delay some extra time to allow other
// stubs to process some work, or else the timing of the fences could
// allow a pattern of alternating fast and slow frames to occur.
const int64 kHandleMoreWorkPeriodMs = 2;
const int64 kHandleMoreWorkPeriodBusyMs = 1;
}
GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager,
GpuWatchdog* watchdog,
gfx::GLShareGroup* share_group,
int client_id,
bool software)
: gpu_channel_manager_(gpu_channel_manager),
client_id_(client_id),
renderer_process_(base::kNullProcessHandle),
renderer_pid_(base::kNullProcessId),
share_group_(share_group ? share_group : new gfx::GLShareGroup),
watchdog_(watchdog),
software_(software),
handle_messages_scheduled_(false),
processed_get_state_fast_(false),
num_contexts_preferring_discrete_gpu_(0),
weak_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
DCHECK(gpu_channel_manager);
DCHECK(client_id);
channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu");
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
disallowed_features_.multisampling =
command_line->HasSwitch(switches::kDisableGLMultisampling);
disallowed_features_.driver_bug_workarounds =
command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds);
}
GpuChannel::~GpuChannel() {
#if defined(OS_WIN)
if (renderer_process_)
CloseHandle(renderer_process_);
#endif
}
bool GpuChannel::OnMessageReceived(const IPC::Message& message) {
if (log_messages_) {
DVLOG(1) << "received message @" << &message << " on channel @" << this
<< " with type " << message.type();
}
// Control messages are not deferred and can be handled out of order with
// respect to routed ones.
if (message.routing_id() == MSG_ROUTING_CONTROL)
return OnControlMessageReceived(message);
if (message.type() == GpuCommandBufferMsg_GetStateFast::ID) {
if (processed_get_state_fast_) {
// Require a non-GetStateFast message in between two GetStateFast
// messages, to ensure progress is made.
std::deque<IPC::Message*>::iterator point = deferred_messages_.begin();
while (point != deferred_messages_.end() &&
(*point)->type() == GpuCommandBufferMsg_GetStateFast::ID) {
++point;
}
if (point != deferred_messages_.end()) {
++point;
}
deferred_messages_.insert(point, new IPC::Message(message));
} else {
// Move GetStateFast commands to the head of the queue, so the renderer
// doesn't have to wait any longer than necessary.
deferred_messages_.push_front(new IPC::Message(message));
}
} else {
deferred_messages_.push_back(new IPC::Message(message));
}
OnScheduled();
return true;
}
void GpuChannel::OnChannelError() {
gpu_channel_manager_->RemoveChannel(client_id_);
}
void GpuChannel::OnChannelConnected(int32 peer_pid) {
renderer_pid_ = peer_pid;
}
bool GpuChannel::Send(IPC::Message* message) {
// The GPU process must never send a synchronous IPC message to the renderer
// process. This could result in deadlock.
DCHECK(!message->is_sync());
if (log_messages_) {
DVLOG(1) << "sending message @" << message << " on channel @" << this
<< " with type " << message->type();
}
if (!channel_.get()) {
delete message;
return false;
}
return channel_->Send(message);
}
void GpuChannel::AppendAllCommandBufferStubs(
std::vector<GpuCommandBufferStubBase*>& stubs) {
for (StubMap::Iterator<GpuCommandBufferStub> it(&stubs_);
!it.IsAtEnd(); it.Advance()) {
stubs.push_back(it.GetCurrentValue());
}
}
void GpuChannel::OnScheduled() {
if (handle_messages_scheduled_)
return;
// Post a task to handle any deferred messages. The deferred message queue is
// not emptied here, which ensures that OnMessageReceived will continue to
// defer newly received messages until the ones in the queue have all been
// handled by HandleMessage. HandleMessage is invoked as a
// task to prevent reentrancy.
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&GpuChannel::HandleMessage, weak_factory_.GetWeakPtr()));
handle_messages_scheduled_ = true;
}
void GpuChannel::LoseAllContexts() {
gpu_channel_manager_->LoseAllContexts();
}
void GpuChannel::DestroySoon() {
MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&GpuChannel::OnDestroy, this));
}
void GpuChannel::OnDestroy() {
TRACE_EVENT0("gpu", "GpuChannel::OnDestroy");
gpu_channel_manager_->RemoveChannel(client_id_);
}
void GpuChannel::CreateViewCommandBuffer(
const gfx::GLSurfaceHandle& window,
int32 surface_id,
const GPUCreateCommandBufferConfig& init_params,
int32* route_id) {
*route_id = MSG_ROUTING_NONE;
content::GetContentClient()->SetActiveURL(init_params.active_url);
#if defined(ENABLE_GPU)
WillCreateCommandBuffer(init_params.gpu_preference);
GpuCommandBufferStub* share_group = stubs_.Lookup(init_params.share_group_id);
*route_id = GenerateRouteID();
scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub(
this,
share_group,
window,
gfx::Size(),
disallowed_features_,
init_params.allowed_extensions,
init_params.attribs,
init_params.gpu_preference,
*route_id,
surface_id,
watchdog_,
software_));
router_.AddRoute(*route_id, stub.get());
stubs_.AddWithID(stub.release(), *route_id);
#endif // ENABLE_GPU
}
GpuCommandBufferStub* GpuChannel::LookupCommandBuffer(int32 route_id) {
return stubs_.Lookup(route_id);
}
bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) {
// Always use IPC_MESSAGE_HANDLER_DELAY_REPLY for synchronous message handlers
// here. This is so the reply can be delayed if the scheduler is unscheduled.
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg)
IPC_MESSAGE_HANDLER(GpuChannelMsg_Initialize, OnInitialize)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer,
OnCreateOffscreenCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer,
OnDestroyCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur,
OnWillGpuSwitchOccur)
IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled) << msg.type();
return handled;
}
void GpuChannel::HandleMessage() {
handle_messages_scheduled_ = false;
if (!deferred_messages_.empty()) {
IPC::Message* m = deferred_messages_.front();
GpuCommandBufferStub* stub = stubs_.Lookup(m->routing_id());
if (stub && !stub->IsScheduled()) {
if (m->type() == GpuCommandBufferMsg_Echo::ID) {
stub->DelayEcho(m);
deferred_messages_.pop_front();
if (!deferred_messages_.empty())
OnScheduled();
}
return;
}
scoped_ptr<IPC::Message> message(m);
deferred_messages_.pop_front();
processed_get_state_fast_ =
(message->type() == GpuCommandBufferMsg_GetStateFast::ID);
// Handle deferred control messages.
if (!router_.RouteMessage(*message)) {
// Respond to sync messages even if router failed to route.
if (message->is_sync()) {
IPC::Message* reply = IPC::SyncMessage::GenerateReply(&*message);
reply->set_reply_error();
Send(reply);
}
} else {
// If the command buffer becomes unscheduled as a result of handling the
// message but still has more commands to process, synthesize an IPC
// message to flush that command buffer.
if (stub) {
if (!stub->IsScheduled() && stub->HasUnprocessedCommands()) {
deferred_messages_.push_front(new GpuCommandBufferMsg_Rescheduled(
stub->route_id()));
}
ScheduleDelayedWork(stub, kHandleMoreWorkPeriodMs);
}
}
}
if (!deferred_messages_.empty()) {
OnScheduled();
}
}
void GpuChannel::PollWork(int route_id) {
GpuCommandBufferStub* stub = stubs_.Lookup(route_id);
if (stub) {
stub->PollWork();
ScheduleDelayedWork(stub, kHandleMoreWorkPeriodBusyMs);
}
}
void GpuChannel::ScheduleDelayedWork(GpuCommandBufferStub *stub,
int64 delay) {
if (stub->HasMoreWork()) {
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&GpuChannel::PollWork,
weak_factory_.GetWeakPtr(),
stub->route_id()),
base::TimeDelta::FromMilliseconds(delay));
}
}
int GpuChannel::GenerateRouteID() {
static int last_id = 0;
return ++last_id;
}
void GpuChannel::AddRoute(int32 route_id, IPC::Channel::Listener* listener) {
router_.AddRoute(route_id, listener);
}
void GpuChannel::RemoveRoute(int32 route_id) {
router_.RemoveRoute(route_id);
}
bool GpuChannel::ShouldPreferDiscreteGpu() const {
return num_contexts_preferring_discrete_gpu_ > 0;
}
void GpuChannel::OnInitialize(base::ProcessHandle renderer_process) {
// Initialize should only happen once.
DCHECK(!renderer_process_);
// Verify that the renderer has passed its own process handle.
if (base::GetProcId(renderer_process) == renderer_pid_)
renderer_process_ = renderer_process;
}
void GpuChannel::OnCreateOffscreenCommandBuffer(
const gfx::Size& size,
const GPUCreateCommandBufferConfig& init_params,
IPC::Message* reply_message) {
int32 route_id = MSG_ROUTING_NONE;
content::GetContentClient()->SetActiveURL(init_params.active_url);
#if defined(ENABLE_GPU)
WillCreateCommandBuffer(init_params.gpu_preference);
GpuCommandBufferStub* share_group = stubs_.Lookup(init_params.share_group_id);
route_id = GenerateRouteID();
scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub(
this,
share_group,
gfx::GLSurfaceHandle(),
size,
disallowed_features_,
init_params.allowed_extensions,
init_params.attribs,
init_params.gpu_preference,
route_id,
0, watchdog_,
software_));
router_.AddRoute(route_id, stub.get());
stubs_.AddWithID(stub.release(), route_id);
TRACE_EVENT1("gpu", "GpuChannel::OnCreateOffscreenCommandBuffer",
"route_id", route_id);
#endif
GpuChannelMsg_CreateOffscreenCommandBuffer::WriteReplyParams(
reply_message,
route_id);
Send(reply_message);
}
void GpuChannel::OnDestroyCommandBuffer(int32 route_id,
IPC::Message* reply_message) {
#if defined(ENABLE_GPU)
TRACE_EVENT1("gpu", "GpuChannel::OnDestroyCommandBuffer",
"route_id", route_id);
if (router_.ResolveRoute(route_id)) {
GpuCommandBufferStub* stub = stubs_.Lookup(route_id);
bool need_reschedule = (stub && !stub->IsScheduled());
gfx::GpuPreference gpu_preference =
stub ? stub->gpu_preference() : gfx::PreferIntegratedGpu;
router_.RemoveRoute(route_id);
stubs_.Remove(route_id);
// In case the renderer is currently blocked waiting for a sync reply from
// the stub, we need to make sure to reschedule the GpuChannel here.
if (need_reschedule)
OnScheduled();
DidDestroyCommandBuffer(gpu_preference);
}
#endif
if (reply_message)
Send(reply_message);
}
void GpuChannel::OnWillGpuSwitchOccur(bool is_creating_context,
gfx::GpuPreference gpu_preference,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuChannel::OnWillGpuSwitchOccur");
bool will_switch_occur = false;
if (gpu_preference == gfx::PreferDiscreteGpu &&
gfx::GLContext::SupportsDualGpus()) {
if (is_creating_context) {
will_switch_occur = !num_contexts_preferring_discrete_gpu_;
} else {
will_switch_occur = (num_contexts_preferring_discrete_gpu_ == 1);
}
}
GpuChannelMsg_WillGpuSwitchOccur::WriteReplyParams(
reply_message,
will_switch_occur);
Send(reply_message);
}
void GpuChannel::OnCloseChannel() {
gpu_channel_manager_->RemoveChannel(client_id_);
// At this point "this" is deleted!
}
bool GpuChannel::Init(base::MessageLoopProxy* io_message_loop,
base::WaitableEvent* shutdown_event) {
DCHECK(!channel_.get());
// Map renderer ID to a (single) channel to that process.
channel_.reset(new IPC::SyncChannel(
channel_id_,
IPC::Channel::MODE_SERVER,
this,
io_message_loop,
false,
shutdown_event));
return true;
}
void GpuChannel::WillCreateCommandBuffer(gfx::GpuPreference gpu_preference) {
if (gpu_preference == gfx::PreferDiscreteGpu)
++num_contexts_preferring_discrete_gpu_;
}
void GpuChannel::DidDestroyCommandBuffer(gfx::GpuPreference gpu_preference) {
if (gpu_preference == gfx::PreferDiscreteGpu)
--num_contexts_preferring_discrete_gpu_;
DCHECK_GE(num_contexts_preferring_discrete_gpu_, 0);
}
std::string GpuChannel::GetChannelName() {
return channel_id_;
}
#if defined(OS_POSIX)
int GpuChannel::TakeRendererFileDescriptor() {
if (!channel_.get()) {
NOTREACHED();
return -1;
}
return channel_->TakeClientFileDescriptor();
}
#endif // defined(OS_POSIX)
<|endoftext|> |
<commit_before>/*
* Copyright 2015-2019 Arm Limited
*
* 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 SPIRV_CROSS_ERROR_HANDLING
#define SPIRV_CROSS_ERROR_HANDLING
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#ifdef SPIRV_CROSS_NAMESPACE_OVERRIDE
#define SPIRV_CROSS_NAMESPACE SPIRV_CROSS_NAMESPACE_OVERRIDE
#else
#define SPIRV_CROSS_NAMESPACE spirv_cross
#endif
namespace SPIRV_CROSS_NAMESPACE
{
#ifdef SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
#ifndef _MSC_VER
[[noreturn]]
#endif
inline void
report_and_abort(const std::string &msg)
{
#ifdef NDEBUG
(void)msg;
#else
fprintf(stderr, "There was a compiler error: %s\n", msg.c_str());
#endif
fflush(stderr);
abort();
}
#define SPIRV_CROSS_THROW(x) report_and_abort(x)
#else
class CompilerError : public std::runtime_error
{
public:
explicit CompilerError(const std::string &str)
: std::runtime_error(str)
{
}
};
#define SPIRV_CROSS_THROW(x) throw CompilerError(x)
#endif
// MSVC 2013 does not have noexcept. We need this for Variant to get move constructor to work correctly
// instead of copy constructor.
// MSVC 2013 ignores that move constructors cannot throw in std::vector, so just don't define it.
#if defined(_MSC_VER) && _MSC_VER < 1900
#define SPIRV_CROSS_NOEXCEPT
#else
#define SPIRV_CROSS_NOEXCEPT noexcept
#endif
#if __cplusplus >= 201402l
#define SPIRV_CROSS_DEPRECATED(reason) [[deprecated(reason)]]
#elif defined(__GNUC__)
#define SPIRV_CROSS_DEPRECATED(reason) __attribute__((deprecated))
#elif defined(_MSC_VER)
#define SPIRV_CROSS_DEPRECATED(reason) __declspec(deprecated(reason))
#else
#define SPIRV_CROSS_DEPRECATED(reason)
#endif
} // namespace SPIRV_CROSS_NAMESPACE
#endif
<commit_msg>Fix guard around [[noreturn]].<commit_after>/*
* Copyright 2015-2019 Arm Limited
*
* 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 SPIRV_CROSS_ERROR_HANDLING
#define SPIRV_CROSS_ERROR_HANDLING
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#ifdef SPIRV_CROSS_NAMESPACE_OVERRIDE
#define SPIRV_CROSS_NAMESPACE SPIRV_CROSS_NAMESPACE_OVERRIDE
#else
#define SPIRV_CROSS_NAMESPACE spirv_cross
#endif
namespace SPIRV_CROSS_NAMESPACE
{
#ifdef SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
#if !defined(_MSC_VER) || defined(__clang__)
[[noreturn]]
#endif
inline void
report_and_abort(const std::string &msg)
{
#ifdef NDEBUG
(void)msg;
#else
fprintf(stderr, "There was a compiler error: %s\n", msg.c_str());
#endif
fflush(stderr);
abort();
}
#define SPIRV_CROSS_THROW(x) report_and_abort(x)
#else
class CompilerError : public std::runtime_error
{
public:
explicit CompilerError(const std::string &str)
: std::runtime_error(str)
{
}
};
#define SPIRV_CROSS_THROW(x) throw CompilerError(x)
#endif
// MSVC 2013 does not have noexcept. We need this for Variant to get move constructor to work correctly
// instead of copy constructor.
// MSVC 2013 ignores that move constructors cannot throw in std::vector, so just don't define it.
#if defined(_MSC_VER) && _MSC_VER < 1900
#define SPIRV_CROSS_NOEXCEPT
#else
#define SPIRV_CROSS_NOEXCEPT noexcept
#endif
#if __cplusplus >= 201402l
#define SPIRV_CROSS_DEPRECATED(reason) [[deprecated(reason)]]
#elif defined(__GNUC__)
#define SPIRV_CROSS_DEPRECATED(reason) __attribute__((deprecated))
#elif defined(_MSC_VER)
#define SPIRV_CROSS_DEPRECATED(reason) __declspec(deprecated(reason))
#else
#define SPIRV_CROSS_DEPRECATED(reason)
#endif
} // namespace SPIRV_CROSS_NAMESPACE
#endif
<|endoftext|> |
<commit_before>/*
* IceWM
*
* Copyright (C) 1998-2003 Marko Macek & Nehal Mistry
*
* Changes:
*
* 2003/06/14
* * created gnome2 support from gnome.cc
*/
#include "config.h"
#ifdef CONFIG_GNOME_MENUS
#include "ylib.h"
#include "default.h"
#include "ypixbuf.h"
#include "yapp.h"
#include "sysdep.h"
#include "base.h"
#include <dirent.h>
#include <string.h>
#include <gnome.h>
#include <libgnome/gnome-desktop-item.h>
#include <libgnomevfs/gnome-vfs-init.h>
#include "yarray.h"
char const * ApplicationName = "icewm-menu-gnome2";
class GnomeMenu;
class GnomeMenuItem {
public:
GnomeMenuItem() { title = 0; icon = 0; dentry = 0; submenu = 0; }
const char *title;
const char *icon;
const char *dentry;
GnomeMenu *submenu;
};
class GnomeMenu {
public:
GnomeMenu() { }
YObjectArray<GnomeMenuItem> items;
bool isDuplicateName(const char *name);
void addEntry(const char *fPath, const char *name, const int plen,
const bool firstRun);
void populateMenu(const char *fPath);
};
void dumpMenu(GnomeMenu *menu) {
for (unsigned int i = 0; i < menu->items.getCount(); i++) {
GnomeMenuItem *item = menu->items.getItem(i);
if (item->dentry && !item->submenu) {
printf("prog \"%s\" %s icewm-menu-gnome2 --open \"%s\"\n",
item->title,
item->icon ? item->icon : "-",
item->dentry);
} else if (item->dentry && item->submenu) {
printf("menuprog \"%s\" %s icewm-menu-gnome2 --list \"%s\"\n",
item->title,
item->icon ? item->icon : "-",
(!strcmp(basename(item->dentry), ".directory") ?
g_dirname(item->dentry) : item->dentry));
}
}
}
bool GnomeMenu::isDuplicateName(const char *name) {
for (unsigned int i = 0; i < items.getCount(); i++) {
GnomeMenuItem *item = items.getItem(i);
if (strcmp(name, item->title) == 0)
return 1;
}
return 0;
}
void GnomeMenu::addEntry(const char *fPath, const char *name, const int plen,
const bool firstRun)
{
const int nlen = (plen == 0 || fPath[plen - 1] != '/')
? plen + 1 + strlen(name)
: plen + strlen(name);
char *npath = new char[nlen + 1];
if (npath) {
strcpy(npath, fPath);
if (plen == 0 || npath[plen - 1] != '/') {
npath[plen] = '/';
strcpy(npath + plen + 1, name);
} else
strcpy(npath + plen, name);
GnomeMenuItem *item = new GnomeMenuItem();
item->title = name;
GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(npath, 0, NULL);
struct stat sb;
char *type;
bool isDir = (!stat(npath, &sb) && S_ISDIR(sb.st_mode));
type = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_TYPE);
if (!isDir && type && strstr(type, "Directory")) {
isDir = 1;
}
if (isDir) {
GnomeMenu *submenu = new GnomeMenu();
item->title = g_basename(npath);
item->icon = gnome_pixmap_file("gnome-folder.png");
item->submenu = submenu;
char *epath = new char[nlen + sizeof("/.directory")];
strcpy(epath, npath);
strcpy(epath + nlen, "/.directory");
if (stat(epath, &sb) == -1) {
strcpy(epath, npath);
}
ditem = gnome_desktop_item_new_from_file(epath, 0, NULL);
if (ditem) {
item->title = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_NAME);
item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON);
}
item->dentry = epath;
} else {
if (type && !strstr(type, "Directory")) {
item->title = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_NAME);
if (gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON))
item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON);
item->dentry = npath;
}
}
if (firstRun || !isDuplicateName(item->title))
items.append(item);
}
}
void GnomeMenu::populateMenu(const char *fPath) {
GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(fPath, 0, NULL);
struct stat sb;
bool isDir = (!stat(fPath, &sb) && S_ISDIR(sb.st_mode));
const int plen = strlen(fPath);
char tmp[256];
strcpy(tmp, fPath);
strcat(tmp, "/.directory");
if (isDir && !stat(tmp, &sb)) { // looks like kde/gnome1 style
char *opath = new char[plen + sizeof("/.order")];
if (opath) {
strcpy(opath, fPath);
strcpy(opath + plen, "/.order");
FILE * order(fopen(opath, "r"));
if (order) {
char oentry[100];
while (fgets(oentry, sizeof (oentry), order)) {
const int oend = strlen(oentry) - 1;
if (oend > 0 && oentry[oend] == '\n')
oentry[oend] = '\0';
addEntry(fPath, oentry, plen, true);
}
fclose(order);
}
delete opath;
}
DIR *dir = opendir(fPath);
if (dir != 0) {
struct dirent *file;
while ((file = readdir(dir)) != NULL) {
if (*file->d_name != '.')
addEntry(fPath, file->d_name, plen, false);
}
closedir(dir);
}
} else { // gnome2 style
char *category = NULL;
char dirname[256] = "a";
if (isDir) {
strcpy(dirname, fPath);
} else if (strstr(fPath, "Settings")) {
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "Advanced")) {
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else {
dirname[0] = '\0';
}
if (isDir) {
DIR *dir = opendir(dirname);
if (dir != 0) {
struct dirent *file;
while ((file = readdir(dir)) != NULL) {
if (!strcmp(dirname, fPath) && (strstr(file->d_name, "Accessibility") ||
strstr(file->d_name, "Advanced") || strstr(file->d_name, "Applications") ||
strstr(file->d_name, "Root") ))
continue;
if (*file->d_name != '.')
addEntry(dirname, file->d_name, strlen(dirname), false);
}
closedir(dir);
}
}
strcpy(dirname, "/usr/share/applications/");
if (isDir) {
category = strdup("ion;Core");
} else if (strstr(fPath, "Applications")) {
category = strdup("ion;Merg");
} else if (strstr(fPath, "Accessories")) {
category = strdup("ion;Util");
} else if (strstr(fPath, "Advanced")) {
category = strdup("ngs;Adva");
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "Accessibility")) {
category = strdup("ngs;Acce");
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "Development")) {
category = strdup("ion;Deve");
} else if (strstr(fPath, "Editors")) {
category = strdup("ion;Text");
} else if (strstr(fPath, "Games")) {
category = strdup("ion;Game");
} else if (strstr(fPath, "Graphics")) {
category = strdup("ion;Grap");
} else if (strstr(fPath, "Internet")) {
category = strdup("ion;Netw");
} else if (strstr(fPath, "Root")) {
category = strdup("ion;Core");
} else if (strstr(fPath, "Multimedia")) {
category = strdup("ion;Audi");
} else if (strstr(fPath, "Office")) {
category = strdup("ion;Offi");
} else if (strstr(fPath, "Settings")) {
category = strdup("ion;Sett");
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "System")) {
category = strdup("ion;Syst");
} else {
category = strdup("xyz");
}
if (!strlen(dirname))
strcpy(dirname, "/usr/share/applications/");
DIR* dir = opendir(dirname);
if (dir != 0) {
struct dirent *file;
while ((file = readdir(dir)) != NULL) {
char fullpath[256];
strcpy(fullpath, dirname);
strcat(fullpath, file->d_name);
GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(fullpath, 0, NULL);
char *categories = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_CATEGORIES);
if (categories && strstr(categories, category)) {
if (*file->d_name != '.') {
if (strstr(fPath, "Settings")) {
if (!strstr(categories, "ngs;Adva") && !strstr(categories, "ngs;Acce"))
addEntry(dirname, file->d_name, strlen(dirname), false);
} else {
addEntry(dirname, file->d_name, strlen(dirname), false);
}
}
}
}
if (strstr(fPath, "Settings")) {
addEntry("/usr/share/gnome/vfolders/", "Accessibility.directory",
strlen("/usr/share/gnome/vfolders/"), false);
addEntry("/usr/share/gnome/vfolders/", "Advanced.directory",
strlen("/usr/share/gnome/vfolders/"), false);
}
closedir(dir);
}
}
}
int makeMenu(const char *base_directory) {
GnomeMenu *menu = new GnomeMenu();
menu->populateMenu(base_directory);
dumpMenu(menu);
return 0;
}
int runFile(const char *dentry_path) {
char arg[32];
int i;
GnomeDesktopItem *ditem = gnome_desktop_item_new_from_file(dentry_path, 0, NULL);
if (ditem == NULL) {
return 1;
} else {
// FIXME: leads to segfault for some reason, so using execlp instead
// gnome_desktop_item_launch(ditem, NULL, 0, NULL);
const char *app = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_EXEC);
for (i = 0; app[i] && app[i] != ' '; ++i) {
arg[i] = app[i];
}
arg[i] = '\0';
execlp(arg, arg);
}
return 0;
}
int main(int argc, char **argv) {
gnome_vfs_init();
for (char ** arg = argv + 1; arg < argv + argc; ++arg) {
if (**arg == '-') {
char *path = 0;
if (IS_SWITCH("h", "help"))
break;
if ((path = GET_LONG_ARGUMENT("open")) != NULL) {
return runFile(path);
} else if ((path = GET_LONG_ARGUMENT("list")) != NULL) {
return makeMenu(path);
}
}
}
msg("Usage: %s [ --open PATH | --list PATH ]", argv[0]);
}
#endif
<commit_msg>fix compile warnings<commit_after>/*
* IceWM
*
* Copyright (C) 1998-2003 Marko Macek & Nehal Mistry
*
* Changes:
*
* 2003/06/14
* * created gnome2 support from gnome.cc
*/
#include "config.h"
#ifdef CONFIG_GNOME_MENUS
#include "ylib.h"
#include "default.h"
#include "ypixbuf.h"
#include "yapp.h"
#include "sysdep.h"
#include "base.h"
#include <dirent.h>
#include <string.h>
#include <gnome.h>
#include <libgnome/gnome-desktop-item.h>
#include <libgnomevfs/gnome-vfs-init.h>
#include "yarray.h"
char const * ApplicationName = "icewm-menu-gnome2";
class GnomeMenu;
class GnomeMenuItem {
public:
GnomeMenuItem() { title = 0; icon = 0; dentry = 0; submenu = 0; }
const char *title;
const char *icon;
const char *dentry;
GnomeMenu *submenu;
};
class GnomeMenu {
public:
GnomeMenu() { }
YObjectArray<GnomeMenuItem> items;
bool isDuplicateName(const char *name);
void addEntry(const char *fPath, const char *name, const int plen,
const bool firstRun);
void populateMenu(const char *fPath);
};
void dumpMenu(GnomeMenu *menu) {
for (unsigned int i = 0; i < menu->items.getCount(); i++) {
GnomeMenuItem *item = menu->items.getItem(i);
if (item->dentry && !item->submenu) {
printf("prog \"%s\" %s icewm-menu-gnome2 --open \"%s\"\n",
item->title,
item->icon ? item->icon : "-",
item->dentry);
} else if (item->dentry && item->submenu) {
printf("menuprog \"%s\" %s icewm-menu-gnome2 --list \"%s\"\n",
item->title,
item->icon ? item->icon : "-",
(!strcmp(basename(item->dentry), ".directory") ?
g_dirname(item->dentry) : item->dentry));
}
}
}
bool GnomeMenu::isDuplicateName(const char *name) {
for (unsigned int i = 0; i < items.getCount(); i++) {
GnomeMenuItem *item = items.getItem(i);
if (strcmp(name, item->title) == 0)
return 1;
}
return 0;
}
void GnomeMenu::addEntry(const char *fPath, const char *name, const int plen,
const bool firstRun)
{
const int nlen = (plen == 0 || fPath[plen - 1] != '/')
? plen + 1 + strlen(name)
: plen + strlen(name);
char *npath = new char[nlen + 1];
if (npath) {
strcpy(npath, fPath);
if (plen == 0 || npath[plen - 1] != '/') {
npath[plen] = '/';
strcpy(npath + plen + 1, name);
} else
strcpy(npath + plen, name);
GnomeMenuItem *item = new GnomeMenuItem();
item->title = name;
GnomeDesktopItem *ditem =
gnome_desktop_item_new_from_file(npath,
(GnomeDesktopItemLoadFlags)0,
NULL);
struct stat sb;
const char *type;
bool isDir = (!stat(npath, &sb) && S_ISDIR(sb.st_mode));
type = gnome_desktop_item_get_string(ditem,
GNOME_DESKTOP_ITEM_TYPE);
if (!isDir && type && strstr(type, "Directory")) {
isDir = 1;
}
if (isDir) {
GnomeMenu *submenu = new GnomeMenu();
item->title = g_basename(npath);
item->icon = gnome_pixmap_file("gnome-folder.png");
item->submenu = submenu;
char *epath = new char[nlen + sizeof("/.directory")];
strcpy(epath, npath);
strcpy(epath + nlen, "/.directory");
if (stat(epath, &sb) == -1) {
strcpy(epath, npath);
}
ditem = gnome_desktop_item_new_from_file(epath,
(GnomeDesktopItemLoadFlags)0,
NULL);
if (ditem) {
item->title = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_NAME);
item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON);
}
item->dentry = epath;
} else {
if (type && !strstr(type, "Directory")) {
item->title = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_NAME);
if (gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON))
item->icon = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_ICON);
item->dentry = npath;
}
}
if (firstRun || !isDuplicateName(item->title))
items.append(item);
}
}
void GnomeMenu::populateMenu(const char *fPath) {
struct stat sb;
bool isDir = (!stat(fPath, &sb) && S_ISDIR(sb.st_mode));
const int plen = strlen(fPath);
char tmp[256];
strcpy(tmp, fPath);
strcat(tmp, "/.directory");
if (isDir && !stat(tmp, &sb)) { // looks like kde/gnome1 style
char *opath = new char[plen + sizeof("/.order")];
if (opath) {
strcpy(opath, fPath);
strcpy(opath + plen, "/.order");
FILE * order(fopen(opath, "r"));
if (order) {
char oentry[100];
while (fgets(oentry, sizeof (oentry), order)) {
const int oend = strlen(oentry) - 1;
if (oend > 0 && oentry[oend] == '\n')
oentry[oend] = '\0';
addEntry(fPath, oentry, plen, true);
}
fclose(order);
}
delete opath;
}
DIR *dir = opendir(fPath);
if (dir != 0) {
struct dirent *file;
while ((file = readdir(dir)) != NULL) {
if (*file->d_name != '.')
addEntry(fPath, file->d_name, plen, false);
}
closedir(dir);
}
} else { // gnome2 style
char *category = NULL;
char dirname[256] = "a";
if (isDir) {
strcpy(dirname, fPath);
} else if (strstr(fPath, "Settings")) {
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "Advanced")) {
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else {
dirname[0] = '\0';
}
if (isDir) {
DIR *dir = opendir(dirname);
if (dir != 0) {
struct dirent *file;
while ((file = readdir(dir)) != NULL) {
if (!strcmp(dirname, fPath) && (strstr(file->d_name, "Accessibility") ||
strstr(file->d_name, "Advanced") || strstr(file->d_name, "Applications") ||
strstr(file->d_name, "Root") ))
continue;
if (*file->d_name != '.')
addEntry(dirname, file->d_name, strlen(dirname), false);
}
closedir(dir);
}
}
strcpy(dirname, "/usr/share/applications/");
if (isDir) {
category = strdup("ion;Core");
} else if (strstr(fPath, "Applications")) {
category = strdup("ion;Merg");
} else if (strstr(fPath, "Accessories")) {
category = strdup("ion;Util");
} else if (strstr(fPath, "Advanced")) {
category = strdup("ngs;Adva");
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "Accessibility")) {
category = strdup("ngs;Acce");
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "Development")) {
category = strdup("ion;Deve");
} else if (strstr(fPath, "Editors")) {
category = strdup("ion;Text");
} else if (strstr(fPath, "Games")) {
category = strdup("ion;Game");
} else if (strstr(fPath, "Graphics")) {
category = strdup("ion;Grap");
} else if (strstr(fPath, "Internet")) {
category = strdup("ion;Netw");
} else if (strstr(fPath, "Root")) {
category = strdup("ion;Core");
} else if (strstr(fPath, "Multimedia")) {
category = strdup("ion;Audi");
} else if (strstr(fPath, "Office")) {
category = strdup("ion;Offi");
} else if (strstr(fPath, "Settings")) {
category = strdup("ion;Sett");
strcpy(dirname, "/usr/share/control-center-2.0/capplets/");
} else if (strstr(fPath, "System")) {
category = strdup("ion;Syst");
} else {
category = strdup("xyz");
}
if (!strlen(dirname))
strcpy(dirname, "/usr/share/applications/");
DIR* dir = opendir(dirname);
if (dir != 0) {
struct dirent *file;
while ((file = readdir(dir)) != NULL) {
char fullpath[256];
strcpy(fullpath, dirname);
strcat(fullpath, file->d_name);
GnomeDesktopItem *ditem =
gnome_desktop_item_new_from_file(fullpath,
(GnomeDesktopItemLoadFlags)0,
NULL);
const char *categories =
gnome_desktop_item_get_string(ditem,
GNOME_DESKTOP_ITEM_CATEGORIES);
if (categories && strstr(categories, category)) {
if (*file->d_name != '.') {
if (strstr(fPath, "Settings")) {
if (!strstr(categories, "ngs;Adva") && !strstr(categories, "ngs;Acce"))
addEntry(dirname, file->d_name, strlen(dirname), false);
} else {
addEntry(dirname, file->d_name, strlen(dirname), false);
}
}
}
}
if (strstr(fPath, "Settings")) {
addEntry("/usr/share/gnome/vfolders/", "Accessibility.directory",
strlen("/usr/share/gnome/vfolders/"), false);
addEntry("/usr/share/gnome/vfolders/", "Advanced.directory",
strlen("/usr/share/gnome/vfolders/"), false);
}
closedir(dir);
}
}
}
int makeMenu(const char *base_directory) {
GnomeMenu *menu = new GnomeMenu();
menu->populateMenu(base_directory);
dumpMenu(menu);
return 0;
}
int runFile(const char *dentry_path) {
char arg[32];
int i;
GnomeDesktopItem *ditem =
gnome_desktop_item_new_from_file(dentry_path,
(GnomeDesktopItemLoadFlags)0,
NULL);
if (ditem == NULL) {
return 1;
} else {
// FIXME: leads to segfault for some reason, so using execlp instead
// gnome_desktop_item_launch(ditem, NULL, 0, NULL);
const char *app = gnome_desktop_item_get_string(ditem, GNOME_DESKTOP_ITEM_EXEC);
for (i = 0; app[i] && app[i] != ' '; ++i) {
arg[i] = app[i];
}
arg[i] = '\0';
execlp(arg, arg);
}
return 0;
}
int main(int argc, char **argv) {
gnome_vfs_init();
for (char ** arg = argv + 1; arg < argv + argc; ++arg) {
if (**arg == '-') {
char *path = 0;
if (IS_SWITCH("h", "help"))
break;
if ((path = GET_LONG_ARGUMENT("open")) != NULL) {
return runFile(path);
} else if ((path = GET_LONG_ARGUMENT("list")) != NULL) {
return makeMenu(path);
}
}
}
msg("Usage: %s [ --open PATH | --list PATH ]", argv[0]);
}
#endif
<|endoftext|> |
<commit_before>/*
* OCILIB - C Driver for Oracle (C Wrapper for Oracle OCI)
*
* Website: http://www.ocilib.net
*
* Copyright (c) 2007-2016 Vincent ROGIER <vince.rogier@ocilib.net>
*
* 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.
*/
/*
* IMPORTANT NOTICE
*
* This C++ header defines C++ wrapper classes around the OCILIB C API
* It requires a compatible version of OCILIB
*
*/
#pragma once
#include <map>
namespace ocilib
{
/* Try to guess C++ Compiler capabilities ... */
#define CPP_98 199711L
#define CPP_11 201103L
#define CPP_14 201402L
#if __cplusplus < CPP_11
#if defined(__GNUC__)
#if defined(__GXX_EXPERIMENTAL_CXX0X__)
#define HAVE_NULLPTR
#define HAVE_MOVE_SEMANTICS
#else
#define override
#endif
#elif defined(_MSC_VER)
#if _MSC_VER >= 1600
#define HAVE_NULLPTR
#define HAVE_MOVE_SEMANTICS
#else
#define override
#endif
#endif
#else
#define HAVE_NULLPTR
#define HAVE_MOVE_SEMANTICS
#endif
/* guessing if nullptr is supported */
#ifndef HAVE_NULLPTR
#define nullptr 0
#endif
#define ARG_NOT_USED(a) (a) = (a)
/* class forward declarations */
class Exception;
class Connection;
class Transaction;
class Environment;
class Statement;
class Resultset;
class Date;
class Timestamp;
class Interval;
class TypeInfo;
class Reference;
class Object;
template<class>
class Element;
template<class>
class Iterator;
template<class>
class Collection;
template<class, int>
class Lob;
class File;
class Pool;
template<class, int>
class Long;
class Column;
class Subscription;
class Event;
class Agent;
class Message;
class Enqueue;
class Dequeue;
class Queue;
class QueueTable;
class DirectPath;
class Thread;
class ThreadKey;
class Mutex;
class BindInfo;
/**
* @brief Internal usage.
* Allow resolving a native type used by C API from a C++ type in binding operations
*/
template<class T> struct BindResolver {};
/**
* @brief Internal usage.
* Checks if the last OCILIB function call has raised an error.
* If so, it raises a C++ exception using the retrieved error handle
*/
template<class T>
static T Check(T result);
/**
* @brief Internal usage.
* Constructs a C++ string object from the given OCILIB string pointer
*/
ostring MakeString(const otext *result, int size = -1);
/**
* @brief Internal usage.
* Constructs a C++ Raw object from the given OCILIB raw buffer
*/
Raw MakeRaw(void *result, unsigned int size);
/**
* @brief
* Template class providing OCILIB handles auto memory, life cycle and scope management
*/
template<class>
class HandleHolder;
/**
* @brief
* Template Enumeration template class providing some type safety to some extends for manipulating enumerated variables
*/
template<class T>
class Enum
{
public:
typedef T Type;
Enum();
Enum(T value);
T GetValue();
operator T ();
operator unsigned int () const;
bool operator == (const Enum& other) const;
bool operator != (const Enum& other) const;
bool operator == (const T& other) const;
bool operator != (const T& other) const;
private:
T _value;
};
/**
* @brief
* Template Flags template class providing some type safety to some extends for manipulating flags set variables
*/
template<class T>
class Flags
{
public:
typedef T Type;
Flags();
Flags(T flag);
Flags(const Flags& other);
Flags operator~ () const;
Flags operator | (T other) const;
Flags operator & (T other) const;
Flags operator ^ (T other) const;
Flags operator | (const Flags& other) const;
Flags operator & (const Flags& other) const;
Flags operator ^ (const Flags& other) const;
Flags& operator |= (T other);
Flags& operator &= (T other);
Flags& operator ^= (T other);
Flags& operator |= (const Flags& other);
Flags& operator &= (const Flags& other);
Flags& operator ^= (const Flags& other);
bool operator == (T other) const;
bool operator == (const Flags& other) const;
unsigned int GetValues() const;
bool IsSet(T other) const;
private:
Flags(unsigned int flags);
unsigned int _flags;
};
template< typename T>
class ManagedBuffer
{
public:
ManagedBuffer();
ManagedBuffer(size_t size);
ManagedBuffer(T *buffer, size_t size);
~ManagedBuffer();
operator T* () const;
operator const T* () const;
private:
T* _buffer;
size_t _size;
};
class Locker
{
public:
Locker();
virtual ~Locker();
void Lock() const;
void Unlock() const;
void SetAccessMode(bool threaded);
private:
MutexHandle _mutex;
};
class Lockable
{
public:
Lockable();
virtual ~Lockable();
void SetLocker(Locker *locker);
void Lock() const;
void Unlock() const;
private:
Locker *_locker;
};
template<class K, class V>
class ConcurrentMap : public Lockable
{
public:
ConcurrentMap();
virtual ~ConcurrentMap();
void Remove(K key);
V Get(K key);
void Set(K key, V value);
void Clear();
size_t GetSize();
private:
std::map<K, V> _map;
};
template<class T>
class ConcurrentList : public Lockable
{
public:
ConcurrentList();
virtual ~ConcurrentList();
void Add(T value);
void Remove(T value);
void Clear();
size_t GetSize();
bool Exists(const T &value);
template<class P>
bool FindIf(P predicate, T &value);
template<class A>
void ForEach(A action);
private:
std::list<T> _list;
};
class Handle
{
public:
virtual ~Handle() {}
virtual ConcurrentList<Handle *> & GetChildren() = 0;
virtual void DetachFromHolders() = 0;
virtual void DetachFromParent() = 0;
};
/**
* @brief
* Smart pointer class with reference counting for managing OCILIB object handles
*/
template<class T>
class HandleHolder
{
public:
bool IsNull() const;
operator bool();
operator bool() const;
operator T();
operator T() const;
protected:
class SmartHandle;
HandleHolder(const HandleHolder &other);
HandleHolder();
~HandleHolder();
HandleHolder& operator= (const HandleHolder &other);
typedef boolean(OCI_API *HandleFreeFunc)(AnyPointer handle);
typedef void(*SmartHandleFreeNotifyFunc)(SmartHandle *smartHandle);
Handle* GetHandle() const;
void Acquire(T handle, HandleFreeFunc handleFreefunc, SmartHandleFreeNotifyFunc freeNotifyFunc, Handle *parent);
void Acquire(HandleHolder &other);
void Release();
class SmartHandle : public Handle
{
public:
SmartHandle(HandleHolder *holder, T handle, HandleFreeFunc handleFreefunc, SmartHandleFreeNotifyFunc freeNotifyFunc, Handle *parent);
virtual ~SmartHandle();
void Acquire(HandleHolder *holder);
void Release(HandleHolder *holder);
T GetHandle() const;
Handle *GetParent() const;
AnyPointer GetExtraInfos() const;
void SetExtraInfos(AnyPointer extraInfo);
ConcurrentList<Handle *> & GetChildren() override;
void DetachFromHolders() override;
void DetachFromParent() override;
private:
static void DeleteHandle(Handle *handle);
static void ResetHolder(HandleHolder *holder);
ConcurrentList<HandleHolder *> _holders;
ConcurrentList<Handle *> _children;
Locker _locker;
T _handle;
HandleFreeFunc _handleFreeFunc;
SmartHandleFreeNotifyFunc _freeNotifyFunc;
Handle *_parent;
AnyPointer _extraInfo;
};
SmartHandle *_smartHandle;
};
/**
* @brief
* Abstract class allowing derived classes to be compatible
* with any type supporting the operator << ocilib::ostring
*/
class Streamable
{
public:
virtual ~Streamable() {}
operator ostring() const
{
return ToString();
}
virtual ostring ToString() const = 0;
template<class T>
friend T& operator << (T &lhs, const Streamable &rhs)
{
lhs << static_cast<ostring>(rhs);
return lhs;
}
};
class BindObject
{
public:
BindObject(const Statement &statement, const ostring& name, unsigned int mode);
virtual ~BindObject();
ostring GetName() const;
Statement GetStatement() const;
unsigned int GetMode() const;
virtual void SetInData() = 0;
virtual void SetOutData() = 0;
protected:
OCI_Statement *_pStatement;
ostring _name;
unsigned int _mode;
};
class BindArray : public BindObject
{
public:
BindArray(const Statement &statement, const ostring& name, unsigned int mode);
virtual ~BindArray();
template<class T>
void SetVector(std::vector<T> & vector, unsigned int elemSize);
template<class T>
typename BindResolver<T>::OutputType * GetData() const;
void SetInData() override;
void SetOutData() override;
private:
class AbstractBindArrayObject
{
public:
AbstractBindArrayObject() { }
virtual ~AbstractBindArrayObject() { }
virtual void SetInData() = 0;
virtual void SetOutData() = 0;
virtual ostring GetName() = 0;
};
template<class T>
class BindArrayObject : public AbstractBindArrayObject
{
public:
typedef T ObjectType;
typedef std::vector<ObjectType> ObjectVector;
typedef typename BindResolver<ObjectType>::OutputType NativeType;
BindArrayObject(const Statement &statement, const ostring& name, ObjectVector &vector, unsigned int mode, unsigned int elemSize);
virtual ~BindArrayObject();
void SetInData() override;
void SetOutData() override;
ostring GetName() override;
operator ObjectVector & () const;
operator NativeType * () const;
private:
void AllocData();
void FreeData() const;
OCI_Statement *_pStatement;
ostring _name;
ObjectVector& _vector;
NativeType *_data;
unsigned int _mode;
unsigned int _elemCount;
unsigned int _elemSize;
};
AbstractBindArrayObject * _object;
};
template<class T>
class BindObjectAdaptor : public BindObject
{
friend class Statement;
public:
typedef T ObjectType;
typedef typename BindResolver<ObjectType>::OutputType NativeType;
operator NativeType *() const;
void SetInData() override;
void SetOutData() override;
BindObjectAdaptor(const Statement &statement, const ostring& name, unsigned int mode, ObjectType &object, unsigned int size);
virtual ~BindObjectAdaptor();
private:
ObjectType& _object;
NativeType* _data;
unsigned int _size;
};
template<class T>
class BindTypeAdaptor : public BindObject
{
friend class Statement;
public:
typedef T ObjectType;
typedef typename BindResolver<ObjectType>::OutputType NativeType;
operator NativeType *() const;
void SetInData() override;
void SetOutData() override;
BindTypeAdaptor(const Statement &statement, const ostring& name, unsigned int mode, ObjectType &object);
virtual ~BindTypeAdaptor();
private:
ObjectType& _object;
NativeType* _data;
};
class BindsHolder
{
public:
BindsHolder(const Statement &statement);
~BindsHolder();
void Clear();
void AddBindObject(BindObject *bindObject);
void SetOutData();
void SetInData();
private:
std::vector<BindObject *> _bindObjects;
OCI_Statement * _pStatement;
};
}
<commit_msg>resolved #63 - Included cstddef header<commit_after>/*
* OCILIB - C Driver for Oracle (C Wrapper for Oracle OCI)
*
* Website: http://www.ocilib.net
*
* Copyright (c) 2007-2016 Vincent ROGIER <vince.rogier@ocilib.net>
*
* 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.
*/
/*
* IMPORTANT NOTICE
*
* This C++ header defines C++ wrapper classes around the OCILIB C API
* It requires a compatible version of OCILIB
*
*/
#pragma once
#include <map>
#include <cstddef>
namespace ocilib
{
/* Try to guess C++ Compiler capabilities ... */
#define CPP_98 199711L
#define CPP_11 201103L
#define CPP_14 201402L
#if __cplusplus < CPP_11
#if defined(__GNUC__)
#if defined(__GXX_EXPERIMENTAL_CXX0X__)
#define HAVE_NULLPTR
#define HAVE_MOVE_SEMANTICS
#else
#define override
#endif
#elif defined(_MSC_VER)
#if _MSC_VER >= 1600
#define HAVE_NULLPTR
#define HAVE_MOVE_SEMANTICS
#else
#define override
#endif
#endif
#else
#define HAVE_NULLPTR
#define HAVE_MOVE_SEMANTICS
#endif
/* guessing if nullptr is supported */
#ifndef HAVE_NULLPTR
#define nullptr 0
#endif
#define ARG_NOT_USED(a) (a) = (a)
/* class forward declarations */
class Exception;
class Connection;
class Transaction;
class Environment;
class Statement;
class Resultset;
class Date;
class Timestamp;
class Interval;
class TypeInfo;
class Reference;
class Object;
template<class>
class Element;
template<class>
class Iterator;
template<class>
class Collection;
template<class, int>
class Lob;
class File;
class Pool;
template<class, int>
class Long;
class Column;
class Subscription;
class Event;
class Agent;
class Message;
class Enqueue;
class Dequeue;
class Queue;
class QueueTable;
class DirectPath;
class Thread;
class ThreadKey;
class Mutex;
class BindInfo;
/**
* @brief Internal usage.
* Allow resolving a native type used by C API from a C++ type in binding operations
*/
template<class T> struct BindResolver {};
/**
* @brief Internal usage.
* Checks if the last OCILIB function call has raised an error.
* If so, it raises a C++ exception using the retrieved error handle
*/
template<class T>
static T Check(T result);
/**
* @brief Internal usage.
* Constructs a C++ string object from the given OCILIB string pointer
*/
ostring MakeString(const otext *result, int size = -1);
/**
* @brief Internal usage.
* Constructs a C++ Raw object from the given OCILIB raw buffer
*/
Raw MakeRaw(void *result, unsigned int size);
/**
* @brief
* Template class providing OCILIB handles auto memory, life cycle and scope management
*/
template<class>
class HandleHolder;
/**
* @brief
* Template Enumeration template class providing some type safety to some extends for manipulating enumerated variables
*/
template<class T>
class Enum
{
public:
typedef T Type;
Enum();
Enum(T value);
T GetValue();
operator T ();
operator unsigned int () const;
bool operator == (const Enum& other) const;
bool operator != (const Enum& other) const;
bool operator == (const T& other) const;
bool operator != (const T& other) const;
private:
T _value;
};
/**
* @brief
* Template Flags template class providing some type safety to some extends for manipulating flags set variables
*/
template<class T>
class Flags
{
public:
typedef T Type;
Flags();
Flags(T flag);
Flags(const Flags& other);
Flags operator~ () const;
Flags operator | (T other) const;
Flags operator & (T other) const;
Flags operator ^ (T other) const;
Flags operator | (const Flags& other) const;
Flags operator & (const Flags& other) const;
Flags operator ^ (const Flags& other) const;
Flags& operator |= (T other);
Flags& operator &= (T other);
Flags& operator ^= (T other);
Flags& operator |= (const Flags& other);
Flags& operator &= (const Flags& other);
Flags& operator ^= (const Flags& other);
bool operator == (T other) const;
bool operator == (const Flags& other) const;
unsigned int GetValues() const;
bool IsSet(T other) const;
private:
Flags(unsigned int flags);
unsigned int _flags;
};
template< typename T>
class ManagedBuffer
{
public:
ManagedBuffer();
ManagedBuffer(size_t size);
ManagedBuffer(T *buffer, size_t size);
~ManagedBuffer();
operator T* () const;
operator const T* () const;
private:
T* _buffer;
size_t _size;
};
class Locker
{
public:
Locker();
virtual ~Locker();
void Lock() const;
void Unlock() const;
void SetAccessMode(bool threaded);
private:
MutexHandle _mutex;
};
class Lockable
{
public:
Lockable();
virtual ~Lockable();
void SetLocker(Locker *locker);
void Lock() const;
void Unlock() const;
private:
Locker *_locker;
};
template<class K, class V>
class ConcurrentMap : public Lockable
{
public:
ConcurrentMap();
virtual ~ConcurrentMap();
void Remove(K key);
V Get(K key);
void Set(K key, V value);
void Clear();
size_t GetSize();
private:
std::map<K, V> _map;
};
template<class T>
class ConcurrentList : public Lockable
{
public:
ConcurrentList();
virtual ~ConcurrentList();
void Add(T value);
void Remove(T value);
void Clear();
size_t GetSize();
bool Exists(const T &value);
template<class P>
bool FindIf(P predicate, T &value);
template<class A>
void ForEach(A action);
private:
std::list<T> _list;
};
class Handle
{
public:
virtual ~Handle() {}
virtual ConcurrentList<Handle *> & GetChildren() = 0;
virtual void DetachFromHolders() = 0;
virtual void DetachFromParent() = 0;
};
/**
* @brief
* Smart pointer class with reference counting for managing OCILIB object handles
*/
template<class T>
class HandleHolder
{
public:
bool IsNull() const;
operator bool();
operator bool() const;
operator T();
operator T() const;
protected:
class SmartHandle;
HandleHolder(const HandleHolder &other);
HandleHolder();
~HandleHolder();
HandleHolder& operator= (const HandleHolder &other);
typedef boolean(OCI_API *HandleFreeFunc)(AnyPointer handle);
typedef void(*SmartHandleFreeNotifyFunc)(SmartHandle *smartHandle);
Handle* GetHandle() const;
void Acquire(T handle, HandleFreeFunc handleFreefunc, SmartHandleFreeNotifyFunc freeNotifyFunc, Handle *parent);
void Acquire(HandleHolder &other);
void Release();
class SmartHandle : public Handle
{
public:
SmartHandle(HandleHolder *holder, T handle, HandleFreeFunc handleFreefunc, SmartHandleFreeNotifyFunc freeNotifyFunc, Handle *parent);
virtual ~SmartHandle();
void Acquire(HandleHolder *holder);
void Release(HandleHolder *holder);
T GetHandle() const;
Handle *GetParent() const;
AnyPointer GetExtraInfos() const;
void SetExtraInfos(AnyPointer extraInfo);
ConcurrentList<Handle *> & GetChildren() override;
void DetachFromHolders() override;
void DetachFromParent() override;
private:
static void DeleteHandle(Handle *handle);
static void ResetHolder(HandleHolder *holder);
ConcurrentList<HandleHolder *> _holders;
ConcurrentList<Handle *> _children;
Locker _locker;
T _handle;
HandleFreeFunc _handleFreeFunc;
SmartHandleFreeNotifyFunc _freeNotifyFunc;
Handle *_parent;
AnyPointer _extraInfo;
};
SmartHandle *_smartHandle;
};
/**
* @brief
* Abstract class allowing derived classes to be compatible
* with any type supporting the operator << ocilib::ostring
*/
class Streamable
{
public:
virtual ~Streamable() {}
operator ostring() const
{
return ToString();
}
virtual ostring ToString() const = 0;
template<class T>
friend T& operator << (T &lhs, const Streamable &rhs)
{
lhs << static_cast<ostring>(rhs);
return lhs;
}
};
class BindObject
{
public:
BindObject(const Statement &statement, const ostring& name, unsigned int mode);
virtual ~BindObject();
ostring GetName() const;
Statement GetStatement() const;
unsigned int GetMode() const;
virtual void SetInData() = 0;
virtual void SetOutData() = 0;
protected:
OCI_Statement *_pStatement;
ostring _name;
unsigned int _mode;
};
class BindArray : public BindObject
{
public:
BindArray(const Statement &statement, const ostring& name, unsigned int mode);
virtual ~BindArray();
template<class T>
void SetVector(std::vector<T> & vector, unsigned int elemSize);
template<class T>
typename BindResolver<T>::OutputType * GetData() const;
void SetInData() override;
void SetOutData() override;
private:
class AbstractBindArrayObject
{
public:
AbstractBindArrayObject() { }
virtual ~AbstractBindArrayObject() { }
virtual void SetInData() = 0;
virtual void SetOutData() = 0;
virtual ostring GetName() = 0;
};
template<class T>
class BindArrayObject : public AbstractBindArrayObject
{
public:
typedef T ObjectType;
typedef std::vector<ObjectType> ObjectVector;
typedef typename BindResolver<ObjectType>::OutputType NativeType;
BindArrayObject(const Statement &statement, const ostring& name, ObjectVector &vector, unsigned int mode, unsigned int elemSize);
virtual ~BindArrayObject();
void SetInData() override;
void SetOutData() override;
ostring GetName() override;
operator ObjectVector & () const;
operator NativeType * () const;
private:
void AllocData();
void FreeData() const;
OCI_Statement *_pStatement;
ostring _name;
ObjectVector& _vector;
NativeType *_data;
unsigned int _mode;
unsigned int _elemCount;
unsigned int _elemSize;
};
AbstractBindArrayObject * _object;
};
template<class T>
class BindObjectAdaptor : public BindObject
{
friend class Statement;
public:
typedef T ObjectType;
typedef typename BindResolver<ObjectType>::OutputType NativeType;
operator NativeType *() const;
void SetInData() override;
void SetOutData() override;
BindObjectAdaptor(const Statement &statement, const ostring& name, unsigned int mode, ObjectType &object, unsigned int size);
virtual ~BindObjectAdaptor();
private:
ObjectType& _object;
NativeType* _data;
unsigned int _size;
};
template<class T>
class BindTypeAdaptor : public BindObject
{
friend class Statement;
public:
typedef T ObjectType;
typedef typename BindResolver<ObjectType>::OutputType NativeType;
operator NativeType *() const;
void SetInData() override;
void SetOutData() override;
BindTypeAdaptor(const Statement &statement, const ostring& name, unsigned int mode, ObjectType &object);
virtual ~BindTypeAdaptor();
private:
ObjectType& _object;
NativeType* _data;
};
class BindsHolder
{
public:
BindsHolder(const Statement &statement);
~BindsHolder();
void Clear();
void AddBindObject(BindObject *bindObject);
void SetOutData();
void SetInData();
private:
std::vector<BindObject *> _bindObjects;
OCI_Statement * _pStatement;
};
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
// PCL specific includes
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <jaco_msgs/SetFingersPositionAction.h>
#include <jaco_msgs/ArmPoseAction.h>
#include <jaco_msgs/FingerPosition.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
geometry_msgs::PoseStamped arm_pose;
jaco_msgs::FingerPosition fingers_pose;
boost::mutex arm_mutex;
boost::mutex fingers_mutex;
bool end_program = false;
bool arm_is_stopped = false;
bool check_arm_status = false;
int arm_is_stopped_counter = 0;
bool fingers_are_stopped = false;
bool check_fingers_status = false;
int fingers_are_stopped_counter = 0;
void open_fingers();
void close_fingers();
void move_up();
void move_to_grasp_point();
bool is_same_pose(geometry_msgs::PoseStamped* pose1, const geometry_msgs::PoseStampedConstPtr pose2);
bool is_same_pose(jaco_msgs::FingerPosition* pose1, jaco_msgs::FingerPositionConstPtr pose2);
void wait_for_arm_stopped();
void wait_for_fingers_stopped();
void arm_position_callback (const geometry_msgs::PoseStampedConstPtr& input_pose){
if(check_arm_status){
bool same_pose = is_same_pose(&arm_pose,input_pose);
if(same_pose){
arm_is_stopped_counter++;
}
if(arm_is_stopped_counter >= 5){
arm_is_stopped = true;
}
}
// Assign new value to arm pose
arm_mutex.lock();
arm_pose = *input_pose;
arm_mutex.unlock();
}
void fingers_position_callback(const jaco_msgs::FingerPositionConstPtr& input_fingers){
if(check_fingers_status){
bool same_pose = is_same_pose(&fingers_pose,input_fingers); //create a new function
if(same_pose){
fingers_are_stopped_counter++;
}
if(fingers_are_stopped_counter >= 5){
fingers_are_stopped = true;
}
}
// Assign new value to arm pose
fingers_mutex.lock();
fingers_pose = *input_fingers;
fingers_mutex.unlock();
}
void thread_function(){
if(ros::ok()){
open_fingers();
move_to_grasp_point();
close_fingers();
move_up();
end_program = true;
}
}
bool is_same_pose(geometry_msgs::PoseStamped* pose1, geometry_msgs::PoseStampedConstPtr pose2){
bool cond1 = pose1->pose.position.x == pose2->pose.position.x;
bool cond2 = pose1->pose.position.y == pose2->pose.position.y;
bool cond3 = pose1->pose.position.z == pose2->pose.position.z;
bool cond4 = pose1->pose.orientation.x == pose2->pose.orientation.x;
bool cond5 = pose1->pose.orientation.y == pose2->pose.orientation.y;
bool cond6 = pose1->pose.orientation.z == pose2->pose.orientation.z;
bool cond7 = pose1->pose.orientation.w == pose2->pose.orientation.w;
if(cond1 && cond2 && cond3 && cond4 && cond5 && cond6 && cond7){
return true;
}
else{
return false;
}
}
bool is_same_pose(jaco_msgs::FingerPosition* pose1, jaco_msgs::FingerPositionConstPtr pose2){
bool cond1 = pose1->Finger_1 == pose2->Finger_1;
bool cond2 = pose1->Finger_2 == pose2->Finger_2;
bool cond3 = pose1->Finger_3 == pose2->Finger_3;
if(cond1 && cond2 && cond3){
return true;
}
else{
return false;
}
}
void wait_for_arm_stopped(){
arm_is_stopped_counter = 0;
arm_is_stopped = false;
check_arm_status = true;
ros::Rate r(30);
while(true){
if(arm_is_stopped) break;
else {r.sleep();}
}
std::cout << "Finished moving the arm!" << std::endl;
check_arm_status = false;
}
void wait_for_fingers_stopped(){
fingers_are_stopped_counter = 0;
fingers_are_stopped = false;
check_fingers_status = true;
ros::Rate r(30);
while(true){
if(fingers_are_stopped) break;
else {r.sleep();}
}
std::cout << "Finished moving the fingers!" << std::endl;
check_fingers_status = false;
}
void move_to_grasp_point(){
actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true);
action_client.waitForServer();
jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal();
pose_goal.pose.header.frame_id = "/jaco_api_origin";
pose_goal.pose.pose.position.x = -0.24;
pose_goal.pose.pose.position.y = 0.366;
pose_goal.pose.pose.position.z = -0.003;
pose_goal.pose.pose.orientation.x = 0.064;
pose_goal.pose.pose.orientation.y = -0.658;
pose_goal.pose.pose.orientation.z = -0.035;
pose_goal.pose.pose.orientation.w = 0.75;
action_client.sendGoal(pose_goal);
wait_for_arm_stopped();
}
void open_fingers(){
actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true);
action_client.waitForServer();
jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal();
fingers.fingers.Finger_1 = 0;
fingers.fingers.Finger_2 = 0;
fingers.fingers.Finger_3 = 0;
action_client.sendGoal(fingers);
wait_for_fingers_stopped();
std::cout << "Grasp completed" << std::endl;
}
void close_fingers(){
actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true);
action_client.waitForServer();
jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal();
fingers.fingers.Finger_1 = 60;
fingers.fingers.Finger_2 = 60;
fingers.fingers.Finger_3 = 60;
action_client.sendGoal(fingers);
wait_for_fingers_stopped();
std::cout << "Grasp completed" << std::endl;
}
void move_up(){
actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true);
action_client.waitForServer();
jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal();
arm_mutex.lock();
pose_goal.pose = arm_pose;
pose_goal.pose.header.frame_id = "/jaco_api_origin";
pose_goal.pose.pose.position.z += 0.4;
arm_mutex.unlock();
action_client.sendGoal(pose_goal);
wait_for_arm_stopped();
}
int main (int argc, char** argv)
{
// Initialize ROS
ros::init (argc, argv, "grasp");
ros::NodeHandle n;
ros::NodeHandle nh("~");
ros::Subscriber sub = n.subscribe ("/jaco/tool_position", 1, arm_position_callback);
ros::Subscriber sub2 = n.subscribe ("/jaco/finger_position", 1, fingers_position_callback);
boost::thread thread_(thread_function);
ros::Rate r(30);
while(ros::ok() && !end_program){
ros::spinOnce();
r.sleep();
}
thread_.join();
return 0;
}
<commit_msg>added function arguments<commit_after>#include <ros/ros.h>
// PCL specific includes
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <jaco_msgs/SetFingersPositionAction.h>
#include <jaco_msgs/ArmPoseAction.h>
#include <jaco_msgs/FingerPosition.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
geometry_msgs::PoseStamped arm_pose;
jaco_msgs::FingerPosition fingers_pose;
boost::mutex arm_mutex;
boost::mutex fingers_mutex;
bool end_program = false;
bool arm_is_stopped = false;
bool check_arm_status = false;
int arm_is_stopped_counter = 0;
bool fingers_are_stopped = false;
bool check_fingers_status = false;
int fingers_are_stopped_counter = 0;
void open_fingers();
void close_fingers();
void move_up(double distance);
void move_to_grasp_point(double x, double y, double z, double rotx, double roty, double rotz, double rotw);
bool is_same_pose(geometry_msgs::PoseStamped* pose1, const geometry_msgs::PoseStampedConstPtr pose2);
bool is_same_pose(jaco_msgs::FingerPosition* pose1, jaco_msgs::FingerPositionConstPtr pose2);
void wait_for_arm_stopped();
void wait_for_fingers_stopped();
void arm_position_callback (const geometry_msgs::PoseStampedConstPtr& input_pose){
if(check_arm_status){
bool same_pose = is_same_pose(&arm_pose,input_pose);
if(same_pose){
arm_is_stopped_counter++;
}
if(arm_is_stopped_counter >= 5){
arm_is_stopped = true;
}
}
// Assign new value to arm pose
arm_mutex.lock();
arm_pose = *input_pose;
arm_mutex.unlock();
}
void fingers_position_callback(const jaco_msgs::FingerPositionConstPtr& input_fingers){
if(check_fingers_status){
bool same_pose = is_same_pose(&fingers_pose,input_fingers); //create a new function
if(same_pose){
fingers_are_stopped_counter++;
}
if(fingers_are_stopped_counter >= 5){
fingers_are_stopped = true;
}
}
// Assign new value to arm pose
fingers_mutex.lock();
fingers_pose = *input_fingers;
fingers_mutex.unlock();
}
void thread_function(){
if(ros::ok()){
open_fingers();
move_to_grasp_point(-0.24, 0.366, -0.003, 0.064, -0.658, -0.035, 0.75);
close_fingers();
move_up(0.4);
end_program = true;
}
}
bool is_same_pose(geometry_msgs::PoseStamped* pose1, geometry_msgs::PoseStampedConstPtr pose2){
bool cond1 = pose1->pose.position.x == pose2->pose.position.x;
bool cond2 = pose1->pose.position.y == pose2->pose.position.y;
bool cond3 = pose1->pose.position.z == pose2->pose.position.z;
bool cond4 = pose1->pose.orientation.x == pose2->pose.orientation.x;
bool cond5 = pose1->pose.orientation.y == pose2->pose.orientation.y;
bool cond6 = pose1->pose.orientation.z == pose2->pose.orientation.z;
bool cond7 = pose1->pose.orientation.w == pose2->pose.orientation.w;
if(cond1 && cond2 && cond3 && cond4 && cond5 && cond6 && cond7){
return true;
}
else{
return false;
}
}
bool is_same_pose(jaco_msgs::FingerPosition* pose1, jaco_msgs::FingerPositionConstPtr pose2){
bool cond1 = pose1->Finger_1 == pose2->Finger_1;
bool cond2 = pose1->Finger_2 == pose2->Finger_2;
bool cond3 = pose1->Finger_3 == pose2->Finger_3;
if(cond1 && cond2 && cond3){
return true;
}
else{
return false;
}
}
void wait_for_arm_stopped(){
arm_is_stopped_counter = 0;
arm_is_stopped = false;
check_arm_status = true;
ros::Rate r(30);
while(true){
if(arm_is_stopped) break;
else {r.sleep();}
}
std::cout << "Finished moving the arm!" << std::endl;
check_arm_status = false;
}
void wait_for_fingers_stopped(){
fingers_are_stopped_counter = 0;
fingers_are_stopped = false;
check_fingers_status = true;
ros::Rate r(30);
while(true){
if(fingers_are_stopped) break;
else {r.sleep();}
}
std::cout << "Finished moving the fingers!" << std::endl;
check_fingers_status = false;
}
void move_to_grasp_point(double x, double y, double z, double rotx, double roty, double rotz, double rotw){
actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true);
action_client.waitForServer();
jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal();
pose_goal.pose.header.frame_id = "/jaco_api_origin";
pose_goal.pose.pose.position.x = x;
pose_goal.pose.pose.position.y = y;
pose_goal.pose.pose.position.z = z;
pose_goal.pose.pose.orientation.x = rotx;
pose_goal.pose.pose.orientation.y = roty;
pose_goal.pose.pose.orientation.z = rotz;
pose_goal.pose.pose.orientation.w = rotw;
action_client.sendGoal(pose_goal);
wait_for_arm_stopped();
}
void open_fingers(){
actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true);
action_client.waitForServer();
jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal();
fingers.fingers.Finger_1 = 0;
fingers.fingers.Finger_2 = 0;
fingers.fingers.Finger_3 = 0;
action_client.sendGoal(fingers);
wait_for_fingers_stopped();
std::cout << "Grasp completed" << std::endl;
}
void close_fingers(){
actionlib::SimpleActionClient<jaco_msgs::SetFingersPositionAction> action_client("jaco/finger_joint_angles",true);
action_client.waitForServer();
jaco_msgs::SetFingersPositionGoal fingers = jaco_msgs::SetFingersPositionGoal();
fingers.fingers.Finger_1 = 60;
fingers.fingers.Finger_2 = 60;
fingers.fingers.Finger_3 = 60;
action_client.sendGoal(fingers);
wait_for_fingers_stopped();
std::cout << "Grasp completed" << std::endl;
}
void move_up(double distance){
actionlib::SimpleActionClient<jaco_msgs::ArmPoseAction> action_client("/jaco/arm_pose",true);
action_client.waitForServer();
jaco_msgs::ArmPoseGoal pose_goal = jaco_msgs::ArmPoseGoal();
arm_mutex.lock();
pose_goal.pose = arm_pose;
pose_goal.pose.header.frame_id = "/jaco_api_origin";
pose_goal.pose.pose.position.z += distance;
arm_mutex.unlock();
action_client.sendGoal(pose_goal);
wait_for_arm_stopped();
}
int main (int argc, char** argv)
{
// Initialize ROS
ros::init (argc, argv, "grasp");
ros::NodeHandle n;
ros::NodeHandle nh("~");
ros::Subscriber sub = n.subscribe ("/jaco/tool_position", 1, arm_position_callback);
ros::Subscriber sub2 = n.subscribe ("/jaco/finger_position", 1, fingers_position_callback);
boost::thread thread_(thread_function);
ros::Rate r(30);
while(ros::ok() && !end_program){
ros::spinOnce();
r.sleep();
}
thread_.join();
return 0;
}
<|endoftext|> |
<commit_before>#define LOG_MODULE CommonLogModuleIpUtils
#include "Logger.h"
#include "IpAddress.h"
#include "IpUtils.h"
#include <string.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
namespace pcpp
{
IPAddress::~IPAddress()
{
}
bool IPAddress::equals(const IPAddress* other)
{
if (other == NULL)
return false;
if (other->getType() != getType())
return false;
if (other->getType() == IPv4AddressType && getType() == IPv4AddressType)
return *((IPv4Address*)other) == *((IPv4Address*)this);
if (other->getType() == IPv6AddressType && getType() == IPv6AddressType)
return *((IPv6Address*)other) == *((IPv6Address*)this);
return false;
}
IPAddress::Ptr_t IPAddress::fromString(char* addressAsString)
{
in_addr ip4Addr;
in6_addr ip6Addr;
if (inet_pton(AF_INET, addressAsString, &ip4Addr) != 0)
{
return IPAddress::Ptr_t(new IPv4Address(addressAsString));
}
else if (inet_pton(AF_INET6, addressAsString, &ip6Addr) != 0)
{
return IPAddress::Ptr_t(new IPv6Address(addressAsString));
}
return IPAddress::Ptr_t();
}
IPAddress::Ptr_t IPAddress::fromString(std::string addressAsString)
{
return fromString((char*)addressAsString.c_str());
}
IPv4Address IPv4Address::Zero((uint32_t)0);
IPv4Address::IPv4Address(const IPv4Address& other)
{
m_pInAddr = new in_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
}
IPv4Address::IPv4Address(uint32_t addressAsInt)
{
m_pInAddr = new in_addr();
memcpy(m_pInAddr, &addressAsInt, sizeof(addressAsInt));
if (inet_ntop(AF_INET, m_pInAddr, m_AddressAsString, MAX_ADDR_STRING_LEN) == 0)
m_IsValid = false;
else
m_IsValid = true;
}
IPv4Address::IPv4Address(in_addr* inAddr)
{
m_pInAddr = new in_addr();
memcpy(m_pInAddr, inAddr, sizeof(in_addr));
if (inet_ntop(AF_INET, m_pInAddr, m_AddressAsString, MAX_ADDR_STRING_LEN) == 0)
m_IsValid = false;
else
m_IsValid = true;
}
IPAddress* IPv4Address::clone() const
{
return new IPv4Address(*this);
}
void IPv4Address::init(const char* addressAsString)
{
m_pInAddr = new in_addr();
if (inet_pton(AF_INET, addressAsString , m_pInAddr) == 0)
{
m_IsValid = false;
return;
}
strncpy(m_AddressAsString, addressAsString, 40);
m_IsValid = true;
}
IPv4Address::~IPv4Address()
{
delete m_pInAddr;
}
IPv4Address::IPv4Address(const char* addressAsString)
{
init(addressAsString);
}
IPv4Address::IPv4Address(std::string addressAsString)
{
init((char*)addressAsString.c_str());
}
uint32_t IPv4Address::toInt() const
{
uint32_t result;
memcpy(&result, m_pInAddr, sizeof(uint32_t));
return result;
}
IPv4Address& IPv4Address::operator=(const IPv4Address& other)
{
if (m_pInAddr != NULL)
delete m_pInAddr;
m_pInAddr = new in_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
return *this;
}
bool IPv4Address::matchSubnet(const IPv4Address& subnet, const std::string& subnetMask) const
{
IPv4Address maskAsIpAddr(subnetMask);
if (!maskAsIpAddr.isValid())
{
LOG_ERROR("Subnet mask '%s' is in illegal format", subnetMask.c_str());
return false;
}
int thisAddrAfterMask = toInt() & maskAsIpAddr.toInt();
int subnetAddrAfterMask = subnet.toInt() & maskAsIpAddr.toInt();
return (thisAddrAfterMask == subnetAddrAfterMask);
}
bool IPv4Address::matchSubnet(const IPv4Address& subnet, const IPv4Address& subnetMask) const
{
unsigned int maskAsInt = subnetMask.toInt();
unsigned int thisAddrAfterMask = toInt() & maskAsInt;
unsigned int subnetAddrAfterMask = subnet.toInt() & maskAsInt;
return thisAddrAfterMask == subnetAddrAfterMask;
}
IPv6Address IPv6Address::Zero(std::string("0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0"));
IPv6Address::IPv6Address(const IPv6Address& other)
{
m_pInAddr = new in6_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in6_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
}
IPv6Address::~IPv6Address()
{
delete m_pInAddr;
}
IPAddress* IPv6Address::clone() const
{
return new IPv6Address(*this);
}
void IPv6Address::init(char* addressAsString)
{
m_pInAddr = new in6_addr();
if (inet_pton(AF_INET6, addressAsString , m_pInAddr) == 0)
{
m_IsValid = false;
return;
}
strncpy(m_AddressAsString, addressAsString, 40);
m_IsValid = true;
}
IPv6Address::IPv6Address(uint8_t* addressAsUintArr)
{
m_pInAddr = new in6_addr();
memcpy(m_pInAddr, addressAsUintArr, 16);
if (inet_ntop(AF_INET6, m_pInAddr, m_AddressAsString, MAX_ADDR_STRING_LEN) == 0)
m_IsValid = false;
else
m_IsValid = true;
}
IPv6Address::IPv6Address(char* addressAsString)
{
init(addressAsString);
}
IPv6Address::IPv6Address(std::string addressAsString)
{
init((char*)addressAsString.c_str());
}
void IPv6Address::copyTo(uint8_t** arr, size_t& length)
{
length = 16;
(*arr) = new uint8_t[length];
memcpy((*arr), m_pInAddr, length);
}
void IPv6Address::copyTo(uint8_t* arr) const
{
memcpy(arr, m_pInAddr, 16);
}
bool IPv6Address::operator==(const IPv6Address& other) const
{
return (memcmp(m_pInAddr, other.m_pInAddr, 16) == 0);
}
bool IPv6Address::operator!=(const IPv6Address& other)
{
return !(*this == other);
}
IPv6Address& IPv6Address::operator=(const IPv6Address& other)
{
if (m_pInAddr != NULL)
delete m_pInAddr;
m_pInAddr = new in6_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in6_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
return *this;
}
} // namespace pcpp
<commit_msg>IPAddress::matchSubnet: correcting the types<commit_after>#define LOG_MODULE CommonLogModuleIpUtils
#include "Logger.h"
#include "IpAddress.h"
#include "IpUtils.h"
#include <string.h>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
namespace pcpp
{
IPAddress::~IPAddress()
{
}
bool IPAddress::equals(const IPAddress* other)
{
if (other == NULL)
return false;
if (other->getType() != getType())
return false;
if (other->getType() == IPv4AddressType && getType() == IPv4AddressType)
return *((IPv4Address*)other) == *((IPv4Address*)this);
if (other->getType() == IPv6AddressType && getType() == IPv6AddressType)
return *((IPv6Address*)other) == *((IPv6Address*)this);
return false;
}
IPAddress::Ptr_t IPAddress::fromString(char* addressAsString)
{
in_addr ip4Addr;
in6_addr ip6Addr;
if (inet_pton(AF_INET, addressAsString, &ip4Addr) != 0)
{
return IPAddress::Ptr_t(new IPv4Address(addressAsString));
}
else if (inet_pton(AF_INET6, addressAsString, &ip6Addr) != 0)
{
return IPAddress::Ptr_t(new IPv6Address(addressAsString));
}
return IPAddress::Ptr_t();
}
IPAddress::Ptr_t IPAddress::fromString(std::string addressAsString)
{
return fromString((char*)addressAsString.c_str());
}
IPv4Address IPv4Address::Zero((uint32_t)0);
IPv4Address::IPv4Address(const IPv4Address& other)
{
m_pInAddr = new in_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
}
IPv4Address::IPv4Address(uint32_t addressAsInt)
{
m_pInAddr = new in_addr();
memcpy(m_pInAddr, &addressAsInt, sizeof(addressAsInt));
if (inet_ntop(AF_INET, m_pInAddr, m_AddressAsString, MAX_ADDR_STRING_LEN) == 0)
m_IsValid = false;
else
m_IsValid = true;
}
IPv4Address::IPv4Address(in_addr* inAddr)
{
m_pInAddr = new in_addr();
memcpy(m_pInAddr, inAddr, sizeof(in_addr));
if (inet_ntop(AF_INET, m_pInAddr, m_AddressAsString, MAX_ADDR_STRING_LEN) == 0)
m_IsValid = false;
else
m_IsValid = true;
}
IPAddress* IPv4Address::clone() const
{
return new IPv4Address(*this);
}
void IPv4Address::init(const char* addressAsString)
{
m_pInAddr = new in_addr();
if (inet_pton(AF_INET, addressAsString , m_pInAddr) == 0)
{
m_IsValid = false;
return;
}
strncpy(m_AddressAsString, addressAsString, 40);
m_IsValid = true;
}
IPv4Address::~IPv4Address()
{
delete m_pInAddr;
}
IPv4Address::IPv4Address(const char* addressAsString)
{
init(addressAsString);
}
IPv4Address::IPv4Address(std::string addressAsString)
{
init((char*)addressAsString.c_str());
}
uint32_t IPv4Address::toInt() const
{
uint32_t result;
memcpy(&result, m_pInAddr, sizeof(uint32_t));
return result;
}
IPv4Address& IPv4Address::operator=(const IPv4Address& other)
{
if (m_pInAddr != NULL)
delete m_pInAddr;
m_pInAddr = new in_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
return *this;
}
bool IPv4Address::matchSubnet(const IPv4Address& subnet, const std::string& subnetMask) const
{
IPv4Address maskAsIpAddr(subnetMask);
if (!maskAsIpAddr.isValid())
{
LOG_ERROR("Subnet mask '%s' is in illegal format", subnetMask.c_str());
return false;
}
int thisAddrAfterMask = toInt() & maskAsIpAddr.toInt();
int subnetAddrAfterMask = subnet.toInt() & maskAsIpAddr.toInt();
return (thisAddrAfterMask == subnetAddrAfterMask);
}
bool IPv4Address::matchSubnet(const IPv4Address& subnet, const IPv4Address& subnetMask) const
{
uint32_t maskAsInt = subnetMask.toInt();
uint32_t thisAddrAfterMask = toInt() & maskAsInt;
uint32_t subnetAddrAfterMask = subnet.toInt() & maskAsInt;
return thisAddrAfterMask == subnetAddrAfterMask;
}
IPv6Address IPv6Address::Zero(std::string("0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0"));
IPv6Address::IPv6Address(const IPv6Address& other)
{
m_pInAddr = new in6_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in6_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
}
IPv6Address::~IPv6Address()
{
delete m_pInAddr;
}
IPAddress* IPv6Address::clone() const
{
return new IPv6Address(*this);
}
void IPv6Address::init(char* addressAsString)
{
m_pInAddr = new in6_addr();
if (inet_pton(AF_INET6, addressAsString , m_pInAddr) == 0)
{
m_IsValid = false;
return;
}
strncpy(m_AddressAsString, addressAsString, 40);
m_IsValid = true;
}
IPv6Address::IPv6Address(uint8_t* addressAsUintArr)
{
m_pInAddr = new in6_addr();
memcpy(m_pInAddr, addressAsUintArr, 16);
if (inet_ntop(AF_INET6, m_pInAddr, m_AddressAsString, MAX_ADDR_STRING_LEN) == 0)
m_IsValid = false;
else
m_IsValid = true;
}
IPv6Address::IPv6Address(char* addressAsString)
{
init(addressAsString);
}
IPv6Address::IPv6Address(std::string addressAsString)
{
init((char*)addressAsString.c_str());
}
void IPv6Address::copyTo(uint8_t** arr, size_t& length)
{
length = 16;
(*arr) = new uint8_t[length];
memcpy((*arr), m_pInAddr, length);
}
void IPv6Address::copyTo(uint8_t* arr) const
{
memcpy(arr, m_pInAddr, 16);
}
bool IPv6Address::operator==(const IPv6Address& other) const
{
return (memcmp(m_pInAddr, other.m_pInAddr, 16) == 0);
}
bool IPv6Address::operator!=(const IPv6Address& other)
{
return !(*this == other);
}
IPv6Address& IPv6Address::operator=(const IPv6Address& other)
{
if (m_pInAddr != NULL)
delete m_pInAddr;
m_pInAddr = new in6_addr();
memcpy(m_pInAddr, other.m_pInAddr, sizeof(in6_addr));
strncpy(m_AddressAsString, other.m_AddressAsString, 40);
m_IsValid = other.m_IsValid;
return *this;
}
} // namespace pcpp
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <set>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>
#include <sys/stat.h>
#include <getopt.h>
#include <unistd.h>
#include <alloca.h>
#include <pcafitter_private.hpp>
// lstorchi: basi code to fit tracks, using the PCA constants generated
// by the related generatepca
namespace
{
bool file_exists(const std::string& filename)
{
struct stat buf;
if (stat(filename.c_str(), &buf) != -1)
return true;
return false;
}
}
void build_and_compare (arma::mat & paramslt, arma::mat & coordslt,
arma::mat & cmtx, arma::rowvec & q, bool verbose,
const std::string & postfname)
{
double * oneoverptcmp, * phicmp, * etacmp, * z0cmp, * d0cmp;
oneoverptcmp = new double [(int)coordslt.n_rows];
phicmp = new double [(int)coordslt.n_rows];
etacmp = new double [(int)coordslt.n_rows];
z0cmp = new double [(int)coordslt.n_rows];
d0cmp = new double [(int)coordslt.n_rows];
pcafitter::computeparameters (cmtx, q, coordslt, oneoverptcmp,
phicmp, etacmp, z0cmp, d0cmp);
std::ostringstream fname;
fname << "results." << postfname << ".txt";
std::ofstream myfile(fname.str().c_str());
myfile << "(1/pt)_orig (1/pt)_cmpt diff (phi)_orig " <<
"(phi)_cmpt diff (cot(tetha/2))_orig (cot(tetha/2))_cmpt diff" <<
"(d0)_orig (d0)_cmpt diff (z0)_orig (z0)_cmpt diff" << std::endl;
arma::running_stat<double> pc[PARAMDIM];
for (int i=0; i<(int)coordslt.n_rows; ++i)
{
pc[PTIDX](fabs(oneoverptcmp[i] - paramslt(i, PTIDX))/
(fabs(oneoverptcmp[i] + paramslt(i, PTIDX))/2.0));
pc[PHIIDX](fabs(phicmp[i] - paramslt(i, PHIIDX))/
(fabs(phicmp[i] + paramslt(i, PHIIDX))/2.0));
pc[TETHAIDX](fabs(etacmp[i] - paramslt(i, TETHAIDX))/
(fabs(etacmp[i] + paramslt(i, TETHAIDX))/2.0));
pc[D0IDX](fabs(d0cmp[i] - paramslt(i, D0IDX))/
(fabs(d0cmp[i] + paramslt(i, D0IDX))/2.0));
pc[Z0IDX](fabs(z0cmp[i] - paramslt(i, Z0IDX))/
(fabs(z0cmp[i] + paramslt(i, Z0IDX))/2.0));
myfile <<
paramslt(i, PTIDX) << " " << oneoverptcmp[i] << " " <<
fabs(oneoverptcmp[i] - paramslt(i, PTIDX)) << " " <<
paramslt(i, PHIIDX) << " " << phicmp[i] << " " <<
fabs(phicmp[i] + paramslt(i, PHIIDX)) << " " <<
paramslt(i, TETHAIDX) << " " << etacmp[i] << " " <<
fabs(etacmp[i] - paramslt(i, TETHAIDX)) << " " <<
paramslt(i, D0IDX) << " " << d0cmp[i] << " " <<
fabs(d0cmp[i] - paramslt(i, D0IDX)) << " " <<
paramslt(i, Z0IDX) << " " << z0cmp[i] << " " <<
fabs(z0cmp[i] - paramslt(i, Z0IDX)) << std::endl;
if (verbose)
{
std::cout << "For track : " << i+1 << std::endl;
std::cout << " 1/pt cmpt " << oneoverptcmp[i] << std::endl;
std::cout << " 1/pt calc " << paramslt(i, PTIDX) << std::endl;
std::cout << " phi cmpt " << phicmp[i] << std::endl;
std::cout << " phi calc " << paramslt(i, PHIIDX) << std::endl;
std::cout << " cot(tetha/2) cmpt " << etacmp[i] << std::endl;
std::cout << " cot(tetha/2) calc " << paramslt(i, TETHAIDX) << std::endl;
std::cout << " d0 cmpt " << d0cmp[i] << std::endl;
std::cout << " d0 calc " << paramslt(i, D0IDX) << std::endl;
std::cout << " z0 cmpt " << z0cmp[i] << std::endl;
std::cout << " z0 calc " << paramslt(i, Z0IDX) << std::endl;
}
}
myfile.close();
for (int i=0; i<PARAMDIM; ++i)
std::cout << "For " << pcafitter::paramidxtostring(i) << " error " <<
100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl;
delete [] oneoverptcmp;
delete [] phicmp;
delete [] etacmp;
delete [] z0cmp;
delete [] d0cmp;
}
void usage (char * name)
{
std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl;
std::cerr << std::endl;
std::cerr << " -h, --help : display this help and exit" << std::endl;
std::cerr << " -V, --verbose : verbose option on" << std::endl;
std::cerr << " -v, --version : print version and exit" << std::endl;
std::cerr << " -c, --cmtx=[fillename] : CMTX filename [default is c.bin]" << std::endl;
std::cerr << " -q, --qvct=[fillename] : QVCT filename [default is q.bin]" << std::endl;
std::cerr << " -s, --subsector=[subsec] : by default use values of the bigger subsector" << std::endl;
std::cerr << " with this option you can speficy to perform " << std::endl;
std::cerr << " prediction for subsector subsec " << std::endl;
std::cerr << " -l, --subladder=[subld] : by default use values of the bigger subladder " << std::endl;
std::cerr << " with this option you can speficy to perform " << std::endl;
std::cerr << " prediction for subladder subld " << std::endl;
std::cerr << " -a, --all-subsectors : perform the fitting for all subsectors" << std::endl;
std::cerr << " -r, --all-subladders : perform the fitting for all subladders" << std::endl;
exit(1);
}
int main (int argc, char ** argv)
{
std::string qfname = "q.bin";
std::string cfname = "c.bin";
std::string subsec = "";
std::string sublad = "";
bool verbose = false;
bool useallsubsectors = false;
bool useallsubladders = false;
while (1)
{
int c, option_index;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"cmtx", 1, NULL, 'c'},
{"qvct", 1, NULL, 'q'},
{"subsector", 1, NULL, 's'},
{"subladder", 1, NULL, 'l'},
{"verbose", 0, NULL, 'V'},
{"version", 0, NULL, 'v'},
{"all-subsectors", 0, NULL, 'a'},
{"all-subladders", 0, NULL, 'r'},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "arvhVc:q:s:l:", long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 'a':
useallsubsectors = true;
break;
case 'r':
useallsubladders = true;
break;
case 'V':
verbose = true;
break;
case 'v':
std::cout << "Version: " << pcafitter::get_version_string() << std::endl;
exit(1);
break;
case 'h':
usage (argv[0]);
break;
case 's':
subsec = optarg;
break;
case 'l':
sublad = optarg;
break;
case'c':
cfname = optarg;
break;
case 'q':
qfname = optarg;
break;
default:
usage (argv[0]);
break;
}
}
if (optind >= argc)
usage (argv[0]);
if (useallsubladders && useallsubsectors)
usage (argv[0]);
char * filename = (char *) alloca (strlen(argv[optind]) + 1);
strcpy (filename, argv[optind]);
// leggere file coordinate tracce e file costanti PCA
// N righe di 9 double sono le coordinate
// matrice C e vettore q sono le costanti
arma::mat cmtx;
arma::rowvec q;
std::cout << "Reading data from " << filename << " file " << std::endl;
int num_of_line = pcafitter::numofline(filename);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << "file has " << num_of_ent << " entries " << std::endl;
arma::mat layer, ladder, module, coord, param;
layer.set_size(num_of_ent,COORDIM);
ladder.set_size(num_of_ent,COORDIM);
module.set_size(num_of_ent,COORDIM);
coord.set_size(num_of_ent,DIMPERCOORD*COORDIM);
param.set_size(num_of_ent,PARAMDIM);
std::map<std::string, int> subsectors, subladders;
std::vector<std::string> subladderslist, subsectorslist;
// leggere file coordinate tracce simulate plus parametri
if (!file_exists(filename))
{
std::cerr << "Inout file does not exist" << std::endl;
return 1;
}
pcafitter::readingfromfile (filename, param, coord,
layer, ladder, module, subsectors, subladders,
subsectorslist, subladderslist, num_of_ent);
if (!useallsubsectors && !useallsubladders)
{
std::cout << "Read constant from files (" << cfname <<
" and " << qfname << ")" << std::endl;
if (!file_exists(cfname) || !file_exists(qfname))
{
std::cerr << "Constants file does not exist" << std::endl;
return 1;
}
pcafitter::readarmmat(cfname.c_str(), cmtx);
pcafitter::readarmvct(qfname.c_str(), q);
if ((subsec == "") && (sublad == ""))
{
int maxnumber;
std::cout << "Looking for bigger subsector" << std::endl;
std::cout << "We found " << subsectors.size() <<
" subsectors " << std::endl;
pcafitter::select_bigger_sub (subsectors, verbose,
maxnumber, subsec);
std::cout << "Selected subsector " << subsec <<
" numevt: " << maxnumber << std::endl;
std::cout << "Looking for bigger subladder" << std::endl;
std::cout << "We found " << subladders.size() <<
" subladders " << std::endl;
pcafitter::select_bigger_sub (subladders, verbose,
maxnumber, sublad);
std::cout << "Selected subladder " << sublad << " numevt: "
<< maxnumber << std::endl;
}
if (subsec != "")
{
arma::mat paramslt, coordslt;
std::cout << "Using subsector " << subsec << std::endl;
pcafitter::extract_sub (subsectorslist,
subsec, param, coord, paramslt,
coordslt);
build_and_compare (paramslt, coordslt, cmtx, q, verbose,
subsec);
}
if (sublad != "")
{
arma::mat paramslt, coordslt;
std::cout << "Using subladder " << sublad << std::endl;
pcafitter::extract_sub (subladderslist,
sublad, param, coord, paramslt,
coordslt);
build_and_compare (paramslt, coordslt, cmtx, q, verbose,
sublad);
}
}
else
{
assert(useallsubladders != useallsubsectors);
std::set<std::string> sectrorset;
std::vector<std::string> * listtouse = NULL;
if (useallsubsectors)
{
std::vector<std::string>::const_iterator selecteds =
subsectorslist.begin();
for (; selecteds != subsectorslist.end(); ++selecteds)
sectrorset.insert(*selecteds);
listtouse = &subsectorslist;
}
else if (useallsubladders)
{
std::vector<std::string>::const_iterator selecteds =
subladderslist.begin();
for (; selecteds != subladderslist.end(); ++selecteds)
sectrorset.insert(*selecteds);
listtouse = &subladderslist;
}
else
usage(argv[0]);
std::set<std::string>::const_iterator selected =
sectrorset.begin();
for (; selected != sectrorset.end(); ++selected)
{
std::ostringstream cfname, qfname;
cfname << "c." << *selected << ".bin";
qfname << "q." << *selected << ".bin";
if (file_exists(cfname.str()) && file_exists(qfname.str()))
{
std::cout << "Perfom fitting for " << *selected << std::endl;
std::cout << "Read constants " << std::endl;
pcafitter::readarmmat(cfname.str().c_str(), cmtx);
pcafitter::readarmvct(qfname.str().c_str(), q);
arma::mat paramslt, coordslt;
pcafitter::extract_sub (*listtouse,
*selected, param, coord, paramslt,
coordslt);
build_and_compare (paramslt, coordslt, cmtx, q, verbose,
*selected);
}
}
// TODO
}
return 0;
}
<commit_msg>minor<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <set>
// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>
#include <sys/stat.h>
#include <getopt.h>
#include <unistd.h>
#include <alloca.h>
#include <pcafitter_private.hpp>
// lstorchi: basi code to fit tracks, using the PCA constants generated
// by the related generatepca
namespace
{
bool file_exists(const std::string& filename)
{
struct stat buf;
if (stat(filename.c_str(), &buf) != -1)
return true;
return false;
}
}
void build_and_compare (arma::mat & paramslt, arma::mat & coordslt,
arma::mat & cmtx, arma::rowvec & q, bool verbose,
const std::string & postfname)
{
double * oneoverptcmp, * phicmp, * etacmp, * z0cmp, * d0cmp;
oneoverptcmp = new double [(int)coordslt.n_rows];
phicmp = new double [(int)coordslt.n_rows];
etacmp = new double [(int)coordslt.n_rows];
z0cmp = new double [(int)coordslt.n_rows];
d0cmp = new double [(int)coordslt.n_rows];
pcafitter::computeparameters (cmtx, q, coordslt, oneoverptcmp,
phicmp, etacmp, z0cmp, d0cmp);
std::ostringstream fname;
fname << "results." << postfname << ".txt";
std::ofstream myfile(fname.str().c_str());
myfile << "(1/pt)_orig (1/pt)_cmpt diff (phi)_orig " <<
"(phi)_cmpt diff (cot(tetha/2))_orig (cot(tetha/2))_cmpt diff" <<
"(d0)_orig (d0)_cmpt diff (z0)_orig (z0)_cmpt diff" << std::endl;
arma::running_stat<double> pc[PARAMDIM];
for (int i=0; i<(int)coordslt.n_rows; ++i)
{
pc[PTIDX](fabs(oneoverptcmp[i] - paramslt(i, PTIDX))/
(fabs(oneoverptcmp[i] + paramslt(i, PTIDX))/2.0));
pc[PHIIDX](fabs(phicmp[i] - paramslt(i, PHIIDX))/
(fabs(phicmp[i] + paramslt(i, PHIIDX))/2.0));
pc[TETHAIDX](fabs(etacmp[i] - paramslt(i, TETHAIDX))/
(fabs(etacmp[i] + paramslt(i, TETHAIDX))/2.0));
pc[D0IDX](fabs(d0cmp[i] - paramslt(i, D0IDX))/
(fabs(d0cmp[i] + paramslt(i, D0IDX))/2.0));
pc[Z0IDX](fabs(z0cmp[i] - paramslt(i, Z0IDX))/
(fabs(z0cmp[i] + paramslt(i, Z0IDX))/2.0));
myfile <<
paramslt(i, PTIDX) << " " << oneoverptcmp[i] << " " <<
(oneoverptcmp[i] - paramslt(i, PTIDX)) << " " <<
paramslt(i, PHIIDX) << " " << phicmp[i] << " " <<
(phicmp[i] + paramslt(i, PHIIDX)) << " " <<
paramslt(i, TETHAIDX) << " " << etacmp[i] << " " <<
(etacmp[i] - paramslt(i, TETHAIDX)) << " " <<
paramslt(i, D0IDX) << " " << d0cmp[i] << " " <<
(d0cmp[i] - paramslt(i, D0IDX)) << " " <<
paramslt(i, Z0IDX) << " " << z0cmp[i] << " " <<
(z0cmp[i] - paramslt(i, Z0IDX)) << std::endl;
if (verbose)
{
std::cout << "For track : " << i+1 << std::endl;
std::cout << " 1/pt cmpt " << oneoverptcmp[i] << std::endl;
std::cout << " 1/pt calc " << paramslt(i, PTIDX) << std::endl;
std::cout << " phi cmpt " << phicmp[i] << std::endl;
std::cout << " phi calc " << paramslt(i, PHIIDX) << std::endl;
std::cout << " cot(tetha/2) cmpt " << etacmp[i] << std::endl;
std::cout << " cot(tetha/2) calc " << paramslt(i, TETHAIDX) << std::endl;
std::cout << " d0 cmpt " << d0cmp[i] << std::endl;
std::cout << " d0 calc " << paramslt(i, D0IDX) << std::endl;
std::cout << " z0 cmpt " << z0cmp[i] << std::endl;
std::cout << " z0 calc " << paramslt(i, Z0IDX) << std::endl;
}
}
myfile.close();
for (int i=0; i<PARAMDIM; ++i)
std::cout << "For " << pcafitter::paramidxtostring(i) << " error " <<
100.0*pc[i].mean() << " " << 100.0*pc[i].stddev() << std::endl;
delete [] oneoverptcmp;
delete [] phicmp;
delete [] etacmp;
delete [] z0cmp;
delete [] d0cmp;
}
void usage (char * name)
{
std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl;
std::cerr << std::endl;
std::cerr << " -h, --help : display this help and exit" << std::endl;
std::cerr << " -V, --verbose : verbose option on" << std::endl;
std::cerr << " -v, --version : print version and exit" << std::endl;
std::cerr << " -c, --cmtx=[fillename] : CMTX filename [default is c.bin]" << std::endl;
std::cerr << " -q, --qvct=[fillename] : QVCT filename [default is q.bin]" << std::endl;
std::cerr << " -s, --subsector=[subsec] : by default use values of the bigger subsector" << std::endl;
std::cerr << " with this option you can speficy to perform " << std::endl;
std::cerr << " prediction for subsector subsec " << std::endl;
std::cerr << " -l, --subladder=[subld] : by default use values of the bigger subladder " << std::endl;
std::cerr << " with this option you can speficy to perform " << std::endl;
std::cerr << " prediction for subladder subld " << std::endl;
std::cerr << " -a, --all-subsectors : perform the fitting for all subsectors" << std::endl;
std::cerr << " -r, --all-subladders : perform the fitting for all subladders" << std::endl;
exit(1);
}
int main (int argc, char ** argv)
{
std::string qfname = "q.bin";
std::string cfname = "c.bin";
std::string subsec = "";
std::string sublad = "";
bool verbose = false;
bool useallsubsectors = false;
bool useallsubladders = false;
while (1)
{
int c, option_index;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"cmtx", 1, NULL, 'c'},
{"qvct", 1, NULL, 'q'},
{"subsector", 1, NULL, 's'},
{"subladder", 1, NULL, 'l'},
{"verbose", 0, NULL, 'V'},
{"version", 0, NULL, 'v'},
{"all-subsectors", 0, NULL, 'a'},
{"all-subladders", 0, NULL, 'r'},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "arvhVc:q:s:l:", long_options, &option_index);
if (c == -1)
break;
switch (c)
{
case 'a':
useallsubsectors = true;
break;
case 'r':
useallsubladders = true;
break;
case 'V':
verbose = true;
break;
case 'v':
std::cout << "Version: " << pcafitter::get_version_string() << std::endl;
exit(1);
break;
case 'h':
usage (argv[0]);
break;
case 's':
subsec = optarg;
break;
case 'l':
sublad = optarg;
break;
case'c':
cfname = optarg;
break;
case 'q':
qfname = optarg;
break;
default:
usage (argv[0]);
break;
}
}
if (optind >= argc)
usage (argv[0]);
if (useallsubladders && useallsubsectors)
usage (argv[0]);
char * filename = (char *) alloca (strlen(argv[optind]) + 1);
strcpy (filename, argv[optind]);
// leggere file coordinate tracce e file costanti PCA
// N righe di 9 double sono le coordinate
// matrice C e vettore q sono le costanti
arma::mat cmtx;
arma::rowvec q;
std::cout << "Reading data from " << filename << " file " << std::endl;
int num_of_line = pcafitter::numofline(filename);
std::cout << "file has " << num_of_line << " line " << std::endl;
int num_of_ent = (num_of_line-1)/ENTDIM;
std::cout << "file has " << num_of_ent << " entries " << std::endl;
arma::mat layer, ladder, module, coord, param;
layer.set_size(num_of_ent,COORDIM);
ladder.set_size(num_of_ent,COORDIM);
module.set_size(num_of_ent,COORDIM);
coord.set_size(num_of_ent,DIMPERCOORD*COORDIM);
param.set_size(num_of_ent,PARAMDIM);
std::map<std::string, int> subsectors, subladders;
std::vector<std::string> subladderslist, subsectorslist;
// leggere file coordinate tracce simulate plus parametri
if (!file_exists(filename))
{
std::cerr << "Inout file does not exist" << std::endl;
return 1;
}
pcafitter::readingfromfile (filename, param, coord,
layer, ladder, module, subsectors, subladders,
subsectorslist, subladderslist, num_of_ent);
if (!useallsubsectors && !useallsubladders)
{
std::cout << "Read constant from files (" << cfname <<
" and " << qfname << ")" << std::endl;
if (!file_exists(cfname) || !file_exists(qfname))
{
std::cerr << "Constants file does not exist" << std::endl;
return 1;
}
pcafitter::readarmmat(cfname.c_str(), cmtx);
pcafitter::readarmvct(qfname.c_str(), q);
if ((subsec == "") && (sublad == ""))
{
int maxnumber;
std::cout << "Looking for bigger subsector" << std::endl;
std::cout << "We found " << subsectors.size() <<
" subsectors " << std::endl;
pcafitter::select_bigger_sub (subsectors, verbose,
maxnumber, subsec);
std::cout << "Selected subsector " << subsec <<
" numevt: " << maxnumber << std::endl;
std::cout << "Looking for bigger subladder" << std::endl;
std::cout << "We found " << subladders.size() <<
" subladders " << std::endl;
pcafitter::select_bigger_sub (subladders, verbose,
maxnumber, sublad);
std::cout << "Selected subladder " << sublad << " numevt: "
<< maxnumber << std::endl;
}
if (subsec != "")
{
arma::mat paramslt, coordslt;
std::cout << "Using subsector " << subsec << std::endl;
pcafitter::extract_sub (subsectorslist,
subsec, param, coord, paramslt,
coordslt);
build_and_compare (paramslt, coordslt, cmtx, q, verbose,
subsec);
}
if (sublad != "")
{
arma::mat paramslt, coordslt;
std::cout << "Using subladder " << sublad << std::endl;
pcafitter::extract_sub (subladderslist,
sublad, param, coord, paramslt,
coordslt);
build_and_compare (paramslt, coordslt, cmtx, q, verbose,
sublad);
}
}
else
{
assert(useallsubladders != useallsubsectors);
std::set<std::string> sectrorset;
std::vector<std::string> * listtouse = NULL;
if (useallsubsectors)
{
std::vector<std::string>::const_iterator selecteds =
subsectorslist.begin();
for (; selecteds != subsectorslist.end(); ++selecteds)
sectrorset.insert(*selecteds);
listtouse = &subsectorslist;
}
else if (useallsubladders)
{
std::vector<std::string>::const_iterator selecteds =
subladderslist.begin();
for (; selecteds != subladderslist.end(); ++selecteds)
sectrorset.insert(*selecteds);
listtouse = &subladderslist;
}
else
usage(argv[0]);
std::set<std::string>::const_iterator selected =
sectrorset.begin();
for (; selected != sectrorset.end(); ++selected)
{
std::ostringstream cfname, qfname;
cfname << "c." << *selected << ".bin";
qfname << "q." << *selected << ".bin";
if (file_exists(cfname.str()) && file_exists(qfname.str()))
{
std::cout << "Perfom fitting for " << *selected << std::endl;
std::cout << "Read constants " << std::endl;
pcafitter::readarmmat(cfname.str().c_str(), cmtx);
pcafitter::readarmvct(qfname.str().c_str(), q);
arma::mat paramslt, coordslt;
pcafitter::extract_sub (*listtouse,
*selected, param, coord, paramslt,
coordslt);
build_and_compare (paramslt, coordslt, cmtx, q, verbose,
*selected);
}
}
// TODO
}
return 0;
}
<|endoftext|> |
<commit_before>//===--- SILLocation.cpp - Location information for SIL nodes -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILLocation.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
SourceLoc SILLocation::getSourceLoc() const {
if (isSILFile())
return Loc.SILFileLoc;
return getSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getSourceLoc(ASTNodeTy N) const {
if (N.isNull())
return SourceLoc();
if (alwaysPointsToStart() ||
alwaysPointsToEnd() ||
is<CleanupLocation>() ||
is<ImplicitReturnLocation>())
return getEndSourceLoc(N);
// Use the start location for the ReturnKind.
if (is<ReturnLocation>())
return getStartSourceLoc(N);
if (auto *decl = N.dyn_cast<Decl*>())
return decl->getLoc();
if (auto *expr = N.dyn_cast<Expr*>())
return expr->getLoc();
if (auto *stmt = N.dyn_cast<Stmt*>())
return stmt->getStartLoc();
if (auto *patt = N.dyn_cast<Pattern*>())
return patt->getStartLoc();
llvm_unreachable("impossible SILLocation");
}
SourceLoc SILLocation::getDebugSourceLoc() const {
assert(!isDebugInfoLoc());
if (isSILFile())
return Loc.SILFileLoc;
if (isAutoGenerated())
return SourceLoc();
if (auto *expr = Loc.ASTNode.Primary.dyn_cast<Expr*>()) {
if (isa<CallExpr>(expr))
return expr->getEndLoc();
// Code that has an autoclosure as location should not show up in
// the line table (rdar://problem/14627460). Note also that the
// closure function still has a valid DW_AT_decl_line. Depending
// on how we decide to resolve rdar://problem/14627460, we may
// want to use the regular getLoc instead and rather use the
// column info.
if (isa<AutoClosureExpr>(expr))
return SourceLoc();
}
if (Loc.ASTNode.ForDebugger)
return getSourceLoc(Loc.ASTNode.ForDebugger);
return getSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getStartSourceLoc() const {
if (isAutoGenerated())
return SourceLoc();
if (isSILFile())
return Loc.SILFileLoc;
return getStartSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getStartSourceLoc(ASTNodeTy N) const {
if (auto *decl = N.dyn_cast<Decl*>())
return decl->getStartLoc();
if (auto *expr = N.dyn_cast<Expr*>())
return expr->getStartLoc();
if (auto *stmt = N.dyn_cast<Stmt*>())
return stmt->getStartLoc();
if (auto *patt = N.dyn_cast<Pattern*>())
return patt->getStartLoc();
llvm_unreachable("impossible SILLocation");
}
SourceLoc SILLocation::getEndSourceLoc() const {
if (isAutoGenerated())
return SourceLoc();
if (isSILFile())
return Loc.SILFileLoc;
return getEndSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getEndSourceLoc(ASTNodeTy N) const {
if (auto decl = N.dyn_cast<Decl*>())
return decl->getEndLoc();
if (auto expr = N.dyn_cast<Expr*>())
return expr->getEndLoc();
if (auto stmt = N.dyn_cast<Stmt*>())
return stmt->getEndLoc();
if (auto patt = N.dyn_cast<Pattern*>())
return patt->getEndLoc();
llvm_unreachable("impossible SILLocation");
}
SILLocation::DebugLoc SILLocation::decode(SourceLoc Loc,
const SourceManager &SM) {
DebugLoc DL;
if (Loc.isValid()) {
DL.Filename = SM.getBufferIdentifierForLoc(Loc);
std::tie(DL.Line, DL.Column) = SM.getLineAndColumn(Loc);
}
return DL;
}
void SILLocation::dump(const SourceManager &SM) const {
if (auto D = getAsASTNode<Decl>())
llvm::errs() << Decl::getKindName(D->getKind()) << "Decl @ ";
if (auto E = getAsASTNode<Expr>())
llvm::errs() << Expr::getKindName(E->getKind()) << "Expr @ ";
if (auto S = getAsASTNode<Stmt>())
llvm::errs() << Stmt::getKindName(S->getKind()) << "Stmt @ ";
if (auto P = getAsASTNode<Pattern>())
llvm::errs() << Pattern::getKindName(P->getKind()) << "Pattern @ ";
print(llvm::errs(), SM);
if (isAutoGenerated()) llvm::errs() << ":auto";
if (alwaysPointsToStart()) llvm::errs() << ":start";
if (alwaysPointsToEnd()) llvm::errs() << ":end";
if (isInTopLevel()) llvm::errs() << ":toplevel";
if (isInPrologue()) llvm::errs() << ":prologue";
if (isSILFile()) llvm::errs() << ":sil";
if (hasDebugLoc()) {
llvm::errs() << ":debug[";
getDebugSourceLoc().print(llvm::errs(), SM);
llvm::errs() << "]\n";
}
}
void SILLocation::print(raw_ostream &OS, const SourceManager &SM) const {
if (isNull())
OS << "<no loc>";
getSourceLoc().print(OS, SM);
}
InlinedLocation InlinedLocation::getInlinedLocation(SILLocation L) {
if (Expr *E = L.getAsASTNode<Expr>())
return InlinedLocation(E, L.getSpecialFlags());
if (Stmt *S = L.getAsASTNode<Stmt>())
return InlinedLocation(S, L.getSpecialFlags());
if (Pattern *P = L.getAsASTNode<Pattern>())
return InlinedLocation(P, L.getSpecialFlags());
if (Decl *D = L.getAsASTNode<Decl>())
return InlinedLocation(D, L.getSpecialFlags());
if (L.isSILFile())
return InlinedLocation(L.Loc.SILFileLoc, L.getSpecialFlags());
if (L.isInTopLevel())
return InlinedLocation::getModuleLocation(L.getSpecialFlags());
if (L.isAutoGenerated()) {
InlinedLocation IL;
IL.markAutoGenerated();
return IL;
}
llvm_unreachable("Cannot construct Inlined loc from the given location.");
}
MandatoryInlinedLocation
MandatoryInlinedLocation::getMandatoryInlinedLocation(SILLocation L) {
if (Expr *E = L.getAsASTNode<Expr>())
return MandatoryInlinedLocation(E, L.getSpecialFlags());
if (Stmt *S = L.getAsASTNode<Stmt>())
return MandatoryInlinedLocation(S, L.getSpecialFlags());
if (Pattern *P = L.getAsASTNode<Pattern>())
return MandatoryInlinedLocation(P, L.getSpecialFlags());
if (Decl *D = L.getAsASTNode<Decl>())
return MandatoryInlinedLocation(D, L.getSpecialFlags());
if (L.isSILFile())
return MandatoryInlinedLocation(L.Loc.SILFileLoc, L.getSpecialFlags());
if (L.isInTopLevel())
return MandatoryInlinedLocation::getModuleLocation(L.getSpecialFlags());
llvm_unreachable("Cannot construct Inlined loc from the given location.");
}
CleanupLocation CleanupLocation::get(SILLocation L) {
if (Expr *E = L.getAsASTNode<Expr>())
return CleanupLocation(E, L.getSpecialFlags());
if (Stmt *S = L.getAsASTNode<Stmt>())
return CleanupLocation(S, L.getSpecialFlags());
if (Pattern *P = L.getAsASTNode<Pattern>())
return CleanupLocation(P, L.getSpecialFlags());
if (Decl *D = L.getAsASTNode<Decl>())
return CleanupLocation(D, L.getSpecialFlags());
if (L.isNull())
return CleanupLocation();
if (L.isSILFile())
return CleanupLocation();
llvm_unreachable("Cannot construct Cleanup loc from the "
"given location.");
}
<commit_msg>Don't crash in IRGen if the location used for diagnostics is a DebugLoc (this is the case if the input file is a SIL file).<commit_after>//===--- SILLocation.cpp - Location information for SIL nodes -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/SIL/SILLocation.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/Basic/SourceManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
SourceLoc SILLocation::getSourceLoc() const {
if (isSILFile())
return Loc.SILFileLoc;
// Don't crash if the location is a DebugLoc.
// TODO: this is a workaround until rdar://problem/25225083 is implemented.
if (isDebugInfoLoc())
return SourceLoc();
return getSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getSourceLoc(ASTNodeTy N) const {
if (N.isNull())
return SourceLoc();
if (alwaysPointsToStart() ||
alwaysPointsToEnd() ||
is<CleanupLocation>() ||
is<ImplicitReturnLocation>())
return getEndSourceLoc(N);
// Use the start location for the ReturnKind.
if (is<ReturnLocation>())
return getStartSourceLoc(N);
if (auto *decl = N.dyn_cast<Decl*>())
return decl->getLoc();
if (auto *expr = N.dyn_cast<Expr*>())
return expr->getLoc();
if (auto *stmt = N.dyn_cast<Stmt*>())
return stmt->getStartLoc();
if (auto *patt = N.dyn_cast<Pattern*>())
return patt->getStartLoc();
llvm_unreachable("impossible SILLocation");
}
SourceLoc SILLocation::getDebugSourceLoc() const {
assert(!isDebugInfoLoc());
if (isSILFile())
return Loc.SILFileLoc;
if (isAutoGenerated())
return SourceLoc();
if (auto *expr = Loc.ASTNode.Primary.dyn_cast<Expr*>()) {
if (isa<CallExpr>(expr))
return expr->getEndLoc();
// Code that has an autoclosure as location should not show up in
// the line table (rdar://problem/14627460). Note also that the
// closure function still has a valid DW_AT_decl_line. Depending
// on how we decide to resolve rdar://problem/14627460, we may
// want to use the regular getLoc instead and rather use the
// column info.
if (isa<AutoClosureExpr>(expr))
return SourceLoc();
}
if (Loc.ASTNode.ForDebugger)
return getSourceLoc(Loc.ASTNode.ForDebugger);
return getSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getStartSourceLoc() const {
if (isAutoGenerated())
return SourceLoc();
if (isSILFile())
return Loc.SILFileLoc;
return getStartSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getStartSourceLoc(ASTNodeTy N) const {
if (auto *decl = N.dyn_cast<Decl*>())
return decl->getStartLoc();
if (auto *expr = N.dyn_cast<Expr*>())
return expr->getStartLoc();
if (auto *stmt = N.dyn_cast<Stmt*>())
return stmt->getStartLoc();
if (auto *patt = N.dyn_cast<Pattern*>())
return patt->getStartLoc();
llvm_unreachable("impossible SILLocation");
}
SourceLoc SILLocation::getEndSourceLoc() const {
if (isAutoGenerated())
return SourceLoc();
if (isSILFile())
return Loc.SILFileLoc;
return getEndSourceLoc(Loc.ASTNode.Primary);
}
SourceLoc SILLocation::getEndSourceLoc(ASTNodeTy N) const {
if (auto decl = N.dyn_cast<Decl*>())
return decl->getEndLoc();
if (auto expr = N.dyn_cast<Expr*>())
return expr->getEndLoc();
if (auto stmt = N.dyn_cast<Stmt*>())
return stmt->getEndLoc();
if (auto patt = N.dyn_cast<Pattern*>())
return patt->getEndLoc();
llvm_unreachable("impossible SILLocation");
}
SILLocation::DebugLoc SILLocation::decode(SourceLoc Loc,
const SourceManager &SM) {
DebugLoc DL;
if (Loc.isValid()) {
DL.Filename = SM.getBufferIdentifierForLoc(Loc);
std::tie(DL.Line, DL.Column) = SM.getLineAndColumn(Loc);
}
return DL;
}
void SILLocation::dump(const SourceManager &SM) const {
if (auto D = getAsASTNode<Decl>())
llvm::errs() << Decl::getKindName(D->getKind()) << "Decl @ ";
if (auto E = getAsASTNode<Expr>())
llvm::errs() << Expr::getKindName(E->getKind()) << "Expr @ ";
if (auto S = getAsASTNode<Stmt>())
llvm::errs() << Stmt::getKindName(S->getKind()) << "Stmt @ ";
if (auto P = getAsASTNode<Pattern>())
llvm::errs() << Pattern::getKindName(P->getKind()) << "Pattern @ ";
print(llvm::errs(), SM);
if (isAutoGenerated()) llvm::errs() << ":auto";
if (alwaysPointsToStart()) llvm::errs() << ":start";
if (alwaysPointsToEnd()) llvm::errs() << ":end";
if (isInTopLevel()) llvm::errs() << ":toplevel";
if (isInPrologue()) llvm::errs() << ":prologue";
if (isSILFile()) llvm::errs() << ":sil";
if (hasDebugLoc()) {
llvm::errs() << ":debug[";
getDebugSourceLoc().print(llvm::errs(), SM);
llvm::errs() << "]\n";
}
}
void SILLocation::print(raw_ostream &OS, const SourceManager &SM) const {
if (isNull())
OS << "<no loc>";
getSourceLoc().print(OS, SM);
}
InlinedLocation InlinedLocation::getInlinedLocation(SILLocation L) {
if (Expr *E = L.getAsASTNode<Expr>())
return InlinedLocation(E, L.getSpecialFlags());
if (Stmt *S = L.getAsASTNode<Stmt>())
return InlinedLocation(S, L.getSpecialFlags());
if (Pattern *P = L.getAsASTNode<Pattern>())
return InlinedLocation(P, L.getSpecialFlags());
if (Decl *D = L.getAsASTNode<Decl>())
return InlinedLocation(D, L.getSpecialFlags());
if (L.isSILFile())
return InlinedLocation(L.Loc.SILFileLoc, L.getSpecialFlags());
if (L.isInTopLevel())
return InlinedLocation::getModuleLocation(L.getSpecialFlags());
if (L.isAutoGenerated()) {
InlinedLocation IL;
IL.markAutoGenerated();
return IL;
}
llvm_unreachable("Cannot construct Inlined loc from the given location.");
}
MandatoryInlinedLocation
MandatoryInlinedLocation::getMandatoryInlinedLocation(SILLocation L) {
if (Expr *E = L.getAsASTNode<Expr>())
return MandatoryInlinedLocation(E, L.getSpecialFlags());
if (Stmt *S = L.getAsASTNode<Stmt>())
return MandatoryInlinedLocation(S, L.getSpecialFlags());
if (Pattern *P = L.getAsASTNode<Pattern>())
return MandatoryInlinedLocation(P, L.getSpecialFlags());
if (Decl *D = L.getAsASTNode<Decl>())
return MandatoryInlinedLocation(D, L.getSpecialFlags());
if (L.isSILFile())
return MandatoryInlinedLocation(L.Loc.SILFileLoc, L.getSpecialFlags());
if (L.isInTopLevel())
return MandatoryInlinedLocation::getModuleLocation(L.getSpecialFlags());
llvm_unreachable("Cannot construct Inlined loc from the given location.");
}
CleanupLocation CleanupLocation::get(SILLocation L) {
if (Expr *E = L.getAsASTNode<Expr>())
return CleanupLocation(E, L.getSpecialFlags());
if (Stmt *S = L.getAsASTNode<Stmt>())
return CleanupLocation(S, L.getSpecialFlags());
if (Pattern *P = L.getAsASTNode<Pattern>())
return CleanupLocation(P, L.getSpecialFlags());
if (Decl *D = L.getAsASTNode<Decl>())
return CleanupLocation(D, L.getSpecialFlags());
if (L.isNull())
return CleanupLocation();
if (L.isSILFile())
return CleanupLocation();
llvm_unreachable("Cannot construct Cleanup loc from the "
"given location.");
}
<|endoftext|> |
<commit_before>#ifndef __RANK_FILTER__
#define __RANK_FILTER__
#include <deque>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>
#include <boost/array.hpp>
#include <boost/container/set.hpp>
#include <boost/container/node_allocator.hpp>
#include <boost/math/special_functions/round.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
namespace rank_filter
{
template<class I1,
class I2>
inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,
I2& dest_begin, I2& dest_end,
size_t half_length, double rank)
{
// Types in use.
typedef typename std::iterator_traits<I1>::value_type T1;
typedef typename std::iterator_traits<I2>::value_type T2;
typedef typename std::iterator_traits<I1>::difference_type I1_diff_t;
typedef typename std::iterator_traits<I2>::difference_type I2_diff_t;
// Establish common types to work with source and destination values.
BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value));
typedef T1 T;
typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t;
// Define container types that will be used.
typedef boost::container::multiset< T,
std::less<T>,
boost::container::node_allocator<T>,
boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;
typedef std::deque< typename multiset::iterator > deque;
// Ensure the result will fit.
assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end));
// Window length cannot exceed input data with reflection.
assert((half_length + 1) <= std::distance(src_begin, src_end));
// Rank must be in the range 0 to 1.
assert((0 <= rank) && (rank <= 1));
// Track values in window both in sorted and sequential order.
multiset sorted_window;
deque window_iters(2 * half_length + 1);
// Iterators in source and destination
I1 src_pos = src_begin;
I1 dest_pos = dest_begin;
// Get the initial window in sequential order with reflection
// Insert elements in order to the multiset for sorting.
// Store all multiset iterators into the deque in sequential order.
{
std::deque<T> window_init(half_length + 1);
for (I_diff_t j = half_length + 1; j > 0;)
{
window_init[--j] = *(src_pos++);
}
for (I_diff_t j = 0; j < half_length; j++)
{
window_iters[j] = sorted_window.insert(window_init[j]);
}
for (I_diff_t j = half_length; j < 2 * half_length + 1; j++)
{
window_iters[j] = sorted_window.insert(window_init.back());
window_init.pop_back();
}
}
// Window position corresponding to this rank.
const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length)));
typename multiset::iterator rank_point = sorted_window.begin();
std::advance(rank_point, rank_pos);
// Roll window forward one value at a time.
typename multiset::iterator prev_iter;
T prev_value;
T next_value;
I_diff_t window_reflect_pos = 2 * half_length;
while ( window_reflect_pos >= 0 )
{
*(dest_pos++) = *rank_point;
prev_iter = window_iters.front();
prev_value = *prev_iter;
window_iters.pop_front();
// Determine next value to add to window.
// Handle special cases like reflection at the end.
if ( src_pos == src_end )
{
if ( window_reflect_pos == 0 )
{
window_reflect_pos -= 2;
next_value = prev_value;
}
else
{
window_reflect_pos -= 2;
next_value = *(window_iters[window_reflect_pos]);
}
}
else
{
next_value = *(src_pos++);
}
// Remove old value and add new value to the window.
// Handle special cases where `rank_pos` may have an adjusted position
// due to where the old and new values are inserted.
if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
{
if ( rank_point == prev_iter )
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
}
else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
{
if (rank_point == prev_iter)
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
}
}
}
}
}
namespace std
{
template <class T, size_t N>
ostream& operator<<(ostream& out, const boost::array<T, N>& that)
{
out << "{ ";
for (unsigned int i = 0; i < (N - 1); i++)
{
out << that[i] << ", ";
}
out << that[N - 1] << " }";
return(out);
}
}
#endif //__RANK_FILTER__
<commit_msg>Precompute some window lengths<commit_after>#ifndef __RANK_FILTER__
#define __RANK_FILTER__
#include <deque>
#include <cassert>
#include <functional>
#include <iostream>
#include <iterator>
#include <boost/array.hpp>
#include <boost/container/set.hpp>
#include <boost/container/node_allocator.hpp>
#include <boost/math/special_functions/round.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
namespace rank_filter
{
template<class I1,
class I2>
inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,
I2& dest_begin, I2& dest_end,
size_t half_length, double rank)
{
// Types in use.
typedef typename std::iterator_traits<I1>::value_type T1;
typedef typename std::iterator_traits<I2>::value_type T2;
typedef typename std::iterator_traits<I1>::difference_type I1_diff_t;
typedef typename std::iterator_traits<I2>::difference_type I2_diff_t;
// Establish common types to work with source and destination values.
BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value));
typedef T1 T;
typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t;
// Define container types that will be used.
typedef boost::container::multiset< T,
std::less<T>,
boost::container::node_allocator<T>,
boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset;
typedef std::deque< typename multiset::iterator > deque;
// Precompute some window lengths.
const size_t half_length_add_1 = half_length + 1;
const size_t length_sub_1 = 2 * half_length;
const size_t length = length_sub_1 + 1;
// Ensure the result will fit.
assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end));
// Window length cannot exceed input data with reflection.
assert(half_length_add_1 <= std::distance(src_begin, src_end));
// Rank must be in the range 0 to 1.
assert((0 <= rank) && (rank <= 1));
// Track values in window both in sorted and sequential order.
multiset sorted_window;
deque window_iters(length);
// Iterators in source and destination
I1 src_pos = src_begin;
I1 dest_pos = dest_begin;
// Get the initial window in sequential order with reflection
// Insert elements in order to the multiset for sorting.
// Store all multiset iterators into the deque in sequential order.
{
std::deque<T> window_init(half_length_add_1);
for (I_diff_t j = half_length_add_1; j > 0;)
{
window_init[--j] = *(src_pos++);
}
for (I_diff_t j = 0; j < half_length; j++)
{
window_iters[j] = sorted_window.insert(window_init[j]);
}
for (I_diff_t j = half_length; j < length; j++)
{
window_iters[j] = sorted_window.insert(window_init.back());
window_init.pop_back();
}
}
// Window position corresponding to this rank.
const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * length_sub_1));
typename multiset::iterator rank_point = sorted_window.begin();
std::advance(rank_point, rank_pos);
// Roll window forward one value at a time.
typename multiset::iterator prev_iter;
T prev_value;
T next_value;
I_diff_t window_reflect_pos = length_sub_1;
while ( window_reflect_pos >= 0 )
{
*(dest_pos++) = *rank_point;
prev_iter = window_iters.front();
prev_value = *prev_iter;
window_iters.pop_front();
// Determine next value to add to window.
// Handle special cases like reflection at the end.
if ( src_pos == src_end )
{
if ( window_reflect_pos == 0 )
{
window_reflect_pos -= 2;
next_value = prev_value;
}
else
{
window_reflect_pos -= 2;
next_value = *(window_iters[window_reflect_pos]);
}
}
else
{
next_value = *(src_pos++);
}
// Remove old value and add new value to the window.
// Handle special cases where `rank_pos` may have an adjusted position
// due to where the old and new values are inserted.
if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )
{
if ( rank_point == prev_iter )
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
}
}
else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point--;
}
else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )
{
if (rank_point == prev_iter)
{
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
sorted_window.erase(prev_iter);
}
else
{
sorted_window.erase(prev_iter);
window_iters.push_back(sorted_window.insert(next_value));
rank_point++;
}
}
}
}
}
namespace std
{
template <class T, size_t N>
ostream& operator<<(ostream& out, const boost::array<T, N>& that)
{
out << "{ ";
for (unsigned int i = 0; i < (N - 1); i++)
{
out << that[i] << ", ";
}
out << that[N - 1] << " }";
return(out);
}
}
#endif //__RANK_FILTER__
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/detail/StaticSingletonManager.h>
#include <mutex>
#include <typeindex>
#include <unordered_map>
namespace folly {
namespace detail {
namespace {
class StaticSingletonManagerWithRttiImpl {
public:
using Make = void*();
template <typename Arg>
static void* create(Arg& arg) {
// This Leaky Meyers Singleton must always live in the .cpp file.
static auto& instance = *new StaticSingletonManagerWithRttiImpl();
auto const ptr = instance.entry(*arg.key).get(arg.make);
arg.cache.store(ptr, std::memory_order_release);
return ptr;
}
private:
struct Entry {
void* ptr{};
std::mutex mutex;
void* get(Make& make) {
std::lock_guard<std::mutex> lock(mutex);
return ptr ? ptr : (ptr = make());
}
};
Entry& entry(std::type_info const& key) {
std::lock_guard<std::mutex> lock(mutex_);
auto& e = map_[key];
return e ? *e : *(e = new Entry());
}
std::unordered_map<std::type_index, Entry*> map_;
std::mutex mutex_;
};
} // namespace
template <bool Noexcept>
void* StaticSingletonManagerWithRtti::create_(Arg& arg) noexcept(Noexcept) {
return StaticSingletonManagerWithRttiImpl::create(arg);
}
template void* StaticSingletonManagerWithRtti::create_<false>(Arg& arg);
template void* StaticSingletonManagerWithRtti::create_<true>(Arg& arg);
} // namespace detail
} // namespace folly
<commit_msg>Fix StaticSingletonManager::create_<true><commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/detail/StaticSingletonManager.h>
#include <mutex>
#include <typeindex>
#include <unordered_map>
namespace folly {
namespace detail {
namespace {
class StaticSingletonManagerWithRttiImpl {
public:
using Make = void*();
template <typename Arg>
static void* create(Arg& arg) {
// This Leaky Meyers Singleton must always live in the .cpp file.
static auto& instance = *new StaticSingletonManagerWithRttiImpl();
auto const ptr = instance.entry(*arg.key).get(arg.make);
arg.cache.store(ptr, std::memory_order_release);
return ptr;
}
private:
struct Entry {
void* ptr{};
std::mutex mutex;
void* get(Make& make) {
std::lock_guard<std::mutex> lock(mutex);
return ptr ? ptr : (ptr = make());
}
};
Entry& entry(std::type_info const& key) {
std::lock_guard<std::mutex> lock(mutex_);
auto& e = map_[key];
return e ? *e : *(e = new Entry());
}
std::unordered_map<std::type_index, Entry*> map_;
std::mutex mutex_;
};
} // namespace
template <bool Noexcept>
void* StaticSingletonManagerWithRtti::create_(Arg& arg) noexcept(Noexcept) {
return StaticSingletonManagerWithRttiImpl::create(arg);
}
template void* StaticSingletonManagerWithRtti::create_<false>(Arg& arg);
template void* StaticSingletonManagerWithRtti::create_<true>(Arg& arg) noexcept;
} // namespace detail
} // namespace folly
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlfiltertabdialog.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2003-12-01 09:35:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include "xmlfilterdialogstrings.hrc"
#include "xmlfiltertabdialog.hxx"
#include "xmlfiltertabdialog.hrc"
#include "xmlfiltertabpagebasic.hrc"
#include "xmlfiltertabpagexslt.hrc"
#include "xmlfiltertabpagebasic.hxx"
#include "xmlfiltertabpagexslt.hxx"
#include "xmlfiltersettingsdialog.hxx"
#include "xmlfiltersettingsdialog.hrc"
#include "xmlfilterhelpids.hrc"
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
XMLFilterTabDialog::XMLFilterTabDialog( Window *pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF, const filter_info_impl* pInfo ) :
TabDialog( pParent, ResId( DLG_XML_FILTER_TABDIALOG, &rResMgr ) ),
mxMSF( rxMSF ),
mrResMgr( rResMgr ),
maTabCtrl( this, ResId( 1, &rResMgr ) ),
maOKBtn( this ),
maCancelBtn( this ),
maHelpBtn( this )
{
FreeResource();
maTabCtrl.SetHelpId( HID_XML_FILTER_TABPAGE_CTRL );
mpOldInfo = pInfo;
mpNewInfo = new filter_info_impl( *mpOldInfo );
String aTitle( GetText() );
aTitle.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s") ), mpNewInfo->maFilterName );
SetText( aTitle );
maTabCtrl.Show();
maOKBtn.Show();
maCancelBtn.Show();
maHelpBtn.Show();
maOKBtn.SetClickHdl( LINK( this, XMLFilterTabDialog, OkHdl ) );
maTabCtrl.SetActivatePageHdl( LINK( this, XMLFilterTabDialog, ActivatePageHdl ) );
maTabCtrl.SetDeactivatePageHdl( LINK( this, XMLFilterTabDialog, DeactivatePageHdl ) );
mpBasicPage = new XMLFilterTabPageBasic( &maTabCtrl, mrResMgr );
mpBasicPage->SetInfo( mpNewInfo );
maTabCtrl.SetTabPage( RID_XML_FILTER_TABPAGE_BASIC, mpBasicPage );
Size aSiz = mpBasicPage->GetSizePixel();
Size aCtrlSiz = maTabCtrl.GetOutputSizePixel();
// set size on TabControl only if smaller than TabPage
if ( aCtrlSiz.Width() < aSiz.Width() || aCtrlSiz.Height() < aSiz.Height() )
{
maTabCtrl.SetOutputSizePixel( aSiz );
aCtrlSiz = aSiz;
}
mpXSLTPage = new XMLFilterTabPageXSLT( &maTabCtrl, mrResMgr, mxMSF );
mpXSLTPage->SetInfo( mpNewInfo );
maTabCtrl.SetTabPage( RID_XML_FILTER_TABPAGE_XSLT, mpXSLTPage );
aSiz = mpXSLTPage->GetSizePixel();
if ( aCtrlSiz.Width() < aSiz.Width() || aCtrlSiz.Height() < aSiz.Height() )
{
maTabCtrl.SetOutputSizePixel( aSiz );
aCtrlSiz = aSiz;
}
ActivatePageHdl( &maTabCtrl );
AdjustLayout();
}
// -----------------------------------------------------------------------
XMLFilterTabDialog::~XMLFilterTabDialog()
{
delete mpBasicPage;
delete mpXSLTPage;
delete mpNewInfo;
}
// -----------------------------------------------------------------------
bool XMLFilterTabDialog::onOk()
{
mpXSLTPage->FillInfo( mpNewInfo );
mpBasicPage->FillInfo( mpNewInfo );
sal_uInt16 nErrorPage = 0;
sal_uInt16 nErrorId = 0;
Window* pFocusWindow = NULL;
String aReplace1;
String aReplace2;
// 1. see if the filter name is ok
if( (mpNewInfo->maFilterName.getLength() == 0) || (mpNewInfo->maFilterName != mpOldInfo->maFilterName) )
{
// if the user deleted the filter name, we reset the original filter name
if( mpNewInfo->maFilterName.getLength() == 0 )
{
mpNewInfo->maFilterName = mpOldInfo->maFilterName;
}
else
{
try
{
Reference< XNameAccess > xFilterContainer( mxMSF->createInstance( OUString::createFromAscii("com.sun.star.document.FilterFactory" ) ), UNO_QUERY );
if( xFilterContainer.is() )
{
if( xFilterContainer->hasByName( mpNewInfo->maFilterName ) )
{
nErrorPage = RID_XML_FILTER_TABPAGE_BASIC;
nErrorId = STR_ERROR_FILTER_NAME_EXISTS;
pFocusWindow = &(mpBasicPage->maEDFilterName);
aReplace1 = mpNewInfo->maFilterName;
}
}
}
catch( Exception& )
{
DBG_ERROR( "XMLFilterTabDialog::onOk exception catched!" );
}
}
}
// 2. see if the interface name is ok
if( (mpNewInfo->maInterfaceName.getLength() == 0) || (mpNewInfo->maInterfaceName != mpOldInfo->maInterfaceName) )
{
// if the user deleted the interface name, we reset the original filter name
if( mpNewInfo->maInterfaceName.getLength() == 0 )
{
mpNewInfo->maInterfaceName = mpOldInfo->maInterfaceName;
}
else
{
try
{
Reference< XNameAccess > xFilterContainer( mxMSF->createInstance( OUString::createFromAscii("com.sun.star.document.FilterFactory" ) ), UNO_QUERY );
if( xFilterContainer.is() )
{
Sequence< OUString > aFilterNames( xFilterContainer->getElementNames() );
OUString* pFilterName = aFilterNames.getArray();
const sal_Int32 nCount = aFilterNames.getLength();
sal_Int32 nFilter;
Sequence< PropertyValue > aValues;
for( nFilter = 0; (nFilter < nCount) && (nErrorId == 0); nFilter++, pFilterName++ )
{
Any aAny( xFilterContainer->getByName( *pFilterName ) );
if( !(aAny >>= aValues) )
continue;
const sal_Int32 nValueCount( aValues.getLength() );
PropertyValue* pValues = aValues.getArray();
sal_Int32 nValue;
for( nValue = 0; (nValue < nValueCount) && (nErrorId == 0); nValue++, pValues++ )
{
if( pValues->Name.equalsAscii( "UIName" ) )
{
OUString aInterfaceName;
pValues->Value >>= aInterfaceName;
if( aInterfaceName == mpNewInfo->maInterfaceName )
{
nErrorPage = RID_XML_FILTER_TABPAGE_BASIC;
nErrorId = STR_ERROR_TYPE_NAME_EXISTS;
pFocusWindow = &(mpBasicPage->maEDInterfaceName);
aReplace1 = mpNewInfo->maInterfaceName;
aReplace2 = *pFilterName;
}
}
}
}
}
}
catch( Exception& )
{
DBG_ERROR( "XMLFilterTabDialog::onOk exception catched!" );
}
}
}
// 3. see if the dtd is valid
if( 0 == nErrorId )
{
if( (mpNewInfo->maDTD != mpOldInfo->maDTD) && isFileURL( mpNewInfo->maDTD ) )
{
osl::File aFile( mpNewInfo->maDTD );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_DTD_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDDTDSchema);
}
}
}
if( 0 == nErrorId )
{
// 4. see if the export xslt is valid
if( (mpNewInfo->maExportXSLT != mpOldInfo->maExportXSLT) && isFileURL( mpNewInfo->maExportXSLT ) )
{
osl::File aFile( mpNewInfo->maExportXSLT );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_EXPORT_XSLT_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDExportXSLT);
}
}
}
if( 0 == nErrorId )
{
// 5. see if the import xslt is valid
if( (mpNewInfo->maImportXSLT != mpOldInfo->maImportXSLT) && isFileURL( mpNewInfo->maImportXSLT ) )
{
osl::File aFile( mpNewInfo->maImportXSLT );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_IMPORT_XSLT_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDImportTemplate);
}
}
}
// see if we have at least an import or an export dtd
if((mpNewInfo->maImportXSLT.getLength() == 0) && (mpNewInfo->maExportXSLT.getLength() == 0) )
{
nErrorId = STR_ERROR_EXPORT_XSLT_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDExportXSLT);
}
if( 0 == nErrorId )
{
// 6. see if the import template is valid
if( (mpNewInfo->maImportTemplate != mpOldInfo->maImportTemplate) && isFileURL( mpNewInfo->maImportTemplate ) )
{
osl::File aFile( mpNewInfo->maImportTemplate );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_IMPORT_TEMPLATE_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDImportTemplate);
}
}
}
if( 0 != nErrorId )
{
maTabCtrl.SetCurPageId( (USHORT)nErrorPage );
ActivatePageHdl( &maTabCtrl );
ResId aResId( nErrorId, &mrResMgr );
String aMessage( aResId );
if( aReplace2.Len() )
{
aMessage.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s1") ), aReplace1 );
aMessage.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s2") ), aReplace2 );
}
else if( aReplace1.Len() )
{
aMessage.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s") ), aReplace1 );
}
ErrorBox aBox(this, (WinBits)(WB_OK), aMessage );
aBox.Execute();
if( pFocusWindow )
pFocusWindow->GrabFocus();
return false;
}
else
{
return true;
}
}
// -----------------------------------------------------------------------
filter_info_impl* XMLFilterTabDialog::getNewFilterInfo() const
{
return mpNewInfo;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, CancelHdl, Button*, pButton )
{
Close();
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, OkHdl, Button *, EMPTYARG )
{
if( onOk() )
EndDialog(1);
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, ActivatePageHdl, TabControl *, pTabCtrl )
{
const USHORT nId = pTabCtrl->GetCurPageId();
TabPage* pTabPage = pTabCtrl->GetTabPage( nId );
pTabPage->Show();
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, DeactivatePageHdl, TabControl *, pTabCtrl )
{
return TRUE;
}
<commit_msg>INTEGRATION: CWS mt802 (1.4.20); FILE MERGED 2004/01/26 16:49:05 mt 1.4.20.1: #115029# Use TabPageSize instead of OutputSizePixel from TabControl<commit_after>/*************************************************************************
*
* $RCSfile: xmlfiltertabdialog.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-02-04 11:14:50 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include "xmlfilterdialogstrings.hrc"
#include "xmlfiltertabdialog.hxx"
#include "xmlfiltertabdialog.hrc"
#include "xmlfiltertabpagebasic.hrc"
#include "xmlfiltertabpagexslt.hrc"
#include "xmlfiltertabpagebasic.hxx"
#include "xmlfiltertabpagexslt.hxx"
#include "xmlfiltersettingsdialog.hxx"
#include "xmlfiltersettingsdialog.hrc"
#include "xmlfilterhelpids.hrc"
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::container;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
XMLFilterTabDialog::XMLFilterTabDialog( Window *pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF, const filter_info_impl* pInfo ) :
TabDialog( pParent, ResId( DLG_XML_FILTER_TABDIALOG, &rResMgr ) ),
mxMSF( rxMSF ),
mrResMgr( rResMgr ),
maTabCtrl( this, ResId( 1, &rResMgr ) ),
maOKBtn( this ),
maCancelBtn( this ),
maHelpBtn( this )
{
FreeResource();
maTabCtrl.SetHelpId( HID_XML_FILTER_TABPAGE_CTRL );
mpOldInfo = pInfo;
mpNewInfo = new filter_info_impl( *mpOldInfo );
String aTitle( GetText() );
aTitle.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s") ), mpNewInfo->maFilterName );
SetText( aTitle );
maTabCtrl.Show();
maOKBtn.Show();
maCancelBtn.Show();
maHelpBtn.Show();
maOKBtn.SetClickHdl( LINK( this, XMLFilterTabDialog, OkHdl ) );
maTabCtrl.SetActivatePageHdl( LINK( this, XMLFilterTabDialog, ActivatePageHdl ) );
maTabCtrl.SetDeactivatePageHdl( LINK( this, XMLFilterTabDialog, DeactivatePageHdl ) );
mpBasicPage = new XMLFilterTabPageBasic( &maTabCtrl, mrResMgr );
mpBasicPage->SetInfo( mpNewInfo );
maTabCtrl.SetTabPage( RID_XML_FILTER_TABPAGE_BASIC, mpBasicPage );
Size aSiz = mpBasicPage->GetSizePixel();
Size aCtrlSiz = maTabCtrl.GetTabPageSizePixel();
// set size on TabControl only if smaller than TabPage
if ( aCtrlSiz.Width() < aSiz.Width() || aCtrlSiz.Height() < aSiz.Height() )
{
maTabCtrl.SetTabPageSizePixel( aSiz );
aCtrlSiz = aSiz;
}
mpXSLTPage = new XMLFilterTabPageXSLT( &maTabCtrl, mrResMgr, mxMSF );
mpXSLTPage->SetInfo( mpNewInfo );
maTabCtrl.SetTabPage( RID_XML_FILTER_TABPAGE_XSLT, mpXSLTPage );
aSiz = mpXSLTPage->GetSizePixel();
if ( aCtrlSiz.Width() < aSiz.Width() || aCtrlSiz.Height() < aSiz.Height() )
{
maTabCtrl.SetTabPageSizePixel( aSiz );
aCtrlSiz = aSiz;
}
ActivatePageHdl( &maTabCtrl );
AdjustLayout();
}
// -----------------------------------------------------------------------
XMLFilterTabDialog::~XMLFilterTabDialog()
{
delete mpBasicPage;
delete mpXSLTPage;
delete mpNewInfo;
}
// -----------------------------------------------------------------------
bool XMLFilterTabDialog::onOk()
{
mpXSLTPage->FillInfo( mpNewInfo );
mpBasicPage->FillInfo( mpNewInfo );
sal_uInt16 nErrorPage = 0;
sal_uInt16 nErrorId = 0;
Window* pFocusWindow = NULL;
String aReplace1;
String aReplace2;
// 1. see if the filter name is ok
if( (mpNewInfo->maFilterName.getLength() == 0) || (mpNewInfo->maFilterName != mpOldInfo->maFilterName) )
{
// if the user deleted the filter name, we reset the original filter name
if( mpNewInfo->maFilterName.getLength() == 0 )
{
mpNewInfo->maFilterName = mpOldInfo->maFilterName;
}
else
{
try
{
Reference< XNameAccess > xFilterContainer( mxMSF->createInstance( OUString::createFromAscii("com.sun.star.document.FilterFactory" ) ), UNO_QUERY );
if( xFilterContainer.is() )
{
if( xFilterContainer->hasByName( mpNewInfo->maFilterName ) )
{
nErrorPage = RID_XML_FILTER_TABPAGE_BASIC;
nErrorId = STR_ERROR_FILTER_NAME_EXISTS;
pFocusWindow = &(mpBasicPage->maEDFilterName);
aReplace1 = mpNewInfo->maFilterName;
}
}
}
catch( Exception& )
{
DBG_ERROR( "XMLFilterTabDialog::onOk exception catched!" );
}
}
}
// 2. see if the interface name is ok
if( (mpNewInfo->maInterfaceName.getLength() == 0) || (mpNewInfo->maInterfaceName != mpOldInfo->maInterfaceName) )
{
// if the user deleted the interface name, we reset the original filter name
if( mpNewInfo->maInterfaceName.getLength() == 0 )
{
mpNewInfo->maInterfaceName = mpOldInfo->maInterfaceName;
}
else
{
try
{
Reference< XNameAccess > xFilterContainer( mxMSF->createInstance( OUString::createFromAscii("com.sun.star.document.FilterFactory" ) ), UNO_QUERY );
if( xFilterContainer.is() )
{
Sequence< OUString > aFilterNames( xFilterContainer->getElementNames() );
OUString* pFilterName = aFilterNames.getArray();
const sal_Int32 nCount = aFilterNames.getLength();
sal_Int32 nFilter;
Sequence< PropertyValue > aValues;
for( nFilter = 0; (nFilter < nCount) && (nErrorId == 0); nFilter++, pFilterName++ )
{
Any aAny( xFilterContainer->getByName( *pFilterName ) );
if( !(aAny >>= aValues) )
continue;
const sal_Int32 nValueCount( aValues.getLength() );
PropertyValue* pValues = aValues.getArray();
sal_Int32 nValue;
for( nValue = 0; (nValue < nValueCount) && (nErrorId == 0); nValue++, pValues++ )
{
if( pValues->Name.equalsAscii( "UIName" ) )
{
OUString aInterfaceName;
pValues->Value >>= aInterfaceName;
if( aInterfaceName == mpNewInfo->maInterfaceName )
{
nErrorPage = RID_XML_FILTER_TABPAGE_BASIC;
nErrorId = STR_ERROR_TYPE_NAME_EXISTS;
pFocusWindow = &(mpBasicPage->maEDInterfaceName);
aReplace1 = mpNewInfo->maInterfaceName;
aReplace2 = *pFilterName;
}
}
}
}
}
}
catch( Exception& )
{
DBG_ERROR( "XMLFilterTabDialog::onOk exception catched!" );
}
}
}
// 3. see if the dtd is valid
if( 0 == nErrorId )
{
if( (mpNewInfo->maDTD != mpOldInfo->maDTD) && isFileURL( mpNewInfo->maDTD ) )
{
osl::File aFile( mpNewInfo->maDTD );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_DTD_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDDTDSchema);
}
}
}
if( 0 == nErrorId )
{
// 4. see if the export xslt is valid
if( (mpNewInfo->maExportXSLT != mpOldInfo->maExportXSLT) && isFileURL( mpNewInfo->maExportXSLT ) )
{
osl::File aFile( mpNewInfo->maExportXSLT );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_EXPORT_XSLT_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDExportXSLT);
}
}
}
if( 0 == nErrorId )
{
// 5. see if the import xslt is valid
if( (mpNewInfo->maImportXSLT != mpOldInfo->maImportXSLT) && isFileURL( mpNewInfo->maImportXSLT ) )
{
osl::File aFile( mpNewInfo->maImportXSLT );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_IMPORT_XSLT_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDImportTemplate);
}
}
}
// see if we have at least an import or an export dtd
if((mpNewInfo->maImportXSLT.getLength() == 0) && (mpNewInfo->maExportXSLT.getLength() == 0) )
{
nErrorId = STR_ERROR_EXPORT_XSLT_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDExportXSLT);
}
if( 0 == nErrorId )
{
// 6. see if the import template is valid
if( (mpNewInfo->maImportTemplate != mpOldInfo->maImportTemplate) && isFileURL( mpNewInfo->maImportTemplate ) )
{
osl::File aFile( mpNewInfo->maImportTemplate );
osl::File::RC aRC = aFile.open( OpenFlag_Read );
if( aRC != osl::File::E_None )
{
nErrorId = STR_ERROR_IMPORT_TEMPLATE_NOT_FOUND;
nErrorPage = RID_XML_FILTER_TABPAGE_XSLT;
pFocusWindow = &(mpXSLTPage->maEDImportTemplate);
}
}
}
if( 0 != nErrorId )
{
maTabCtrl.SetCurPageId( (USHORT)nErrorPage );
ActivatePageHdl( &maTabCtrl );
ResId aResId( nErrorId, &mrResMgr );
String aMessage( aResId );
if( aReplace2.Len() )
{
aMessage.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s1") ), aReplace1 );
aMessage.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s2") ), aReplace2 );
}
else if( aReplace1.Len() )
{
aMessage.SearchAndReplace( String( RTL_CONSTASCII_USTRINGPARAM("%s") ), aReplace1 );
}
ErrorBox aBox(this, (WinBits)(WB_OK), aMessage );
aBox.Execute();
if( pFocusWindow )
pFocusWindow->GrabFocus();
return false;
}
else
{
return true;
}
}
// -----------------------------------------------------------------------
filter_info_impl* XMLFilterTabDialog::getNewFilterInfo() const
{
return mpNewInfo;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, CancelHdl, Button*, pButton )
{
Close();
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, OkHdl, Button *, EMPTYARG )
{
if( onOk() )
EndDialog(1);
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, ActivatePageHdl, TabControl *, pTabCtrl )
{
const USHORT nId = pTabCtrl->GetCurPageId();
TabPage* pTabPage = pTabCtrl->GetTabPage( nId );
pTabPage->Show();
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( XMLFilterTabDialog, DeactivatePageHdl, TabControl *, pTabCtrl )
{
return TRUE;
}
<|endoftext|> |
<commit_before>// -----------------------------------------------------------------------------
// Copyright 2016 Marco Biasini
//
// 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 TYPUS_RESULT_HH
#define TYPUS_RESULT_HH
#include <string>
#include <iostream>
#include <cassert>
#include <vector>
#include <type_traits>
namespace typus {
template <typename E>
struct error_traits {
/**
* Whether the result is OK.
*/
static bool is_ok(const E& value);
/**
* Error value to be used to indicate that result is OK, e.g. contains a
* constructed value of type T.
*/
constexpr static E ok_value();
/**
* May be provided for an error type as the default error status, so
* \code result<T,E>::fail() \endcode can be called without arguments. For
* types where there is no clear default failed value, this can be omitted.
*/
constexpr static E default_fail_value();
};
/**
* Default error traits for boolean errors.
*/
template <>
struct error_traits<bool> {
static bool is_ok(const bool& error) {
return !error;
}
constexpr static bool ok_value() { return false; }
constexpr static bool default_fail_value() { return true; }
};
namespace detail {
// Tag type for failed result construction.
struct failed_tag_t {};
// holder class for the actual result. This class is required, because we want
// to have separate implementations for trivially destructible value types and
// types that require the destructor to be invoked.
template <typename T, typename E,
bool =std::is_trivially_destructible<T>::value>
class result_storage {
public:
using value_type = T;
using error_type = E;
protected:
result_storage(): value_(), error_(error_traits<E>::ok_value()) {
}
result_storage(const result_storage &rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) value_type(rhs.value_);
}
}
result_storage(const result_storage &&rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) T(std::move(rhs.value_));
}
}
result_storage(const value_type &rhs):
value_(rhs), error_(error_traits<E>::ok_value()) {
}
result_storage(const value_type &&rhs):
value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {
}
result_storage(failed_tag_t, E error): nul_state_('\0'), error_(error) {
}
~result_storage() {
if (error_traits<E>::is_ok(error_)) {
value_.~T();
}
}
union {
char nul_state_;
T value_;
};
E error_;
};
template <typename T, typename E>
class result_storage<T, E, true> {
public:
using value_type = T;
using error_type = E;
protected:
result_storage(): value_(), error_(error_traits<E>::ok_value()) {
}
result_storage(const result_storage &rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) value_type(rhs.value_);
}
}
result_storage(const result_storage &&rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) value_type(std::move(rhs.value_));
}
}
result_storage(const value_type &rhs):
value_(rhs), error_(error_traits<E>::ok_value()) {
}
result_storage(const value_type &&rhs):
value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {
}
result_storage(failed_tag_t, E error): nul_state_('\0'), error_(error) {
}
// nothing to be done, value_type is trivially destructible
~result_storage() { }
union {
char nul_state_;
T value_;
};
E error_;
};
} // namespace detail
/**
* \brief class holding a value of type T or an error of type E.
*
* Typical uses of this class include as a return type for a function/method
* that can fail. The result acts as a replacement for exception-based error
* handling.
*/
template <typename T, typename E=bool>
class result : public detail::result_storage<T, E> {
public:
typedef T value_type;
typedef E error_type;
/**
* \brief construct a failed result using the provided error value
*/
static result<T, E> fail(E error) {
return result<T,E>(detail::failed_tag_t{}, error);
}
/**
* \brief construct a failed result using the default fail value.
*
* This is probably only useful when using a boolean error type as
* for all others there is not meaningful default error value.
*/
static result<T, E> fail() {
return result<T,E>(detail::failed_tag_t{},
error_traits<E>::default_fail_value());
}
/**
* \brief whether the result contains a valid value.
*/
bool ok() const {
return error_traits<E>::is_ok(this->error_);
}
/**
* \brief whether the result contains a valid value.
*
* Identical to calling \ref ok.
*/
operator bool() const {
return this->ok();
}
/**
* \brief access the value in-place.
*
* Aborts if the result does not hold a valid value.
*/
const T& value() const {
assert(this->ok());
return this->value_;
}
/**
* \brief access the value in-place.
*
* Aborts if the result does not hold a valid value.
*/
T& value() {
assert(this->ok());
return this->value_;
}
/**
* \brief extract the value out of the result.
*/
T && extract() {
assert(this->ok());
return std::move(this->value_);
}
public:
/**
* \brief create a result containing a default-constructed value.
*/
result() = default;
/**
* \brief copy-construct a result.
*/
result(const result& rhs) = default;
/**
* \brief construct a new result holding a value by copy-constructor.
*/
result(const value_type &rhs): detail::result_storage<T, E>(rhs) {}
/**
* \brief construct a new result holding a value through move construction.
*/
result(value_type &&rhs): detail::result_storage<T, E>(std::move(rhs)) {}
template <typename T2, typename E2>
friend class result;
/**
* Allow for implicit conversion from one failed result type to another.
* Only supported if error types are the same. aborts if the value is
* ok.
*/
template<typename U>
result(const result<U, E> &other):
detail::result_storage<T,E>(detail::failed_tag_t{}, other.error_) {
assert(!other.ok());
}
/**
* \brief The error state of the result.
*/
E error() const { return this->error_; }
private:
result(detail::failed_tag_t, const error_type &e):
detail::result_storage<T, E>(detail::failed_tag_t{}, e) {
}
};
/**
* macro for Rust-style function return value checking. Note that is is
* not standard C++ and is only supported in clang and gcc, since it relies
* on statement expressions. So if you want to be portable, don't use it.
*
* Typical usage:
* \code
* result<std::string> may_fail() { ... }
*
* result<std::string> foo() {
* std::string value = TRY(may_fail());
* return do_stuff(value);
*
* }
* \endcode
*/
#define TRY(expr) ({ \
auto v = expr; \
if (!v.ok()) { \
return v; \
}; \
v.extract(); \
})
} // namespace typus
#endif // TYPUS_RESULT_HH
<commit_msg>trim set of includes<commit_after>// -----------------------------------------------------------------------------
// Copyright 2016 Marco Biasini
//
// 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 TYPUS_RESULT_HH
#define TYPUS_RESULT_HH
#include <memory>
#include <cassert>
#include <type_traits>
namespace typus {
template <typename E>
struct error_traits {
/**
* Whether the result is OK.
*/
static bool is_ok(const E& value);
/**
* Error value to be used to indicate that result is OK, e.g. contains a
* constructed value of type T.
*/
constexpr static E ok_value();
/**
* May be provided for an error type as the default error status, so
* \code result<T,E>::fail() \endcode can be called without arguments. For
* types where there is no clear default failed value, this can be omitted.
*/
constexpr static E default_fail_value();
};
/**
* Default error traits for boolean errors.
*/
template <>
struct error_traits<bool> {
static bool is_ok(const bool& error) {
return !error;
}
constexpr static bool ok_value() { return false; }
constexpr static bool default_fail_value() { return true; }
};
namespace detail {
// Tag type for failed result construction.
struct failed_tag_t {};
// holder class for the actual result. This class is required, because we want
// to have separate implementations for trivially destructible value types and
// types that require the destructor to be invoked.
template <typename T, typename E,
bool =std::is_trivially_destructible<T>::value>
class result_storage {
public:
using value_type = T;
using error_type = E;
protected:
result_storage(): value_(), error_(error_traits<E>::ok_value()) {
}
result_storage(const result_storage &rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) value_type(rhs.value_);
}
}
result_storage(const result_storage &&rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) T(std::move(rhs.value_));
}
}
result_storage(const value_type &rhs):
value_(rhs), error_(error_traits<E>::ok_value()) {
}
result_storage(const value_type &&rhs):
value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {
}
result_storage(failed_tag_t, E error): nul_state_('\0'), error_(error) {
}
~result_storage() {
if (error_traits<E>::is_ok(error_)) {
value_.~T();
}
}
union {
char nul_state_;
T value_;
};
E error_;
};
template <typename T, typename E>
class result_storage<T, E, true> {
public:
using value_type = T;
using error_type = E;
protected:
result_storage(): value_(), error_(error_traits<E>::ok_value()) {
}
result_storage(const result_storage &rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) value_type(rhs.value_);
}
}
result_storage(const result_storage &&rhs): error_(rhs.error_) {
if (error_traits<E>::is_ok(error_)) {
// in-place new
::new (std::addressof(value_)) value_type(std::move(rhs.value_));
}
}
result_storage(const value_type &rhs):
value_(rhs), error_(error_traits<E>::ok_value()) {
}
result_storage(const value_type &&rhs):
value_(std::move(rhs)), error_(error_traits<E>::ok_value()) {
}
result_storage(failed_tag_t, E error): nul_state_('\0'), error_(error) {
}
// nothing to be done, value_type is trivially destructible
~result_storage() { }
union {
char nul_state_;
T value_;
};
E error_;
};
} // namespace detail
/**
* \brief class holding a value of type T or an error of type E.
*
* Typical uses of this class include as a return type for a function/method
* that can fail. The result acts as a replacement for exception-based error
* handling.
*/
template <typename T, typename E=bool>
class result : public detail::result_storage<T, E> {
public:
typedef T value_type;
typedef E error_type;
/**
* \brief construct a failed result using the provided error value
*/
static result<T, E> fail(E error) {
return result<T,E>(detail::failed_tag_t{}, error);
}
/**
* \brief construct a failed result using the default fail value.
*
* This is probably only useful when using a boolean error type as
* for all others there is not meaningful default error value.
*/
static result<T, E> fail() {
return result<T,E>(detail::failed_tag_t{},
error_traits<E>::default_fail_value());
}
/**
* \brief whether the result contains a valid value.
*/
bool ok() const {
return error_traits<E>::is_ok(this->error_);
}
/**
* \brief whether the result contains a valid value.
*
* Identical to calling \ref ok.
*/
operator bool() const {
return this->ok();
}
/**
* \brief access the value in-place.
*
* Aborts if the result does not hold a valid value.
*/
const T& value() const {
assert(this->ok());
return this->value_;
}
/**
* \brief access the value in-place.
*
* Aborts if the result does not hold a valid value.
*/
T& value() {
assert(this->ok());
return this->value_;
}
/**
* \brief extract the value out of the result.
*/
T && extract() {
assert(this->ok());
return std::move(this->value_);
}
public:
/**
* \brief create a result containing a default-constructed value.
*/
result() = default;
/**
* \brief copy-construct a result.
*/
result(const result& rhs) = default;
/**
* \brief construct a new result holding a value by copy-constructor.
*/
result(const value_type &rhs): detail::result_storage<T, E>(rhs) {}
/**
* \brief construct a new result holding a value through move construction.
*/
result(value_type &&rhs): detail::result_storage<T, E>(std::move(rhs)) {}
template <typename T2, typename E2>
friend class result;
/**
* Allow for implicit conversion from one failed result type to another.
* Only supported if error types are the same. aborts if the value is
* ok.
*/
template<typename U>
result(const result<U, E> &other):
detail::result_storage<T,E>(detail::failed_tag_t{}, other.error_) {
assert(!other.ok());
}
/**
* \brief The error state of the result.
*/
E error() const { return this->error_; }
private:
result(detail::failed_tag_t, const error_type &e):
detail::result_storage<T, E>(detail::failed_tag_t{}, e) {
}
};
/**
* macro for Rust-style function return value checking. Note that is is
* not standard C++ and is only supported in clang and gcc, since it relies
* on statement expressions. So if you want to be portable, don't use it.
*
* Typical usage:
* \code
* result<std::string> may_fail() { ... }
*
* result<std::string> foo() {
* std::string value = TRY(may_fail());
* return do_stuff(value);
*
* }
* \endcode
*/
#define TRY(expr) ({ \
auto v = expr; \
if (!v.ok()) { \
return v; \
}; \
v.extract(); \
})
} // namespace typus
#endif // TYPUS_RESULT_HH
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class QGCCore
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QFile>
#include <QFlags>
#include <QThread>
#include <QSplashScreen>
#include <QPixmap>
#include <QDesktopWidget>
#include <QPainter>
#include <QStyleFactory>
#include <QAction>
#include <QDebug>
#include "configuration.h"
#include "QGC.h"
#include "QGCCore.h"
#include "MainWindow.h"
#include "GAudioOutput.h"
#ifdef OPAL_RT
#include "OpalLink.h"
#endif
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
/**
* @brief Constructor for the main application.
*
* This constructor initializes and starts the whole application. It takes standard
* command-line parameters
*
* @param argc The number of command-line parameters
* @param argv The string array of parameters
**/
QGCCore::QGCCore(int &argc, char* argv[]) : QApplication(argc, argv)
{
// Set application name
this->setApplicationName(QGC_APPLICATION_NAME);
this->setApplicationVersion(QGC_APPLICATION_VERSION);
this->setOrganizationName(QLatin1String("QGroundControl"));
this->setOrganizationDomain("org.qgroundcontrol");
// Set settings format
QSettings::setDefaultFormat(QSettings::IniFormat);
// Check application settings
// clear them if they mismatch
// QGC then falls back to default
QSettings settings;
// Show user an upgrade message if QGC got upgraded (see code below, after splash screen)
bool upgraded = false;
QString lastApplicationVersion("");
if (settings.contains("QGC_APPLICATION_VERSION"))
{
QString qgcVersion = settings.value("QGC_APPLICATION_VERSION").toString();
if (qgcVersion != QGC_APPLICATION_VERSION)
{
lastApplicationVersion = qgcVersion;
settings.clear();
// Write current application version
settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION);
upgraded = true;
}
}
else
{
// If application version is not set, clear settings anyway
settings.clear();
// Write current application version
settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION);
}
settings.sync();
// Show splash screen
QPixmap splashImage(":/files/images/splash.png");
QSplashScreen* splashScreen = new QSplashScreen(splashImage);
// Delete splash screen after mainWindow was displayed
splashScreen->setAttribute(Qt::WA_DeleteOnClose);
splashScreen->show();
processEvents();
splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// Exit main application when last window is closed
connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));
// Load application font
QFontDatabase fontDatabase = QFontDatabase();
const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
//const QString fontFamilyName = "Bitstream Vera Sans";
if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str());
fontDatabase.addApplicationFont(fontFileName);
// Avoid Using setFont(). In the Qt docu you can read the following:
// "Warning: Do not use this function in conjunction with Qt Style Sheets."
// setFont(fontDatabase.font(fontFamilyName, "Roman", 12));
// Start the comm link manager
splashScreen->showMessage(tr("Starting communication links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startLinkManager();
// Start the UAS Manager
splashScreen->showMessage(tr("Starting UAS manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startUASManager();
// Start the user interface
splashScreen->showMessage(tr("Starting user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// The first call to instance() creates the MainWindow, so make sure it's passed the splashScreen.
mainWindow = MainWindow::instance(splashScreen);
// Connect links
// to make sure that all components are initialized when the
// first messages arrive
UDPLink* udpLink = new UDPLink(QHostAddress::Any, 14550);
MainWindow::instance()->addLink(udpLink);
#ifdef OPAL_RT
// Add OpalRT Link, but do not connect
OpalLink* opalLink = new OpalLink();
MainWindow::instance()->addLink(opalLink);
#endif
MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(":/demo-log.txt");
simulationLink->disconnect();
// Remove splash screen
splashScreen->finish(mainWindow);
if (upgraded) mainWindow->showInfoMessage(tr("Default Settings Loaded"), tr("QGroundControl has been upgraded from version %1 to version %2. Some of your user preferences have been reset to defaults for safety reasons. Please adjust them where needed.").arg(lastApplicationVersion).arg(QGC_APPLICATION_VERSION));
}
/**
* @brief Destructor for the groundstation. It destroys all loaded instances.
*
**/
QGCCore::~QGCCore()
{
//mainWindow->storeSettings();
//mainWindow->close();
//mainWindow->deleteLater();
// Delete singletons
// First systems
delete UASManager::instance();
// then links
delete LinkManager::instance();
// Finally the main window
//delete MainWindow::instance();
//The main window now autodeletes on close.
}
/**
* @brief Start the link managing component.
*
* The link manager keeps track of all communication links and provides the global
* packet queue. It is the main communication hub
**/
void QGCCore::startLinkManager()
{
LinkManager::instance();
}
/**
* @brief Start the Unmanned Air System Manager
*
**/
void QGCCore::startUASManager()
{
// Load UAS plugins
QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_LINUX)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS") {
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
UASManager::instance();
// Load plugins
QStringList pluginFileNames;
foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin) {
//populateMenus(plugin);
pluginFileNames += fileName;
//printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str());
}
}
}
<commit_msg>Revert "No longer automatically connect UDP on startup. Also removed some dead code"<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2010 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class QGCCore
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QFile>
#include <QFlags>
#include <QThread>
#include <QSplashScreen>
#include <QPixmap>
#include <QDesktopWidget>
#include <QPainter>
#include <QStyleFactory>
#include <QAction>
#include <QDebug>
#include "configuration.h"
#include "QGC.h"
#include "QGCCore.h"
#include "MainWindow.h"
#include "GAudioOutput.h"
#ifdef OPAL_RT
#include "OpalLink.h"
#endif
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
/**
* @brief Constructor for the main application.
*
* This constructor initializes and starts the whole application. It takes standard
* command-line parameters
*
* @param argc The number of command-line parameters
* @param argv The string array of parameters
**/
QGCCore::QGCCore(int &argc, char* argv[]) : QApplication(argc, argv)
{
// Set application name
this->setApplicationName(QGC_APPLICATION_NAME);
this->setApplicationVersion(QGC_APPLICATION_VERSION);
this->setOrganizationName(QLatin1String("QGroundControl"));
this->setOrganizationDomain("org.qgroundcontrol");
// Set settings format
QSettings::setDefaultFormat(QSettings::IniFormat);
// Check application settings
// clear them if they mismatch
// QGC then falls back to default
QSettings settings;
// Show user an upgrade message if QGC got upgraded (see code below, after splash screen)
bool upgraded = false;
QString lastApplicationVersion("");
if (settings.contains("QGC_APPLICATION_VERSION"))
{
QString qgcVersion = settings.value("QGC_APPLICATION_VERSION").toString();
if (qgcVersion != QGC_APPLICATION_VERSION)
{
lastApplicationVersion = qgcVersion;
settings.clear();
// Write current application version
settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION);
upgraded = true;
}
}
else
{
// If application version is not set, clear settings anyway
settings.clear();
// Write current application version
settings.setValue("QGC_APPLICATION_VERSION", QGC_APPLICATION_VERSION);
}
settings.sync();
// Show splash screen
QPixmap splashImage(":/files/images/splash.png");
QSplashScreen* splashScreen = new QSplashScreen(splashImage);
// Delete splash screen after mainWindow was displayed
splashScreen->setAttribute(Qt::WA_DeleteOnClose);
splashScreen->show();
processEvents();
splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// Exit main application when last window is closed
connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));
// Load application font
QFontDatabase fontDatabase = QFontDatabase();
const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
//const QString fontFamilyName = "Bitstream Vera Sans";
if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str());
fontDatabase.addApplicationFont(fontFileName);
// Avoid Using setFont(). In the Qt docu you can read the following:
// "Warning: Do not use this function in conjunction with Qt Style Sheets."
// setFont(fontDatabase.font(fontFamilyName, "Roman", 12));
// Start the comm link manager
splashScreen->showMessage(tr("Starting communication links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startLinkManager();
// Start the UAS Manager
splashScreen->showMessage(tr("Starting UAS manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startUASManager();
// Start the user interface
splashScreen->showMessage(tr("Starting user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// The first call to instance() creates the MainWindow, so make sure it's passed the splashScreen.
mainWindow = MainWindow::instance(splashScreen);
// Connect links
// to make sure that all components are initialized when the
// first messages arrive
UDPLink* udpLink = new UDPLink(QHostAddress::Any, 14550);
MainWindow::instance()->addLink(udpLink);
// Listen on Multicast-Address 239.255.77.77, Port 14550
//QHostAddress * multicast_udp = new QHostAddress("239.255.77.77");
//UDPLink* udpLink = new UDPLink(*multicast_udp, 14550);
#ifdef OPAL_RT
// Add OpalRT Link, but do not connect
OpalLink* opalLink = new OpalLink();
MainWindow::instance()->addLink(opalLink);
#endif
MAVLinkSimulationLink* simulationLink = new MAVLinkSimulationLink(":/demo-log.txt");
simulationLink->disconnect();
// Remove splash screen
splashScreen->finish(mainWindow);
if (upgraded) mainWindow->showInfoMessage(tr("Default Settings Loaded"), tr("QGroundControl has been upgraded from version %1 to version %2. Some of your user preferences have been reset to defaults for safety reasons. Please adjust them where needed.").arg(lastApplicationVersion).arg(QGC_APPLICATION_VERSION));
// Check if link could be connected
if (!udpLink->connect())
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Could not connect UDP port. Is an instance of " + qAppName() + "already running?");
msgBox.setInformativeText("You will not be able to receive data via UDP. Please check that you're running the right executable and then re-start " + qAppName() + ". Do you want to close the application?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
int ret = msgBox.exec();
// Close the message box shortly after the click to prevent accidental clicks
QTimer::singleShot(15000, &msgBox, SLOT(reject()));
// Exit application
if (ret == QMessageBox::Yes)
{
//mainWindow->close();
QTimer::singleShot(200, mainWindow, SLOT(close()));
}
}
// forever
// {
// QGC::SLEEP::msleep(5000);
// }
// mainWindow->close();
// mainWindow->deleteLater();
// QGC::SLEEP::msleep(200);
}
/**
* @brief Destructor for the groundstation. It destroys all loaded instances.
*
**/
QGCCore::~QGCCore()
{
//mainWindow->storeSettings();
//mainWindow->close();
//mainWindow->deleteLater();
// Delete singletons
// First systems
delete UASManager::instance();
// then links
delete LinkManager::instance();
// Finally the main window
//delete MainWindow::instance();
//The main window now autodeletes on close.
}
/**
* @brief Start the link managing component.
*
* The link manager keeps track of all communication links and provides the global
* packet queue. It is the main communication hub
**/
void QGCCore::startLinkManager()
{
LinkManager::instance();
}
/**
* @brief Start the Unmanned Air System Manager
*
**/
void QGCCore::startUASManager()
{
// Load UAS plugins
QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_LINUX)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS") {
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
UASManager::instance();
// Load plugins
QStringList pluginFileNames;
foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin) {
//populateMenus(plugin);
pluginFileNames += fileName;
//printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str());
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: GroupManager.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2003-03-25 18:01:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FRM_GROUPMANAGER_HXX_
#define _FRM_GROUPMANAGER_HXX_
#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_
#include <com/sun/star/sdbc/XRowSet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_
#include <com/sun/star/awt/XControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace comphelper;
/*========================================================================
Funktionsweise GroupManager:
Der GroupManager horcht an der starform, ob FormComponents eingefuegt oder entfernt
werden. Zusaetzlich horcht er bei den FormComponents an den Properties
"Name" und "TabIndex". Mit diesen Infos aktualisiert er seine Gruppen.
Der GroupManager verwaltet eine Gruppe, in der alle Controls nach TabIndex
geordnet sind, und ein Array von Gruppen, in dem jede FormComponent noch
einmal einer Gruppe dem Namen nach zugeordnet wird.
Die einzelnen Gruppen werden ueber eine Map aktiviert, wenn sie mehr als
ein Element besitzen.
Die Gruppen verwalten intern die FormComponents in zwei Arrays. In dem
GroupCompArray werden die Components nach TabIndex und Einfuegepostion
sortiert. Da auf dieses Array ueber die FormComponent zugegriffen
wird, gibt es noch das GroupCompAccessArray, in dem die FormComponents
nach ihrer Speicheradresse sortiert sind. Jedes Element des
GroupCompAccessArrays ist mit einem Element des GroupCompArrays verpointert.
========================================================================*/
//.........................................................................
namespace frm
{
//.........................................................................
//========================================================================
template <class ELEMENT, class LESS_COMPARE>
sal_Int32 insert_sorted(::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, const LESS_COMPARE& _rCompareOp)
{
::std::vector<ELEMENT>::iterator aInsertPos = lower_bound(
_rArray.begin(),
_rArray.end(),
_rNewElement,
_rCompareOp
);
aInsertPos = _rArray.insert(aInsertPos, _rNewElement);
return aInsertPos - _rArray.begin();
}
template <class ELEMENT, class LESS_COMPARE>
sal_Bool seek_entry(const ::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, sal_Int32& nPos, const LESS_COMPARE& _rCompareOp)
{
::std::vector<ELEMENT>::const_iterator aExistentPos = ::std::lower_bound(
_rArray.begin(),
_rArray.end(),
_rNewElement,
_rCompareOp
);
if ((aExistentPos != _rArray.end()) && (*aExistentPos == _rNewElement))
{ // we have a valid "lower or equal" element and it's really "equal"
nPos = aExistentPos - _rArray.begin();
return sal_True;
}
nPos = -1;
return sal_False;
}
//========================================================================
class OGroupComp
{
::rtl::OUString m_aName;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xComponent;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> m_xControlModel;
sal_Int32 m_nPos;
sal_Int16 m_nTabIndex;
friend class OGroupCompLess;
public:
OGroupComp(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, sal_Int32 nInsertPos );
OGroupComp(const OGroupComp& _rSource);
OGroupComp();
sal_Bool operator==( const OGroupComp& rComp ) const;
inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
inline const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>& GetControlModel() const { return m_xControlModel; }
sal_Int32 GetPos() const { return m_nPos; }
sal_Int16 GetTabIndex() const { return m_nTabIndex; }
::rtl::OUString GetName() const { return m_aName; }
};
DECLARE_STL_VECTOR(OGroupComp, OGroupCompArr);
//========================================================================
class OGroupComp;
class OGroupCompAcc
{
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xComponent;
OGroupComp m_aGroupComp;
friend class OGroupCompAccLess;
public:
OGroupCompAcc(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, const OGroupComp& _rGroupComp );
sal_Bool operator==( const OGroupCompAcc& rCompAcc ) const;
inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
const OGroupComp& GetGroupComponent() const { return m_aGroupComp; }
};
DECLARE_STL_VECTOR(OGroupCompAcc, OGroupCompAccArr);
//========================================================================
class OGroup
{
OGroupCompArr m_aCompArray;
OGroupCompAccArr m_aCompAccArray;
::rtl::OUString m_aGroupName;
sal_uInt16 m_nInsertPos; // Die Einfugeposition der GroupComps wird von der Gruppe bestimmt.
friend class OGroupLess;
public:
OGroup( const ::rtl::OUString& rGroupName );
#ifdef DBG_UTIL
OGroup( const OGroup& _rSource ); // just to ensure the DBG_CTOR call
#endif
virtual ~OGroup();
sal_Bool operator==( const OGroup& rGroup ) const;
::rtl::OUString GetGroupName() const { return m_aGroupName; }
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > GetControlModels() const;
void InsertComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void RemoveComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
sal_uInt16 Count() const { return m_aCompArray.size(); }
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetObject( sal_uInt16 nP ) const
{ return m_aCompArray[nP].GetComponent(); }
};
DECLARE_STL_USTRINGACCESS_MAP(OGroup, OGroupArr);
DECLARE_STL_VECTOR(OGroupArr::iterator, OActiveGroups);
//========================================================================
class OGroupManager : public ::cppu::WeakImplHelper2< ::com::sun::star::beans::XPropertyChangeListener, ::com::sun::star::container::XContainerListener>
{
OGroup* m_pCompGroup; // Alle Components nach TabIndizes sortiert
OGroupArr m_aGroupArr; // Alle Components nach Gruppen sortiert
OActiveGroups m_aActiveGroupMap; // In dieser Map werden die Indizes aller Gruppen gehalten,
// die mehr als 1 Element haben
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >
m_xContainer;
// Helper functions
void InsertElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void RemoveElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void removeFromGroupMap(const ::rtl::OUString& _sGroupName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xSet);
public:
OGroupManager(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _rxContainer);
virtual ~OGroupManager();
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::beans::XPropertyChangeListener
virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::container::XContainerListener
virtual void SAL_CALL elementInserted(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementRemoved(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementReplaced(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
// Other functions
sal_Int32 getGroupCount();
void getGroup(sal_Int32 nGroup, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup, ::rtl::OUString& Name);
void getGroupByName(const ::rtl::OUString& Name, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup);
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > getControlModels();
};
//.........................................................................
} // namespace frm
//.........................................................................
#endif // _FRM_GROUPMANAGER_HXX_
<commit_msg>INTEGRATION: CWS ooo20031216 (1.7.82); FILE MERGED 2003/12/13 13:14:28 waratah 1.7.82.1: #i1858# implement typename where they are needed<commit_after>/*************************************************************************
*
* $RCSfile: GroupManager.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: hr $ $Date: 2004-02-04 12:34:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FRM_GROUPMANAGER_HXX_
#define _FRM_GROUPMANAGER_HXX_
#ifndef _COM_SUN_STAR_SDBC_XROWSET_HPP_
#include <com/sun/star/sdbc/XRowSet.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XCONTROLMODEL_HPP_
#include <com/sun/star/awt/XControlModel.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_
#include <com/sun/star/container/XContainerListener.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINER_HPP_
#include <com/sun/star/container/XContainer.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
using namespace comphelper;
/*========================================================================
Funktionsweise GroupManager:
Der GroupManager horcht an der starform, ob FormComponents eingefuegt oder entfernt
werden. Zusaetzlich horcht er bei den FormComponents an den Properties
"Name" und "TabIndex". Mit diesen Infos aktualisiert er seine Gruppen.
Der GroupManager verwaltet eine Gruppe, in der alle Controls nach TabIndex
geordnet sind, und ein Array von Gruppen, in dem jede FormComponent noch
einmal einer Gruppe dem Namen nach zugeordnet wird.
Die einzelnen Gruppen werden ueber eine Map aktiviert, wenn sie mehr als
ein Element besitzen.
Die Gruppen verwalten intern die FormComponents in zwei Arrays. In dem
GroupCompArray werden die Components nach TabIndex und Einfuegepostion
sortiert. Da auf dieses Array ueber die FormComponent zugegriffen
wird, gibt es noch das GroupCompAccessArray, in dem die FormComponents
nach ihrer Speicheradresse sortiert sind. Jedes Element des
GroupCompAccessArrays ist mit einem Element des GroupCompArrays verpointert.
========================================================================*/
//.........................................................................
namespace frm
{
//.........................................................................
//========================================================================
template <class ELEMENT, class LESS_COMPARE>
sal_Int32 insert_sorted(::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, const LESS_COMPARE& _rCompareOp)
{
typename ::std::vector<ELEMENT>::iterator aInsertPos = lower_bound(
_rArray.begin(),
_rArray.end(),
_rNewElement,
_rCompareOp
);
aInsertPos = _rArray.insert(aInsertPos, _rNewElement);
return aInsertPos - _rArray.begin();
}
template <class ELEMENT, class LESS_COMPARE>
sal_Bool seek_entry(const ::std::vector<ELEMENT>& _rArray, const ELEMENT& _rNewElement, sal_Int32& nPos, const LESS_COMPARE& _rCompareOp)
{
typename ::std::vector<ELEMENT>::const_iterator aExistentPos = ::std::lower_bound(
_rArray.begin(),
_rArray.end(),
_rNewElement,
_rCompareOp
);
if ((aExistentPos != _rArray.end()) && (*aExistentPos == _rNewElement))
{ // we have a valid "lower or equal" element and it's really "equal"
nPos = aExistentPos - _rArray.begin();
return sal_True;
}
nPos = -1;
return sal_False;
}
//========================================================================
class OGroupComp
{
::rtl::OUString m_aName;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xComponent;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> m_xControlModel;
sal_Int32 m_nPos;
sal_Int16 m_nTabIndex;
friend class OGroupCompLess;
public:
OGroupComp(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, sal_Int32 nInsertPos );
OGroupComp(const OGroupComp& _rSource);
OGroupComp();
sal_Bool operator==( const OGroupComp& rComp ) const;
inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
inline const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel>& GetControlModel() const { return m_xControlModel; }
sal_Int32 GetPos() const { return m_nPos; }
sal_Int16 GetTabIndex() const { return m_nTabIndex; }
::rtl::OUString GetName() const { return m_aName; }
};
DECLARE_STL_VECTOR(OGroupComp, OGroupCompArr);
//========================================================================
class OGroupComp;
class OGroupCompAcc
{
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xComponent;
OGroupComp m_aGroupComp;
friend class OGroupCompAccLess;
public:
OGroupCompAcc(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement, const OGroupComp& _rGroupComp );
sal_Bool operator==( const OGroupCompAcc& rCompAcc ) const;
inline const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetComponent() const { return m_xComponent; }
const OGroupComp& GetGroupComponent() const { return m_aGroupComp; }
};
DECLARE_STL_VECTOR(OGroupCompAcc, OGroupCompAccArr);
//========================================================================
class OGroup
{
OGroupCompArr m_aCompArray;
OGroupCompAccArr m_aCompAccArray;
::rtl::OUString m_aGroupName;
sal_uInt16 m_nInsertPos; // Die Einfugeposition der GroupComps wird von der Gruppe bestimmt.
friend class OGroupLess;
public:
OGroup( const ::rtl::OUString& rGroupName );
#ifdef DBG_UTIL
OGroup( const OGroup& _rSource ); // just to ensure the DBG_CTOR call
#endif
virtual ~OGroup();
sal_Bool operator==( const OGroup& rGroup ) const;
::rtl::OUString GetGroupName() const { return m_aGroupName; }
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > GetControlModels() const;
void InsertComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void RemoveComponent( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
sal_uInt16 Count() const { return m_aCompArray.size(); }
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& GetObject( sal_uInt16 nP ) const
{ return m_aCompArray[nP].GetComponent(); }
};
DECLARE_STL_USTRINGACCESS_MAP(OGroup, OGroupArr);
DECLARE_STL_VECTOR(OGroupArr::iterator, OActiveGroups);
//========================================================================
class OGroupManager : public ::cppu::WeakImplHelper2< ::com::sun::star::beans::XPropertyChangeListener, ::com::sun::star::container::XContainerListener>
{
OGroup* m_pCompGroup; // Alle Components nach TabIndizes sortiert
OGroupArr m_aGroupArr; // Alle Components nach Gruppen sortiert
OActiveGroups m_aActiveGroupMap; // In dieser Map werden die Indizes aller Gruppen gehalten,
// die mehr als 1 Element haben
::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >
m_xContainer;
// Helper functions
void InsertElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void RemoveElement( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& rxElement );
void removeFromGroupMap(const ::rtl::OUString& _sGroupName,const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xSet);
public:
OGroupManager(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainer >& _rxContainer);
virtual ~OGroupManager();
// ::com::sun::star::lang::XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);
// ::com::sun::star::beans::XPropertyChangeListener
virtual void SAL_CALL propertyChange(const ::com::sun::star::beans::PropertyChangeEvent& evt) throw ( ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::container::XContainerListener
virtual void SAL_CALL elementInserted(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementRemoved(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementReplaced(const ::com::sun::star::container::ContainerEvent& _rEvent) throw ( ::com::sun::star::uno::RuntimeException);
// Other functions
sal_Int32 getGroupCount();
void getGroup(sal_Int32 nGroup, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup, ::rtl::OUString& Name);
void getGroupByName(const ::rtl::OUString& Name, ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> >& _rGroup);
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel> > getControlModels();
};
//.........................................................................
} // namespace frm
//.........................................................................
#endif // _FRM_GROUPMANAGER_HXX_
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* [ Peter Jentsch <pjotr@guineapics.de> ]
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Peter Jentsch <pjotr@guineapics.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_filter.hxx"
#include <cstdio>
#include <cstring>
#include <list>
#include <map>
#include <iostream>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlIO.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <libxslt/variables.h>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase4.hxx>
#include <cppuhelper/implbase.hxx>
#include <osl/module.h>
#include <osl/file.hxx>
#include <osl/process.h>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include <LibXSLTTransformer.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::osl;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using ::std::list;
using ::std::map;
using ::std::pair;
#define _INPUT_BUFFER_SIZE 4096
#define _OUTPUT_BUFFER_SIZE 4096
namespace XSLT
{
const char* const LibXSLTTransformer::PARAM_SOURCE_URL = "sourceURL";
const char* const LibXSLTTransformer::PARAM_SOURCE_BASE_URL =
"sourceBaseURL";
const char* const LibXSLTTransformer::PARAM_TARGET_URL = "targetURL";
const char* const LibXSLTTransformer::PARAM_TARGET_BASE_URL =
"targetBaseURL";
const char* const LibXSLTTransformer::PARAM_DOCTYPE_SYSTEM = "sytemType";
const char* const LibXSLTTransformer::PARAM_DOCTYPE_PUBLIC = "publicType";
const sal_Int32 Reader::OUTPUT_BUFFER_SIZE = _OUTPUT_BUFFER_SIZE;
const sal_Int32 Reader::INPUT_BUFFER_SIZE = _INPUT_BUFFER_SIZE;
struct ParserInputBufferCallback
{
static int
on_read(void * context, char * buffer, int len)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->read(buffer, len);
}
static int
on_close(void * context)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->closeInput();
}
};
struct ParserOutputBufferCallback
{
static int
on_write(void * context, const char * buffer, int len)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->write(buffer, len);
}
static int
on_close(void * context)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->closeOutput();
}
};
Reader::Reader(LibXSLTTransformer* transformer) :
m_transformer(transformer), m_terminated(false), m_readBuf(
INPUT_BUFFER_SIZE), m_writeBuf(OUTPUT_BUFFER_SIZE)
{
LIBXML_TEST_VERSION;
}
;
int
Reader::read(char * buffer, int len)
{
// const char *ptr = (const char *) context;
if (buffer == NULL || len < 0)
return (-1);
sal_Int32 n;
Reference<XInputStream> xis = this->m_transformer->getInputStream();
n = xis.get()->readBytes(m_readBuf, len);
if (n > 0)
{
memcpy(buffer, m_readBuf.getArray(), n);
}
return n;
}
int
Reader::write(const char * buffer, int len)
{
if (buffer == NULL || len < 0)
return -1;
if (len > 0)
{
Reference<XOutputStream> xos = m_transformer->getOutputStream();
sal_Int32 writeLen = len;
sal_Int32 bufLen = ::std::min(writeLen,
this->OUTPUT_BUFFER_SIZE);
const sal_uInt8* memPtr =
reinterpret_cast<const sal_uInt8*> (buffer);
while (writeLen > 0)
{
sal_Int32 n = ::std::min(writeLen, bufLen);
m_writeBuf.realloc(n);
memcpy(m_writeBuf.getArray(), memPtr,
static_cast<size_t> (n));
xos.get()->writeBytes(m_writeBuf);
memPtr += n;
writeLen -= n;
}
}
return len;
}
int
Reader::closeInput()
{
return 0;
}
int
Reader::closeOutput()
{
Reference<XOutputStream> xos = m_transformer->getOutputStream();
if (xos.is())
{
xos.get()->flush();
xos.get()->closeOutput();
}
m_transformer->done();
return 0;
}
void
Reader::run()
{
OSL_ASSERT(m_transformer != NULL);
OSL_ASSERT(m_transformer->getInputStream().is());
OSL_ASSERT(m_transformer->getOutputStream().is());
OSL_ASSERT(m_transformer->getStyleSheetURL());
::std::map<const char*, OString>::iterator pit;
::std::map<const char*, OString> pmap = m_transformer->getParameters();
const char* params[pmap.size() * 2 + 1]; // build parameters
int paramIndex = 0;
for (pit = pmap.begin(); pit != pmap.end(); pit++)
{
params[paramIndex++] = (*pit).first;
params[paramIndex++] = (*pit).second.getStr();
}
params[paramIndex] = NULL;
xmlDocPtr doc = xmlReadIO(&ParserInputBufferCallback::on_read,
&ParserInputBufferCallback::on_close,
static_cast<void*> (this), NULL, NULL, 0);
xsltStylesheetPtr styleSheet = xsltParseStylesheetFile(
(const xmlChar *) m_transformer->getStyleSheetURL().getStr());
xmlDocPtr result = NULL;
xsltTransformContextPtr tcontext = NULL;
if (styleSheet)
{
tcontext = xsltNewTransformContext(styleSheet, doc);
xsltQuoteUserParams(tcontext, params);
result = xsltApplyStylesheetUser(styleSheet, doc, 0, 0, 0,
tcontext);
}
if (result)
{
xmlCharEncodingHandlerPtr encoder = xmlGetCharEncodingHandler(
XML_CHAR_ENCODING_UTF8);
xmlOutputBufferPtr outBuf = xmlAllocOutputBuffer(encoder);
outBuf->context = static_cast<void *> (this);
outBuf->writecallback = &ParserOutputBufferCallback::on_write;
outBuf->closecallback = &ParserOutputBufferCallback::on_close;
xsltSaveResultTo(outBuf, result, styleSheet);
}
else
{
xmlErrorPtr lastErr = xmlGetLastError();
OUString msg;
if (lastErr)
msg = OUString::createFromAscii(lastErr->message);
else
msg = OUString::createFromAscii(
"Unknown XSLT transformation error");
m_transformer->error(msg);
}
closeOutput();
xsltFreeStylesheet(styleSheet);
xsltFreeTransformContext(tcontext);
xmlFreeDoc(doc);
xmlFreeDoc(result);
}
;
void
Reader::onTerminated()
{
m_terminated = true;
}
;
Reader::~Reader()
{
}
LibXSLTTransformer::LibXSLTTransformer(
const Reference<XMultiServiceFactory> &r) :
m_rServiceFactory(r)
{
}
void
LibXSLTTransformer::setInputStream(
const Reference<XInputStream>& inputStream)
throw (RuntimeException)
{
m_rInputStream = inputStream;
}
Reference<XInputStream>
LibXSLTTransformer::getInputStream() throw (RuntimeException)
{
return m_rInputStream;
}
void
LibXSLTTransformer::setOutputStream(
const Reference<XOutputStream>& outputStream)
throw (RuntimeException)
{
m_rOutputStream = outputStream;
}
Reference<XOutputStream>
LibXSLTTransformer::getOutputStream() throw (RuntimeException)
{
return m_rOutputStream;
}
void
LibXSLTTransformer::addListener(const Reference<XStreamListener>& listener)
throw (RuntimeException)
{
m_listeners.insert(m_listeners.begin(), listener);
}
void
LibXSLTTransformer::removeListener(
const Reference<XStreamListener>& listener)
throw (RuntimeException)
{
m_listeners.remove(listener);
}
void
LibXSLTTransformer::start() throw (RuntimeException)
{
ListenerList::iterator it;
ListenerList* l = &m_listeners;
for (it = l->begin(); it != l->end(); it++)
{
Reference<XStreamListener> xl = *it;
xl.get()->started();
}
Reader* r = new Reader(this);
r->create();
}
void
LibXSLTTransformer::error(const OUString& msg)
{
ListenerList* l = &m_listeners;
Any arg;
arg <<= Exception(msg, *this);
for (ListenerList::iterator it = l->begin(); it != l->end(); it++)
{
Reference<XStreamListener> xl = *it;
if (xl.is())
{
xl.get()->error(arg);
}
}
}
void
LibXSLTTransformer::done()
{
ListenerList* l = &m_listeners;
for (ListenerList::iterator it = l->begin(); it != l->end(); it++)
{
Reference<XStreamListener> xl = *it;
if (xl.is())
{
xl.get()->closed();
}
}
}
void
LibXSLTTransformer::terminate() throw (RuntimeException)
{
m_parameters.clear();
}
void
LibXSLTTransformer::initialize(const Sequence<Any>& params)
throw (RuntimeException)
{
xmlSubstituteEntitiesDefault(0);
m_parameters.clear();
for (int i = 0; i < params.getLength(); i++)
{
NamedValue nv;
params[i] >>= nv;
OString nameUTF8 = OUStringToOString(nv.Name,
RTL_TEXTENCODING_UTF8);
OUString value;
OString valueUTF8;
if (nv.Value >>= value)
{
valueUTF8 = OUStringToOString(value,
RTL_TEXTENCODING_UTF8);
}
else
{
// ignore non-string parameters
continue;
}
if (nameUTF8.equals("StylesheetURL"))
{
m_styleSheetURL = valueUTF8;
}
else if (nameUTF8.equals("SourceURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_SOURCE_URL, valueUTF8));
}
else if (nameUTF8.equals("SourceBaseURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_SOURCE_BASE_URL, valueUTF8));
}
else if (nameUTF8.equals("TargetURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_TARGET_URL, valueUTF8));
}
else if (nameUTF8.equals("TargetBaseURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_TARGET_BASE_URL, valueUTF8));
}
else if (nameUTF8.equals("DoctypeSystem"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_DOCTYPE_SYSTEM, valueUTF8));
}
else if (nameUTF8.equals("DoctypePublic"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_DOCTYPE_PUBLIC, valueUTF8));
}
}
}
const OString
LibXSLTTransformer::getStyleSheetURL()
{
return m_styleSheetURL;
}
::std::map<const char*, OString>
LibXSLTTransformer::getParameters()
{
return m_parameters;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>variable-size arrays is a gccism<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Initial Developer of the Original Code is
* [ Peter Jentsch <pjotr@guineapics.de> ]
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s): Peter Jentsch <pjotr@guineapics.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_filter.hxx"
#include <cstdio>
#include <cstring>
#include <list>
#include <map>
#include <vector>
#include <iostream>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlIO.h>
#include <libxslt/transform.h>
#include <libxslt/xsltutils.h>
#include <libxslt/variables.h>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase4.hxx>
#include <cppuhelper/implbase.hxx>
#include <osl/module.h>
#include <osl/file.hxx>
#include <osl/process.h>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>
#include <com/sun/star/io/XStreamListener.hpp>
#include <LibXSLTTransformer.hxx>
using namespace ::rtl;
using namespace ::cppu;
using namespace ::osl;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using ::std::list;
using ::std::map;
using ::std::pair;
#define _INPUT_BUFFER_SIZE 4096
#define _OUTPUT_BUFFER_SIZE 4096
namespace XSLT
{
const char* const LibXSLTTransformer::PARAM_SOURCE_URL = "sourceURL";
const char* const LibXSLTTransformer::PARAM_SOURCE_BASE_URL =
"sourceBaseURL";
const char* const LibXSLTTransformer::PARAM_TARGET_URL = "targetURL";
const char* const LibXSLTTransformer::PARAM_TARGET_BASE_URL =
"targetBaseURL";
const char* const LibXSLTTransformer::PARAM_DOCTYPE_SYSTEM = "sytemType";
const char* const LibXSLTTransformer::PARAM_DOCTYPE_PUBLIC = "publicType";
const sal_Int32 Reader::OUTPUT_BUFFER_SIZE = _OUTPUT_BUFFER_SIZE;
const sal_Int32 Reader::INPUT_BUFFER_SIZE = _INPUT_BUFFER_SIZE;
struct ParserInputBufferCallback
{
static int
on_read(void * context, char * buffer, int len)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->read(buffer, len);
}
static int
on_close(void * context)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->closeInput();
}
};
struct ParserOutputBufferCallback
{
static int
on_write(void * context, const char * buffer, int len)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->write(buffer, len);
}
static int
on_close(void * context)
{
Reader * tmp = static_cast<Reader*> (context);
return tmp->closeOutput();
}
};
Reader::Reader(LibXSLTTransformer* transformer) :
m_transformer(transformer), m_terminated(false), m_readBuf(
INPUT_BUFFER_SIZE), m_writeBuf(OUTPUT_BUFFER_SIZE)
{
LIBXML_TEST_VERSION;
}
;
int
Reader::read(char * buffer, int len)
{
// const char *ptr = (const char *) context;
if (buffer == NULL || len < 0)
return (-1);
sal_Int32 n;
Reference<XInputStream> xis = this->m_transformer->getInputStream();
n = xis.get()->readBytes(m_readBuf, len);
if (n > 0)
{
memcpy(buffer, m_readBuf.getArray(), n);
}
return n;
}
int
Reader::write(const char * buffer, int len)
{
if (buffer == NULL || len < 0)
return -1;
if (len > 0)
{
Reference<XOutputStream> xos = m_transformer->getOutputStream();
sal_Int32 writeLen = len;
sal_Int32 bufLen = ::std::min(writeLen,
this->OUTPUT_BUFFER_SIZE);
const sal_uInt8* memPtr =
reinterpret_cast<const sal_uInt8*> (buffer);
while (writeLen > 0)
{
sal_Int32 n = ::std::min(writeLen, bufLen);
m_writeBuf.realloc(n);
memcpy(m_writeBuf.getArray(), memPtr,
static_cast<size_t> (n));
xos.get()->writeBytes(m_writeBuf);
memPtr += n;
writeLen -= n;
}
}
return len;
}
int
Reader::closeInput()
{
return 0;
}
int
Reader::closeOutput()
{
Reference<XOutputStream> xos = m_transformer->getOutputStream();
if (xos.is())
{
xos.get()->flush();
xos.get()->closeOutput();
}
m_transformer->done();
return 0;
}
void
Reader::run()
{
OSL_ASSERT(m_transformer != NULL);
OSL_ASSERT(m_transformer->getInputStream().is());
OSL_ASSERT(m_transformer->getOutputStream().is());
OSL_ASSERT(m_transformer->getStyleSheetURL());
::std::map<const char*, OString>::iterator pit;
::std::map<const char*, OString> pmap = m_transformer->getParameters();
::std::vector< const char* > params( pmap.size() * 2 + 1 ); // build parameters
int paramIndex = 0;
for (pit = pmap.begin(); pit != pmap.end(); pit++)
{
params[paramIndex++] = (*pit).first;
params[paramIndex++] = (*pit).second.getStr();
}
params[paramIndex] = NULL;
xmlDocPtr doc = xmlReadIO(&ParserInputBufferCallback::on_read,
&ParserInputBufferCallback::on_close,
static_cast<void*> (this), NULL, NULL, 0);
xsltStylesheetPtr styleSheet = xsltParseStylesheetFile(
(const xmlChar *) m_transformer->getStyleSheetURL().getStr());
xmlDocPtr result = NULL;
xsltTransformContextPtr tcontext = NULL;
if (styleSheet)
{
tcontext = xsltNewTransformContext(styleSheet, doc);
xsltQuoteUserParams(tcontext, ¶ms[0]);
result = xsltApplyStylesheetUser(styleSheet, doc, 0, 0, 0,
tcontext);
}
if (result)
{
xmlCharEncodingHandlerPtr encoder = xmlGetCharEncodingHandler(
XML_CHAR_ENCODING_UTF8);
xmlOutputBufferPtr outBuf = xmlAllocOutputBuffer(encoder);
outBuf->context = static_cast<void *> (this);
outBuf->writecallback = &ParserOutputBufferCallback::on_write;
outBuf->closecallback = &ParserOutputBufferCallback::on_close;
xsltSaveResultTo(outBuf, result, styleSheet);
}
else
{
xmlErrorPtr lastErr = xmlGetLastError();
OUString msg;
if (lastErr)
msg = OUString::createFromAscii(lastErr->message);
else
msg = OUString::createFromAscii(
"Unknown XSLT transformation error");
m_transformer->error(msg);
}
closeOutput();
xsltFreeStylesheet(styleSheet);
xsltFreeTransformContext(tcontext);
xmlFreeDoc(doc);
xmlFreeDoc(result);
}
;
void
Reader::onTerminated()
{
m_terminated = true;
}
;
Reader::~Reader()
{
}
LibXSLTTransformer::LibXSLTTransformer(
const Reference<XMultiServiceFactory> &r) :
m_rServiceFactory(r)
{
}
void
LibXSLTTransformer::setInputStream(
const Reference<XInputStream>& inputStream)
throw (RuntimeException)
{
m_rInputStream = inputStream;
}
Reference<XInputStream>
LibXSLTTransformer::getInputStream() throw (RuntimeException)
{
return m_rInputStream;
}
void
LibXSLTTransformer::setOutputStream(
const Reference<XOutputStream>& outputStream)
throw (RuntimeException)
{
m_rOutputStream = outputStream;
}
Reference<XOutputStream>
LibXSLTTransformer::getOutputStream() throw (RuntimeException)
{
return m_rOutputStream;
}
void
LibXSLTTransformer::addListener(const Reference<XStreamListener>& listener)
throw (RuntimeException)
{
m_listeners.insert(m_listeners.begin(), listener);
}
void
LibXSLTTransformer::removeListener(
const Reference<XStreamListener>& listener)
throw (RuntimeException)
{
m_listeners.remove(listener);
}
void
LibXSLTTransformer::start() throw (RuntimeException)
{
ListenerList::iterator it;
ListenerList* l = &m_listeners;
for (it = l->begin(); it != l->end(); it++)
{
Reference<XStreamListener> xl = *it;
xl.get()->started();
}
Reader* r = new Reader(this);
r->create();
}
void
LibXSLTTransformer::error(const OUString& msg)
{
ListenerList* l = &m_listeners;
Any arg;
arg <<= Exception(msg, *this);
for (ListenerList::iterator it = l->begin(); it != l->end(); it++)
{
Reference<XStreamListener> xl = *it;
if (xl.is())
{
xl.get()->error(arg);
}
}
}
void
LibXSLTTransformer::done()
{
ListenerList* l = &m_listeners;
for (ListenerList::iterator it = l->begin(); it != l->end(); it++)
{
Reference<XStreamListener> xl = *it;
if (xl.is())
{
xl.get()->closed();
}
}
}
void
LibXSLTTransformer::terminate() throw (RuntimeException)
{
m_parameters.clear();
}
void
LibXSLTTransformer::initialize(const Sequence<Any>& params)
throw (RuntimeException)
{
xmlSubstituteEntitiesDefault(0);
m_parameters.clear();
for (int i = 0; i < params.getLength(); i++)
{
NamedValue nv;
params[i] >>= nv;
OString nameUTF8 = OUStringToOString(nv.Name,
RTL_TEXTENCODING_UTF8);
OUString value;
OString valueUTF8;
if (nv.Value >>= value)
{
valueUTF8 = OUStringToOString(value,
RTL_TEXTENCODING_UTF8);
}
else
{
// ignore non-string parameters
continue;
}
if (nameUTF8.equals("StylesheetURL"))
{
m_styleSheetURL = valueUTF8;
}
else if (nameUTF8.equals("SourceURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_SOURCE_URL, valueUTF8));
}
else if (nameUTF8.equals("SourceBaseURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_SOURCE_BASE_URL, valueUTF8));
}
else if (nameUTF8.equals("TargetURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_TARGET_URL, valueUTF8));
}
else if (nameUTF8.equals("TargetBaseURL"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_TARGET_BASE_URL, valueUTF8));
}
else if (nameUTF8.equals("DoctypeSystem"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_DOCTYPE_SYSTEM, valueUTF8));
}
else if (nameUTF8.equals("DoctypePublic"))
{
m_parameters.insert(pair<const char*, OString> (
PARAM_DOCTYPE_PUBLIC, valueUTF8));
}
}
}
const OString
LibXSLTTransformer::getStyleSheetURL()
{
return m_styleSheetURL;
}
::std::map<const char*, OString>
LibXSLTTransformer::getParameters()
{
return m_parameters;
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////
//
// Utility Library
// Copyright (C) 2012 Chase Warrington (staff@spacechase0.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef UTIL_STRING_HPP
#define UTIL_STRING_HPP
#include <iomanip>
#include <ios>
#include <sstream>
#include <string>
#include <vector>
namespace util
{
namespace priv
{
template< typename... ARGS >
void applyManips( std::ios& stream, ARGS&&... args );
template< typename T, typename... ARGS >
void applyManips( std::ios& stream, T&& t, ARGS&&... args )
{
stream << std::forward( t );
applyManips( stream, std::forward( args )... );
}
inline void applyManips( std::ios& stream )
{
}
}
std::vector< std::string > tokenize( const std::string& str, const std::string& symbol = "," );
template< typename T, typename... ARGS >
T fromString( const std::string& str, ARGS&&... args )
{
T tmp;
std::stringstream ss;
priv::applyManips( ss, std::forward( args )... );
ss << str;
ss >> tmp;
return tmp;
}
template< typename T, typename... ARGS >
std::string toString( const T& t, ARGS&&... args )
{
std::stringstream ss;
priv::applyManips( ss, std::forward( args )... );
ss << t;
return ss.str();
}
// from/toStringHex -> from/toString( ..., std::hex )
}
#endif // UTIL_STRING_HPP
<commit_msg>...And make sure everything actually works.<commit_after>////////////////////////////////////////////////////////////
//
// Utility Library
// Copyright (C) 2012 Chase Warrington (staff@spacechase0.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef UTIL_STRING_HPP
#define UTIL_STRING_HPP
#include <iomanip>
#include <ios>
#include <sstream>
#include <string>
#include <vector>
namespace util
{
namespace priv
{
template< typename... ARGS >
void applyManips( std::ios& stream, ARGS&... args )
{
}
template< typename T, typename... ARGS >
inline void applyManips( std::ios& stream, T& t, ARGS&... args )
{
t( stream );
applyManips( stream, t, args... );
}
template< typename T >
inline void applyManips( std::ios& stream, T& t )
{
t( stream );
}
}
std::vector< std::string > tokenize( const std::string& str, const std::string& symbol = "," );
template< typename T, typename... ARGS >
T fromString( const std::string& str, ARGS&&... args )
{
T tmp;
std::stringstream ss;
priv::applyManips( ss, args... );
ss << str;
ss >> tmp;
return tmp;
}
template< typename T, typename... ARGS >
std::string toString( const T& t, ARGS&... args )
{
std::stringstream ss;
priv::applyManips( ss, args... );
ss << t;
return ss.str();
}
// from/toStringHex -> from/toString( ..., std::hex )
}
#endif // UTIL_STRING_HPP
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Class header file.
#include "XercesParserLiaison.hpp"
#include <algorithm>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <framework/URLInputSource.hpp>
#include <parsers/DOMParser.hpp>
#include <parsers/SAXParser.hpp>
#include <sax/SAXParseException.hpp>
#include <Include/XalanAutoPtr.hpp>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/ExecutionContext.hpp>
#include <PlatformSupport/XalanUnicode.hpp>
#include <DOMSupport/DOMSupport.hpp>
#include "XercesDocumentBridge.hpp"
#include "XercesDOMSupport.hpp"
static const XalanDOMChar theDefaultSpecialCharacters[] =
{
XalanUnicode::charLessThanSign,
XalanUnicode::charGreaterThanSign,
XalanUnicode::charAmpersand,
XalanUnicode::charApostrophe,
XalanUnicode::charQuoteMark,
XalanUnicode::charCR,
XalanUnicode::charLF,
0
};
XercesParserLiaison::XercesParserLiaison(XercesDOMSupport& /* theSupport */) :
m_specialCharacters(theDefaultSpecialCharacters),
m_indent(-1),
m_shouldExpandEntityRefs(true),
m_useValidation(false),
m_includeIgnorableWhitespace(true),
m_doNamespaces(true),
m_exitOnFirstFatalError(true),
m_entityResolver(0),
m_errorHandler(this),
m_documentMap(),
m_buildBridge(true),
m_threadSafe(false),
m_executionContext(0)
{
}
XercesParserLiaison::XercesParserLiaison() :
m_specialCharacters(theDefaultSpecialCharacters),
m_indent(-1),
m_shouldExpandEntityRefs(true),
m_useValidation(false),
m_includeIgnorableWhitespace(true),
m_doNamespaces(true),
m_exitOnFirstFatalError(true),
m_entityResolver(0),
m_errorHandler(this),
m_documentMap(),
m_buildBridge(true),
m_threadSafe(false),
m_executionContext(0)
{
}
XercesParserLiaison::~XercesParserLiaison()
{
reset();
}
void
XercesParserLiaison::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Delete any live documents.
for_each(m_documentMap.begin(),
m_documentMap.end(),
makeMapValueDeleteFunctor(m_documentMap));
m_documentMap.clear();
m_executionContext = 0;
}
ExecutionContext*
XercesParserLiaison::getExecutionContext() const
{
return m_executionContext;
}
void
XercesParserLiaison::setExecutionContext(ExecutionContext& theContext)
{
m_executionContext = &theContext;
}
bool
XercesParserLiaison::supportsSAX() const
{
return true;
}
void
XercesParserLiaison::parseXMLStream(
const InputSource& urlInputSource,
DocumentHandler& handler,
const XalanDOMString& /* identifier */)
{
XalanAutoPtr<SAXParser> theParser(CreateSAXParser());
theParser->setDocumentHandler(&handler);
theParser->parse(urlInputSource);
}
XalanDocument*
XercesParserLiaison::parseXMLStream(
const InputSource& reader,
const XalanDOMString& /* identifier */)
{
XalanAutoPtr<DOMParser> theParser(CreateDOMParser());
theParser->parse(reader);
const DOM_Document theXercesDocument =
theParser->getDocument();
XercesDocumentBridge* theNewDocument = 0;
if (theXercesDocument.isNull() == false)
{
theNewDocument = createDocument(theXercesDocument, m_threadSafe, m_buildBridge);
m_documentMap[theNewDocument] = theNewDocument;
}
return theNewDocument;
}
XalanDocument*
XercesParserLiaison::createDocument()
{
const DOM_Document theXercesDocument =
DOM_Document::createDocument();
return createDocument(theXercesDocument, false, false);
}
XalanDocument*
XercesParserLiaison::createDOMFactory()
{
return createDocument();
}
void
XercesParserLiaison::destroyDocument(XalanDocument* theDocument)
{
if (mapDocument(theDocument) != 0)
{
m_documentMap.erase(theDocument);
delete theDocument;
}
}
void
XercesParserLiaison::setSpecialCharacters(const XalanDOMString& str)
{
m_specialCharacters = str;
}
const XalanDOMString&
XercesParserLiaison::getSpecialCharacters() const
{
return m_specialCharacters;
}
int
XercesParserLiaison::getIndent() const
{
return m_indent;
}
void
XercesParserLiaison::setIndent(int i)
{
m_indent = i;
}
bool
XercesParserLiaison::getShouldExpandEntityRefs() const
{
return m_shouldExpandEntityRefs;
}
void
XercesParserLiaison::SetShouldExpandEntityRefs(bool b)
{
m_shouldExpandEntityRefs = b;
}
bool
XercesParserLiaison::getUseValidation() const
{
return m_useValidation;
}
void
XercesParserLiaison::setUseValidation(bool b)
{
m_useValidation = b;
}
const XalanDOMString
XercesParserLiaison::getParserDescription() const
{
return XALAN_STATIC_UCODE_STRING("Xerces");
}
bool
XercesParserLiaison::getIncludeIgnorableWhitespace() const
{
return m_includeIgnorableWhitespace;
}
void
XercesParserLiaison::setIncludeIgnorableWhitespace(bool include)
{
m_includeIgnorableWhitespace = include;
}
ErrorHandler*
XercesParserLiaison::getErrorHandler()
{
return m_errorHandler;
}
const ErrorHandler*
XercesParserLiaison::getErrorHandler() const
{
return m_errorHandler;
}
void
XercesParserLiaison::setErrorHandler(ErrorHandler* handler)
{
assert(handler != 0);
m_errorHandler = handler;
}
bool
XercesParserLiaison::getDoNamespaces() const
{
return m_doNamespaces;
}
void
XercesParserLiaison::setDoNamespaces(bool newState)
{
m_doNamespaces = newState;
}
bool
XercesParserLiaison::getExitOnFirstFatalError() const
{
return m_exitOnFirstFatalError;
}
void
XercesParserLiaison::setExitOnFirstFatalError(bool newState)
{
m_exitOnFirstFatalError = newState;
}
EntityResolver*
XercesParserLiaison::getEntityResolver()
{
return m_entityResolver;
}
void
XercesParserLiaison::setEntityResolver(EntityResolver* resolver)
{
m_entityResolver = resolver;
}
XalanDocument*
XercesParserLiaison::createDocument(const DOM_Document& theXercesDocument)
{
return createDocument(theXercesDocument, false, false);
}
XercesDocumentBridge*
XercesParserLiaison::mapDocument(const XalanDocument* theDocument) const
{
const DocumentMapType::const_iterator i =
m_documentMap.find(theDocument);
return i != m_documentMap.end() ? (*i).second : 0;
}
DOM_Document
XercesParserLiaison::mapXercesDocument(const XalanDocument* theDocument) const
{
const DocumentMapType::const_iterator i =
m_documentMap.find(theDocument);
return i != m_documentMap.end() ? (*i).second->getXercesDocument() : DOM_Document();
}
void
XercesParserLiaison::fatalError(const SAXParseException& e)
{
XalanDOMString theMessage("Fatal Error");
formatErrorMessage(e, theMessage);
if (m_executionContext != 0)
{
// We call warning() because we don't want the execution
// context to potentially throw an exception.
m_executionContext->warn(theMessage);
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
#endif
cerr << endl << theMessage << endl;
}
throw e;
}
void
XercesParserLiaison::error(const SAXParseException& e)
{
XalanDOMString theMessage("Error ");
formatErrorMessage(e, theMessage);
if (m_executionContext != 0)
{
// We call warn() because we don't want the execution
// context to potentially throw an exception.
m_executionContext->warn(theMessage);
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
#endif
cerr << endl << theMessage << endl;
}
}
void
XercesParserLiaison::warning(const SAXParseException& e)
{
XalanDOMString theMessage("Warning ");
formatErrorMessage(e, theMessage);
if (m_executionContext != 0)
{
m_executionContext->warn(theMessage);
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
#endif
cerr << endl << theMessage << endl;
}
}
void
XercesParserLiaison::formatErrorMessage(
const SAXParseException& e,
XalanDOMString& theMessage)
{
append(theMessage, " at (file ");
const XalanDOMChar* const theSystemID = e.getSystemId();
if (theSystemID == 0)
{
append(theMessage, "<unknown>");
}
else
{
append(theMessage, theSystemID);
}
append(theMessage, ", line ");
append(theMessage, LongToDOMString(long(e.getLineNumber())));
append(theMessage, ", column ");
append(theMessage, LongToDOMString(long(e.getColumnNumber())));
append(theMessage, "): ");
append(theMessage, e.getMessage());
}
void
XercesParserLiaison::resetErrors()
{
}
DOMParser*
XercesParserLiaison::CreateDOMParser()
{
DOMParser* const theParser = new DOMParser;
theParser->setExpandEntityReferences(m_shouldExpandEntityRefs);
theParser->setDoValidation(m_useValidation);
theParser->setIncludeIgnorableWhitespace(m_includeIgnorableWhitespace);
theParser->setDoNamespaces(m_doNamespaces);
theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);
if (m_entityResolver != 0)
{
theParser->setEntityResolver(m_entityResolver);
}
theParser->setErrorHandler(m_errorHandler);
// Xerces has a non-standard node type to represent the XML decl.
// Why did they ever do this?
theParser->setToCreateXMLDeclTypeNode(false);
return theParser;
}
SAXParser*
XercesParserLiaison::CreateSAXParser()
{
SAXParser* const theParser = new SAXParser;
theParser->setDoValidation(m_useValidation);
theParser->setDoNamespaces(false);
theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);
if (m_entityResolver != 0)
{
theParser->setEntityResolver(m_entityResolver);
}
theParser->setErrorHandler(m_errorHandler);
return theParser;
}
XercesDocumentBridge*
XercesParserLiaison::createDocument(
const DOM_Document& theXercesDocument,
bool threadSafe,
bool buildBridge)
{
XercesDocumentBridge* const theNewDocument =
new XercesDocumentBridge(theXercesDocument, threadSafe, buildBridge);
m_documentMap[theNewDocument] = theNewDocument;
return theNewDocument;
}
<commit_msg>Make sure validation is disabled for SAX parsing.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// Class header file.
#include "XercesParserLiaison.hpp"
#include <algorithm>
#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif
#include <framework/URLInputSource.hpp>
#include <parsers/DOMParser.hpp>
#include <parsers/SAXParser.hpp>
#include <sax/SAXParseException.hpp>
#include <Include/XalanAutoPtr.hpp>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/ExecutionContext.hpp>
#include <PlatformSupport/XalanUnicode.hpp>
#include <DOMSupport/DOMSupport.hpp>
#include "XercesDocumentBridge.hpp"
#include "XercesDOMSupport.hpp"
static const XalanDOMChar theDefaultSpecialCharacters[] =
{
XalanUnicode::charLessThanSign,
XalanUnicode::charGreaterThanSign,
XalanUnicode::charAmpersand,
XalanUnicode::charApostrophe,
XalanUnicode::charQuoteMark,
XalanUnicode::charCR,
XalanUnicode::charLF,
0
};
XercesParserLiaison::XercesParserLiaison(XercesDOMSupport& /* theSupport */) :
m_specialCharacters(theDefaultSpecialCharacters),
m_indent(-1),
m_shouldExpandEntityRefs(true),
m_useValidation(false),
m_includeIgnorableWhitespace(true),
m_doNamespaces(true),
m_exitOnFirstFatalError(true),
m_entityResolver(0),
m_errorHandler(this),
m_documentMap(),
m_buildBridge(true),
m_threadSafe(false),
m_executionContext(0)
{
}
XercesParserLiaison::XercesParserLiaison() :
m_specialCharacters(theDefaultSpecialCharacters),
m_indent(-1),
m_shouldExpandEntityRefs(true),
m_useValidation(false),
m_includeIgnorableWhitespace(true),
m_doNamespaces(true),
m_exitOnFirstFatalError(true),
m_entityResolver(0),
m_errorHandler(this),
m_documentMap(),
m_buildBridge(true),
m_threadSafe(false),
m_executionContext(0)
{
}
XercesParserLiaison::~XercesParserLiaison()
{
reset();
}
void
XercesParserLiaison::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Delete any live documents.
for_each(m_documentMap.begin(),
m_documentMap.end(),
makeMapValueDeleteFunctor(m_documentMap));
m_documentMap.clear();
m_executionContext = 0;
}
ExecutionContext*
XercesParserLiaison::getExecutionContext() const
{
return m_executionContext;
}
void
XercesParserLiaison::setExecutionContext(ExecutionContext& theContext)
{
m_executionContext = &theContext;
}
bool
XercesParserLiaison::supportsSAX() const
{
return true;
}
void
XercesParserLiaison::parseXMLStream(
const InputSource& urlInputSource,
DocumentHandler& handler,
const XalanDOMString& /* identifier */)
{
XalanAutoPtr<SAXParser> theParser(CreateSAXParser());
theParser->setDocumentHandler(&handler);
theParser->parse(urlInputSource);
}
XalanDocument*
XercesParserLiaison::parseXMLStream(
const InputSource& reader,
const XalanDOMString& /* identifier */)
{
XalanAutoPtr<DOMParser> theParser(CreateDOMParser());
theParser->parse(reader);
const DOM_Document theXercesDocument =
theParser->getDocument();
XercesDocumentBridge* theNewDocument = 0;
if (theXercesDocument.isNull() == false)
{
theNewDocument = createDocument(theXercesDocument, m_threadSafe, m_buildBridge);
m_documentMap[theNewDocument] = theNewDocument;
}
return theNewDocument;
}
XalanDocument*
XercesParserLiaison::createDocument()
{
const DOM_Document theXercesDocument =
DOM_Document::createDocument();
return createDocument(theXercesDocument, false, false);
}
XalanDocument*
XercesParserLiaison::createDOMFactory()
{
return createDocument();
}
void
XercesParserLiaison::destroyDocument(XalanDocument* theDocument)
{
if (mapDocument(theDocument) != 0)
{
m_documentMap.erase(theDocument);
delete theDocument;
}
}
void
XercesParserLiaison::setSpecialCharacters(const XalanDOMString& str)
{
m_specialCharacters = str;
}
const XalanDOMString&
XercesParserLiaison::getSpecialCharacters() const
{
return m_specialCharacters;
}
int
XercesParserLiaison::getIndent() const
{
return m_indent;
}
void
XercesParserLiaison::setIndent(int i)
{
m_indent = i;
}
bool
XercesParserLiaison::getShouldExpandEntityRefs() const
{
return m_shouldExpandEntityRefs;
}
void
XercesParserLiaison::SetShouldExpandEntityRefs(bool b)
{
m_shouldExpandEntityRefs = b;
}
bool
XercesParserLiaison::getUseValidation() const
{
return m_useValidation;
}
void
XercesParserLiaison::setUseValidation(bool b)
{
m_useValidation = b;
}
const XalanDOMString
XercesParserLiaison::getParserDescription() const
{
return XALAN_STATIC_UCODE_STRING("Xerces");
}
bool
XercesParserLiaison::getIncludeIgnorableWhitespace() const
{
return m_includeIgnorableWhitespace;
}
void
XercesParserLiaison::setIncludeIgnorableWhitespace(bool include)
{
m_includeIgnorableWhitespace = include;
}
ErrorHandler*
XercesParserLiaison::getErrorHandler()
{
return m_errorHandler;
}
const ErrorHandler*
XercesParserLiaison::getErrorHandler() const
{
return m_errorHandler;
}
void
XercesParserLiaison::setErrorHandler(ErrorHandler* handler)
{
assert(handler != 0);
m_errorHandler = handler;
}
bool
XercesParserLiaison::getDoNamespaces() const
{
return m_doNamespaces;
}
void
XercesParserLiaison::setDoNamespaces(bool newState)
{
m_doNamespaces = newState;
}
bool
XercesParserLiaison::getExitOnFirstFatalError() const
{
return m_exitOnFirstFatalError;
}
void
XercesParserLiaison::setExitOnFirstFatalError(bool newState)
{
m_exitOnFirstFatalError = newState;
}
EntityResolver*
XercesParserLiaison::getEntityResolver()
{
return m_entityResolver;
}
void
XercesParserLiaison::setEntityResolver(EntityResolver* resolver)
{
m_entityResolver = resolver;
}
XalanDocument*
XercesParserLiaison::createDocument(const DOM_Document& theXercesDocument)
{
return createDocument(theXercesDocument, false, false);
}
XercesDocumentBridge*
XercesParserLiaison::mapDocument(const XalanDocument* theDocument) const
{
const DocumentMapType::const_iterator i =
m_documentMap.find(theDocument);
return i != m_documentMap.end() ? (*i).second : 0;
}
DOM_Document
XercesParserLiaison::mapXercesDocument(const XalanDocument* theDocument) const
{
const DocumentMapType::const_iterator i =
m_documentMap.find(theDocument);
return i != m_documentMap.end() ? (*i).second->getXercesDocument() : DOM_Document();
}
void
XercesParserLiaison::fatalError(const SAXParseException& e)
{
XalanDOMString theMessage("Fatal Error");
formatErrorMessage(e, theMessage);
if (m_executionContext != 0)
{
// We call warning() because we don't want the execution
// context to potentially throw an exception.
m_executionContext->warn(theMessage);
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
#endif
cerr << endl << theMessage << endl;
}
throw e;
}
void
XercesParserLiaison::error(const SAXParseException& e)
{
XalanDOMString theMessage("Error ");
formatErrorMessage(e, theMessage);
if (m_executionContext != 0)
{
// We call warn() because we don't want the execution
// context to potentially throw an exception.
m_executionContext->warn(theMessage);
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
#endif
cerr << endl << theMessage << endl;
}
}
void
XercesParserLiaison::warning(const SAXParseException& e)
{
XalanDOMString theMessage("Warning ");
formatErrorMessage(e, theMessage);
if (m_executionContext != 0)
{
m_executionContext->warn(theMessage);
}
else
{
#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
#endif
cerr << endl << theMessage << endl;
}
}
void
XercesParserLiaison::formatErrorMessage(
const SAXParseException& e,
XalanDOMString& theMessage)
{
append(theMessage, " at (file ");
const XalanDOMChar* const theSystemID = e.getSystemId();
if (theSystemID == 0)
{
append(theMessage, "<unknown>");
}
else
{
append(theMessage, theSystemID);
}
append(theMessage, ", line ");
append(theMessage, LongToDOMString(long(e.getLineNumber())));
append(theMessage, ", column ");
append(theMessage, LongToDOMString(long(e.getColumnNumber())));
append(theMessage, "): ");
append(theMessage, e.getMessage());
}
void
XercesParserLiaison::resetErrors()
{
}
DOMParser*
XercesParserLiaison::CreateDOMParser()
{
DOMParser* const theParser = new DOMParser;
theParser->setExpandEntityReferences(m_shouldExpandEntityRefs);
theParser->setDoValidation(m_useValidation);
theParser->setIncludeIgnorableWhitespace(m_includeIgnorableWhitespace);
theParser->setDoNamespaces(m_doNamespaces);
theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);
if (m_entityResolver != 0)
{
theParser->setEntityResolver(m_entityResolver);
}
theParser->setErrorHandler(m_errorHandler);
// Xerces has a non-standard node type to represent the XML decl.
// Why did they ever do this?
theParser->setToCreateXMLDeclTypeNode(false);
return theParser;
}
SAXParser*
XercesParserLiaison::CreateSAXParser()
{
SAXParser* const theParser = new SAXParser;
theParser->setDoValidation(false);
theParser->setDoNamespaces(false);
theParser->setExitOnFirstFatalError(m_exitOnFirstFatalError);
if (m_entityResolver != 0)
{
theParser->setEntityResolver(m_entityResolver);
}
theParser->setErrorHandler(m_errorHandler);
return theParser;
}
XercesDocumentBridge*
XercesParserLiaison::createDocument(
const DOM_Document& theXercesDocument,
bool threadSafe,
bool buildBridge)
{
XercesDocumentBridge* const theNewDocument =
new XercesDocumentBridge(theXercesDocument, threadSafe, buildBridge);
m_documentMap[theNewDocument] = theNewDocument;
return theNewDocument;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Vinitha Ranganeni, Brian Lee
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
////////////////////////////////////////////////////////////////////////////////
#ifndef COZMO_UTILS_HPP_
#define COZMO_UTILS_HPP_
#include <vector>
namespace libcozmo {
namespace utils {
// https://gist.github.com/lorenzoriano/5414671
template <typename T>
std::vector<T> linspace(T a, T b, std::size_t N) {
T h = (b - a) / static_cast<T>(N-1);
std::vector<T> xs(N);
typename std::vector<T>::iterator x;
T val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
*x = val;
return xs;
}
} // namespace utils
} // namespace libcozmo
#endif // COZMO_UTILS_HPP_
<commit_msg>compute euclidean added to utils<commit_after>////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Vinitha Ranganeni, Brian Lee
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
////////////////////////////////////////////////////////////////////////////////
#ifndef COZMO_UTILS_HPP_
#define COZMO_UTILS_HPP_
#include <vector>
#include <cmath>
namespace libcozmo {
namespace utils {
// https://gist.github.com/lorenzoriano/5414671
template <typename T>
std::vector<T> linspace(T a, T b, std::size_t N) {
T h = (b - a) / static_cast<T>(N-1);
std::vector<T> xs(N);
typename std::vector<T>::iterator x;
T val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h)
*x = val;
return xs;
}
double euclidean(std::vector<T> a, std::vector<T> b) {
double distance = 0;
for (int i = 0; i < a.size(); i++) {
distance = distance + pow((a[i] - b[i]), 2)
}
return sqrt(distance);
}
} // namespace utils
} // namespace libcozmo
#endif // COZMO_UTILS_HPP_
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "TagVectorAux.h"
registerMooseObject("MooseApp", TagVectorAux);
defineLegacyParams(TagVectorAux);
InputParameters
TagVectorAux::validParams()
{
InputParameters params = AuxKernel::validParams();
params.addParam<std::string>("vector_tag", "TagName", "Tag Name this Aux works on");
params.addRequiredCoupledVar("v",
"The coupled variable whose components are coupled to AuxVariable");
params.set<ExecFlagEnum>("execute_on", true) = {EXEC_TIMESTEP_END};
params.addClassDescription("Couple a tag vector, and return its nodal value");
return params;
}
TagVectorAux::TagVectorAux(const InputParameters & parameters)
: AuxKernel(parameters),
_tag_id(_subproblem.getVectorTagID(getParam<std::string>("vector_tag"))),
_v(coupledVectorTagValue("v", _tag_id))
{
auto & execute_on = getParam<ExecFlagEnum>("execute_on");
if (execute_on.size() != 1 || !execute_on.contains(EXEC_TIMESTEP_END))
mooseError("execute_on for TagVectorAux must be set to EXEC_TIMESTEP_END");
}
Real
TagVectorAux::computeValue()
{
return _v[_qp];
}
<commit_msg>Make vector_tag required<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "TagVectorAux.h"
registerMooseObject("MooseApp", TagVectorAux);
defineLegacyParams(TagVectorAux);
InputParameters
TagVectorAux::validParams()
{
InputParameters params = AuxKernel::validParams();
params.addRequiredParam<std::string>("vector_tag", "Tag Name this Aux works on");
params.addRequiredCoupledVar("v",
"The coupled variable whose components are coupled to AuxVariable");
params.set<ExecFlagEnum>("execute_on", true) = {EXEC_TIMESTEP_END};
params.addClassDescription("Couple a tag vector, and return its nodal value");
return params;
}
TagVectorAux::TagVectorAux(const InputParameters & parameters)
: AuxKernel(parameters),
_tag_id(_subproblem.getVectorTagID(getParam<std::string>("vector_tag"))),
_v(coupledVectorTagValue("v", _tag_id))
{
auto & execute_on = getParam<ExecFlagEnum>("execute_on");
if (execute_on.size() != 1 || !execute_on.contains(EXEC_TIMESTEP_END))
mooseError("execute_on for TagVectorAux must be set to EXEC_TIMESTEP_END");
}
Real
TagVectorAux::computeValue()
{
return _v[_qp];
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17
void foo(int* a, int *b) {
a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from 'long'}}
}
template<typename T> T declval();
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
template<bool, typename T, typename U> struct select { using type = T; };
template<typename T, typename U> struct select<false, T, U> { using type = U; };
template<typename T>
typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...);
template<typename T> false_type test(...);
template<typename T>
static const auto has_minus_assign = decltype(test<T>())::value;
static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}
<commit_msg>Fix test failure from r351495<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify %s
// RUN: %clang_cc1 -fsyntax-only -verify %s -std=c++17
void foo(int* a, int *b) {
a -= b; // expected-warning {{incompatible integer to pointer conversion assigning to 'int *' from}}
}
template<typename T> T declval();
struct true_type { static const bool value = true; };
struct false_type { static const bool value = false; };
template<bool, typename T, typename U> struct select { using type = T; };
template<typename T, typename U> struct select<false, T, U> { using type = U; };
template<typename T>
typename select<(sizeof(declval<T>() -= declval<T>(), 1) != 1), true_type, false_type>::type test(...);
template<typename T> false_type test(...);
template<typename T>
static const auto has_minus_assign = decltype(test<T>())::value;
static_assert(has_minus_assign<int*>, "failed"); // expected-error {{static_assert failed due to requirement 'has_minus_assign<int *>' "failed"}}
<|endoftext|> |
<commit_before>/**
* \file
* \brief SignalsWaitTestCase class implementation
*
* \author Copyright (C) 2015 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/.
*
* \date 2015-04-01
*/
#include "SignalsWaitTestCase.hpp"
#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread-Signals.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread function
using TestThreadFunction = void(SequenceAsserter&, unsigned int);
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize, true, totalThreads>({},
std::declval<TestThreadFunction>(), std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread.
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal. The signal number of first
* accepted signal is used to calculate "sequence point offset". This value is then used to mark sequence points for all
* following signals that will be accepted.
*
* It is assumed that \a totalThreads signals will be generated for each test thread.
*
* First \a totalThreads sequence points will be marked before test threads block waiting for signal. Then each test
* thread must mark sequence points in the range <em>[totalThreads * (i + 1); totalThreads * (i + 2))</em>, where \a i
* is the index of unblocked thread in <em>[0; totalThreads)</em> range. Because it is not possible to fit all required
* sequence points into signal number values, these are "encoded". The ranges of sequence points mentioned earlier are
* obtained from ranges of received signal numbers in the following form <em>[0 + 1; totalThreads + i)</em>.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void thread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
const SignalSet signalSet {SignalSet::full};
auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
const auto& signalInformation = waitResult.second;
if (signalInformation.getCode() != SignalInformation::Code::Generated)
return;
const auto signalNumber = signalInformation.getSignalNumber();
const auto sequencePointOffset = totalThreads + totalThreads * signalNumber - signalNumber;
sequenceAsserter.sequencePoint(signalNumber + sequencePointOffset);
while (waitResult = ThisThread::Signals::tryWait(signalSet), waitResult.first == 0 &&
signalInformation.getCode() == SignalInformation::Code::Generated)
sequenceAsserter.sequencePoint(signalInformation.getSignalNumber() + sequencePointOffset);
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this
* thread will be started
*
* \return constructed TestThread object
*/
TestThread makeTestThread(const uint8_t priority, SequenceAsserter& sequenceAsserter,
const unsigned int firstSequencePoint)
{
return makeStaticThread<testThreadStackSize, true, totalThreads>(priority, thread, std::ref(sequenceAsserter),
static_cast<unsigned int>(firstSequencePoint));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SignalsWaitTestCase::Implementation::run_() const
{
// priority required for this whole test to work
static_assert(testCasePriority_ + 2 <= UINT8_MAX, "Invalid test case priority");
constexpr decltype(testCasePriority_) testThreadPriority {testCasePriority_ + 1};
constexpr decltype(testCasePriority_) aboveTestThreadPriority {testThreadPriority + 1};
const auto contextSwitchCount = statistics::getContextSwitchCount();
std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {};
for (const auto& phase : priorityTestPhases)
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(testThreadPriority, sequenceAsserter, 0),
makeTestThread(testThreadPriority, sequenceAsserter, 1),
makeTestThread(testThreadPriority, sequenceAsserter, 2),
makeTestThread(testThreadPriority, sequenceAsserter, 3),
makeTestThread(testThreadPriority, sequenceAsserter, 4),
makeTestThread(testThreadPriority, sequenceAsserter, 5),
makeTestThread(testThreadPriority, sequenceAsserter, 6),
makeTestThread(testThreadPriority, sequenceAsserter, 7),
makeTestThread(testThreadPriority, sequenceAsserter, 8),
makeTestThread(testThreadPriority, sequenceAsserter, 9),
}};
bool result {true};
for (auto& thread : threads)
{
thread.start();
// 2 context switches: "into" the thread and "back" to main thread when test thread blocks
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
if (sequenceAsserter.assertSequence(totalThreads) == false)
result = false;
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto threadIndex = phase.second[i];
ThisThread::setPriority(aboveTestThreadPriority);
for (size_t j = 0; j < phase.second.size(); ++j)
{
const auto ret = threads[threadIndex].generateSignal(i + phase.second[j]);
if (ret != 0)
result = false;
}
ThisThread::setPriority(testCasePriority_);
// 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
for (auto& thread : threads)
thread.join();
if (result == false || sequenceAsserter.assertSequence(totalThreads * (totalThreads + 1)) == false)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != 4 * totalThreads * priorityTestPhases.size())
return false;
return true;
}
} // namespace test
} // namespace distortos
<commit_msg>test: rename thread() to generatedSignalsThread() in SignalsWaitTestCase<commit_after>/**
* \file
* \brief SignalsWaitTestCase class implementation
*
* \author Copyright (C) 2015 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/.
*
* \date 2015-04-01
*/
#include "SignalsWaitTestCase.hpp"
#include "priorityTestPhases.hpp"
#include "SequenceAsserter.hpp"
#include "distortos/StaticThread.hpp"
#include "distortos/statistics.hpp"
#include "distortos/ThisThread-Signals.hpp"
#include "distortos/ThisThread.hpp"
namespace distortos
{
namespace test
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local constants
+---------------------------------------------------------------------------------------------------------------------*/
/// size of stack for test thread, bytes
constexpr size_t testThreadStackSize {384};
/*---------------------------------------------------------------------------------------------------------------------+
| local types
+---------------------------------------------------------------------------------------------------------------------*/
/// type of test thread function
using TestThreadFunction = void(SequenceAsserter&, unsigned int);
/// type of test thread
using TestThread = decltype(makeStaticThread<testThreadStackSize, true, totalThreads>({},
std::declval<TestThreadFunction>(), std::ref(std::declval<SequenceAsserter&>()), std::declval<unsigned int>()));
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Test thread for signals that were "generated"
*
* Marks the first sequence point in SequenceAsserter, waits for any possible signal. The signal number of first
* accepted signal is used to calculate "sequence point offset". This value is then used to mark sequence points for all
* following signals that will be accepted.
*
* It is assumed that \a totalThreads signals will be generated for each test thread.
*
* First \a totalThreads sequence points will be marked before test threads block waiting for signal. Then each test
* thread must mark sequence points in the range <em>[totalThreads * (i + 1); totalThreads * (i + 2))</em>, where \a i
* is the index of unblocked thread in <em>[0; totalThreads)</em> range. Because it is not possible to fit all required
* sequence points into signal number values, these are "encoded". The ranges of sequence points mentioned earlier are
* obtained from ranges of received signal numbers in the following form <em>[0 + 1; totalThreads + i)</em>.
*
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point of this instance
*/
void generatedSignalsThread(SequenceAsserter& sequenceAsserter, const unsigned int firstSequencePoint)
{
sequenceAsserter.sequencePoint(firstSequencePoint);
const SignalSet signalSet {SignalSet::full};
auto waitResult = ThisThread::Signals::wait(signalSet);
if (waitResult.first != 0)
return;
const auto& signalInformation = waitResult.second;
if (signalInformation.getCode() != SignalInformation::Code::Generated)
return;
const auto signalNumber = signalInformation.getSignalNumber();
const auto sequencePointOffset = totalThreads + totalThreads * signalNumber - signalNumber;
sequenceAsserter.sequencePoint(signalNumber + sequencePointOffset);
while (waitResult = ThisThread::Signals::tryWait(signalSet), waitResult.first == 0 &&
signalInformation.getCode() == SignalInformation::Code::Generated)
sequenceAsserter.sequencePoint(signalInformation.getSignalNumber() + sequencePointOffset);
}
/**
* \brief Builder of TestThread objects.
*
* \param [in] priority is the thread's priority
* \param [in] sequenceAsserter is a reference to SequenceAsserter shared object
* \param [in] firstSequencePoint is the first sequence point for this instance - equal to the order in which this
* thread will be started
*
* \return constructed TestThread object
*/
TestThread makeTestThread(const uint8_t priority, SequenceAsserter& sequenceAsserter,
const unsigned int firstSequencePoint)
{
return makeStaticThread<testThreadStackSize, true, totalThreads>(priority, generatedSignalsThread,
std::ref(sequenceAsserter), static_cast<unsigned int>(firstSequencePoint));
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| private functions
+---------------------------------------------------------------------------------------------------------------------*/
bool SignalsWaitTestCase::Implementation::run_() const
{
// priority required for this whole test to work
static_assert(testCasePriority_ + 2 <= UINT8_MAX, "Invalid test case priority");
constexpr decltype(testCasePriority_) testThreadPriority {testCasePriority_ + 1};
constexpr decltype(testCasePriority_) aboveTestThreadPriority {testThreadPriority + 1};
const auto contextSwitchCount = statistics::getContextSwitchCount();
std::remove_const<decltype(contextSwitchCount)>::type expectedContextSwitchCount {};
for (const auto& phase : priorityTestPhases)
{
SequenceAsserter sequenceAsserter;
std::array<TestThread, totalThreads> threads
{{
makeTestThread(testThreadPriority, sequenceAsserter, 0),
makeTestThread(testThreadPriority, sequenceAsserter, 1),
makeTestThread(testThreadPriority, sequenceAsserter, 2),
makeTestThread(testThreadPriority, sequenceAsserter, 3),
makeTestThread(testThreadPriority, sequenceAsserter, 4),
makeTestThread(testThreadPriority, sequenceAsserter, 5),
makeTestThread(testThreadPriority, sequenceAsserter, 6),
makeTestThread(testThreadPriority, sequenceAsserter, 7),
makeTestThread(testThreadPriority, sequenceAsserter, 8),
makeTestThread(testThreadPriority, sequenceAsserter, 9),
}};
bool result {true};
for (auto& thread : threads)
{
thread.start();
// 2 context switches: "into" the thread and "back" to main thread when test thread blocks
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
if (sequenceAsserter.assertSequence(totalThreads) == false)
result = false;
for (size_t i = 0; i < phase.second.size(); ++i)
{
const auto threadIndex = phase.second[i];
ThisThread::setPriority(aboveTestThreadPriority);
for (size_t j = 0; j < phase.second.size(); ++j)
{
const auto ret = threads[threadIndex].generateSignal(i + phase.second[j]);
if (ret != 0)
result = false;
}
ThisThread::setPriority(testCasePriority_);
// 2 context switches: into" the unblocked thread and "back" to main thread when test thread terminates
expectedContextSwitchCount += 2;
if (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)
result = false;
}
for (auto& thread : threads)
thread.join();
if (result == false || sequenceAsserter.assertSequence(totalThreads * (totalThreads + 1)) == false)
return false;
}
if (statistics::getContextSwitchCount() - contextSwitchCount != 4 * totalThreads * priorityTestPhases.size())
return false;
return true;
}
} // namespace test
} // namespace distortos
<|endoftext|> |
<commit_before>//===- include/seec/Trace/StateMovement.hpp ------------------------- C++ -===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_TRACE_STATEMOVEMENT_HPP
#define SEEC_TRACE_STATEMOVEMENT_HPP
#include <cstdint>
#include <functional>
#include <map>
namespace llvm {
class Instruction;
}
namespace seec {
namespace trace {
class ProcessState;
class ThreadState;
/// \name Typedefs
/// @{
typedef std::function<bool (ProcessState &)> ProcessPredTy;
typedef std::function<bool (ThreadState &)> ThreadPredTy;
typedef std::map<ThreadState const *, ThreadPredTy> ThreadPredMapTy;
typedef std::function<bool (llvm::Instruction const &)> InstructionPredTy;
/// @}
/// \name ProcessState movement.
/// @{
/// \brief Move State forward until Predicate returns true.
/// \return true iff the State was moved.
bool moveForwardUntil(ProcessState &State,
ProcessPredTy Predicate);
/// \brief Move State backward until Predicate returns true.
/// \return true iff the State was moved.
bool moveBackwardUntil(ProcessState &State,
ProcessPredTy Predicate);
/// \brief Move State forward to the next process time.
/// \return true iff the State was moved.
bool moveForward(ProcessState &State);
/// \brief Move State backward to the previous process time.
/// \return true iff the State was moved.
bool moveBackward(ProcessState &State);
/// \brief Move State forward until the memory state in Area changes.
/// \return true iff the State was moved.
bool moveForwardUntilMemoryChanges(ProcessState &State, MemoryArea const &Area);
/// \brief Move State backward until the memory state in Area changes.
/// \return true iff the State was moved.
bool
moveBackwardUntilMemoryChanges(ProcessState &State, MemoryArea const &Area);
/// @} (ProcessState movement)
/// \name ThreadState movement.
/// @{
/// \brief Move State forward until Predicate returns true.
/// \return true iff the State was moved.
bool moveForwardUntil(ThreadState &State,
ThreadPredTy Predicate);
/// \brief Move State backward until Predicate returns true.
/// \return true iff the State was moved.
bool moveBackwardUntil(ThreadState &State,
ThreadPredTy Predicate);
/// \brief Move State forward to the next thread time.
/// \return true iff the State was moved.
bool moveForward(ThreadState &State);
/// \brief Move State backward to the previous thread time.
/// \return true iff the State was moved.
bool moveBackward(ThreadState &State);
/// @} (ThreadState movement)
/// \name ThreadState queries.
/// @{
/// \brief Find the Instruction that will be active if State is moved forward.
/// \return the Instruction if it exists, or nullptr.
///
llvm::Instruction const *
getNextInstructionInActiveFunction(ThreadState const &State);
/// \brief Find the Instruction that will be active if State is moved backward.
/// \return the Instruction if it exists, or nullptr.
///
llvm::Instruction const *
getPreviousInstructionInActiveFunction(ThreadState const &State);
/// \brief
///
bool
findPreviousInstructionInActiveFunctionIf(ThreadState const &State,
InstructionPredTy Predicate);
/// @} (ThreadState queries)
} // namespace trace (in seec)
} // namespace seec
#endif // SEEC_TRACE_STATEMOVEMENT_HPP
<commit_msg>Update doxygen comment for findPreviousInstructionInActiveFunctionIf().<commit_after>//===- include/seec/Trace/StateMovement.hpp ------------------------- C++ -===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#ifndef SEEC_TRACE_STATEMOVEMENT_HPP
#define SEEC_TRACE_STATEMOVEMENT_HPP
#include <cstdint>
#include <functional>
#include <map>
namespace llvm {
class Instruction;
}
namespace seec {
namespace trace {
class ProcessState;
class ThreadState;
/// \name Typedefs
/// @{
typedef std::function<bool (ProcessState &)> ProcessPredTy;
typedef std::function<bool (ThreadState &)> ThreadPredTy;
typedef std::map<ThreadState const *, ThreadPredTy> ThreadPredMapTy;
typedef std::function<bool (llvm::Instruction const &)> InstructionPredTy;
/// @}
/// \name ProcessState movement.
/// @{
/// \brief Move State forward until Predicate returns true.
/// \return true iff the State was moved.
bool moveForwardUntil(ProcessState &State,
ProcessPredTy Predicate);
/// \brief Move State backward until Predicate returns true.
/// \return true iff the State was moved.
bool moveBackwardUntil(ProcessState &State,
ProcessPredTy Predicate);
/// \brief Move State forward to the next process time.
/// \return true iff the State was moved.
bool moveForward(ProcessState &State);
/// \brief Move State backward to the previous process time.
/// \return true iff the State was moved.
bool moveBackward(ProcessState &State);
/// \brief Move State forward until the memory state in Area changes.
/// \return true iff the State was moved.
bool moveForwardUntilMemoryChanges(ProcessState &State, MemoryArea const &Area);
/// \brief Move State backward until the memory state in Area changes.
/// \return true iff the State was moved.
bool
moveBackwardUntilMemoryChanges(ProcessState &State, MemoryArea const &Area);
/// @} (ProcessState movement)
/// \name ThreadState movement.
/// @{
/// \brief Move State forward until Predicate returns true.
/// \return true iff the State was moved.
bool moveForwardUntil(ThreadState &State,
ThreadPredTy Predicate);
/// \brief Move State backward until Predicate returns true.
/// \return true iff the State was moved.
bool moveBackwardUntil(ThreadState &State,
ThreadPredTy Predicate);
/// \brief Move State forward to the next thread time.
/// \return true iff the State was moved.
bool moveForward(ThreadState &State);
/// \brief Move State backward to the previous thread time.
/// \return true iff the State was moved.
bool moveBackward(ThreadState &State);
/// @} (ThreadState movement)
/// \name ThreadState queries.
/// @{
/// \brief Find the Instruction that will be active if State is moved forward.
/// \return the Instruction if it exists, or nullptr.
///
llvm::Instruction const *
getNextInstructionInActiveFunction(ThreadState const &State);
/// \brief Find the Instruction that will be active if State is moved backward.
/// \return the Instruction if it exists, or nullptr.
///
llvm::Instruction const *
getPreviousInstructionInActiveFunction(ThreadState const &State);
/// \brief Check if any previously executed \c llvm::Instruction in the active
/// \c FunctionState matches the given \c Predicate.
/// \param State the \c ThreadState to search.
/// \param Predicate the predicate to check each previously executed
/// \c llvm::Instruction against.
/// \return true iff \c Predicate(I) returns true for any \c llvm::Instruction
/// I that was previously executed in the active \c FunctionState.
///
bool
findPreviousInstructionInActiveFunctionIf(ThreadState const &State,
InstructionPredTy Predicate);
/// @} (ThreadState queries)
} // namespace trace (in seec)
} // namespace seec
#endif // SEEC_TRACE_STATEMOVEMENT_HPP
<|endoftext|> |
<commit_before>// $Id: Parameters_test.C,v 1.4 2001/08/27 09:06:00 aubertin Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/FORMAT/parameters.h>
///////////////////////////
START_TEST(Parameters, "$Id: Parameters_test.C,v 1.4 2001/08/27 09:06:00 aubertin Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
// tests for class Parameters::
Parameters* pointer;
CHECK(Parameters::Parameters())
pointer = new Parameters;
TEST_NOT_EQUAL(pointer, 0)
RESULT
CHECK(Parameters::~Parameters())
delete pointer;
RESULT
CHECK(Parameters::Parameters(const String& filename))
String filename("data/Parameters_test.ini");
Parameters para(filename);
TEST_EQUAL(para.getFilename(), filename)
RESULT
CHECK(Parameters::Parameters(const Parameters& parameter))
String filename("data/Parameters_test.ini");
Parameters para(filename);
TEST_EQUAL(para.getFilename(), filename)
Parameters para2(para);
TEST_EQUAL(para.getFilename(), filename)
RESULT
CHECK(Parameters::clear())
String filename("data/Parameters_test.ini");
Parameters para(filename);
INIFile* inif = ¶.getParameterFile();
para.clear();
TEST_EQUAL(para.isValid(),false)
TEST_EQUAL( "", para.getFilename())
TEST_EQUAL(inif->getDuplicateKeyCheck(),false)
TEST_EQUAL(inif->isValid(),false)
RESULT
CHECK(Parameters::Parameters& operator = (const Parameters& parameters))
String filename("data/Parameters_test.ini");
Parameters para(filename);
Parameters para2;
para2 = para;
TEST_EQUAL(para2.getFilename(),"data/Parameters_test.ini")
TEST_EQUAL(para2 == para, true)
RESULT
CHECK(Parameters::setFilename(const String& filename) + Parameters::getFilename() const + Parameters::getParameterFile())
Parameters para;
para.setFilename("data/Parameters_test.ini");
TEST_EQUAL(para.getFilename(),"data/Parameters_test.ini")
INIFile* inif = ¶.getParameterFile();
TEST_NOT_EQUAL(inif,0)
RESULT
CHECK(Parameters::init())
Parameters para;
para.setFilename("data/Parameters_test.ini");
bool test = para.init();
TEST_EQUAL(test,true)
RESULT
CHECK(Parameters::isValid() const )
String filename("data/Parameters_test.ini");
Parameters para(filename);
TEST_EQUAL(para.isValid(),true)
RESULT
CHECK(bool Parameters::operator == (const Parameters& parameters))
String filename("data/Parameters_test.ini");
Parameters para(filename);
Parameters para2(para);
bool test = (para == para2);
TEST_EQUAL(test,true)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>cosmetic changes<commit_after>// $Id: Parameters_test.C,v 1.5 2001/08/27 09:24:50 aubertin Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/FORMAT/parameters.h>
///////////////////////////
START_TEST(Parameters, "$Id: Parameters_test.C,v 1.5 2001/08/27 09:24:50 aubertin Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
using namespace std;
// tests for class Parameters::
Parameters* pointer;
CHECK(Parameters::Parameters())
pointer = new Parameters;
TEST_NOT_EQUAL(pointer, 0)
RESULT
CHECK(Parameters::~Parameters())
delete pointer;
RESULT
CHECK(Parameters::Parameters(const String& filename))
String filename("data/Parameters_test.ini");
Parameters para(filename);
TEST_EQUAL(para.getFilename(), filename)
RESULT
CHECK(Parameters::Parameters(const Parameters& parameter))
String filename("data/Parameters_test.ini");
Parameters para(filename);
TEST_EQUAL(para.getFilename(), filename)
Parameters para2(para);
TEST_EQUAL(para.getFilename(), filename)
RESULT
CHECK(Parameters::clear())
String filename("data/Parameters_test.ini");
Parameters para(filename);
INIFile* inif = ¶.getParameterFile();
para.clear();
TEST_EQUAL(para.isValid(),false)
TEST_EQUAL( "", para.getFilename())
TEST_EQUAL(inif->getDuplicateKeyCheck(),false)
TEST_EQUAL(inif->isValid(),false)
RESULT
CHECK(Parameters::Parameters& operator = (const Parameters& parameters))
String filename("data/Parameters_test.ini");
Parameters para(filename);
Parameters para2;
para2 = para;
TEST_EQUAL(para2.getFilename(),"data/Parameters_test.ini")
TEST_EQUAL(para2 == para, true)
RESULT
CHECK(Parameters::setFilename(const String& filename) + Parameters::getFilename() const + Parameters::getParameterFile())
Parameters para;
para.setFilename("data/Parameters_test.ini");
TEST_EQUAL(para.getFilename(),"data/Parameters_test.ini")
INIFile* inif = ¶.getParameterFile();
TEST_NOT_EQUAL(inif,0)
RESULT
CHECK(Parameters::init())
Parameters para;
para.setFilename("data/Parameters_test.ini");
bool test = para.init();
TEST_EQUAL(test,true)
RESULT
CHECK(Parameters::isValid() const )
String filename("data/Parameters_test.ini");
Parameters para(filename);
TEST_EQUAL(para.isValid(),true)
RESULT
CHECK(bool Parameters::operator == (const Parameters& parameters))
String filename("data/Parameters_test.ini");
Parameters para(filename);
Parameters para2(para);
bool test = (para == para2);
TEST_EQUAL(test,true)
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>#ifndef ARROWS_VERT_GLSL_HXX
#define ARROWS_VERT_GLSL_HXX
static const std::string ARROWS_VERT_GLSL = R"LITERAL(
#version 330
uniform mat4 uProjectionMatrix;
uniform mat4 uModelviewMatrix;
uniform vec2 uZRange;
in vec3 ivPosition;
in vec3 ivNormal;
in vec3 ivInstanceOffset;
in vec3 ivInstanceDirection;
out vec3 vfPosition;
out vec3 vfNormal;
out vec3 vfColor;
mat3 matrixFromDirection(vec3 direction) {
float c = direction.z;
float s = length(direction.xy);
if (s == 0.0) {
s = 1.0;
}
float x = -direction.y / s;
float y = direction.x / s;
mat3 matrix;
matrix[0][0] = x*x*(1.0-c)+c;
matrix[0][1] = y*x*(1.0-c);
matrix[0][2] = -y*s;
matrix[1][0] = x*y*(1.0-c);
matrix[1][1] = y*y*(1.0-c)+c;
matrix[1][2] = x*s;
matrix[2][0] = y*s;
matrix[2][1] = -x*s;
matrix[2][2] = c;
return matrix;
}
vec3 colormap(vec3 direction);
bool is_visible(vec3 position, vec3 direction);
void main(void) {
vfColor = colormap(normalize(ivInstanceDirection));
mat3 instanceMatrix = matrixFromDirection(ivInstanceDirection);
vfNormal = (uModelviewMatrix * vec4(instanceMatrix*ivNormal, 0.0)).xyz;
vfPosition = (uModelviewMatrix * vec4(instanceMatrix*ivPosition+ivInstanceOffset, 1.0)).xyz;
if (is_visible(ivInstanceOffset, ivInstanceDirection)) {
gl_Position = uProjectionMatrix * vec4(vfPosition, 1.0);
} else {
gl_Position = vec4(2.0, 2.0, 2.0, 0.0);
}
}
)LITERAL";
#endif
<commit_msg>Fixed arrow scaling<commit_after>#ifndef ARROWS_VERT_GLSL_HXX
#define ARROWS_VERT_GLSL_HXX
static const std::string ARROWS_VERT_GLSL = R"LITERAL(
#version 330
uniform mat4 uProjectionMatrix;
uniform mat4 uModelviewMatrix;
uniform vec2 uZRange;
in vec3 ivPosition;
in vec3 ivNormal;
in vec3 ivInstanceOffset;
in vec3 ivInstanceDirection;
out vec3 vfPosition;
out vec3 vfNormal;
out vec3 vfColor;
mat3 matrixFromDirection(vec3 direction) {
float c = direction.z;
float s = length(direction.xy);
if (s == 0.0) {
s = 1.0;
}
float x = -direction.y / s;
float y = direction.x / s;
mat3 matrix;
matrix[0][0] = x*x*(1.0-c)+c;
matrix[0][1] = y*x*(1.0-c);
matrix[0][2] = -y*s;
matrix[1][0] = x*y*(1.0-c);
matrix[1][1] = y*y*(1.0-c)+c;
matrix[1][2] = x*s;
matrix[2][0] = y*s;
matrix[2][1] = -x*s;
matrix[2][2] = c;
return matrix;
}
vec3 colormap(vec3 direction);
bool is_visible(vec3 position, vec3 direction);
void main(void) {
float direction_length = length(ivInstanceDirection);
if (is_visible(ivInstanceOffset, ivInstanceDirection) && direction_length > 0) {
vfColor = colormap(normalize(ivInstanceDirection));
mat3 instanceMatrix = direction_length * matrixFromDirection(ivInstanceDirection/direction_length);
vfNormal = (uModelviewMatrix * vec4(instanceMatrix*ivNormal, 0.0)).xyz;
vfPosition = (uModelviewMatrix * vec4(instanceMatrix*ivPosition+ivInstanceOffset, 1.0)).xyz;
gl_Position = uProjectionMatrix * vec4(vfPosition, 1.0);
} else {
gl_Position = vec4(2.0, 2.0, 2.0, 0.0);
}
}
)LITERAL";
#endif
<|endoftext|> |
<commit_before>/*
* TTBlue Audio Engine
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTAudioEngine.h"
#include "TTEnvironment.h"
#define thisTTClass TTAudioEngine
TTAudioEngine::TTAudioEngine()
:TTObject("audioEngine"),
numInputChannels(2),
numOutputChannels(2),
vectorSize(64),
sampleRate(44100),
stream(NULL),
inputDevice(NULL),
outputDevice(NULL),
isRunning(false),
inputBuffer(NULL),
outputBuffer(NULL)
{
callbackObservers = new TTList;
callbackObservers->setThreadProtection(NO); // ... because we make calls into this at every audio vector calculation ...
TTObjectInstantiate(kTTSym_audiosignal, &inputBuffer, 1);
TTObjectInstantiate(kTTSym_audiosignal, &outputBuffer, 1);
// numChannels should be readonly -- how do we do that?
registerAttributeSimple(numInputChannels, kTypeUInt16);
registerAttributeSimple(numOutputChannels, kTypeUInt16);
registerAttributeWithSetter(vectorSize, kTypeUInt16);
registerAttributeWithSetter(sampleRate, kTypeUInt32);
registerAttributeWithSetter(inputDevice, kTypeSymbol);
registerAttributeWithSetter(outputDevice, kTypeSymbol);
registerMessageSimple(start);
registerMessageSimple(stop);
registerMessageWithArgument(getCpuLoad);
registerMessageWithArgument(addCallbackObserver);
registerMessageWithArgument(removeCallbackObserver);
// Set defaults
setAttributeValue(TT("inputDevice"), TT("default"));
setAttributeValue(TT("outputDevice"), TT("default"));
}
TTAudioEngine::~TTAudioEngine()
{
PaError err;
if(stream){
if(isRunning)
stop();
err = Pa_CloseStream(stream);
if(err != paNoError)
TTLogError("PortAudio error freeing engine: %s", Pa_GetErrorText(err));
}
delete callbackObservers;
TTObjectRelease(&inputBuffer);
TTObjectRelease(&outputBuffer);
}
TTErr TTAudioEngine::initStream()
{
PaError err;
TTBoolean shouldRun = isRunning;
if(isRunning)
stop();
if(stream){
Pa_CloseStream(stream);
stream = NULL;
}
if((inputDevice == TT("default") || inputDevice == NULL) && (outputDevice == TT("default") || outputDevice == NULL)){
err = Pa_OpenDefaultStream(&stream,
numInputChannels,
numOutputChannels,
paFloat32,
sampleRate,
vectorSize,
TTAudioEngineStreamCallback,
this);
}
else{
PaStreamParameters outputParameters;
PaStreamParameters inputParameters;
inputParameters.channelCount = numInputChannels;
inputParameters.device = inputDeviceIndex;
inputParameters.hostApiSpecificStreamInfo = NULL;
inputParameters.sampleFormat = paFloat32;
inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputDeviceIndex)->defaultLowInputLatency;
outputParameters.channelCount = numOutputChannels;
outputParameters.device = outputDeviceIndex;
outputParameters.hostApiSpecificStreamInfo = NULL;
outputParameters.sampleFormat = paFloat32;
outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputDeviceIndex)->defaultLowOutputLatency;
err = Pa_OpenStream(
&stream,
&inputParameters,
&outputParameters,
sampleRate,
vectorSize,
paNoFlag, //flags that can be used to define dither, clip settings and more
TTAudioEngineStreamCallback, //your callback function
this);
}
if(err != paNoError )
TTLogError("PortAudio error creating TTAudioEngine: %s", Pa_GetErrorText(err));
// Now that the stream is initialized, we need to setup our own buffers for reading and writing.
inputBuffer->setmaxNumChannels(numInputChannels);
inputBuffer->setnumChannels(numInputChannels);
inputBuffer->setvectorSize(vectorSize);
inputBuffer->alloc();
outputBuffer->setmaxNumChannels(numInputChannels);
outputBuffer->setnumChannels(numInputChannels);
outputBuffer->setvectorSize(vectorSize);
outputBuffer->alloc();
if(shouldRun)
start();
return (TTErr)err;
}
TTErr TTAudioEngine::start()
{
PaError err = paNoError;
if(!isRunning){
if(!stream)
initStream();
err = Pa_StartStream(stream);
if(err != paNoError)
TTLogError("PortAudio error starting engine: %s", Pa_GetErrorText(err));
isRunning = true;
}
return (TTErr)err;
}
TTErr TTAudioEngine::stop()
{
PaError err = paNoError;
if(stream){
err = Pa_StopStream(stream);
if(err != paNoError)
TTLogError("PortAudio error starting engine: %s", Pa_GetErrorText(err));
}
isRunning = false;
return (TTErr)err;
}
TTErr TTAudioEngine::getCpuLoad(TTValue& returnedValue)
{
TTFloat64 cpuLoad = Pa_GetStreamCpuLoad(stream);
returnedValue = cpuLoad;
return kTTErrNone;
}
TTErr TTAudioEngine::getAvailableInputDevices(TTValue& returnedDeviceNames)
{
const PaDeviceInfo* deviceInfo;
int numDevices;
returnedDeviceNames.clear();
numDevices = Pa_GetDeviceCount();
if(numDevices < 0){
printf("ERROR: Pa_CountDevices returned 0x%x\n", numDevices);
return kTTErrGeneric;
}
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(deviceInfo->maxInputChannels)
returnedDeviceNames.append(TT(deviceInfo->name));
}
return kTTErrNone;
}
TTErr TTAudioEngine::getAvailableOutputDevices(TTValue& returnedDeviceNames)
{
const PaDeviceInfo* deviceInfo;
int numDevices;
returnedDeviceNames.clear();
numDevices = Pa_GetDeviceCount();
if(numDevices < 0){
printf("ERROR: Pa_CountDevices returned 0x%x\n", numDevices);
return kTTErrGeneric;
}
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(deviceInfo->maxOutputChannels)
returnedDeviceNames.append(TT(deviceInfo->name));
}
return kTTErrNone;
}
TTErr TTAudioEngine::setinputDevice(TTValue& newDeviceName)
{
TTSymbolPtr newDevice = newDeviceName;
const PaDeviceInfo* deviceInfo;
int numDevices;
if(newDevice != inputDevice){
numDevices = Pa_GetDeviceCount();
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(newDevice == TT(deviceInfo->name)){
inputDeviceInfo = deviceInfo;
inputDeviceIndex = i;
numInputChannels = inputDeviceInfo->maxInputChannels;
inputDevice = newDevice;
if(isRunning)
return initStream();
return kTTErrNone;
}
}
return kTTErrGeneric;
}
return kTTErrNone;
}
TTErr TTAudioEngine::setoutputDevice(TTValue& newDeviceName)
{
TTSymbolPtr newDevice = newDeviceName;
const PaDeviceInfo* deviceInfo;
int numDevices;
if(newDevice != outputDevice){
numDevices = Pa_GetDeviceCount();
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(newDevice == TT(deviceInfo->name)){
outputDeviceInfo = deviceInfo;
outputDeviceIndex = i;
numOutputChannels = outputDeviceInfo->maxOutputChannels;
outputDevice = newDevice;
if(isRunning)
return initStream();
return kTTErrNone;
}
}
return kTTErrGeneric;
}
return kTTErrNone;
}
TTErr TTAudioEngine::setvectorSize(TTValue& newVectorSize)
{
if(TTUInt16(newVectorSize) != vectorSize){
vectorSize = newVectorSize;
if(isRunning)
return initStream();
}
return kTTErrNone;
}
TTErr TTAudioEngine::setsampleRate(TTValue& newSampleRate)
{
if(TTUInt32(newSampleRate) != sampleRate){
sampleRate = newSampleRate;
if(isRunning)
return initStream();
}
return kTTErrNone;
}
TTErr TTAudioEngine::addCallbackObserver(const TTValue& objectToReceiveNotifications)
{
callbackObservers->append(objectToReceiveNotifications);
return kTTErrNone;
}
TTErr TTAudioEngine::removeCallbackObserver(const TTValue& objectCurrentlyReceivingNotifications)
{
callbackObservers->remove(objectCurrentlyReceivingNotifications);
return kTTErrNone;
}
TTInt32 TTAudioEngine::callback(const TTFloat32* input,
TTFloat32* output,
TTUInt32 frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags)
{
inputBuffer->clear();
outputBuffer->clear();
// notify any observers that we are about to process a vector
// for example, a lydbaer graph will do all of its processing in response to this
// also, the scheduler will be serviced as a result of this
callbackObservers->iterateObjectsSendingMessage(kTTSym_audioEngineWillProcess);
// right now we copy all of the channels, regardless of whether or not they are actually being used
// TODO: only copy the channels that actually contain new audio samples
for(unsigned int i=0; i<frameCount; i++){
for(TTUInt16 channel=0; channel<numInputChannels; channel++)
inputBuffer->sampleVectors[channel][i] = *input++;
for(TTUInt16 channel=0; channel<numOutputChannels; channel++)
*output++ = outputBuffer->sampleVectors[channel][i];
}
return 0;
}
#if 0
#pragma mark -
#endif
static TTAudioEnginePtr sAudioEngine = NULL;
TTErr TTAudioEngineCreate()
{
TTErr err = kTTErrNone;
PaError paErr;
if(!sAudioEngine){
paErr = Pa_Initialize();
if(paErr == paNoError)
sAudioEngine = new TTAudioEngine;
else
TTLogError("PortAudio error: %s", Pa_GetErrorText(paErr));
err = kTTErrGeneric;
}
return err;
}
TTErr TTAudioEngineFree()
{
PaError err = Pa_Terminate();
if(err != paNoError)
TTLogError("PortAudio error: %s\n", Pa_GetErrorText( err ) );
else{
delete sAudioEngine;
sAudioEngine = NULL;
}
return (TTErr)err;
}
TTObjectPtr TTAudioEngineReference()
{
return TTObjectReference(sAudioEngine);
}
TTAudioSignalPtr TTAudioEngineGetInputSignalReference()
{
return (TTAudioSignalPtr)TTObjectReference(sAudioEngine->inputBuffer);
}
TTAudioSignalPtr TTAudioEngineGetOutputSignalReference()
{
return (TTAudioSignalPtr)TTObjectReference(sAudioEngine->outputBuffer);
}
TTErr TTAudioEngineStart()
{
if(sAudioEngine)
return sAudioEngine->start();
else
return kTTErrGeneric;
}
TTErr TTAudioEngineStop()
{
if(sAudioEngine)
return sAudioEngine->stop();
else
return kTTErrGeneric;
}
int TTAudioEngineStreamCallback(const void* input,
void* output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void* userData )
{
TTAudioEnginePtr engine = TTAudioEnginePtr(userData);
return engine->callback((const TTFloat32*)input, (TTFloat32*)output, frameCount, timeInfo, statusFlags);
}
<commit_msg>TTAudioEngine: fixing typo in a log message<commit_after>/*
* TTBlue Audio Engine
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the GNU LGPL
* http://www.gnu.org/licenses/lgpl.html
*/
#include "TTAudioEngine.h"
#include "TTEnvironment.h"
#define thisTTClass TTAudioEngine
TTAudioEngine::TTAudioEngine()
:TTObject("audioEngine"),
numInputChannels(2),
numOutputChannels(2),
vectorSize(64),
sampleRate(44100),
stream(NULL),
inputDevice(NULL),
outputDevice(NULL),
isRunning(false),
inputBuffer(NULL),
outputBuffer(NULL)
{
callbackObservers = new TTList;
callbackObservers->setThreadProtection(NO); // ... because we make calls into this at every audio vector calculation ...
TTObjectInstantiate(kTTSym_audiosignal, &inputBuffer, 1);
TTObjectInstantiate(kTTSym_audiosignal, &outputBuffer, 1);
// numChannels should be readonly -- how do we do that?
registerAttributeSimple(numInputChannels, kTypeUInt16);
registerAttributeSimple(numOutputChannels, kTypeUInt16);
registerAttributeWithSetter(vectorSize, kTypeUInt16);
registerAttributeWithSetter(sampleRate, kTypeUInt32);
registerAttributeWithSetter(inputDevice, kTypeSymbol);
registerAttributeWithSetter(outputDevice, kTypeSymbol);
registerMessageSimple(start);
registerMessageSimple(stop);
registerMessageWithArgument(getCpuLoad);
registerMessageWithArgument(addCallbackObserver);
registerMessageWithArgument(removeCallbackObserver);
// Set defaults
setAttributeValue(TT("inputDevice"), TT("default"));
setAttributeValue(TT("outputDevice"), TT("default"));
}
TTAudioEngine::~TTAudioEngine()
{
PaError err;
if(stream){
if(isRunning)
stop();
err = Pa_CloseStream(stream);
if(err != paNoError)
TTLogError("PortAudio error freeing engine: %s", Pa_GetErrorText(err));
}
delete callbackObservers;
TTObjectRelease(&inputBuffer);
TTObjectRelease(&outputBuffer);
}
TTErr TTAudioEngine::initStream()
{
PaError err;
TTBoolean shouldRun = isRunning;
if(isRunning)
stop();
if(stream){
Pa_CloseStream(stream);
stream = NULL;
}
if((inputDevice == TT("default") || inputDevice == NULL) && (outputDevice == TT("default") || outputDevice == NULL)){
err = Pa_OpenDefaultStream(&stream,
numInputChannels,
numOutputChannels,
paFloat32,
sampleRate,
vectorSize,
TTAudioEngineStreamCallback,
this);
}
else{
PaStreamParameters outputParameters;
PaStreamParameters inputParameters;
inputParameters.channelCount = numInputChannels;
inputParameters.device = inputDeviceIndex;
inputParameters.hostApiSpecificStreamInfo = NULL;
inputParameters.sampleFormat = paFloat32;
inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputDeviceIndex)->defaultLowInputLatency;
outputParameters.channelCount = numOutputChannels;
outputParameters.device = outputDeviceIndex;
outputParameters.hostApiSpecificStreamInfo = NULL;
outputParameters.sampleFormat = paFloat32;
outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputDeviceIndex)->defaultLowOutputLatency;
err = Pa_OpenStream(
&stream,
&inputParameters,
&outputParameters,
sampleRate,
vectorSize,
paNoFlag, //flags that can be used to define dither, clip settings and more
TTAudioEngineStreamCallback, //your callback function
this);
}
if(err != paNoError )
TTLogError("PortAudio error creating TTAudioEngine: %s", Pa_GetErrorText(err));
// Now that the stream is initialized, we need to setup our own buffers for reading and writing.
inputBuffer->setmaxNumChannels(numInputChannels);
inputBuffer->setnumChannels(numInputChannels);
inputBuffer->setvectorSize(vectorSize);
inputBuffer->alloc();
outputBuffer->setmaxNumChannels(numInputChannels);
outputBuffer->setnumChannels(numInputChannels);
outputBuffer->setvectorSize(vectorSize);
outputBuffer->alloc();
if(shouldRun)
start();
return (TTErr)err;
}
TTErr TTAudioEngine::start()
{
PaError err = paNoError;
if(!isRunning){
if(!stream)
initStream();
err = Pa_StartStream(stream);
if(err != paNoError)
TTLogError("PortAudio error starting engine: %s", Pa_GetErrorText(err));
isRunning = true;
}
return (TTErr)err;
}
TTErr TTAudioEngine::stop()
{
PaError err = paNoError;
if(stream){
err = Pa_StopStream(stream);
if(err != paNoError)
TTLogError("PortAudio error stopping engine: %s", Pa_GetErrorText(err));
}
isRunning = false;
return (TTErr)err;
}
TTErr TTAudioEngine::getCpuLoad(TTValue& returnedValue)
{
TTFloat64 cpuLoad = Pa_GetStreamCpuLoad(stream);
returnedValue = cpuLoad;
return kTTErrNone;
}
TTErr TTAudioEngine::getAvailableInputDevices(TTValue& returnedDeviceNames)
{
const PaDeviceInfo* deviceInfo;
int numDevices;
returnedDeviceNames.clear();
numDevices = Pa_GetDeviceCount();
if(numDevices < 0){
printf("ERROR: Pa_CountDevices returned 0x%x\n", numDevices);
return kTTErrGeneric;
}
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(deviceInfo->maxInputChannels)
returnedDeviceNames.append(TT(deviceInfo->name));
}
return kTTErrNone;
}
TTErr TTAudioEngine::getAvailableOutputDevices(TTValue& returnedDeviceNames)
{
const PaDeviceInfo* deviceInfo;
int numDevices;
returnedDeviceNames.clear();
numDevices = Pa_GetDeviceCount();
if(numDevices < 0){
printf("ERROR: Pa_CountDevices returned 0x%x\n", numDevices);
return kTTErrGeneric;
}
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(deviceInfo->maxOutputChannels)
returnedDeviceNames.append(TT(deviceInfo->name));
}
return kTTErrNone;
}
TTErr TTAudioEngine::setinputDevice(TTValue& newDeviceName)
{
TTSymbolPtr newDevice = newDeviceName;
const PaDeviceInfo* deviceInfo;
int numDevices;
if(newDevice != inputDevice){
numDevices = Pa_GetDeviceCount();
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(newDevice == TT(deviceInfo->name)){
inputDeviceInfo = deviceInfo;
inputDeviceIndex = i;
numInputChannels = inputDeviceInfo->maxInputChannels;
inputDevice = newDevice;
if(isRunning)
return initStream();
return kTTErrNone;
}
}
return kTTErrGeneric;
}
return kTTErrNone;
}
TTErr TTAudioEngine::setoutputDevice(TTValue& newDeviceName)
{
TTSymbolPtr newDevice = newDeviceName;
const PaDeviceInfo* deviceInfo;
int numDevices;
if(newDevice != outputDevice){
numDevices = Pa_GetDeviceCount();
for(int i=0; i<numDevices; i++){
deviceInfo = Pa_GetDeviceInfo(i);
if(newDevice == TT(deviceInfo->name)){
outputDeviceInfo = deviceInfo;
outputDeviceIndex = i;
numOutputChannels = outputDeviceInfo->maxOutputChannels;
outputDevice = newDevice;
if(isRunning)
return initStream();
return kTTErrNone;
}
}
return kTTErrGeneric;
}
return kTTErrNone;
}
TTErr TTAudioEngine::setvectorSize(TTValue& newVectorSize)
{
if(TTUInt16(newVectorSize) != vectorSize){
vectorSize = newVectorSize;
if(isRunning)
return initStream();
}
return kTTErrNone;
}
TTErr TTAudioEngine::setsampleRate(TTValue& newSampleRate)
{
if(TTUInt32(newSampleRate) != sampleRate){
sampleRate = newSampleRate;
if(isRunning)
return initStream();
}
return kTTErrNone;
}
TTErr TTAudioEngine::addCallbackObserver(const TTValue& objectToReceiveNotifications)
{
callbackObservers->append(objectToReceiveNotifications);
return kTTErrNone;
}
TTErr TTAudioEngine::removeCallbackObserver(const TTValue& objectCurrentlyReceivingNotifications)
{
callbackObservers->remove(objectCurrentlyReceivingNotifications);
return kTTErrNone;
}
TTInt32 TTAudioEngine::callback(const TTFloat32* input,
TTFloat32* output,
TTUInt32 frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags)
{
inputBuffer->clear();
outputBuffer->clear();
// notify any observers that we are about to process a vector
// for example, a lydbaer graph will do all of its processing in response to this
// also, the scheduler will be serviced as a result of this
callbackObservers->iterateObjectsSendingMessage(kTTSym_audioEngineWillProcess);
// right now we copy all of the channels, regardless of whether or not they are actually being used
// TODO: only copy the channels that actually contain new audio samples
for(unsigned int i=0; i<frameCount; i++){
for(TTUInt16 channel=0; channel<numInputChannels; channel++)
inputBuffer->sampleVectors[channel][i] = *input++;
for(TTUInt16 channel=0; channel<numOutputChannels; channel++)
*output++ = outputBuffer->sampleVectors[channel][i];
}
return 0;
}
#if 0
#pragma mark -
#endif
static TTAudioEnginePtr sAudioEngine = NULL;
TTErr TTAudioEngineCreate()
{
TTErr err = kTTErrNone;
PaError paErr;
if(!sAudioEngine){
paErr = Pa_Initialize();
if(paErr == paNoError)
sAudioEngine = new TTAudioEngine;
else
TTLogError("PortAudio error: %s", Pa_GetErrorText(paErr));
err = kTTErrGeneric;
}
return err;
}
TTErr TTAudioEngineFree()
{
PaError err = Pa_Terminate();
if(err != paNoError)
TTLogError("PortAudio error: %s\n", Pa_GetErrorText( err ) );
else{
delete sAudioEngine;
sAudioEngine = NULL;
}
return (TTErr)err;
}
TTObjectPtr TTAudioEngineReference()
{
return TTObjectReference(sAudioEngine);
}
TTAudioSignalPtr TTAudioEngineGetInputSignalReference()
{
return (TTAudioSignalPtr)TTObjectReference(sAudioEngine->inputBuffer);
}
TTAudioSignalPtr TTAudioEngineGetOutputSignalReference()
{
return (TTAudioSignalPtr)TTObjectReference(sAudioEngine->outputBuffer);
}
TTErr TTAudioEngineStart()
{
if(sAudioEngine)
return sAudioEngine->start();
else
return kTTErrGeneric;
}
TTErr TTAudioEngineStop()
{
if(sAudioEngine)
return sAudioEngine->stop();
else
return kTTErrGeneric;
}
int TTAudioEngineStreamCallback(const void* input,
void* output,
unsigned long frameCount,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags,
void* userData )
{
TTAudioEnginePtr engine = TTAudioEnginePtr(userData);
return engine->callback((const TTFloat32*)input, (TTFloat32*)output, frameCount, timeInfo, statusFlags);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCompositePainter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCompositePainter.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataSet.h"
#include "vtkGarbageCollector.h"
#include "vtkHardwareSelector.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
#include "vtkPolyData.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkMultiPieceDataSet.h"
#include "vtkCompositeDataDisplayAttributes.h"
vtkStandardNewMacro(vtkCompositePainter);
//----------------------------------------------------------------------------
vtkCompositePainter::vtkCompositePainter()
{
this->OutputData = 0;
}
//----------------------------------------------------------------------------
vtkCompositePainter::~vtkCompositePainter()
{
}
//----------------------------------------------------------------------------
vtkDataObject* vtkCompositePainter::GetOutput()
{
return this->OutputData? this->OutputData : this->GetInput();
}
//----------------------------------------------------------------------------
void vtkCompositePainter::RenderInternal(vtkRenderer* renderer,
vtkActor* actor,
unsigned long typeflags,
bool forceCompileOnly)
{
vtkCompositeDataSet* input = vtkCompositeDataSet::SafeDownCast(this->GetInput());
if (!input || !this->DelegatePainter)
{
this->Superclass::RenderInternal(renderer, actor, typeflags,
forceCompileOnly);
return;
}
vtkHardwareSelector* selector = renderer->GetSelector();
if(this->CompositeDataDisplayAttributes)
{
// render using the composite data attributes
unsigned int flat_index = 0;
bool visible = true;
this->RenderBlock(renderer, actor, typeflags, forceCompileOnly, input, flat_index, visible);
}
else
{
// render using the multi-block structure itself
vtkCompositeDataIterator* iter = input->NewIterator();
for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())
{
vtkDataObject* dobj = iter->GetCurrentDataObject();
if (dobj)
{
if (selector)
{
selector->BeginRenderProp();
// If hardware selection is in progress, we need to pass the composite
// index to the selection framework,
selector->RenderCompositeIndex(iter->GetCurrentFlatIndex());
}
this->DelegatePainter->SetInput(dobj);
this->OutputData = dobj;
this->Superclass::RenderInternal(renderer, actor, typeflags,
forceCompileOnly);
this->OutputData = 0;
if (selector)
{
selector->EndRenderProp();
}
}
}
iter->Delete();
}
}
//-----------------------------------------------------------------------------
void vtkCompositePainter::RenderBlock(vtkRenderer *renderer,
vtkActor *actor,
unsigned long typeflags,
bool forceCompileOnly,
vtkDataObject *dobj,
unsigned int &flat_index,
bool &visible)
{
vtkHardwareSelector *selector = renderer->GetSelector();
// push display attributes
bool prev_visible = visible;
if(this->CompositeDataDisplayAttributes->HasBlockVisibility(flat_index))
{
visible = this->CompositeDataDisplayAttributes->GetBlockVisibility(flat_index);
}
vtkMultiBlockDataSet *mbds = vtkMultiBlockDataSet::SafeDownCast(dobj);
vtkMultiPieceDataSet *mpds = vtkMultiPieceDataSet::SafeDownCast(dobj);
if(mbds || mpds)
{
// recurse down to child blocks
unsigned int childCount =
mbds ? mbds->GetNumberOfBlocks() : mpds->GetNumberOfPieces();
for(unsigned int i = 0; i < childCount; i++)
{
flat_index++;
this->RenderBlock(renderer,
actor,
typeflags,
forceCompileOnly,
mbds ? mbds->GetBlock(i) : mpds->GetPiece(i),
flat_index,
visible);
}
// pop display attributes
if(this->CompositeDataDisplayAttributes->HasBlockVisibility(flat_index))
{
visible = prev_visible;
}
flat_index++;
}
else if(dobj)
{
// render leaf-node
if(visible)
{
if(selector)
{
selector->BeginRenderProp();
// If hardware selection is in progress, we need to pass the composite
// index to the selection framework,
selector->RenderCompositeIndex(flat_index);
}
this->DelegatePainter->SetInput(dobj);
this->OutputData = dobj;
this->Superclass::RenderInternal(renderer,
actor,
typeflags,
forceCompileOnly);
this->OutputData = 0;
if(selector)
{
selector->EndRenderProp();
}
}
// pop display attributes
if(this->CompositeDataDisplayAttributes->HasBlockVisibility(flat_index))
{
visible = prev_visible;
}
}
}
//-----------------------------------------------------------------------------
void vtkCompositePainter::ReportReferences(vtkGarbageCollector *collector)
{
this->Superclass::ReportReferences(collector);
vtkGarbageCollectorReport(collector, this->OutputData, "Output");
}
//----------------------------------------------------------------------------
void vtkCompositePainter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<commit_msg>Fix display attribute handling in vtkCompositePainter<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCompositePainter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCompositePainter.h"
#include "vtkCompositeDataIterator.h"
#include "vtkCompositeDataSet.h"
#include "vtkGarbageCollector.h"
#include "vtkHardwareSelector.h"
#include "vtkObjectFactory.h"
#include "vtkRenderer.h"
#include "vtkPolyData.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkMultiPieceDataSet.h"
#include "vtkCompositeDataDisplayAttributes.h"
vtkStandardNewMacro(vtkCompositePainter);
//----------------------------------------------------------------------------
vtkCompositePainter::vtkCompositePainter()
{
this->OutputData = 0;
}
//----------------------------------------------------------------------------
vtkCompositePainter::~vtkCompositePainter()
{
}
//----------------------------------------------------------------------------
vtkDataObject* vtkCompositePainter::GetOutput()
{
return this->OutputData? this->OutputData : this->GetInput();
}
//----------------------------------------------------------------------------
void vtkCompositePainter::RenderInternal(vtkRenderer* renderer,
vtkActor* actor,
unsigned long typeflags,
bool forceCompileOnly)
{
vtkCompositeDataSet* input = vtkCompositeDataSet::SafeDownCast(this->GetInput());
if (!input || !this->DelegatePainter)
{
this->Superclass::RenderInternal(renderer, actor, typeflags,
forceCompileOnly);
return;
}
vtkHardwareSelector* selector = renderer->GetSelector();
if(this->CompositeDataDisplayAttributes)
{
// render using the composite data attributes
unsigned int flat_index = 0;
bool visible = true;
this->RenderBlock(renderer, actor, typeflags, forceCompileOnly, input, flat_index, visible);
}
else
{
// render using the multi-block structure itself
vtkCompositeDataIterator* iter = input->NewIterator();
for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())
{
vtkDataObject* dobj = iter->GetCurrentDataObject();
if (dobj)
{
if (selector)
{
selector->BeginRenderProp();
// If hardware selection is in progress, we need to pass the composite
// index to the selection framework,
selector->RenderCompositeIndex(iter->GetCurrentFlatIndex());
}
this->DelegatePainter->SetInput(dobj);
this->OutputData = dobj;
this->Superclass::RenderInternal(renderer, actor, typeflags,
forceCompileOnly);
this->OutputData = 0;
if (selector)
{
selector->EndRenderProp();
}
}
}
iter->Delete();
}
}
//-----------------------------------------------------------------------------
void vtkCompositePainter::RenderBlock(vtkRenderer *renderer,
vtkActor *actor,
unsigned long typeflags,
bool forceCompileOnly,
vtkDataObject *dobj,
unsigned int &flat_index,
bool &visible)
{
vtkHardwareSelector *selector = renderer->GetSelector();
// push display attributes
bool pop_visibility = false;
bool prev_visible = visible;
if(this->CompositeDataDisplayAttributes->HasBlockVisibility(flat_index))
{
visible = this->CompositeDataDisplayAttributes->GetBlockVisibility(flat_index);
pop_visibility = true;
}
vtkMultiBlockDataSet *mbds = vtkMultiBlockDataSet::SafeDownCast(dobj);
vtkMultiPieceDataSet *mpds = vtkMultiPieceDataSet::SafeDownCast(dobj);
if(mbds || mpds)
{
// move flat_index to first child
flat_index++;
// recurse down to child blocks
unsigned int childCount =
mbds ? mbds->GetNumberOfBlocks() : mpds->GetNumberOfPieces();
for(unsigned int i = 0; i < childCount; i++)
{
this->RenderBlock(renderer,
actor,
typeflags,
forceCompileOnly,
mbds ? mbds->GetBlock(i) : mpds->GetPiece(i),
flat_index,
visible);
}
}
else if(dobj)
{
// render leaf-node
if(visible)
{
if(selector)
{
selector->BeginRenderProp();
// If hardware selection is in progress, we need to pass the composite
// index to the selection framework,
selector->RenderCompositeIndex(flat_index);
}
this->DelegatePainter->SetInput(dobj);
this->OutputData = dobj;
this->Superclass::RenderInternal(renderer,
actor,
typeflags,
forceCompileOnly);
this->OutputData = 0;
if(selector)
{
selector->EndRenderProp();
}
}
flat_index++;
}
else
{
flat_index++;
}
// pop display attributes (if neccessary)
if(pop_visibility)
{
visible = prev_visible;
}
}
//-----------------------------------------------------------------------------
void vtkCompositePainter::ReportReferences(vtkGarbageCollector *collector)
{
this->Superclass::ReportReferences(collector);
vtkGarbageCollectorReport(collector, this->OutputData, "Output");
}
//----------------------------------------------------------------------------
void vtkCompositePainter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWin32OpenGLTextMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkWin32OpenGLTextMapper.h"
#include <GL/gl.h>
#include "vtkObjectFactory.h"
#include "vtkgluPickMatrix.h"
vtkCxxRevisionMacro(vtkWin32OpenGLTextMapper, "1.38");
vtkStandardNewMacro(vtkWin32OpenGLTextMapper);
struct vtkFontStruct
{
vtkWindow *Window;
int Italic;
int Bold;
int FontSize;
int FontFamily;
int ListBase;
};
static vtkFontStruct *cache[30] = {
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL};
static int numCached = 0;
int vtkWin32OpenGLTextMapper::GetListBaseForFont(vtkTextMapper *tm,
vtkViewport *vp)
{
int i, j;
vtkWindow *win = vp->GetVTKWindow();
// has the font been cached ?
for (i = 0; i < numCached; i++)
{
if (cache[i]->Window == win &&
cache[i]->Italic == tm->GetItalic() &&
cache[i]->Bold == tm->GetBold() &&
cache[i]->FontSize == tm->GetFontSize() &&
cache[i]->FontFamily == tm->GetFontFamily())
{
// make this the most recently used
if (i != 0)
{
vtkFontStruct *tmp = cache[i];
for (j = i-1; j >= 0; j--)
{
cache[j+1] = cache[j];
}
cache[0] = tmp;
}
return cache[0]->ListBase;
}
}
HDC hdc = (HDC) win->GetGenericContext();
// OK the font is not cached
// so we need to make room for a new font
if (numCached == 30)
{
wglMakeCurrent((HDC)cache[29]->Window->GetGenericContext(),
(HGLRC)cache[29]->Window->GetGenericDisplayId());
glDeleteLists(cache[29]->ListBase,255);
wglMakeCurrent(hdc, (HGLRC)win->GetGenericDisplayId());
numCached = 29;
}
// add the new font
if (!cache[numCached])
{
cache[numCached] = new vtkFontStruct;
int done = 0;
cache[numCached]->ListBase = 1000;
do
{
done = 1;
cache[numCached]->ListBase += 260;
for (i = 0; i < numCached; i++)
{
if (cache[i]->ListBase == cache[numCached]->ListBase)
{
done = 0;
}
}
}
while (!done);
}
// set the other info and build the font
cache[numCached]->Window = win;
cache[numCached]->Italic = tm->GetItalic();
cache[numCached]->Bold = tm->GetBold();
cache[numCached]->FontSize = tm->GetFontSize();
cache[numCached]->FontFamily = tm->GetFontFamily();
wglUseFontBitmaps(hdc, 0, 255, cache[numCached]->ListBase);
// now resort the list
vtkFontStruct *tmp = cache[numCached];
for (i = numCached-1; i >= 0; i--)
{
cache[i+1] = cache[i];
}
cache[0] = tmp;
numCached++;
return cache[0]->ListBase;
}
void vtkWin32OpenGLTextMapper::ReleaseGraphicsResources(vtkWindow *win)
{
int i,j;
// free up any cached font associated with this window
// has the font been cached ?
for (i = 0; i < numCached; i++)
{
if (cache[i]->Window == win)
{
win->MakeCurrent();
glDeleteLists(cache[i]->ListBase,255);
delete cache[i];
// resort them
numCached--;
for (j = i; j < numCached; j++)
{
cache[j] = cache[j+1];
}
cache[numCached] = NULL;
i--;
}
}
if ( this->Font )
{
DeleteObject( this->Font );
this->Font = 0;
}
this->LastWindow = NULL;
// very important
// the release of graphics resources indicates that significant changes have
// occurred. Old fonts, cached sizes etc are all no longer valid, so we send
// ourselves a general modified message.
this->Modified();
}
vtkWin32OpenGLTextMapper::vtkWin32OpenGLTextMapper()
{
}
vtkWin32OpenGLTextMapper::~vtkWin32OpenGLTextMapper()
{
if (this->LastWindow)
{
this->ReleaseGraphicsResources(this->LastWindow);
}
}
void vtkWin32OpenGLTextMapper::RenderOpaqueGeometry(vtkViewport* viewport,
vtkActor2D* actor)
{
float* actorColor = actor->GetProperty()->GetColor();
if ( actorColor[3] == 1.0 )
{
this->RenderGeometry( viewport, actor );
}
}
void vtkWin32OpenGLTextMapper::RenderTranslucentGeometry(vtkViewport* viewport,
vtkActor2D* actor)
{
float* actorColor = actor->GetProperty()->GetColor();
if ( actorColor[3] != 1.0 )
{
this->RenderGeometry( viewport, actor );
}
}
void vtkWin32OpenGLTextMapper::RenderGeometry(vtkViewport* viewport,
vtkActor2D* actor)
{
vtkDebugMacro (<< "RenderOpaqueGeometry");
// turn off texturing in case it is on
glDisable( GL_TEXTURE_2D );
// Get the window information for display
vtkWindow* window = viewport->GetVTKWindow();
if (this->LastWindow && this->LastWindow != window)
{
this->ReleaseGraphicsResources(this->LastWindow);
}
this->LastWindow = window;
// Check for input
if ( this->NumberOfLines > 1 )
{
this->RenderOpaqueGeometryMultipleLines(viewport, actor);
return;
}
if ( this->Input == NULL )
{
vtkErrorMacro (<<"Render - No input");
return;
}
int size[2];
this->GetSize(viewport, size);
// Get the device context from the window
HDC hdc = (HDC) window->GetGenericContext();
// Select the font
HFONT hOldFont = (HFONT) SelectObject(hdc, this->Font);
// Get the position of the text actor
POINT ptDestOff;
int* actorPos =
actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);
ptDestOff.x = actorPos[0];
ptDestOff.y = static_cast<long>(actorPos[1] - this->LineOffset);
// Set up the font color from the text actor
unsigned char red = 0;
unsigned char green = 0;
unsigned char blue = 0;
unsigned char alpha = 0;
float* actorColor = actor->GetProperty()->GetColor();
red = (unsigned char) (actorColor[0] * 255.0);
green = (unsigned char) (actorColor[1] * 255.0);
blue = (unsigned char) (actorColor[2] * 255.0);
alpha = (unsigned char) (actorColor[3] * 255.0);
// Set up the shadow color
float intensity;
intensity = (red + green + blue)/3.0;
unsigned char shadowRed, shadowGreen, shadowBlue;
if (intensity > 128)
{
shadowRed = shadowBlue = shadowGreen = 0;
}
else
{
shadowRed = shadowBlue = shadowGreen = 255;
}
// Define bounding rectangle
RECT rect;
rect.left = ptDestOff.x;
rect.top = ptDestOff.y;
rect.bottom = ptDestOff.y;
rect.right = ptDestOff.x;
rect.right = rect.left + size[0];
rect.top = rect.bottom + size[1];
switch (this->Justification)
{
int tmp;
case VTK_TEXT_LEFT:
break;
case VTK_TEXT_CENTERED:
tmp = rect.right - rect.left + 1;
rect.left = rect.left - tmp/2;
rect.right = rect.left + tmp;
break;
case VTK_TEXT_RIGHT:
tmp = rect.right - rect.left + 1;
rect.right = rect.left;
rect.left = rect.left - tmp;
}
switch (this->VerticalJustification)
{
case VTK_TEXT_TOP:
rect.top = rect.bottom;
rect.bottom = rect.bottom - size[1];
break;
case VTK_TEXT_CENTERED:
rect.bottom = rect.bottom - size[1]/2;
rect.top = rect.bottom + size[1];
break;
case VTK_TEXT_BOTTOM:
break;
}
// push a 2D matrix on the stack
int *vsize = viewport->GetSize();
glMatrixMode( GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
if(viewport->GetIsPicking())
{
vtkgluPickMatrix(viewport->GetPickX(), viewport->GetPickY(),
1, 1, viewport->GetOrigin(), viewport->GetSize());
}
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadIdentity();
glDisable( GL_LIGHTING);
int front =
(actor->GetProperty()->GetDisplayLocation() == VTK_FOREGROUND_LOCATION);
float *tileViewport = viewport->GetVTKWindow()->GetTileViewport();
float visVP[4];
visVP[0] = (vport[0] >= tileViewPort[0]) ? vport[0] : tileViewPort[0];
visVP[1] = (vport[1] >= tileViewPort[1]) ? vport[1] : tileViewPort[1];
visVP[2] = (vport[2] <= tileViewPort[2]) ? vport[2] : tileViewPort[2];
visVP[3] = (vport[3] <= tileViewPort[3]) ? vport[3] : tileViewPort[3];
if (visVP[0] == visVP[2])
{
return;
}
if (visVP[1] == visVP[3])
{
return;
}
int *winSize = viewport->GetVTKWindow()->GetSize();
int xoff = static_cast<int>
(rect.left - winSize[0]*((visVP[2] + visVP[0])/2.0 - vport[0]));
int yoff = static_cast<int>
(rect.bottom - winSize[1]*((visVP[3] + visVP[1])/2.0 - vport[1]));
// When picking draw the bounds of the text as a rectangle,
// as text only picks when the pick point is exactly on the
// origin of the text
if(viewport->GetIsPicking())
{
float width = 2.0 * ((float)rect.right - rect.left) / vsize[0];
float height = 2.0 * ((float)rect.top - rect.bottom) / vsize[1];
float x1 = (2.0 * (GLfloat)(rect.left) / vsize[0] - 1);
float y1 = (2.0 * (GLfloat)(rect.bottom) / vsize[1] - 1);
glRectf(x1, y1, x1+width, y1+height);
// Clean up and return after drawing the rectangle
glMatrixMode( GL_PROJECTION);
glPopMatrix();
glMatrixMode( GL_MODELVIEW);
glPopMatrix();
glEnable( GL_LIGHTING);
// Restore the state
SelectObject(hdc, hOldFont);
return;
}
glListBase(vtkWin32OpenGLTextMapper::GetListBaseForFont(this,viewport));
// Set the colors for the shadow
if (this->Shadow)
{
// set the colors for the foreground
glColor4ub(shadowRed, shadowGreen, shadowBlue, alpha);
glRasterPos3f(0,0,(front)?(-1):(.99999));
// required for clipping to work correctly
glBitmap(0, 0, 0, 0, xoff + 1, yoff - 1, NULL);
// Draw the shadow text
glCallLists (strlen(this->Input), GL_UNSIGNED_BYTE, this->Input);
}
// set the colors for the foreground
glColor4ub(red, green, blue, alpha);
glRasterPos3f(0,0,(front)?(-1):(.99999));
// required for clipping to work correctly
glBitmap(0, 0, 0, 0, xoff, yoff, NULL);
// display a string: // indicate start of glyph display lists
glCallLists (strlen(this->Input), GL_UNSIGNED_BYTE, this->Input);
glFlush();
#ifndef _WIN32_WCE
GdiFlush();
#endif
glMatrixMode( GL_PROJECTION);
glPopMatrix();
glMatrixMode( GL_MODELVIEW);
glPopMatrix();
glEnable( GL_LIGHTING);
// Restore the state
SelectObject(hdc, hOldFont);
}
<commit_msg>compile on windows<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWin32OpenGLTextMapper.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkWin32OpenGLTextMapper.h"
#include <GL/gl.h>
#include "vtkObjectFactory.h"
#include "vtkgluPickMatrix.h"
vtkCxxRevisionMacro(vtkWin32OpenGLTextMapper, "1.39");
vtkStandardNewMacro(vtkWin32OpenGLTextMapper);
struct vtkFontStruct
{
vtkWindow *Window;
int Italic;
int Bold;
int FontSize;
int FontFamily;
int ListBase;
};
static vtkFontStruct *cache[30] = {
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL};
static int numCached = 0;
int vtkWin32OpenGLTextMapper::GetListBaseForFont(vtkTextMapper *tm,
vtkViewport *vp)
{
int i, j;
vtkWindow *win = vp->GetVTKWindow();
// has the font been cached ?
for (i = 0; i < numCached; i++)
{
if (cache[i]->Window == win &&
cache[i]->Italic == tm->GetItalic() &&
cache[i]->Bold == tm->GetBold() &&
cache[i]->FontSize == tm->GetFontSize() &&
cache[i]->FontFamily == tm->GetFontFamily())
{
// make this the most recently used
if (i != 0)
{
vtkFontStruct *tmp = cache[i];
for (j = i-1; j >= 0; j--)
{
cache[j+1] = cache[j];
}
cache[0] = tmp;
}
return cache[0]->ListBase;
}
}
HDC hdc = (HDC) win->GetGenericContext();
// OK the font is not cached
// so we need to make room for a new font
if (numCached == 30)
{
wglMakeCurrent((HDC)cache[29]->Window->GetGenericContext(),
(HGLRC)cache[29]->Window->GetGenericDisplayId());
glDeleteLists(cache[29]->ListBase,255);
wglMakeCurrent(hdc, (HGLRC)win->GetGenericDisplayId());
numCached = 29;
}
// add the new font
if (!cache[numCached])
{
cache[numCached] = new vtkFontStruct;
int done = 0;
cache[numCached]->ListBase = 1000;
do
{
done = 1;
cache[numCached]->ListBase += 260;
for (i = 0; i < numCached; i++)
{
if (cache[i]->ListBase == cache[numCached]->ListBase)
{
done = 0;
}
}
}
while (!done);
}
// set the other info and build the font
cache[numCached]->Window = win;
cache[numCached]->Italic = tm->GetItalic();
cache[numCached]->Bold = tm->GetBold();
cache[numCached]->FontSize = tm->GetFontSize();
cache[numCached]->FontFamily = tm->GetFontFamily();
wglUseFontBitmaps(hdc, 0, 255, cache[numCached]->ListBase);
// now resort the list
vtkFontStruct *tmp = cache[numCached];
for (i = numCached-1; i >= 0; i--)
{
cache[i+1] = cache[i];
}
cache[0] = tmp;
numCached++;
return cache[0]->ListBase;
}
void vtkWin32OpenGLTextMapper::ReleaseGraphicsResources(vtkWindow *win)
{
int i,j;
// free up any cached font associated with this window
// has the font been cached ?
for (i = 0; i < numCached; i++)
{
if (cache[i]->Window == win)
{
win->MakeCurrent();
glDeleteLists(cache[i]->ListBase,255);
delete cache[i];
// resort them
numCached--;
for (j = i; j < numCached; j++)
{
cache[j] = cache[j+1];
}
cache[numCached] = NULL;
i--;
}
}
if ( this->Font )
{
DeleteObject( this->Font );
this->Font = 0;
}
this->LastWindow = NULL;
// very important
// the release of graphics resources indicates that significant changes have
// occurred. Old fonts, cached sizes etc are all no longer valid, so we send
// ourselves a general modified message.
this->Modified();
}
vtkWin32OpenGLTextMapper::vtkWin32OpenGLTextMapper()
{
}
vtkWin32OpenGLTextMapper::~vtkWin32OpenGLTextMapper()
{
if (this->LastWindow)
{
this->ReleaseGraphicsResources(this->LastWindow);
}
}
void vtkWin32OpenGLTextMapper::RenderOpaqueGeometry(vtkViewport* viewport,
vtkActor2D* actor)
{
float* actorColor = actor->GetProperty()->GetColor();
if ( actorColor[3] == 1.0 )
{
this->RenderGeometry( viewport, actor );
}
}
void vtkWin32OpenGLTextMapper::RenderTranslucentGeometry(vtkViewport* viewport,
vtkActor2D* actor)
{
float* actorColor = actor->GetProperty()->GetColor();
if ( actorColor[3] != 1.0 )
{
this->RenderGeometry( viewport, actor );
}
}
void vtkWin32OpenGLTextMapper::RenderGeometry(vtkViewport* viewport,
vtkActor2D* actor)
{
vtkDebugMacro (<< "RenderOpaqueGeometry");
// turn off texturing in case it is on
glDisable( GL_TEXTURE_2D );
// Get the window information for display
vtkWindow* window = viewport->GetVTKWindow();
if (this->LastWindow && this->LastWindow != window)
{
this->ReleaseGraphicsResources(this->LastWindow);
}
this->LastWindow = window;
// Check for input
if ( this->NumberOfLines > 1 )
{
this->RenderOpaqueGeometryMultipleLines(viewport, actor);
return;
}
if ( this->Input == NULL )
{
vtkErrorMacro (<<"Render - No input");
return;
}
int size[2];
this->GetSize(viewport, size);
// Get the device context from the window
HDC hdc = (HDC) window->GetGenericContext();
// Select the font
HFONT hOldFont = (HFONT) SelectObject(hdc, this->Font);
// Get the position of the text actor
POINT ptDestOff;
int* actorPos =
actor->GetPositionCoordinate()->GetComputedViewportValue(viewport);
ptDestOff.x = actorPos[0];
ptDestOff.y = static_cast<long>(actorPos[1] - this->LineOffset);
// Set up the font color from the text actor
unsigned char red = 0;
unsigned char green = 0;
unsigned char blue = 0;
unsigned char alpha = 0;
float* actorColor = actor->GetProperty()->GetColor();
red = (unsigned char) (actorColor[0] * 255.0);
green = (unsigned char) (actorColor[1] * 255.0);
blue = (unsigned char) (actorColor[2] * 255.0);
alpha = (unsigned char) (actorColor[3] * 255.0);
// Set up the shadow color
float intensity;
intensity = (red + green + blue)/3.0;
unsigned char shadowRed, shadowGreen, shadowBlue;
if (intensity > 128)
{
shadowRed = shadowBlue = shadowGreen = 0;
}
else
{
shadowRed = shadowBlue = shadowGreen = 255;
}
// Define bounding rectangle
RECT rect;
rect.left = ptDestOff.x;
rect.top = ptDestOff.y;
rect.bottom = ptDestOff.y;
rect.right = ptDestOff.x;
rect.right = rect.left + size[0];
rect.top = rect.bottom + size[1];
switch (this->Justification)
{
int tmp;
case VTK_TEXT_LEFT:
break;
case VTK_TEXT_CENTERED:
tmp = rect.right - rect.left + 1;
rect.left = rect.left - tmp/2;
rect.right = rect.left + tmp;
break;
case VTK_TEXT_RIGHT:
tmp = rect.right - rect.left + 1;
rect.right = rect.left;
rect.left = rect.left - tmp;
}
switch (this->VerticalJustification)
{
case VTK_TEXT_TOP:
rect.top = rect.bottom;
rect.bottom = rect.bottom - size[1];
break;
case VTK_TEXT_CENTERED:
rect.bottom = rect.bottom - size[1]/2;
rect.top = rect.bottom + size[1];
break;
case VTK_TEXT_BOTTOM:
break;
}
// push a 2D matrix on the stack
int *vsize = viewport->GetSize();
glMatrixMode( GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
if(viewport->GetIsPicking())
{
vtkgluPickMatrix(viewport->GetPickX(), viewport->GetPickY(),
1, 1, viewport->GetOrigin(), viewport->GetSize());
}
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadIdentity();
glDisable( GL_LIGHTING);
int front =
(actor->GetProperty()->GetDisplayLocation() == VTK_FOREGROUND_LOCATION);
float *tileViewport = viewport->GetVTKWindow()->GetTileViewport();
float *vport = viewport->GetViewport();
float visVP[4];
visVP[0] = (vport[0] >= tileViewport[0]) ? vport[0] : tileViewport[0];
visVP[1] = (vport[1] >= tileViewport[1]) ? vport[1] : tileViewport[1];
visVP[2] = (vport[2] <= tileViewport[2]) ? vport[2] : tileViewport[2];
visVP[3] = (vport[3] <= tileViewport[3]) ? vport[3] : tileViewport[3];
if (visVP[0] == visVP[2])
{
return;
}
if (visVP[1] == visVP[3])
{
return;
}
int *winSize = viewport->GetVTKWindow()->GetSize();
int xoff = static_cast<int>
(rect.left - winSize[0]*((visVP[2] + visVP[0])/2.0 - vport[0]));
int yoff = static_cast<int>
(rect.bottom - winSize[1]*((visVP[3] + visVP[1])/2.0 - vport[1]));
// When picking draw the bounds of the text as a rectangle,
// as text only picks when the pick point is exactly on the
// origin of the text
if(viewport->GetIsPicking())
{
float width = 2.0 * ((float)rect.right - rect.left) / vsize[0];
float height = 2.0 * ((float)rect.top - rect.bottom) / vsize[1];
float x1 = (2.0 * (GLfloat)(rect.left) / vsize[0] - 1);
float y1 = (2.0 * (GLfloat)(rect.bottom) / vsize[1] - 1);
glRectf(x1, y1, x1+width, y1+height);
// Clean up and return after drawing the rectangle
glMatrixMode( GL_PROJECTION);
glPopMatrix();
glMatrixMode( GL_MODELVIEW);
glPopMatrix();
glEnable( GL_LIGHTING);
// Restore the state
SelectObject(hdc, hOldFont);
return;
}
glListBase(vtkWin32OpenGLTextMapper::GetListBaseForFont(this,viewport));
// Set the colors for the shadow
if (this->Shadow)
{
// set the colors for the foreground
glColor4ub(shadowRed, shadowGreen, shadowBlue, alpha);
glRasterPos3f(0,0,(front)?(-1):(.99999));
// required for clipping to work correctly
glBitmap(0, 0, 0, 0, xoff + 1, yoff - 1, NULL);
// Draw the shadow text
glCallLists (strlen(this->Input), GL_UNSIGNED_BYTE, this->Input);
}
// set the colors for the foreground
glColor4ub(red, green, blue, alpha);
glRasterPos3f(0,0,(front)?(-1):(.99999));
// required for clipping to work correctly
glBitmap(0, 0, 0, 0, xoff, yoff, NULL);
// display a string: // indicate start of glyph display lists
glCallLists (strlen(this->Input), GL_UNSIGNED_BYTE, this->Input);
glFlush();
#ifndef _WIN32_WCE
GdiFlush();
#endif
glMatrixMode( GL_PROJECTION);
glPopMatrix();
glMatrixMode( GL_MODELVIEW);
glPopMatrix();
glEnable( GL_LIGHTING);
// Restore the state
SelectObject(hdc, hOldFont);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: previewbase.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:48:00 $
*
* 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 _PREVIEWBASE_HXX_
#define _PREVIEWBASE_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#include <windows.h>
//---------------------------------------------
// Common interface for previews
//---------------------------------------------
class PreviewBase
{
public:
PreviewBase();
// dtor
virtual ~PreviewBase();
virtual sal_Int32 SAL_CALL getTargetColorDepth()
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableWidth()
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableHeight()
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getShowState()
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL getImage(sal_Int16& aImageFormat,com::sun::star::uno::Any& aImage);
sal_Int16 SAL_CALL getImaginaryShowState() const;
virtual HWND SAL_CALL getWindowHandle() const;
protected:
::com::sun::star::uno::Any m_ImageData;
sal_Int16 m_ImageFormat;
sal_Bool m_bShowState;
};
#endif
<commit_msg>INTEGRATION: CWS sb59 (1.3.100); FILE MERGED 2006/08/10 12:04:53 sb 1.3.100.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: previewbase.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-10-12 10:54:56 $
*
* 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 _PREVIEWBASE_HXX_
#define _PREVIEWBASE_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
//---------------------------------------------
// Common interface for previews
//---------------------------------------------
class PreviewBase
{
public:
PreviewBase();
// dtor
virtual ~PreviewBase();
virtual sal_Int32 SAL_CALL getTargetColorDepth()
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableWidth()
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getAvailableHeight()
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL getShowState()
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL getImage(sal_Int16& aImageFormat,com::sun::star::uno::Any& aImage);
sal_Bool SAL_CALL getImaginaryShowState() const;
virtual HWND SAL_CALL getWindowHandle() const;
protected:
::com::sun::star::uno::Any m_ImageData;
sal_Int16 m_ImageFormat;
sal_Bool m_bShowState;
};
#endif
<|endoftext|> |
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "BatchEncoder.h"
#include "Hyperlink.h"
#include ".\hyperlink.h"
IMPLEMENT_DYNAMIC(CHyperlink, CStatic)
CHyperlink::CHyperlink()
{
m_hCursor = NULL;
m_bVisited = false;
m_bCaptured = false;
}
CHyperlink::~CHyperlink()
{
}
BEGIN_MESSAGE_MAP(CHyperlink, CMyStatic)
ON_CONTROL_REFLECT(STN_CLICKED, OnStnClicked)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_MOUSEMOVE()
ON_WM_SETCURSOR()
ON_WM_DESTROY()
END_MESSAGE_MAP()
void CHyperlink::OnStnClicked()
{
::ShellExecute(NULL, _T("open"), m_szURL, NULL, NULL, SW_SHOW);
m_bVisited = true;
}
HBRUSH CHyperlink::CtlColor(CDC* pDC, UINT nCtlColor)
{
SetTextColor(pDC->GetSafeHdc(), m_bVisited ? colorVisited : m_bCaptured ? colorHover : colorLink);
SetBkMode(pDC->GetSafeHdc(), TRANSPARENT);
return (HBRUSH) ::GetStockObject(NULL_BRUSH);
}
void CHyperlink::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bCaptured)
{
RECT rc;
GetClientRect(&rc);
if (PtInRect(&rc, point) == FALSE)
{
m_bCaptured = false;
ReleaseCapture();
RedrawWindow();
}
}
else
{
SetCapture();
m_bCaptured = true;
RedrawWindow();
}
CMyStatic::OnMouseMove(nFlags, point);
}
BOOL CHyperlink::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if (m_hCursor)
{
::SetCursor(m_hCursor);
return TRUE;
}
return CMyStatic::OnSetCursor(pWnd, nHitTest, message);
}
void CHyperlink::OnDestroy()
{
CMyStatic::OnDestroy();
if (m_hCursor != NULL)
::DestroyCursor(m_hCursor);
}
void CHyperlink::PreSubclassWindow()
{
colorHover = ::GetSysColor(COLOR_HIGHLIGHT);
colorLink = RGB(0, 0, 255);
colorVisited = RGB(128, 0, 128);
SetWindowLong(this->GetSafeHwnd(), GWL_STYLE, GetStyle() | SS_NOTIFY);
m_hCursor = ::LoadCursor(NULL, IDC_HAND);
if (m_hCursor == NULL)
{
TCHAR szPath[MAX_PATH + 1];
::GetWindowsDirectory(szPath, sizeof(szPath));
lstrcat(szPath, _T("\\winhlp32.exe"));
HMODULE hModule = ::LoadLibrary(szPath);
if (hModule)
{
HCURSOR hm_hCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
if (hm_hCursor)
m_hCursor = CopyCursor(hm_hCursor);
}
::FreeLibrary(hModule);
}
CMyStatic::PreSubclassWindow();
}
<commit_msg>Update Hyperlink.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "..\StdAfx.h"
#include "..\BatchEncoder.h"
#include "Hyperlink.h"
IMPLEMENT_DYNAMIC(CHyperlink, CStatic)
CHyperlink::CHyperlink()
{
m_hCursor = NULL;
m_bVisited = false;
m_bCaptured = false;
}
CHyperlink::~CHyperlink()
{
}
BEGIN_MESSAGE_MAP(CHyperlink, CMyStatic)
ON_CONTROL_REFLECT(STN_CLICKED, OnStnClicked)
ON_WM_CTLCOLOR_REFLECT()
ON_WM_MOUSEMOVE()
ON_WM_SETCURSOR()
ON_WM_DESTROY()
END_MESSAGE_MAP()
void CHyperlink::OnStnClicked()
{
::ShellExecute(NULL, _T("open"), m_szURL, NULL, NULL, SW_SHOW);
m_bVisited = true;
}
HBRUSH CHyperlink::CtlColor(CDC* pDC, UINT nCtlColor)
{
SetTextColor(pDC->GetSafeHdc(), m_bVisited ? colorVisited : m_bCaptured ? colorHover : colorLink);
SetBkMode(pDC->GetSafeHdc(), TRANSPARENT);
return (HBRUSH) ::GetStockObject(NULL_BRUSH);
}
void CHyperlink::OnMouseMove(UINT nFlags, CPoint point)
{
if (m_bCaptured)
{
RECT rc;
GetClientRect(&rc);
if (PtInRect(&rc, point) == FALSE)
{
m_bCaptured = false;
ReleaseCapture();
RedrawWindow();
}
}
else
{
SetCapture();
m_bCaptured = true;
RedrawWindow();
}
CMyStatic::OnMouseMove(nFlags, point);
}
BOOL CHyperlink::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{
if (m_hCursor)
{
::SetCursor(m_hCursor);
return TRUE;
}
return CMyStatic::OnSetCursor(pWnd, nHitTest, message);
}
void CHyperlink::OnDestroy()
{
CMyStatic::OnDestroy();
if (m_hCursor != NULL)
::DestroyCursor(m_hCursor);
}
void CHyperlink::PreSubclassWindow()
{
colorHover = ::GetSysColor(COLOR_HIGHLIGHT);
colorLink = RGB(0, 0, 255);
colorVisited = RGB(128, 0, 128);
SetWindowLong(this->GetSafeHwnd(), GWL_STYLE, GetStyle() | SS_NOTIFY);
m_hCursor = ::LoadCursor(NULL, IDC_HAND);
if (m_hCursor == NULL)
{
TCHAR szPath[MAX_PATH + 1];
::GetWindowsDirectory(szPath, sizeof(szPath));
lstrcat(szPath, _T("\\winhlp32.exe"));
HMODULE hModule = ::LoadLibrary(szPath);
if (hModule)
{
HCURSOR hm_hCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106));
if (hm_hCursor)
m_hCursor = CopyCursor(hm_hCursor);
}
::FreeLibrary(hModule);
}
CMyStatic::PreSubclassWindow();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qtcontactsglobal.h"
#include <QSet>
#include <QMetaType>
#include <QTypeInfo>
//TESTED_CLASS=
//TESTED_FILES=
QTM_USE_NAMESPACE
Q_DEFINE_LATIN1_CONSTANT(a, "a");
Q_DEFINE_LATIN1_CONSTANT(a2, "a");
Q_DEFINE_LATIN1_CONSTANT(b, "b");
Q_DEFINE_LATIN1_CONSTANT(b2, "b");
Q_DEFINE_LATIN1_CONSTANT(bb, "bb");
Q_DEFINE_LATIN1_CONSTANT(bb2, "bb");
Q_DEFINE_LATIN1_CONSTANT(z, "");
Q_DEFINE_LATIN1_CONSTANT(z2, "");
Q_DEFINE_LATIN1_CONSTANT(z3, "\0");
Q_DEFINE_LATIN1_CONSTANT(soup, "alphabet soup"); // but you can't have any
QLatin1String ln(0);
QLatin1String lz("");
QLatin1String la("a");
QLatin1String lb("b");
QLatin1String lbb("bb");
QLatin1String lsoup("alphabet soup");
QString sn;
QString sz("");
QString sa(la);
QString sb(lb);
QString sbb(lbb);
QString ssoup("alphabet soup");
class tst_QLatin1Constant: public QObject
{
Q_OBJECT
public:
tst_QLatin1Constant();
virtual ~tst_QLatin1Constant();
// Overload testers
int overloaded(const char *) {return 1;}
//int overloaded(const QLatin1String& ) {return 2;}
int overloaded(QLatin1String ) {return 3;}
int overloaded(const QString& ) {return 4;}
//int overloaded(QString ){return 5;}
//template<int N> int overloaded(const QLatin1Constant<N>& ) {return 6;}
template<int N> int overloaded(QLatin1Constant<N> ) {return 7;}
int overloaded(const QVariant&) {return 8;}
// More overload testers
int overloaded2(QLatin1String) {return 3;}
int overloaded2(const QString&) {return 4;}
int overloaded3(const char*) {return 1;}
int overloaded3(QLatin1String) {return 3;}
int overloaded4(const char*) {return 1;}
int overloaded4(const QString&) {return 4;}
// Conversion testers
bool charfunc(const char* str) {return qstrcmp(str, "alphabet soup") == 0;}
bool latfunc(QLatin1String lat) {return qstrcmp(lat.latin1(), "alphabet soup") == 0;}
bool latreffunc(const QLatin1String& lat) {return qstrcmp(lat.latin1(), "alphabet soup") == 0;}
bool strfunc(QString str) {return str == QString::fromAscii("alphabet soup");}
bool strreffunc(const QString& str) {return str == QString::fromAscii("alphabet soup");}
bool varfunc(const QVariant& var) {return (var.type() == QVariant::String) && var.toString() == QString::fromAscii("alphabet soup");}
private slots:
void hash();
void conversion();
void overloads();
void equals();
void latinEquals();
void stringEquals();
void ordering();
void latinaccessor();
};
tst_QLatin1Constant::tst_QLatin1Constant()
{
}
tst_QLatin1Constant::~tst_QLatin1Constant()
{
}
void tst_QLatin1Constant::hash()
{
// Test that if a == b, hash(a) == hash(b)
// (also for ===)
QVERIFY(qHash(a) == qHash(a));
QVERIFY(qHash(a) == qHash(a2));
QVERIFY(qHash(b) == qHash(b));
QVERIFY(qHash(b) == qHash(b));
QVERIFY(qHash(bb) == qHash(bb));
QVERIFY(qHash(bb) == qHash(bb));
// As a convenience, make sure that hashing
// the same string gives the same results
// no matter the storage
QVERIFY(qHash(a) == qHash(la));
QVERIFY(qHash(a) == qHash(sa));
}
void tst_QLatin1Constant::equals()
{
// Check symmetry and dupes
QVERIFY(a == a);
QVERIFY(a == a2);
QVERIFY(a2 == a);
QVERIFY(b == b);
QVERIFY(b == b2);
QVERIFY(b2 == b2);
QVERIFY(bb == bb);
QVERIFY(bb == bb2);
QVERIFY(bb2 == bb);
QVERIFY(z == z);
QVERIFY(z == z2);
QVERIFY(z2 == z);
// Now make sure that the length is taken into account
QVERIFY(b != bb2);
QVERIFY(bb2 != b);
QVERIFY(a != z);
QVERIFY(z != a);
// and just in case something is really wrong
QVERIFY(a != b);
QVERIFY(b != a);
}
void tst_QLatin1Constant::latinaccessor()
{
QVERIFY(a.chars == a.latin1());
QVERIFY(z.latin1() == z.chars);
}
void tst_QLatin1Constant::latinEquals()
{
// Test operator== with latin1 strings
QVERIFY(a == la);
QVERIFY(la == a);
QVERIFY(a2 == la);
QVERIFY(la == a2);
QVERIFY(b == lb);
QVERIFY(lb == b);
QVERIFY(bb == lbb);
QVERIFY(lbb == bb);
QVERIFY(b != lbb);
QVERIFY(lbb != b);
QVERIFY(a != lb);
QVERIFY(lb != a);
QVERIFY(z == lz);
QVERIFY((z == ln) == (lz == ln)); // QLatin1String(0) != QLatin1String("")
QVERIFY(lz == z);
QVERIFY((ln == z) == (ln == lz));
}
void tst_QLatin1Constant::stringEquals()
{
// Test operator== with QStrings
QVERIFY(a == sa);
QVERIFY(sa == a);
QVERIFY(a2 == sa);
QVERIFY(sa == a2);
QVERIFY(b == sb);
QVERIFY(sb == b);
QVERIFY(bb == sbb);
QVERIFY(sbb == bb);
QVERIFY(b != sbb);
QVERIFY(sbb != b);
QVERIFY(a != sb);
QVERIFY(sb != a);
QVERIFY(z == sz);
QVERIFY((z == sn) == (sz == sn)); // QString(0) != QString("")
QVERIFY(sz == z);
QVERIFY((sn == z) == (sn == sz));
}
void tst_QLatin1Constant::conversion()
{
QVERIFY(charfunc("alphabet soup"));
QVERIFY(charfunc(soup.chars));
QVERIFY(charfunc(soup.latin1()));
QVERIFY(latfunc(lsoup));
QVERIFY(latreffunc(lsoup));
QVERIFY(strfunc(ssoup));
QVERIFY(strreffunc(ssoup));
// See if soup gets converted appropriately
QVERIFY(latfunc(soup));
QVERIFY(strfunc(soup));
QVERIFY(latreffunc(soup));
QVERIFY(strreffunc(soup));
QVERIFY(varfunc(soup));
// Now we also want to make sure that converting to QLatin1String doesn't copy the string
QLatin1String lsoup2 = soup; // implicit operator QLatin1String
QLatin1String lsoup3 = (QLatin1String) soup; // explicit operator QLatin1String
QLatin1String lsoup4 = QLatin1String(soup); // implicit operator QLatin1String
QVERIFY(lsoup2.latin1() == soup.latin1());
QVERIFY(lsoup3.latin1() == soup.latin1());
QVERIFY(lsoup4.latin1() == soup.latin1());
}
void tst_QLatin1Constant::overloads()
{
QVERIFY(overloaded("alphabet soup") == 1);
QVERIFY(overloaded(soup) == 7);
QVERIFY(overloaded(lsoup) == 2 || overloaded(lsoup) == 3);
QVERIFY(overloaded(ssoup) == 4 || overloaded(ssoup) == 5);
QVERIFY(overloaded2(lsoup) == 3);
QVERIFY(overloaded2(ssoup) == 4);
QCOMPARE(overloaded2(soup.latin1()), 4); // XXX grr, can't call with just soup [ambiguous], this goes to QString
QVERIFY(overloaded3(lsoup) == 3);
QCOMPARE(overloaded3(soup), 3); // XXX this goes with QLatin1String
QVERIFY(overloaded4(ssoup) == 4);
QCOMPARE(overloaded4(soup), 4); // XXX this goes with QString
}
void tst_QLatin1Constant::ordering()
{
QVERIFY(z < a);
QVERIFY(not (a < z));
QVERIFY(a < b);
QVERIFY(not (b < a));
QVERIFY(a < bb);
QVERIFY(not (bb < a));
QVERIFY(b < bb);
QVERIFY(not (bb < b));
QVERIFY(not (a < a));
QVERIFY(not (z < z));
}
QTEST_MAIN(tst_QLatin1Constant)
#include "tst_qlatin1constant.moc"
<commit_msg>Hmm. Don't use C++ operator synonyms.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qtcontactsglobal.h"
#include <QSet>
#include <QMetaType>
#include <QTypeInfo>
//TESTED_CLASS=
//TESTED_FILES=
QTM_USE_NAMESPACE
Q_DEFINE_LATIN1_CONSTANT(a, "a");
Q_DEFINE_LATIN1_CONSTANT(a2, "a");
Q_DEFINE_LATIN1_CONSTANT(b, "b");
Q_DEFINE_LATIN1_CONSTANT(b2, "b");
Q_DEFINE_LATIN1_CONSTANT(bb, "bb");
Q_DEFINE_LATIN1_CONSTANT(bb2, "bb");
Q_DEFINE_LATIN1_CONSTANT(z, "");
Q_DEFINE_LATIN1_CONSTANT(z2, "");
Q_DEFINE_LATIN1_CONSTANT(z3, "\0");
Q_DEFINE_LATIN1_CONSTANT(soup, "alphabet soup"); // but you can't have any
QLatin1String ln(0);
QLatin1String lz("");
QLatin1String la("a");
QLatin1String lb("b");
QLatin1String lbb("bb");
QLatin1String lsoup("alphabet soup");
QString sn;
QString sz("");
QString sa(la);
QString sb(lb);
QString sbb(lbb);
QString ssoup("alphabet soup");
class tst_QLatin1Constant: public QObject
{
Q_OBJECT
public:
tst_QLatin1Constant();
virtual ~tst_QLatin1Constant();
// Overload testers
int overloaded(const char *) {return 1;}
//int overloaded(const QLatin1String& ) {return 2;}
int overloaded(QLatin1String ) {return 3;}
int overloaded(const QString& ) {return 4;}
//int overloaded(QString ){return 5;}
//template<int N> int overloaded(const QLatin1Constant<N>& ) {return 6;}
template<int N> int overloaded(QLatin1Constant<N> ) {return 7;}
int overloaded(const QVariant&) {return 8;}
// More overload testers
int overloaded2(QLatin1String) {return 3;}
int overloaded2(const QString&) {return 4;}
int overloaded3(const char*) {return 1;}
int overloaded3(QLatin1String) {return 3;}
int overloaded4(const char*) {return 1;}
int overloaded4(const QString&) {return 4;}
// Conversion testers
bool charfunc(const char* str) {return qstrcmp(str, "alphabet soup") == 0;}
bool latfunc(QLatin1String lat) {return qstrcmp(lat.latin1(), "alphabet soup") == 0;}
bool latreffunc(const QLatin1String& lat) {return qstrcmp(lat.latin1(), "alphabet soup") == 0;}
bool strfunc(QString str) {return str == QString::fromAscii("alphabet soup");}
bool strreffunc(const QString& str) {return str == QString::fromAscii("alphabet soup");}
bool varfunc(const QVariant& var) {return (var.type() == QVariant::String) && var.toString() == QString::fromAscii("alphabet soup");}
private slots:
void hash();
void conversion();
void overloads();
void equals();
void latinEquals();
void stringEquals();
void ordering();
void latinaccessor();
};
tst_QLatin1Constant::tst_QLatin1Constant()
{
}
tst_QLatin1Constant::~tst_QLatin1Constant()
{
}
void tst_QLatin1Constant::hash()
{
// Test that if a == b, hash(a) == hash(b)
// (also for ===)
QVERIFY(qHash(a) == qHash(a));
QVERIFY(qHash(a) == qHash(a2));
QVERIFY(qHash(b) == qHash(b));
QVERIFY(qHash(b) == qHash(b));
QVERIFY(qHash(bb) == qHash(bb));
QVERIFY(qHash(bb) == qHash(bb));
// As a convenience, make sure that hashing
// the same string gives the same results
// no matter the storage
QVERIFY(qHash(a) == qHash(la));
QVERIFY(qHash(a) == qHash(sa));
}
void tst_QLatin1Constant::equals()
{
// Check symmetry and dupes
QVERIFY(a == a);
QVERIFY(a == a2);
QVERIFY(a2 == a);
QVERIFY(b == b);
QVERIFY(b == b2);
QVERIFY(b2 == b2);
QVERIFY(bb == bb);
QVERIFY(bb == bb2);
QVERIFY(bb2 == bb);
QVERIFY(z == z);
QVERIFY(z == z2);
QVERIFY(z2 == z);
// Now make sure that the length is taken into account
QVERIFY(b != bb2);
QVERIFY(bb2 != b);
QVERIFY(a != z);
QVERIFY(z != a);
// and just in case something is really wrong
QVERIFY(a != b);
QVERIFY(b != a);
}
void tst_QLatin1Constant::latinaccessor()
{
QVERIFY(a.chars == a.latin1());
QVERIFY(z.latin1() == z.chars);
}
void tst_QLatin1Constant::latinEquals()
{
// Test operator== with latin1 strings
QVERIFY(a == la);
QVERIFY(la == a);
QVERIFY(a2 == la);
QVERIFY(la == a2);
QVERIFY(b == lb);
QVERIFY(lb == b);
QVERIFY(bb == lbb);
QVERIFY(lbb == bb);
QVERIFY(b != lbb);
QVERIFY(lbb != b);
QVERIFY(a != lb);
QVERIFY(lb != a);
QVERIFY(z == lz);
QVERIFY((z == ln) == (lz == ln)); // QLatin1String(0) != QLatin1String("")
QVERIFY(lz == z);
QVERIFY((ln == z) == (ln == lz));
}
void tst_QLatin1Constant::stringEquals()
{
// Test operator== with QStrings
QVERIFY(a == sa);
QVERIFY(sa == a);
QVERIFY(a2 == sa);
QVERIFY(sa == a2);
QVERIFY(b == sb);
QVERIFY(sb == b);
QVERIFY(bb == sbb);
QVERIFY(sbb == bb);
QVERIFY(b != sbb);
QVERIFY(sbb != b);
QVERIFY(a != sb);
QVERIFY(sb != a);
QVERIFY(z == sz);
QVERIFY((z == sn) == (sz == sn)); // QString(0) != QString("")
QVERIFY(sz == z);
QVERIFY((sn == z) == (sn == sz));
}
void tst_QLatin1Constant::conversion()
{
QVERIFY(charfunc("alphabet soup"));
QVERIFY(charfunc(soup.chars));
QVERIFY(charfunc(soup.latin1()));
QVERIFY(latfunc(lsoup));
QVERIFY(latreffunc(lsoup));
QVERIFY(strfunc(ssoup));
QVERIFY(strreffunc(ssoup));
// See if soup gets converted appropriately
QVERIFY(latfunc(soup));
QVERIFY(strfunc(soup));
QVERIFY(latreffunc(soup));
QVERIFY(strreffunc(soup));
QVERIFY(varfunc(soup));
// Now we also want to make sure that converting to QLatin1String doesn't copy the string
QLatin1String lsoup2 = soup; // implicit operator QLatin1String
QLatin1String lsoup3 = (QLatin1String) soup; // explicit operator QLatin1String
QLatin1String lsoup4 = QLatin1String(soup); // implicit operator QLatin1String
QVERIFY(lsoup2.latin1() == soup.latin1());
QVERIFY(lsoup3.latin1() == soup.latin1());
QVERIFY(lsoup4.latin1() == soup.latin1());
}
void tst_QLatin1Constant::overloads()
{
QVERIFY(overloaded("alphabet soup") == 1);
QVERIFY(overloaded(soup) == 7);
QVERIFY(overloaded(lsoup) == 2 || overloaded(lsoup) == 3);
QVERIFY(overloaded(ssoup) == 4 || overloaded(ssoup) == 5);
QVERIFY(overloaded2(lsoup) == 3);
QVERIFY(overloaded2(ssoup) == 4);
QCOMPARE(overloaded2(soup.latin1()), 4); // XXX grr, can't call with just soup [ambiguous], this goes to QString
QVERIFY(overloaded3(lsoup) == 3);
QCOMPARE(overloaded3(soup), 3); // XXX this goes with QLatin1String
QVERIFY(overloaded4(ssoup) == 4);
QCOMPARE(overloaded4(soup), 4); // XXX this goes with QString
}
void tst_QLatin1Constant::ordering()
{
QVERIFY(z < a);
QVERIFY(!(a < z));
QVERIFY(a < b);
QVERIFY(!(b < a));
QVERIFY(a < bb);
QVERIFY(!(bb < a));
QVERIFY(b < bb);
QVERIFY(!(bb < b));
QVERIFY(!(a < a));
QVERIFY(!(z < z));
}
QTEST_MAIN(tst_QLatin1Constant)
#include "tst_qlatin1constant.moc"
<|endoftext|> |
<commit_before>/// \file dtscfix.cpp
/// Contains the code that will attempt to fix the metadata contained in an DTSC file.
#include <string>
#include <mist/dtsc.h>
#include <mist/json.h>
#include <mist/config.h>
///\brief Holds everything unique to converters.
namespace Converters {
class HeaderEntryDTSC {
public:
HeaderEntryDTSC() : totalSize(0), lastKeyTime(-5001), trackID(0), firstms(0x7FFFFFFF), lastms(0), keynum(0) {}
long long int totalSize;
std::vector<long long int> parts;
long long int lastKeyTime;
long long int trackID;
long long int firstms;
long long int lastms;
long long int keynum;
std::string type;
};
///\brief Reads a DTSC file and attempts to fix the metadata in it.
///\param conf The current configuration of the program.
///\return The return code for the fixed program.
int DTSCFix(Util::Config & conf){
DTSC::File F(conf.getString("filename"));
F.seek_bpos(0);
F.parseNext();
JSON::Value oriheader = F.getJSON();
JSON::Value meta = F.getMeta();
JSON::Value pack;
if ( !oriheader.isMember("moreheader")){
std::cerr << "This file is too old to fix - please reconvert." << std::endl;
return 1;
}
if (oriheader["moreheader"].asInt() > 0 && !conf.getBool("force")){
if (meta.isMember("tracks") && meta["tracks"].size() > 0){
bool isFixed = true;
for ( JSON::ObjIter trackIt = meta["tracks"].ObjBegin(); trackIt != meta["tracks"].ObjEnd(); trackIt ++) {
if ( !trackIt->second.isMember("frags") || !trackIt->second.isMember("keynum")){
isFixed = false;
}
}
if (isFixed){
std::cerr << "This file was already fixed or doesn't need fixing - cancelling." << std::endl;
return 0;
}
}
}
meta.removeMember("isFixed");
meta.removeMember("keytime");
meta.removeMember("keybpos");
meta.removeMember("moreheader");
std::map<std::string,int> trackIDs;
std::map<std::string,HeaderEntryDTSC> trackData;
long long int nowpack = 0;
std::string currentID;
int nextFreeID = 0;
for (JSON::ObjIter it = meta["tracks"].ObjBegin(); it != meta["tracks"].ObjEnd(); it++){
trackIDs.insert(std::pair<std::string,int>(it->first,it->second["trackid"].asInt()));
trackData[it->first].type = it->second["type"].asString();
trackData[it->first].trackID = it->second["trackid"].asInt();
trackData[it->first].type = it->second["type"].asString();
if (it->second["trackid"].asInt() >= nextFreeID){
nextFreeID = it->second["trackid"].asInt() + 1;
}
it->second.removeMember("keylen");
it->second.removeMember("keybpos");
it->second.removeMember("frags");
it->second.removeMember("keytime");
it->second.removeMember("keynum");
it->second.removeMember("keydata");
it->second.removeMember("keyparts");
it->second.removeMember("keys");
}
F.parseNext();
while ( !F.getJSON().isNull()){
currentID = "";
if (F.getJSON()["trackid"].asInt() == 0){
if (F.getJSON()["datatype"].asString() == "video"){
currentID = "video0";
if (trackData[currentID].trackID == 0){
trackData[currentID].trackID = nextFreeID++;
}
if (meta.isMember("video")){
meta["tracks"][currentID] = meta["video"];
meta.removeMember("video");
}
trackData[currentID].type = F.getJSON()["datatype"].asString();
}else{
if (F.getJSON()["datatype"].asString() == "audio"){
currentID = "audio0";
if (trackData[currentID].trackID == 0){
trackData[currentID].trackID = nextFreeID++;
}
if (meta.isMember("audio")){
meta["tracks"][currentID] = meta["audio"];
meta.removeMember("audio");
}
trackData[currentID].type = F.getJSON()["datatype"].asString();
}else{
//fprintf(stderr, "Found an unknown package with packetid 0 and datatype %s\n",F.getJSON()["datatype"].asString().c_str());
F.parseNext();
continue;
}
}
}else{
for( std::map<std::string,int>::iterator it = trackIDs.begin(); it != trackIDs.end(); it++ ) {
if( it->second == F.getJSON()["trackid"].asInt() ) {
currentID = it->first;
break;
}
}
if( currentID == "" ) {
//fprintf(stderr, "Found an unknown v2 packet with id %d\n", F.getJSON()["trackid"].asInt());
F.parseNext();
continue;
//should create new track but this shouldnt be needed...
}
}
if (F.getJSON()["time"].asInt() < trackData[currentID].firstms){
trackData[currentID].firstms = F.getJSON()["time"].asInt();
}
if (F.getJSON()["time"].asInt() >= nowpack){
nowpack = F.getJSON()["time"].asInt();
}
if (trackData[currentID].type == "video"){
if (F.getJSON().isMember("keyframe")){
int newNum = meta["tracks"][currentID]["keys"].size();
meta["tracks"][currentID]["keys"][newNum]["num"] = ++trackData[currentID].keynum;
meta["tracks"][currentID]["keys"][newNum]["time"] = F.getJSON()["time"];
meta["tracks"][currentID]["keys"][newNum]["bpos"] = F.getLastReadPos();
if (meta["tracks"][currentID]["keys"].size() > 1){
meta["tracks"][currentID]["keys"][newNum - 1]["len"] = F.getJSON()["time"].asInt() - meta["tracks"][currentID]["keys"][newNum - 1]["time"].asInt();
meta["tracks"][currentID]["keys"][newNum - 1]["size"] = trackData[currentID].totalSize;
trackData[currentID].totalSize = 0;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts );
meta["tracks"][currentID]["keys"][newNum - 1]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][newNum - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
trackData[currentID].parts.clear();
}
}
}else{
if ((F.getJSON()["time"].asInt() - trackData[currentID].lastKeyTime) > 5000){
trackData[currentID].lastKeyTime = F.getJSON()["time"].asInt();
int newNum = meta["tracks"][currentID]["keys"].size();
meta["tracks"][currentID]["keys"][newNum]["num"] = ++trackData[currentID].keynum;
meta["tracks"][currentID]["keys"][newNum]["time"] = F.getJSON()["time"];
meta["tracks"][currentID]["keys"][newNum]["bpos"] = F.getLastReadPos();
if (meta["tracks"][currentID]["keys"].size() > 1){
meta["tracks"][currentID]["keys"][newNum - 1]["len"] = F.getJSON()["time"].asInt() - meta["tracks"][currentID]["keys"][newNum - 1]["time"].asInt();
meta["tracks"][currentID]["keys"][newNum - 1]["size"] = trackData[currentID].totalSize;
trackData[currentID].totalSize = 0;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts );
meta["tracks"][currentID]["keys"][newNum - 1]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][newNum - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
trackData[currentID].parts.clear();
}
}
}
trackData[currentID].totalSize += F.getJSON()["data"].asString().size();
trackData[currentID].lastms = nowpack;
trackData[currentID].parts.push_back(F.getJSON()["data"].asString().size());
F.parseNext();
}
long long int firstms = 0x7fffffff;
long long int lastms = -1;
for (std::map<std::string,HeaderEntryDTSC>::iterator it = trackData.begin(); it != trackData.end(); it++){
if (it->second.firstms < firstms){
firstms = it->second.firstms;
}
if (it->second.lastms > lastms){
lastms = it->second.lastms;
}
meta["tracks"][it->first]["firstms"] = it->second.firstms;
meta["tracks"][it->first]["lastms"] = it->second.lastms;
meta["tracks"][it->first]["length"] = (it->second.lastms - it->second.firstms) / 1000;
if ( !meta["tracks"][it->first].isMember("bps")){
meta["tracks"][it->first]["bps"] = (long long int)(it->second.lastms / ((it->second.lastms - it->second.firstms) / 1000));
}
if (it->second.trackID != 0){
meta["tracks"][it->first]["trackid"] = trackIDs[it->first];
}else{
meta["tracks"][it->first]["trackid"] = nextFreeID ++;
}
meta["tracks"][it->first]["type"] = it->second.type;
int tmp = meta["tracks"][it->first]["keys"].size();
if (tmp > 0){
if (tmp > 1){
meta["tracks"][it->first]["keys"][tmp - 1]["len"] = it->second.lastms - meta["tracks"][it->first]["keys"][tmp - 2]["time"].asInt();
}else{
meta["tracks"][it->first]["keys"][tmp - 1]["len"] = it->second.lastms;
}
meta["tracks"][it->first]["keys"][tmp - 1]["size"] = it->second.totalSize;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
meta["tracks"][currentID]["keys"][tmp - 1]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][tmp - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
}else{
meta["tracks"][it->first]["keys"][tmp]["len"] = it->second.lastms;
meta["tracks"][it->first]["keys"][tmp]["size"] = it->second.totalSize;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
meta["tracks"][currentID]["keys"][tmp]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][tmp]["partsize"] = (long long int)trackData[currentID].parts.size();
}
//calculate fragments
meta["tracks"][it->first]["frags"].null();
long long int currFrag = -1;
long long int maxBps = 0;
for (JSON::ArrIter arrIt = meta["tracks"][it->first]["keys"].ArrBegin(); arrIt != meta["tracks"][it->first]["keys"].ArrEnd(); arrIt++) {
if ((*arrIt)["time"].asInt() / 10000 > currFrag){
currFrag = (*arrIt)["time"].asInt() / 10000;
long long int fragLen = 1;
long long int fragDur = (*arrIt)["len"].asInt();
long long int fragSize = (*arrIt)["size"].asInt();
for (JSON::ArrIter it2 = arrIt + 1; it2 != meta["tracks"][it->first]["keys"].ArrEnd(); it2++){
if ((*it2)["time"].asInt() / 10000 > currFrag || (it2 + 1) == meta["tracks"][it->first]["keys"].ArrEnd()){
JSON::Value thisFrag;
thisFrag["num"] = (*arrIt)["num"].asInt();
thisFrag["time"] = (*arrIt)["time"].asInt();
thisFrag["len"] = fragLen;
thisFrag["dur"] = fragDur;
thisFrag["size"] = fragSize;
if (fragDur / 1000){
thisFrag["bps"] = fragSize / (fragDur / 1000);
if (maxBps < (fragSize / (fragDur / 1000))){
maxBps = (fragSize / (fragDur / 999));
}
} else {
thisFrag["bps"] = 1;
}
meta["tracks"][it->first]["frags"].append(thisFrag);
break;
}
fragLen ++;
fragDur += (*it2)["len"].asInt();
fragSize += (*it2)["size"].asInt();
}
}
}
meta["tracks"][it->first]["maxbps"] = maxBps;
}
meta["firstms"] = firstms;
meta["lastms"] = lastms;
meta["length"] = (lastms - firstms) / 1000;
//append the revised header
std::string loader = meta.toPacked();
long long int newHPos = F.addHeader(loader);
if ( !newHPos){
std::cerr << "Failure appending new header." << std::endl;
return -1;
}
//re-write the original header with information about the location of the new one
oriheader["moreheader"] = newHPos;
loader = oriheader.toPacked();
if (F.writeHeader(loader)){
return 0;
}else{
std::cerr << "Failure rewriting header." << std::endl;
return -1;
}
} //DTSCFix
}
/// Entry point for DTSCFix, simply calls Converters::DTSCFix().
int main(int argc, char ** argv){
Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);
conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"arg\":\"string\", \"help\":\"Filename of the file to attempt to fix.\"}"));
conf.addOption("force", JSON::fromString("{\"short\":\"f\", \"long\":\"force\", \"default\":0, \"help\":\"Force fixing.\"}"));
conf.parseArgs(argc, argv);
return Converters::DTSCFix(conf);
} //main
<commit_msg>Switched DTSCFix to use template based encodeVector<commit_after>/// \file dtscfix.cpp
/// Contains the code that will attempt to fix the metadata contained in an DTSC file.
#include <string>
#include <mist/dtsc.h>
#include <mist/json.h>
#include <mist/config.h>
///\brief Holds everything unique to converters.
namespace Converters {
class HeaderEntryDTSC {
public:
HeaderEntryDTSC() : totalSize(0), lastKeyTime(-5001), trackID(0), firstms(0x7FFFFFFF), lastms(0), keynum(0) {}
long long int totalSize;
std::vector<long long int> parts;
long long int lastKeyTime;
long long int trackID;
long long int firstms;
long long int lastms;
long long int keynum;
std::string type;
};
///\brief Reads a DTSC file and attempts to fix the metadata in it.
///\param conf The current configuration of the program.
///\return The return code for the fixed program.
int DTSCFix(Util::Config & conf){
DTSC::File F(conf.getString("filename"));
F.seek_bpos(0);
F.parseNext();
JSON::Value oriheader = F.getJSON();
JSON::Value meta = F.getMeta();
JSON::Value pack;
if ( !oriheader.isMember("moreheader")){
std::cerr << "This file is too old to fix - please reconvert." << std::endl;
return 1;
}
if (oriheader["moreheader"].asInt() > 0 && !conf.getBool("force")){
if (meta.isMember("tracks") && meta["tracks"].size() > 0){
bool isFixed = true;
for ( JSON::ObjIter trackIt = meta["tracks"].ObjBegin(); trackIt != meta["tracks"].ObjEnd(); trackIt ++) {
if ( !trackIt->second.isMember("frags") || !trackIt->second.isMember("keynum")){
isFixed = false;
}
}
if (isFixed){
std::cerr << "This file was already fixed or doesn't need fixing - cancelling." << std::endl;
return 0;
}
}
}
meta.removeMember("isFixed");
meta.removeMember("keytime");
meta.removeMember("keybpos");
meta.removeMember("moreheader");
std::map<std::string,int> trackIDs;
std::map<std::string,HeaderEntryDTSC> trackData;
long long int nowpack = 0;
std::string currentID;
int nextFreeID = 0;
for (JSON::ObjIter it = meta["tracks"].ObjBegin(); it != meta["tracks"].ObjEnd(); it++){
trackIDs.insert(std::pair<std::string,int>(it->first,it->second["trackid"].asInt()));
trackData[it->first].type = it->second["type"].asString();
trackData[it->first].trackID = it->second["trackid"].asInt();
trackData[it->first].type = it->second["type"].asString();
if (it->second["trackid"].asInt() >= nextFreeID){
nextFreeID = it->second["trackid"].asInt() + 1;
}
it->second.removeMember("keylen");
it->second.removeMember("keybpos");
it->second.removeMember("frags");
it->second.removeMember("keytime");
it->second.removeMember("keynum");
it->second.removeMember("keydata");
it->second.removeMember("keyparts");
it->second.removeMember("keys");
}
F.parseNext();
while ( !F.getJSON().isNull()){
currentID = "";
if (F.getJSON()["trackid"].asInt() == 0){
if (F.getJSON()["datatype"].asString() == "video"){
currentID = "video0";
if (trackData[currentID].trackID == 0){
trackData[currentID].trackID = nextFreeID++;
}
if (meta.isMember("video")){
meta["tracks"][currentID] = meta["video"];
meta.removeMember("video");
}
trackData[currentID].type = F.getJSON()["datatype"].asString();
}else{
if (F.getJSON()["datatype"].asString() == "audio"){
currentID = "audio0";
if (trackData[currentID].trackID == 0){
trackData[currentID].trackID = nextFreeID++;
}
if (meta.isMember("audio")){
meta["tracks"][currentID] = meta["audio"];
meta.removeMember("audio");
}
trackData[currentID].type = F.getJSON()["datatype"].asString();
}else{
//fprintf(stderr, "Found an unknown package with packetid 0 and datatype %s\n",F.getJSON()["datatype"].asString().c_str());
F.parseNext();
continue;
}
}
}else{
for( std::map<std::string,int>::iterator it = trackIDs.begin(); it != trackIDs.end(); it++ ) {
if( it->second == F.getJSON()["trackid"].asInt() ) {
currentID = it->first;
break;
}
}
if( currentID == "" ) {
//fprintf(stderr, "Found an unknown v2 packet with id %d\n", F.getJSON()["trackid"].asInt());
F.parseNext();
continue;
//should create new track but this shouldnt be needed...
}
}
if (F.getJSON()["time"].asInt() < trackData[currentID].firstms){
trackData[currentID].firstms = F.getJSON()["time"].asInt();
}
if (F.getJSON()["time"].asInt() >= nowpack){
nowpack = F.getJSON()["time"].asInt();
}
if (trackData[currentID].type == "video"){
if (F.getJSON().isMember("keyframe")){
int newNum = meta["tracks"][currentID]["keys"].size();
meta["tracks"][currentID]["keys"][newNum]["num"] = ++trackData[currentID].keynum;
meta["tracks"][currentID]["keys"][newNum]["time"] = F.getJSON()["time"];
meta["tracks"][currentID]["keys"][newNum]["bpos"] = F.getLastReadPos();
if (meta["tracks"][currentID]["keys"].size() > 1){
meta["tracks"][currentID]["keys"][newNum - 1]["len"] = F.getJSON()["time"].asInt() - meta["tracks"][currentID]["keys"][newNum - 1]["time"].asInt();
meta["tracks"][currentID]["keys"][newNum - 1]["size"] = trackData[currentID].totalSize;
trackData[currentID].totalSize = 0;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
meta["tracks"][currentID]["keys"][newNum - 1]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][newNum - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
trackData[currentID].parts.clear();
}
}
}else{
if ((F.getJSON()["time"].asInt() - trackData[currentID].lastKeyTime) > 5000){
trackData[currentID].lastKeyTime = F.getJSON()["time"].asInt();
int newNum = meta["tracks"][currentID]["keys"].size();
meta["tracks"][currentID]["keys"][newNum]["num"] = ++trackData[currentID].keynum;
meta["tracks"][currentID]["keys"][newNum]["time"] = F.getJSON()["time"];
meta["tracks"][currentID]["keys"][newNum]["bpos"] = F.getLastReadPos();
if (meta["tracks"][currentID]["keys"].size() > 1){
meta["tracks"][currentID]["keys"][newNum - 1]["len"] = F.getJSON()["time"].asInt() - meta["tracks"][currentID]["keys"][newNum - 1]["time"].asInt();
meta["tracks"][currentID]["keys"][newNum - 1]["size"] = trackData[currentID].totalSize;
trackData[currentID].totalSize = 0;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
meta["tracks"][currentID]["keys"][newNum - 1]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][newNum - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
trackData[currentID].parts.clear();
}
}
}
trackData[currentID].totalSize += F.getJSON()["data"].asString().size();
trackData[currentID].lastms = nowpack;
trackData[currentID].parts.push_back(F.getJSON()["data"].asString().size());
F.parseNext();
}
long long int firstms = 0x7fffffff;
long long int lastms = -1;
for (std::map<std::string,HeaderEntryDTSC>::iterator it = trackData.begin(); it != trackData.end(); it++){
if (it->second.firstms < firstms){
firstms = it->second.firstms;
}
if (it->second.lastms > lastms){
lastms = it->second.lastms;
}
meta["tracks"][it->first]["firstms"] = it->second.firstms;
meta["tracks"][it->first]["lastms"] = it->second.lastms;
meta["tracks"][it->first]["length"] = (it->second.lastms - it->second.firstms) / 1000;
if ( !meta["tracks"][it->first].isMember("bps")){
meta["tracks"][it->first]["bps"] = (long long int)(it->second.lastms / ((it->second.lastms - it->second.firstms) / 1000));
}
if (it->second.trackID != 0){
meta["tracks"][it->first]["trackid"] = trackIDs[it->first];
}else{
meta["tracks"][it->first]["trackid"] = nextFreeID ++;
}
meta["tracks"][it->first]["type"] = it->second.type;
int tmp = meta["tracks"][it->first]["keys"].size();
if (tmp > 0){
if (tmp > 1){
meta["tracks"][it->first]["keys"][tmp - 1]["len"] = it->second.lastms - meta["tracks"][it->first]["keys"][tmp - 2]["time"].asInt();
}else{
meta["tracks"][it->first]["keys"][tmp - 1]["len"] = it->second.lastms;
}
meta["tracks"][it->first]["keys"][tmp - 1]["size"] = it->second.totalSize;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
meta["tracks"][currentID]["keys"][tmp - 1]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][tmp - 1]["partsize"] = (long long int)trackData[currentID].parts.size();
}else{
meta["tracks"][it->first]["keys"][tmp]["len"] = it->second.lastms;
meta["tracks"][it->first]["keys"][tmp]["size"] = it->second.totalSize;
std::string encodeVec = JSON::encodeVector( trackData[currentID].parts.begin(), trackData[currentID].parts.end() );
meta["tracks"][currentID]["keys"][tmp]["parts"] = encodeVec;
meta["tracks"][currentID]["keys"][tmp]["partsize"] = (long long int)trackData[currentID].parts.size();
}
//calculate fragments
meta["tracks"][it->first]["frags"].null();
long long int currFrag = -1;
long long int maxBps = 0;
for (JSON::ArrIter arrIt = meta["tracks"][it->first]["keys"].ArrBegin(); arrIt != meta["tracks"][it->first]["keys"].ArrEnd(); arrIt++) {
if ((*arrIt)["time"].asInt() / 10000 > currFrag){
currFrag = (*arrIt)["time"].asInt() / 10000;
long long int fragLen = 1;
long long int fragDur = (*arrIt)["len"].asInt();
long long int fragSize = (*arrIt)["size"].asInt();
for (JSON::ArrIter it2 = arrIt + 1; it2 != meta["tracks"][it->first]["keys"].ArrEnd(); it2++){
if ((*it2)["time"].asInt() / 10000 > currFrag || (it2 + 1) == meta["tracks"][it->first]["keys"].ArrEnd()){
JSON::Value thisFrag;
thisFrag["num"] = (*arrIt)["num"].asInt();
thisFrag["time"] = (*arrIt)["time"].asInt();
thisFrag["len"] = fragLen;
thisFrag["dur"] = fragDur;
thisFrag["size"] = fragSize;
if (fragDur / 1000){
thisFrag["bps"] = fragSize / (fragDur / 1000);
if (maxBps < (fragSize / (fragDur / 1000))){
maxBps = (fragSize / (fragDur / 999));
}
} else {
thisFrag["bps"] = 1;
}
meta["tracks"][it->first]["frags"].append(thisFrag);
break;
}
fragLen ++;
fragDur += (*it2)["len"].asInt();
fragSize += (*it2)["size"].asInt();
}
}
}
meta["tracks"][it->first]["maxbps"] = maxBps;
}
meta["firstms"] = firstms;
meta["lastms"] = lastms;
meta["length"] = (lastms - firstms) / 1000;
//append the revised header
std::string loader = meta.toPacked();
long long int newHPos = F.addHeader(loader);
if ( !newHPos){
std::cerr << "Failure appending new header." << std::endl;
return -1;
}
//re-write the original header with information about the location of the new one
oriheader["moreheader"] = newHPos;
loader = oriheader.toPacked();
if (F.writeHeader(loader)){
return 0;
}else{
std::cerr << "Failure rewriting header." << std::endl;
return -1;
}
} //DTSCFix
}
/// Entry point for DTSCFix, simply calls Converters::DTSCFix().
int main(int argc, char ** argv){
Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION);
conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"arg\":\"string\", \"help\":\"Filename of the file to attempt to fix.\"}"));
conf.addOption("force", JSON::fromString("{\"short\":\"f\", \"long\":\"force\", \"default\":0, \"help\":\"Force fixing.\"}"));
conf.parseArgs(argc, argv);
return Converters::DTSCFix(conf);
} //main
<|endoftext|> |
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP
#define OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP
#include <cuda_runtime.h>
#include "math.hpp"
namespace cv { namespace dnn { namespace cuda4dnn { namespace kernels {
template <class T>
struct abs_functor {
__device__ T operator()(T value) {
using csl::device::abs;
return abs(value);
}
};
template <class T>
struct tanh_functor {
__device__ T operator()(T value) {
using csl::device::tanh;
return tanh(value);
}
};
template <class T>
struct swish_functor {
__device__ T operator()(T value) {
// f(x) = x * sigmoid(x)
using csl::device::fast_divide;
using csl::device::fast_exp;
return fast_divide(value, static_cast<T>(1) + fast_exp(-value));
}
};
template <class T>
struct mish_functor {
__device__ T operator()(T value) {
using csl::device::tanh;
using csl::device::log1pexp;
return value * tanh(log1pexp(value));
}
};
template <>
struct mish_functor<float> {
__device__ float operator()(float value) {
// f(x) = x * tanh(log1pexp(x));
using csl::device::fast_divide;
using csl::device::fast_exp;
auto e = fast_exp(value);
if (value <= -18.0f)
return value * e;
auto n = e * e + 2 * e;
if (value <= -5.0f)
return value * fast_divide(n, n + 2);
return value - 2 * fast_divide(value, n + 2);
}
};
template <class T>
struct sigmoid_functor {
__device__ T operator()(T value) {
using csl::device::fast_sigmoid;
return fast_sigmoid(value);
}
};
template <class T>
struct bnll_functor {
__device__ T operator()(T value) {
using csl::device::log1pexp;
return value > T(0) ? value + log1pexp(-value) : log1pexp(value);
}
};
template <class T>
struct elu_functor {
__device__ T operator()(T value) {
using csl::device::expm1;
return value >= T(0) ? value : expm1(value);
}
};
template <class T>
struct relu_functor {
__device__ relu_functor(T slope_) : slope{slope_} { }
__device__ T operator()(T value) {
using csl::device::log1pexp;
return value >= T(0) ? value : slope * value;
}
T slope;
};
template <class T>
struct clipped_relu_functor {
__device__ clipped_relu_functor(T floor_, T ceiling_) : floor{floor_}, ceiling{ceiling_} { }
__device__ T operator()(T value) {
using csl::device::clamp;
return clamp(value, floor, ceiling);
}
T floor, ceiling;
};
template <class T>
struct power_functor {
__device__ power_functor(T exp_, T scale_, T shift_) : exp{exp_}, scale{scale_}, shift{shift_} { }
__device__ T operator()(T value) {
using csl::device::pow;
return pow(shift + scale * value, exp);
}
T exp, scale, shift;
};
template <class T>
struct max_functor {
__device__ T operator()(T x, T y) {
using csl::device::max;
return max(x, y);
}
};
template <class T>
struct sum_functor {
__device__ T operator()(T x, T y) { return x + y; }
};
template <class T>
struct scaled_sum_functor {
__device__ scaled_sum_functor(T scale_x_, T scale_y_)
: scale_x{scale_x_}, scale_y{scale_y_} { }
__device__ T operator()(T x, T y) { return scale_x * x + scale_y * y; }
T scale_x, scale_y;
};
template <class T>
struct product_functor {
__device__ T operator()(T x, T y) { return x * y; }
};
template <class T>
struct div_functor {
__device__ T operator()(T x, T y) { return x / y; }
};
}}}} /* namespace cv::dnn::cuda4dnn::kernels */
#endif /* OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP */<commit_msg>improve mish performance and accuracy<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP
#define OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP
#include <cuda_runtime.h>
#include "math.hpp"
namespace cv { namespace dnn { namespace cuda4dnn { namespace kernels {
template <class T>
struct abs_functor {
__device__ T operator()(T value) {
using csl::device::abs;
return abs(value);
}
};
template <class T>
struct tanh_functor {
__device__ T operator()(T value) {
using csl::device::tanh;
return tanh(value);
}
};
template <class T>
struct swish_functor {
__device__ T operator()(T value) {
// f(x) = x * sigmoid(x)
using csl::device::fast_divide;
using csl::device::fast_exp;
return fast_divide(value, static_cast<T>(1) + fast_exp(-value));
}
};
template <class T>
struct mish_functor {
__device__ T operator()(T value) {
using csl::device::tanh;
using csl::device::log1pexp;
return value * tanh(log1pexp(value));
}
};
template <>
struct mish_functor<float> {
__device__ float operator()(float value) {
// f(x) = x * tanh(log1pexp(x));
using csl::device::fast_divide;
using csl::device::fast_exp;
auto e = fast_exp(value);
auto n = e * e + 2 * e;
if (value <= -0.6f)
return value * fast_divide(n, n + 2);
return value - 2 * fast_divide(value, n + 2);
}
};
template <class T>
struct sigmoid_functor {
__device__ T operator()(T value) {
using csl::device::fast_sigmoid;
return fast_sigmoid(value);
}
};
template <class T>
struct bnll_functor {
__device__ T operator()(T value) {
using csl::device::log1pexp;
return value > T(0) ? value + log1pexp(-value) : log1pexp(value);
}
};
template <class T>
struct elu_functor {
__device__ T operator()(T value) {
using csl::device::expm1;
return value >= T(0) ? value : expm1(value);
}
};
template <class T>
struct relu_functor {
__device__ relu_functor(T slope_) : slope{slope_} { }
__device__ T operator()(T value) {
using csl::device::log1pexp;
return value >= T(0) ? value : slope * value;
}
T slope;
};
template <class T>
struct clipped_relu_functor {
__device__ clipped_relu_functor(T floor_, T ceiling_) : floor{floor_}, ceiling{ceiling_} { }
__device__ T operator()(T value) {
using csl::device::clamp;
return clamp(value, floor, ceiling);
}
T floor, ceiling;
};
template <class T>
struct power_functor {
__device__ power_functor(T exp_, T scale_, T shift_) : exp{exp_}, scale{scale_}, shift{shift_} { }
__device__ T operator()(T value) {
using csl::device::pow;
return pow(shift + scale * value, exp);
}
T exp, scale, shift;
};
template <class T>
struct max_functor {
__device__ T operator()(T x, T y) {
using csl::device::max;
return max(x, y);
}
};
template <class T>
struct sum_functor {
__device__ T operator()(T x, T y) { return x + y; }
};
template <class T>
struct scaled_sum_functor {
__device__ scaled_sum_functor(T scale_x_, T scale_y_)
: scale_x{scale_x_}, scale_y{scale_y_} { }
__device__ T operator()(T x, T y) { return scale_x * x + scale_y * y; }
T scale_x, scale_y;
};
template <class T>
struct product_functor {
__device__ T operator()(T x, T y) { return x * y; }
};
template <class T>
struct div_functor {
__device__ T operator()(T x, T y) { return x / y; }
};
}}}} /* namespace cv::dnn::cuda4dnn::kernels */
#endif /* OPENCV_DNN_SRC_CUDA_FUNCTORS_HPP */<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "ep_engine.h"
#include "connmap.h"
#include "dcp-backfill-manager.h"
#include "dcp-backfill.h"
#include "dcp-producer.h"
class BackfillManagerTask : public GlobalTask {
public:
BackfillManagerTask(EventuallyPersistentEngine* e, connection_t c,
const Priority &p, double sleeptime = 0,
bool shutdown = false)
: GlobalTask(e, p, sleeptime, shutdown), conn(c) {}
bool run();
std::string getDescription();
private:
connection_t conn;
static const size_t sleepTime;
};
const size_t BackfillManagerTask::sleepTime = 1;
bool BackfillManagerTask::run() {
DcpProducer* producer = static_cast<DcpProducer*>(conn.get());
if (producer->doDisconnect()) {
return false;
}
backfill_status_t status = producer->getBackfillManager()->backfill();
if (status == backfill_finished) {
return false;
} else if (status == backfill_snooze) {
snooze(sleepTime);
}
if (engine->getEpStats().isShutdown) {
return false;
}
return true;
}
std::string BackfillManagerTask::getDescription() {
std::stringstream ss;
ss << "Backfilling items for " << conn->getName();
return ss.str();
}
BackfillManager::BackfillManager(EventuallyPersistentEngine* e, connection_t c)
: engine(e), conn(c), taskId(0) {
Configuration& config = e->getConfiguration();
scanBuffer.bytesRead = 0;
scanBuffer.itemsRead = 0;
scanBuffer.maxBytes = config.getDcpScanByteLimit();
scanBuffer.maxItems = config.getDcpScanItemLimit();
buffer.bytesRead = 0;
buffer.maxBytes = config.getDcpBackfillByteLimit();
buffer.nextReadSize = 0;
buffer.full = false;
}
BackfillManager::~BackfillManager() {
LockHolder lh(lock);
ExecutorPool::get()->cancel(taskId);
while (!backfills.empty()) {
DCPBackfill* backfill = backfills.front();
backfills.pop();
backfill->cancel();
delete backfill;
}
}
void BackfillManager::schedule(stream_t stream, uint64_t start, uint64_t end) {
LockHolder lh(lock);
backfills.push(new DCPBackfill(engine, stream, start, end));
if (taskId != 0) {
ExecutorPool::get()->wake(taskId);
return;
}
ExTask task = new BackfillManagerTask(engine, conn,
Priority::BackfillTaskPriority);
taskId = ExecutorPool::get()->schedule(task, NONIO_TASK_IDX);
}
bool BackfillManager::bytesRead(uint32_t bytes) {
LockHolder lh(lock);
if (scanBuffer.itemsRead >= scanBuffer.maxItems) {
return false;
}
// Always allow an item to be backfilled if the scan buffer is empty,
// otherwise check to see if there is room for the item.
if (scanBuffer.bytesRead + bytes <= scanBuffer.maxBytes ||
scanBuffer.bytesRead == 0) {
scanBuffer.bytesRead += bytes;
}
if (buffer.bytesRead == 0 || buffer.bytesRead + bytes <= buffer.maxBytes) {
buffer.bytesRead += bytes;
} else {
scanBuffer.bytesRead -= bytes;
buffer.full = true;
buffer.nextReadSize = bytes;
return false;
}
scanBuffer.itemsRead++;
return true;
}
void BackfillManager::bytesSent(uint32_t bytes) {
LockHolder lh(lock);
cb_assert(buffer.bytesRead >= bytes);
buffer.bytesRead -= bytes;
if (buffer.full) {
uint32_t bufferSize = buffer.bytesRead;
bool canFitNext = buffer.maxBytes - bufferSize >= buffer.nextReadSize;
bool enoughCleared = bufferSize < (buffer.maxBytes * 3 / 4);
if (canFitNext && enoughCleared) {
buffer.nextReadSize = 0;
buffer.full = false;
ExecutorPool::get()->wake(taskId);
}
}
}
backfill_status_t BackfillManager::backfill() {
LockHolder lh(lock);
if (buffer.full) {
return backfill_snooze;
}
if (engine->getEpStore()->isMemoryUsageTooHigh()) {
LOG(EXTENSION_LOG_INFO, "DCP backfilling task for connection %s "
"temporarily suspended because the current memory usage is too "
"high", conn->getName().c_str());
return backfill_snooze;
}
DCPBackfill* backfill = backfills.front();
lh.unlock();
backfill_status_t status = backfill->run();
lh.lock();
if (status == backfill_success && buffer.full) {
// Snooze while the buffer is full
return backfill_snooze;
}
scanBuffer.bytesRead = 0;
scanBuffer.itemsRead = 0;
backfills.pop();
if (status == backfill_success) {
backfills.push(backfill);
} else if (status == backfill_finished) {
delete backfill;
if (backfills.empty()) {
taskId = 0;
return backfill_finished;
}
} else if (status == backfill_snooze) {
backfills.push(backfill);
return backfill_snooze;
} else {
abort();
}
return backfill_success;
}
bool BackfillManager::addIfLessThanMax(AtomicValue<uint32_t>& val,
uint32_t incr, uint32_t max) {
do {
uint32_t oldVal = val.load();
uint32_t newVal = oldVal + incr;
if (newVal > max) {
return false;
}
if (val.compare_exchange_strong(oldVal, newVal)) {
return true;
}
} while (true);
}
<commit_msg>MB-12636: Release the lock before deleting a finished backfill<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "ep_engine.h"
#include "connmap.h"
#include "dcp-backfill-manager.h"
#include "dcp-backfill.h"
#include "dcp-producer.h"
class BackfillManagerTask : public GlobalTask {
public:
BackfillManagerTask(EventuallyPersistentEngine* e, connection_t c,
const Priority &p, double sleeptime = 0,
bool shutdown = false)
: GlobalTask(e, p, sleeptime, shutdown), conn(c) {}
bool run();
std::string getDescription();
private:
connection_t conn;
static const size_t sleepTime;
};
const size_t BackfillManagerTask::sleepTime = 1;
bool BackfillManagerTask::run() {
DcpProducer* producer = static_cast<DcpProducer*>(conn.get());
if (producer->doDisconnect()) {
return false;
}
backfill_status_t status = producer->getBackfillManager()->backfill();
if (status == backfill_finished) {
return false;
} else if (status == backfill_snooze) {
snooze(sleepTime);
}
if (engine->getEpStats().isShutdown) {
return false;
}
return true;
}
std::string BackfillManagerTask::getDescription() {
std::stringstream ss;
ss << "Backfilling items for " << conn->getName();
return ss.str();
}
BackfillManager::BackfillManager(EventuallyPersistentEngine* e, connection_t c)
: engine(e), conn(c), taskId(0) {
Configuration& config = e->getConfiguration();
scanBuffer.bytesRead = 0;
scanBuffer.itemsRead = 0;
scanBuffer.maxBytes = config.getDcpScanByteLimit();
scanBuffer.maxItems = config.getDcpScanItemLimit();
buffer.bytesRead = 0;
buffer.maxBytes = config.getDcpBackfillByteLimit();
buffer.nextReadSize = 0;
buffer.full = false;
}
BackfillManager::~BackfillManager() {
LockHolder lh(lock);
ExecutorPool::get()->cancel(taskId);
while (!backfills.empty()) {
DCPBackfill* backfill = backfills.front();
backfills.pop();
backfill->cancel();
delete backfill;
}
}
void BackfillManager::schedule(stream_t stream, uint64_t start, uint64_t end) {
LockHolder lh(lock);
backfills.push(new DCPBackfill(engine, stream, start, end));
if (taskId != 0) {
ExecutorPool::get()->wake(taskId);
return;
}
ExTask task = new BackfillManagerTask(engine, conn,
Priority::BackfillTaskPriority);
taskId = ExecutorPool::get()->schedule(task, NONIO_TASK_IDX);
}
bool BackfillManager::bytesRead(uint32_t bytes) {
LockHolder lh(lock);
if (scanBuffer.itemsRead >= scanBuffer.maxItems) {
return false;
}
// Always allow an item to be backfilled if the scan buffer is empty,
// otherwise check to see if there is room for the item.
if (scanBuffer.bytesRead + bytes <= scanBuffer.maxBytes ||
scanBuffer.bytesRead == 0) {
scanBuffer.bytesRead += bytes;
}
if (buffer.bytesRead == 0 || buffer.bytesRead + bytes <= buffer.maxBytes) {
buffer.bytesRead += bytes;
} else {
scanBuffer.bytesRead -= bytes;
buffer.full = true;
buffer.nextReadSize = bytes;
return false;
}
scanBuffer.itemsRead++;
return true;
}
void BackfillManager::bytesSent(uint32_t bytes) {
LockHolder lh(lock);
cb_assert(buffer.bytesRead >= bytes);
buffer.bytesRead -= bytes;
if (buffer.full) {
uint32_t bufferSize = buffer.bytesRead;
bool canFitNext = buffer.maxBytes - bufferSize >= buffer.nextReadSize;
bool enoughCleared = bufferSize < (buffer.maxBytes * 3 / 4);
if (canFitNext && enoughCleared) {
buffer.nextReadSize = 0;
buffer.full = false;
ExecutorPool::get()->wake(taskId);
}
}
}
backfill_status_t BackfillManager::backfill() {
LockHolder lh(lock);
if (buffer.full) {
return backfill_snooze;
}
if (engine->getEpStore()->isMemoryUsageTooHigh()) {
LOG(EXTENSION_LOG_INFO, "DCP backfilling task for connection %s "
"temporarily suspended because the current memory usage is too "
"high", conn->getName().c_str());
return backfill_snooze;
}
DCPBackfill* backfill = backfills.front();
lh.unlock();
backfill_status_t status = backfill->run();
lh.lock();
if (status == backfill_success && buffer.full) {
// Snooze while the buffer is full
return backfill_snooze;
}
scanBuffer.bytesRead = 0;
scanBuffer.itemsRead = 0;
backfills.pop();
if (status == backfill_success) {
backfills.push(backfill);
} else if (status == backfill_finished) {
if (backfills.empty()) {
taskId = 0;
lh.unlock();
delete backfill;
return backfill_finished;
}
lh.unlock();
delete backfill;
} else if (status == backfill_snooze) {
backfills.push(backfill);
return backfill_snooze;
} else {
abort();
}
return backfill_success;
}
bool BackfillManager::addIfLessThanMax(AtomicValue<uint32_t>& val,
uint32_t incr, uint32_t max) {
do {
uint32_t oldVal = val.load();
uint32_t newVal = oldVal + incr;
if (newVal > max) {
return false;
}
if (val.compare_exchange_strong(oldVal, newVal)) {
return true;
}
} while (true);
}
<|endoftext|> |
<commit_before>#include "variant/pwm_platform.hpp"
#include "hal.h"
static const PWMConfig motor_pwm_config = {
500000, // 500 kHz PWM clock frequency.
1000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL}
}, // Channel configurations
0,0 // HW dependent
};
PWMPlatform::PWMPlatform() {
pwmStart(&PWMD8, &motor_pwm_config);
palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
}
void PWMPlatform::set(std::uint8_t ch, float dc) {
pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f);
pwmEnableChannel(&PWMD8, ch, width);
}
<commit_msg>Fix PWM period on F3.<commit_after>#include "variant/pwm_platform.hpp"
#include "hal.h"
static const PWMConfig motor_pwm_config = {
500000, // 500 kHz PWM clock frequency.
2000, // PWM period 2.0 ms.
NULL, // No callback.
{
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL},
{PWM_OUTPUT_ACTIVE_HIGH, NULL}
}, // Channel configurations
0,0 // HW dependent
};
PWMPlatform::PWMPlatform() {
pwmStart(&PWMD8, &motor_pwm_config);
palSetPadMode(GPIOC, 6, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 7, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 8, PAL_MODE_ALTERNATE(4));
palSetPadMode(GPIOC, 9, PAL_MODE_ALTERNATE(4));
}
void PWMPlatform::set(std::uint8_t ch, float dc) {
pwmcnt_t width = PWM_PERCENTAGE_TO_WIDTH(&PWMD8, dc * 10000.0f);
pwmEnableChannel(&PWMD8, ch, width);
}
<|endoftext|> |
<commit_before>#include <vector>
#include <thread>
#include <memory>
#include <queue>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
Mutex mu;
struct ThreadSafeContainer
{
queue<unsigned char*> safeContainer;
};
struct Producer
{
Producer(std::shared_ptr<ThreadSafeContainer> c) : container(c)
{
}
void run()
{
while(true)
{
// grab image from camera
// store image in container
Mat image(400, 400, CV_8UC3, Scalar(10, 100,180) );
unsigned char *pt_src = image.data;
mu.lock();
container->safeContainer.push(pt_src);
mu.unlock();
}
}
std::shared_ptr<ThreadSafeContainer> container;
};
struct Consumer
{
Consumer(std::shared_ptr<ThreadSafeContainer> c) : container(c)
{
}
~Consumer()
{
}
void run()
{
while(true)
{
// read next image from container
mu.lock();
if (!container->safeContainer.empty())
{
unsigned char *ptr_consumer_Image;
ptr_consumer_Image = container->safeContainer.front(); //The front of the queue contain the pointer to the image data
container->safeContainer.pop();
Mat image(400, 400, CV_8UC3);
image.data = ptr_consumer_Image;
imshow("consumer image", image);
waitKey(33);
}
mu.unlock();
}
}
std::shared_ptr<ThreadSafeContainer> container;
};
int main()
{
//Pointer object to the class containing a "container" which will help "Producer" and "Consumer" to put and take images
auto ptrObject_container = make_shared<ThreadSafeContainer>();
//Pointer object to the Producer...intialize the "container" variable of "Struct Producer" with the above created common "container"
auto ptrObject_producer = make_shared<Producer>(ptrObject_container);
//FIRST Pointer object to the Consumer...intialize the "container" variable of "Struct Consumer" with the above created common "container"
auto first_ptrObject_consumer = make_shared<Consumer>(ptrObject_container);
//SECOND Pointer object to the Consumer...intialize the "container" variable of "Struct Consumer" with the above created common "container"
auto second_ptrObject_consumer = make_shared<Consumer>(ptrObject_container);
//RUN producer thread
thread producerThread(&Producer::run, ptrObject_producer);
//RUN first thread of Consumer
thread first_consumerThread(&Consumer::run, first_ptrObject_consumer);
//RUN second thread of Consumer
thread second_consumerThread(&Consumer::run, second_ptrObject_consumer);
//JOIN all threads
producerThread.join();
first_consumerThread.join();
second_consumerThread.join();
return 0;
}
<commit_msg>added first code file for frameproducerconsumer<commit_after>#include <vector>
#include <thread>
#include <memory>
#include <queue>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
template <class T>
class ThreadSafeQueue
{
std::queue<T> m_queue;
std::mutex m_mutex;
void push(const T &ba){
std::lock_guard<std::mutext> lg(&m_mutex);
m_queue.push(ba);
};
T top () {
std::lock_guard<std::mutext> lg(&m_mutex);
return m_queu.front();
}
void pop() {
std::lock_guard<std::mutext> lg(&m_mutex);
m_queu.pop();
}
}
struct ThreadSafeContainer
{
ThreadSafeQueue<unsigned char*> safeContainer;
};
struct Producer
{
Producer(std::shared_ptr<ThreadSafeContainer> c) : container(c)
{
}
void run()
{
while(true)
{
// grab image from camera
// store image in container
Mat image(400, 400, CV_8UC3, Scalar(10, 100,180) );
unsigned char *pt_src = image.data;
container->safeContainer.push(pt_src);
}
}
std::shared_ptr<ThreadSafeContainer> container;
};
struct Consumer
{
Consumer(std::shared_ptr<ThreadSafeContainer> c) : container(c)
{
}
~Consumer()
{
}
void run()
{
while(true)
{
// read next image from container
if (!container->safeContainer.empty())
{
unsigned char *ptr_consumer_Image;
ptr_consumer_Image = container->safeContainer.top(); //The front of the queue contain the pointer to the image data
container->safeContainer.pop();
Mat image(400, 400, CV_8UC3);
image.data = ptr_consumer_Image;
imshow("consumer image", image);
waitKey(33);
}
}
}
std::shared_ptr<ThreadSafeContainer> container;
};
int main()
{
//Pointer object to the class containing a "container" which will help "Producer" and "Consumer" to put and take images
auto ptrObject_container = make_shared<ThreadSafeContainer>();
//Pointer object to the Producer...intialize the "container" variable of "Struct Producer" with the above created common "container"
auto ptrObject_producer = make_shared<Producer>(ptrObject_container);
//FIRST Pointer object to the Consumer...intialize the "container" variable of "Struct Consumer" with the above created common "container"
auto first_ptrObject_consumer = make_shared<Consumer>(ptrObject_container);
//SECOND Pointer object to the Consumer...intialize the "container" variable of "Struct Consumer" with the above created common "container"
auto second_ptrObject_consumer = make_shared<Consumer>(ptrObject_container);
//RUN producer thread
thread producerThread(&Producer::run, ptrObject_producer);
//RUN first thread of Consumer
thread first_consumerThread(&Consumer::run, first_ptrObject_consumer);
//RUN second thread of Consumer
thread second_consumerThread(&Consumer::run, second_ptrObject_consumer);
//JOIN all threads
producerThread.join();
first_consumerThread.join();
second_consumerThread.join();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Update the EventSendingController to send complete touch events.<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/
#include <QLocale>
#include <QStringList>
#include <QVariant>
#include <QVariantMap>
#include <QGuiApplication>
#include <QClipboard>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QDateTime>
#include <QStandardPaths>
#include "declarativewebutils.h"
#include "qmozcontext.h"
static const QString system_components_time_stamp("/var/lib/_MOZEMBED_CACHE_CLEAN_");
static const QString profilePath("/.mozilla/mozembed");
DeclarativeWebUtils::DeclarativeWebUtils(QStringList arguments,
BrowserService *service,
QObject *parent) :
QObject(parent),
m_homePage("http://www.jolla.com"),
m_arguments(arguments),
m_service(service)
{
connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),
this, SLOT(updateWebEngineSettings()));
connect(QMozContext::GetInstance(), SIGNAL(recvObserve(QString, QVariant)),
this, SLOT(handleObserve(QString, QVariant)));
connect(service, SIGNAL(openUrlRequested(QString)),
this, SLOT(openUrl(QString)));
QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QStringLiteral("/.firstUseDone");
m_firstUseDone = fileExists(path);
}
QUrl DeclarativeWebUtils::getFaviconForUrl(QUrl url)
{
QUrl faviconUrl(url);
faviconUrl.setPath("/favicon.ico");
return faviconUrl;
}
int DeclarativeWebUtils::getLightness(QColor color) const
{
return color.lightness();
}
bool DeclarativeWebUtils::fileExists(QString fileName) const
{
QFile file(fileName);
return file.exists();
}
void DeclarativeWebUtils::clearStartupCacheIfNeeded()
{
QFileInfo systemStamp(system_components_time_stamp);
if (systemStamp.exists()) {
QString mostProfilePath = QDir::homePath() + profilePath;
QString localStampString(mostProfilePath + QString("/_CACHE_CLEAN_"));
QFileInfo localStamp(localStampString);
if (localStamp.exists() && systemStamp.lastModified() > localStamp.lastModified()) {
QDir cacheDir(mostProfilePath + "/startupCache");
cacheDir.removeRecursively();
QFile(localStampString).remove();
}
}
}
void DeclarativeWebUtils::updateWebEngineSettings()
{
// Infer and set Accept-Language header from the current system locale
QString langs;
QStringList locale = QLocale::system().name().split("_", QString::SkipEmptyParts);
if (locale.size() > 1) {
langs = QString("%1-%2,%3").arg(locale.at(0)).arg(locale.at(1)).arg(locale.at(0));
} else {
langs = locale.at(0);
}
QMozContext* mozContext = QMozContext::GetInstance();
mozContext->setPref(QString("intl.accept_languages"), QVariant(langs));
// these are magic numbers defining touch radius required to detect <image src=""> touch
mozContext->setPref(QString("browser.ui.touch.left"), QVariant(32));
mozContext->setPref(QString("browser.ui.touch.right"), QVariant(32));
mozContext->setPref(QString("browser.ui.touch.top"), QVariant(48));
mozContext->setPref(QString("browser.ui.touch.bottom"), QVariant(16));
// Install embedlite handlers for guestures
mozContext->setPref(QString("embedlite.azpc.handle.singletap"), QVariant(false));
mozContext->setPref(QString("embedlite.azpc.json.singletap"), QVariant(true));
mozContext->setPref(QString("embedlite.azpc.handle.longtap"), QVariant(false));
mozContext->setPref(QString("embedlite.azpc.json.longtap"), QVariant(true));
mozContext->setPref(QString("embedlite.azpc.json.viewport"), QVariant(true));
// Without this pref placeholders get cleaned as soon as a character gets committed
// by VKB and that happens only when Enter is pressed or comma/space/dot is entered.
mozContext->setPref(QString("dom.placeholder.show_on_focus"), QVariant(false));
mozContext->setPref(QString("security.alternate_certificate_error_page"), QString("certerror"));
// Use autodownload, never ask
mozContext->setPref(QString("browser.download.useDownloadDir"), QVariant(true));
// see https://developer.mozilla.org/en-US/docs/Download_Manager_preferences
// Use custom downloads location defined in browser.download.dir
mozContext->setPref(QString("browser.download.folderList"), QVariant(2));
mozContext->setPref(QString("browser.download.dir"), downloadDir());
// Downloads should never be removed automatically
mozContext->setPref(QString("browser.download.manager.retention"), QVariant(2));
// Downloads will be canceled on quit
// TODO: this doesn't really work. Instead the incomplete downloads get restarted
// on browser launch.
mozContext->setPref(QString("browser.download.manager.quitBehavior"), QVariant(2));
// TODO: this doesn't really work too
mozContext->setPref(QString("browser.helperApps.deleteTempFileOnExit"), QVariant(true));
mozContext->setPref(QString("geo.wifi.scan"), QVariant(false));
mozContext->setPref(QString("browser.enable_automatic_image_resizing"), QVariant(true));
// Default value for embedlite is 0.55f which is a bit slower than needed.
mozContext->setPref(QString("gfx.axis.velocity_multiplier"), QString("1.0f"));
// Make long press timeout equal to the one in Qt
mozContext->setPref(QString("ui.click_hold_context_menus.delay"), QVariant(800));
mozContext->setPref(QString("gfx.axis.fling_stopped_threshold"), QString("0.13f"));
// subscribe to gecko messages
mozContext->addObservers(QStringList()
<< "clipboard:setdata"
<< "media-decoder-info"
<< "embed:download"
<< "embed:search"
<< "embedlite-before-first-paint");
// Enable internet search
mozContext->setPref(QString("keyword.enabled"), QVariant(true));
// Scale up content size
mozContext->setPixelRatio(1.5);
mozContext->setPref(QString("embedlite.inputItemSize"), QVariant(38));
mozContext->setPref(QString("embedlite.zoomMargin"), QVariant(14));
}
void DeclarativeWebUtils::openUrl(QString url)
{
m_arguments << url;
emit openUrlRequested(url);
}
QString DeclarativeWebUtils::initialPage()
{
if (m_arguments.count() > 1) {
return m_arguments.last();
} else {
return "";
}
}
void DeclarativeWebUtils::setFirstUseDone(bool firstUseDone) {
QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QStringLiteral("/.firstUseDone");
if (m_firstUseDone != firstUseDone) {
m_firstUseDone = firstUseDone;
if (!firstUseDone) {
QFile f(path);
f.remove();
} else {
QProcess process;
process.startDetached("touch", QStringList() << path);
}
emit firstUseDoneChanged();
}
}
bool DeclarativeWebUtils::firstUseDone() const {
return m_firstUseDone;
}
QString DeclarativeWebUtils::homePage()
{
return m_homePage;
}
QString DeclarativeWebUtils::downloadDir() const
{
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
}
QString DeclarativeWebUtils::picturesDir() const
{
return QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
}
void DeclarativeWebUtils::deleteThumbnail(QString path) const
{
QFile f(path);
if (f.exists()) {
f.remove();
}
}
QString DeclarativeWebUtils::displayableUrl(QString fullUrl) const
{
QUrl url(fullUrl);
// Leaving only the scheme, host address, and port (if present).
return url.toDisplayString(QUrl::RemoveUserInfo |
QUrl::RemovePath |
QUrl::RemoveQuery |
QUrl::RemoveFragment |
QUrl::StripTrailingSlash);
}
void DeclarativeWebUtils::handleObserve(const QString message, const QVariant data)
{
const QVariantMap dataMap = data.toMap();
if (message == "clipboard:setdata") {
QClipboard *clipboard = QGuiApplication::clipboard();
// check if we copied password
if (!dataMap.value("private").toBool()) {
clipboard->setText(dataMap.value("data").toString());
}
} else if (message == "embed:search") {
QString msg = dataMap.value("msg").toString();
if (msg == "init") {
if (!dataMap.value("defaultEngine").isValid()) {
QMozContext *mozContext = QMozContext::GetInstance();
QVariantMap loadsearch;
// load opensearch descriptions
loadsearch.insert(QString("msg"), QVariant(QString("loadxml")));
loadsearch.insert(QString("uri"), QVariant(QString("chrome://embedlite/content/google.xml")));
loadsearch.insert(QString("confirm"), QVariant(false));
mozContext->sendObserve("embedui:search", QVariant(loadsearch));
loadsearch.insert(QString("uri"), QVariant(QString("chrome://embedlite/content/bing.xml")));
mozContext->sendObserve("embedui:search", QVariant(loadsearch));
loadsearch.insert(QString("uri"), QVariant(QString("chrome://embedlite/content/yahoo.xml")));
mozContext->sendObserve("embedui:search", QVariant(loadsearch));
}
}
}
}
<commit_msg>[sailfish-browser] Sync with prefs available in gecko 29.0<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/
#include <QLocale>
#include <QStringList>
#include <QVariant>
#include <QVariantMap>
#include <QGuiApplication>
#include <QClipboard>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QDateTime>
#include <QStandardPaths>
#include "declarativewebutils.h"
#include "qmozcontext.h"
static const QString system_components_time_stamp("/var/lib/_MOZEMBED_CACHE_CLEAN_");
static const QString profilePath("/.mozilla/mozembed");
DeclarativeWebUtils::DeclarativeWebUtils(QStringList arguments,
BrowserService *service,
QObject *parent) :
QObject(parent),
m_homePage("http://www.jolla.com"),
m_arguments(arguments),
m_service(service)
{
connect(QMozContext::GetInstance(), SIGNAL(onInitialized()),
this, SLOT(updateWebEngineSettings()));
connect(QMozContext::GetInstance(), SIGNAL(recvObserve(QString, QVariant)),
this, SLOT(handleObserve(QString, QVariant)));
connect(service, SIGNAL(openUrlRequested(QString)),
this, SLOT(openUrl(QString)));
QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QStringLiteral("/.firstUseDone");
m_firstUseDone = fileExists(path);
}
QUrl DeclarativeWebUtils::getFaviconForUrl(QUrl url)
{
QUrl faviconUrl(url);
faviconUrl.setPath("/favicon.ico");
return faviconUrl;
}
int DeclarativeWebUtils::getLightness(QColor color) const
{
return color.lightness();
}
bool DeclarativeWebUtils::fileExists(QString fileName) const
{
QFile file(fileName);
return file.exists();
}
void DeclarativeWebUtils::clearStartupCacheIfNeeded()
{
QFileInfo systemStamp(system_components_time_stamp);
if (systemStamp.exists()) {
QString mostProfilePath = QDir::homePath() + profilePath;
QString localStampString(mostProfilePath + QString("/_CACHE_CLEAN_"));
QFileInfo localStamp(localStampString);
if (localStamp.exists() && systemStamp.lastModified() > localStamp.lastModified()) {
QDir cacheDir(mostProfilePath + "/startupCache");
cacheDir.removeRecursively();
QFile(localStampString).remove();
}
}
}
void DeclarativeWebUtils::updateWebEngineSettings()
{
// Infer and set Accept-Language header from the current system locale
QString langs;
QStringList locale = QLocale::system().name().split("_", QString::SkipEmptyParts);
if (locale.size() > 1) {
langs = QString("%1-%2,%3").arg(locale.at(0)).arg(locale.at(1)).arg(locale.at(0));
} else {
langs = locale.at(0);
}
QMozContext* mozContext = QMozContext::GetInstance();
mozContext->setPref(QString("intl.accept_languages"), QVariant(langs));
// these are magic numbers defining touch radius required to detect <image src=""> touch
mozContext->setPref(QString("browser.ui.touch.left"), QVariant(32));
mozContext->setPref(QString("browser.ui.touch.right"), QVariant(32));
mozContext->setPref(QString("browser.ui.touch.top"), QVariant(48));
mozContext->setPref(QString("browser.ui.touch.bottom"), QVariant(16));
// Install embedlite handlers for guestures
mozContext->setPref(QString("embedlite.azpc.handle.singletap"), QVariant(false));
mozContext->setPref(QString("embedlite.azpc.json.singletap"), QVariant(true));
mozContext->setPref(QString("embedlite.azpc.handle.longtap"), QVariant(false));
mozContext->setPref(QString("embedlite.azpc.json.longtap"), QVariant(true));
mozContext->setPref(QString("embedlite.azpc.json.viewport"), QVariant(true));
// Without this pref placeholders get cleaned as soon as a character gets committed
// by VKB and that happens only when Enter is pressed or comma/space/dot is entered.
mozContext->setPref(QString("dom.placeholder.show_on_focus"), QVariant(false));
mozContext->setPref(QString("security.alternate_certificate_error_page"), QString("certerror"));
// Use autodownload, never ask
mozContext->setPref(QString("browser.download.useDownloadDir"), QVariant(true));
// see https://developer.mozilla.org/en-US/docs/Download_Manager_preferences
// Use custom downloads location defined in browser.download.dir
mozContext->setPref(QString("browser.download.folderList"), QVariant(2));
mozContext->setPref(QString("browser.download.dir"), downloadDir());
// Downloads should never be removed automatically
mozContext->setPref(QString("browser.download.manager.retention"), QVariant(2));
// Downloads will be canceled on quit
// TODO: this doesn't really work. Instead the incomplete downloads get restarted
// on browser launch.
mozContext->setPref(QString("browser.download.manager.quitBehavior"), QVariant(2));
// TODO: this doesn't really work too
mozContext->setPref(QString("browser.helperApps.deleteTempFileOnExit"), QVariant(true));
mozContext->setPref(QString("geo.wifi.scan"), QVariant(false));
mozContext->setPref(QString("browser.enable_automatic_image_resizing"), QVariant(true));
// Make long press timeout equal to the one in Qt
mozContext->setPref(QString("ui.click_hold_context_menus.delay"), QVariant(800));
mozContext->setPref(QString("apz.fling_stopped_threshold"), QString("0.13f"));
// subscribe to gecko messages
mozContext->addObservers(QStringList()
<< "clipboard:setdata"
<< "media-decoder-info"
<< "embed:download"
<< "embed:search"
<< "embedlite-before-first-paint");
// Enable internet search
mozContext->setPref(QString("keyword.enabled"), QVariant(true));
// Scale up content size
mozContext->setPixelRatio(1.5);
mozContext->setPref(QString("embedlite.inputItemSize"), QVariant(38));
mozContext->setPref(QString("embedlite.zoomMargin"), QVariant(14));
}
void DeclarativeWebUtils::openUrl(QString url)
{
m_arguments << url;
emit openUrlRequested(url);
}
QString DeclarativeWebUtils::initialPage()
{
if (m_arguments.count() > 1) {
return m_arguments.last();
} else {
return "";
}
}
void DeclarativeWebUtils::setFirstUseDone(bool firstUseDone) {
QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QStringLiteral("/.firstUseDone");
if (m_firstUseDone != firstUseDone) {
m_firstUseDone = firstUseDone;
if (!firstUseDone) {
QFile f(path);
f.remove();
} else {
QProcess process;
process.startDetached("touch", QStringList() << path);
}
emit firstUseDoneChanged();
}
}
bool DeclarativeWebUtils::firstUseDone() const {
return m_firstUseDone;
}
QString DeclarativeWebUtils::homePage()
{
return m_homePage;
}
QString DeclarativeWebUtils::downloadDir() const
{
return QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
}
QString DeclarativeWebUtils::picturesDir() const
{
return QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
}
void DeclarativeWebUtils::deleteThumbnail(QString path) const
{
QFile f(path);
if (f.exists()) {
f.remove();
}
}
QString DeclarativeWebUtils::displayableUrl(QString fullUrl) const
{
QUrl url(fullUrl);
// Leaving only the scheme, host address, and port (if present).
return url.toDisplayString(QUrl::RemoveUserInfo |
QUrl::RemovePath |
QUrl::RemoveQuery |
QUrl::RemoveFragment |
QUrl::StripTrailingSlash);
}
void DeclarativeWebUtils::handleObserve(const QString message, const QVariant data)
{
const QVariantMap dataMap = data.toMap();
if (message == "clipboard:setdata") {
QClipboard *clipboard = QGuiApplication::clipboard();
// check if we copied password
if (!dataMap.value("private").toBool()) {
clipboard->setText(dataMap.value("data").toString());
}
} else if (message == "embed:search") {
QString msg = dataMap.value("msg").toString();
if (msg == "init") {
if (!dataMap.value("defaultEngine").isValid()) {
QMozContext *mozContext = QMozContext::GetInstance();
QVariantMap loadsearch;
// load opensearch descriptions
loadsearch.insert(QString("msg"), QVariant(QString("loadxml")));
loadsearch.insert(QString("uri"), QVariant(QString("chrome://embedlite/content/google.xml")));
loadsearch.insert(QString("confirm"), QVariant(false));
mozContext->sendObserve("embedui:search", QVariant(loadsearch));
loadsearch.insert(QString("uri"), QVariant(QString("chrome://embedlite/content/bing.xml")));
mozContext->sendObserve("embedui:search", QVariant(loadsearch));
loadsearch.insert(QString("uri"), QVariant(QString("chrome://embedlite/content/yahoo.xml")));
mozContext->sendObserve("embedui:search", QVariant(loadsearch));
}
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Un Shyam
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 its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <iostream>
#include "libtorrent/hasher.hpp"
#include "libtorrent/pe_crypto.hpp"
#include "libtorrent/session.hpp"
#include "setup_transfer.hpp"
#include "test.hpp"
#ifndef TORRENT_DISABLE_ENCRYPTION
void display_pe_policy(libtorrent::pe_settings::enc_policy policy)
{
using namespace libtorrent;
using std::cerr;
if (policy == pe_settings::disabled) cerr << "disabled ";
else if (policy == pe_settings::enabled) cerr << "enabled ";
else if (policy == pe_settings::forced) cerr << "forced ";
}
void display_pe_settings(libtorrent::pe_settings s)
{
using namespace libtorrent;
using std::cerr;
cerr << "out_enc_policy - ";
display_pe_policy(s.out_enc_policy);
cerr << "\tin_enc_policy - ";
display_pe_policy(s.in_enc_policy);
cerr << "\nenc_level - ";
if (s.allowed_enc_level == pe_settings::plaintext) cerr << "plaintext ";
else if (s.allowed_enc_level == pe_settings::rc4) cerr << "rc4 ";
else if (s.allowed_enc_level == pe_settings::both) cerr << "both ";
cerr << "\t\tprefer_rc4 - ";
(s.prefer_rc4) ? cerr << "true" : cerr << "false";
cerr << "\n\n";
}
void test_transfer(libtorrent::pe_settings::enc_policy policy,
libtorrent::pe_settings::enc_level level = libtorrent::pe_settings::both,
bool pref_rc4 = false, bool encrypted_torrent = false)
{
using namespace libtorrent;
using std::cerr;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48800, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49800, 50000), "0.0.0.0", 0);
pe_settings s;
s.out_enc_policy = libtorrent::pe_settings::enabled;
s.in_enc_policy = libtorrent::pe_settings::enabled;
s.allowed_enc_level = pe_settings::both;
ses2.set_pe_settings(s);
s.out_enc_policy = policy;
s.in_enc_policy = policy;
s.allowed_enc_level = level;
s.prefer_rc4 = pref_rc4;
ses1.set_pe_settings(s);
// s = ses1.get_pe_settings();
// cerr << " Session1 \n";
// display_pe_settings(s);
// s = ses2.get_pe_settings();
// cerr << " Session2 \n";
// display_pe_settings(s);
torrent_handle tor1;
torrent_handle tor2;
using boost::tuples::ignore;
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, true, false, true
, "_pe", 16 * 1024, 0, false, 0, true, encrypted_torrent);
std::cerr << "waiting for transfer to complete\n";
for (int i = 0; i < 50; ++i)
{
torrent_status s = tor2.status();
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
if (s.is_seeding) break;
test_sleep(1000);
}
TEST_CHECK(tor2.status().is_seeding);
if (tor2.status().is_seeding) std::cerr << "done\n";
ses1.remove_torrent(tor1);
ses2.remove_torrent(tor2);
error_code ec;
remove_all("./tmp1_pe", ec);
remove_all("./tmp2_pe", ec);
remove_all("./tmp3_pe", ec);
}
void test_enc_handler(libtorrent::encryption_handler* a, libtorrent::encryption_handler* b)
{
int repcount = 128;
for (int rep = 0; rep < repcount; ++rep)
{
std::size_t buf_len = rand() % (512 * 1024);
char* buf = new char[buf_len];
char* cmp_buf = new char[buf_len];
std::generate(buf, buf + buf_len, &std::rand);
std::memcpy(cmp_buf, buf, buf_len);
a->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
b->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
b->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
a->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
delete[] buf;
delete[] cmp_buf;
}
}
int test_main()
{
using namespace libtorrent;
int repcount = 128;
for (int rep = 0; rep < repcount; ++rep)
{
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
}
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
sha1_hash test1_key = hasher("test1_key",8).final();
sha1_hash test2_key = hasher("test2_key",8).final();
fprintf(stderr, "testing RC4 handler\n");
rc4_handler rc41;
rc41.set_incoming_key(&test2_key[0], 20);
rc41.set_outgoing_key(&test1_key[0], 20);
rc4_handler rc42;
rc42.set_incoming_key(&test1_key[0], 20);
rc42.set_outgoing_key(&test2_key[0], 20);
test_enc_handler(&rc41, &rc42);
#ifdef TORRENT_USE_OPENSSL
fprintf(stderr, "testing AES-256 handler\n");
char key1[32];
std::generate(key1, key1 + 32, &std::rand);
aes256_handler aes1;
aes1.set_incoming_key((const unsigned char*)key1, 32);
aes256_handler aes2;
aes2.set_incoming_key((const unsigned char*)key1, 32);
test_enc_handler(&aes1, &aes2);
#endif
test_transfer(pe_settings::enabled, pe_settings::both, false, true);
test_transfer(pe_settings::enabled, pe_settings::both, true, true);
return 0;
test_transfer(pe_settings::disabled);
test_transfer(pe_settings::forced, pe_settings::plaintext);
test_transfer(pe_settings::forced, pe_settings::rc4);
test_transfer(pe_settings::forced, pe_settings::both, false);
test_transfer(pe_settings::forced, pe_settings::both, true);
test_transfer(pe_settings::enabled, pe_settings::plaintext);
test_transfer(pe_settings::enabled, pe_settings::rc4);
test_transfer(pe_settings::enabled, pe_settings::both, false);
test_transfer(pe_settings::enabled, pe_settings::both, true);
return 0;
}
#else
int test_main()
{
std::cerr << "PE test not run because it's disabled" << std::endl;
return 0;
}
#endif
<commit_msg>convert test_pe_crypto to use stdio instead of iostream<commit_after>/*
Copyright (c) 2007, Un Shyam
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 its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include <iostream>
#include "libtorrent/hasher.hpp"
#include "libtorrent/pe_crypto.hpp"
#include "libtorrent/session.hpp"
#include "setup_transfer.hpp"
#include "test.hpp"
#ifndef TORRENT_DISABLE_ENCRYPTION
char const* pe_policy(libtorrent::pe_settings::enc_policy policy)
{
using namespace libtorrent;
if (policy == pe_settings::disabled) return "disabled";
else if (policy == pe_settings::enabled) return "enabled";
else if (policy == pe_settings::forced) return "forced";
return "unknown";
}
void display_pe_settings(libtorrent::pe_settings s)
{
using namespace libtorrent;
fprintf(stderr, "out_enc_policy - %s\tin_enc_policy - %s\n"
, pe_policy(s.out_enc_policy), pe_policy(s.in_enc_policy));
fprintf(stderr, "enc_level - %s\t\tprefer_rc4 - %s\n"
, s.allowed_enc_level == pe_settings::plaintext ? "plaintext"
: s.allowed_enc_level == pe_settings::rc4 ? "rc4"
: s.allowed_enc_level == pe_settings::both ? "both" : "unknown"
, s.prefer_rc4 ? "true": "false");
}
void test_transfer(libtorrent::pe_settings::enc_policy policy,
libtorrent::pe_settings::enc_level level = libtorrent::pe_settings::both,
bool pref_rc4 = false, bool encrypted_torrent = false)
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48800, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49800, 50000), "0.0.0.0", 0);
pe_settings s;
s.out_enc_policy = libtorrent::pe_settings::enabled;
s.in_enc_policy = libtorrent::pe_settings::enabled;
s.allowed_enc_level = pe_settings::both;
ses2.set_pe_settings(s);
s.out_enc_policy = policy;
s.in_enc_policy = policy;
s.allowed_enc_level = level;
s.prefer_rc4 = pref_rc4;
ses1.set_pe_settings(s);
s = ses1.get_pe_settings();
fprintf(stderr, " Session1 \n");
display_pe_settings(s);
s = ses2.get_pe_settings();
fprintf(stderr, " Session2 \n");
display_pe_settings(s);
torrent_handle tor1;
torrent_handle tor2;
using boost::tuples::ignore;
boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, true, false, true
, "_pe", 16 * 1024, 0, false, 0, true, encrypted_torrent);
fprintf(stderr, "waiting for transfer to complete\n");
for (int i = 0; i < 50; ++i)
{
torrent_status s = tor2.status();
print_alerts(ses1, "ses1");
print_alerts(ses2, "ses2");
if (s.is_seeding) break;
test_sleep(1000);
}
TEST_CHECK(tor2.status().is_seeding);
if (tor2.status().is_seeding) fprintf(stderr, "done\n");
ses1.remove_torrent(tor1);
ses2.remove_torrent(tor2);
error_code ec;
remove_all("./tmp1_pe", ec);
remove_all("./tmp2_pe", ec);
remove_all("./tmp3_pe", ec);
}
void test_enc_handler(libtorrent::encryption_handler* a, libtorrent::encryption_handler* b)
{
int repcount = 128;
for (int rep = 0; rep < repcount; ++rep)
{
std::size_t buf_len = rand() % (512 * 1024);
char* buf = new char[buf_len];
char* cmp_buf = new char[buf_len];
std::generate(buf, buf + buf_len, &std::rand);
std::memcpy(cmp_buf, buf, buf_len);
a->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
b->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
b->encrypt(buf, buf_len);
TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf));
a->decrypt(buf, buf_len);
TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf));
delete[] buf;
delete[] cmp_buf;
}
}
int test_main()
{
using namespace libtorrent;
int repcount = 128;
for (int rep = 0; rep < repcount; ++rep)
{
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
}
dh_key_exchange DH1, DH2;
DH1.compute_secret(DH2.get_local_key());
DH2.compute_secret(DH1.get_local_key());
TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret()));
sha1_hash test1_key = hasher("test1_key",8).final();
sha1_hash test2_key = hasher("test2_key",8).final();
fprintf(stderr, "testing RC4 handler\n");
rc4_handler rc41;
rc41.set_incoming_key(&test2_key[0], 20);
rc41.set_outgoing_key(&test1_key[0], 20);
rc4_handler rc42;
rc42.set_incoming_key(&test1_key[0], 20);
rc42.set_outgoing_key(&test2_key[0], 20);
test_enc_handler(&rc41, &rc42);
#ifdef TORRENT_USE_OPENSSL
fprintf(stderr, "testing AES-256 handler\n");
char key1[32];
std::generate(key1, key1 + 32, &std::rand);
aes256_handler aes1;
aes1.set_incoming_key((const unsigned char*)key1, 32);
aes256_handler aes2;
aes2.set_incoming_key((const unsigned char*)key1, 32);
test_enc_handler(&aes1, &aes2);
#endif
test_transfer(pe_settings::enabled, pe_settings::both, false, true);
test_transfer(pe_settings::enabled, pe_settings::both, true, true);
return 0;
test_transfer(pe_settings::disabled);
test_transfer(pe_settings::forced, pe_settings::plaintext);
test_transfer(pe_settings::forced, pe_settings::rc4);
test_transfer(pe_settings::forced, pe_settings::both, false);
test_transfer(pe_settings::forced, pe_settings::both, true);
test_transfer(pe_settings::enabled, pe_settings::plaintext);
test_transfer(pe_settings::enabled, pe_settings::rc4);
test_transfer(pe_settings::enabled, pe_settings::both, false);
test_transfer(pe_settings::enabled, pe_settings::both, true);
return 0;
}
#else
int test_main()
{
fprintf(stderr, "PE test not run because it's disabled\n");
return 0;
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(WIN32)
#include <windows.h>
#include <direct.h>
#elif defined(_XBOX)
#include <xtl.h>
#else
#include <unistd.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
namespace sofa
{
namespace helper
{
namespace system
{
// replacing every occurences of "//" by "/"
std::string cleanPath( const std::string& path )
{
std::string p = path;
size_t pos = p.find("//");
size_t len = p.length();
while( pos != std::string::npos )
{
if ( pos == (len-1))
p.replace( pos, 2, "");
else
p.replace(pos,2,"/");
pos = p.find("//");
}
return p;
}
#define ADD_SOFA_BUILD_DIR( x ) sofa_tostring(SOFA_BUILD_DIR)sofa_tostring(x)
#define ADD_SOFA_SRC_DIR( x ) sofa_tostring(SOFA_SRC_DIR)sofa_tostring(x)
#if defined (WIN32) || defined (_XBOX)
#define SOFA_PLUGIN_SUBDIR /bin
#else
#define SOFA_PLUGIN_SUBDIR /lib
#endif
FileRepository PluginRepository("SOFA_PLUGIN_PATH", ADD_SOFA_BUILD_DIR(SOFA_PLUGIN_SUBDIR));
#undef SOFA_PLUGIN_SUBDIR
static FileRepository createSofaDataPath()
{
FileRepository repository("SOFA_DATA_PATH");
#if defined (WIN32) || defined (_XBOX) || defined(PS3)
repository.addLastPath( ADD_SOFA_BUILD_DIR( / ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /share ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /examples ) );
#elif defined (__APPLE__)
repository.addLastPath( ADD_SOFA_BUILD_DIR( / ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /share ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /examples ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /Resources/examples ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /Resources ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /../../../examples ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /../../../share ) );
#else // LINUX
repository.addLastPath( ADD_SOFA_BUILD_DIR( / ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /share ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /examples ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /../Verification/data ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /../Verification/simulation ) );
#endif
return repository;
}
FileRepository DataRepository = createSofaDataPath();
#undef ADD_SOFA_BUILD_DIR
#undef ADD_SOFA_SRC_DIR
#if defined (_XBOX) || defined(PS3)
char* getenv(const char* varname) { return NULL; } // NOT IMPLEMENTED
#endif
FileRepository::FileRepository(const char* envVar, const char* relativePath)
{
if (envVar != NULL && envVar[0]!='\0')
{
const char* envpath = getenv(envVar);
if (envpath != NULL && envpath[0]!='\0')
addFirstPath(envpath);
}
if (relativePath != NULL && relativePath[0]!='\0')
{
std::string path = relativePath;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
std::string p = path.substr(p0,p1-p0);
addLastPath(SetDirectory::GetRelativeFromProcess(p.c_str()));
}
p0 = p1+1;
}
}
//print();
}
FileRepository::~FileRepository()
{
}
std::string FileRepository::cleanPath( const std::string& path )
{
std::string p = path;
size_t pos = p.find("//");
size_t len = p.length();
while( pos != std::string::npos )
{
if ( pos == (len-2))
p.replace( pos, 2, "");
else
p.replace(pos,2,"/");
pos = p.find("//");
}
return p;
}
void FileRepository::addFirstPath(const std::string& p)
{
// replacing every occurences of "//" by "/"
std::string path = cleanPath( p );
std::vector<std::string> entries;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
entries.push_back(path.substr(p0,p1-p0));
}
p0 = p1+1;
}
vpath.insert(vpath.begin(), entries.begin(), entries.end());
}
void FileRepository::addLastPath(const std::string& p)
{
// replacing every occurences of "//" by "/"
std::string path = cleanPath( p );
std::vector<std::string> entries;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
entries.push_back(path.substr(p0,p1-p0));
}
p0 = p1+1;
}
vpath.insert(vpath.end(), entries.begin(), entries.end());
// std::cout << path << std::endl;
}
void FileRepository::removePath(const std::string& path)
{
std::vector<std::string> entries;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
entries.push_back(path.substr(p0,p1-p0));
}
p0 = p1+1;
}
for(std::vector<std::string>::iterator it=entries.begin();
it!=entries.end(); it++)
{
vpath.erase( find(vpath.begin(), vpath.end(), *it) );
}
// Display
// std::cout<<(*this)<<std::endl;
}
std::string FileRepository::getFirstPath()
{
if (vpath.size() > 0)
return vpath.front();
else return "";
}
bool FileRepository::findFileIn(std::string& filename, const std::string& path)
{
if (filename.empty()) return false; // no filename
struct stat s;
std::string newfname = SetDirectory::GetRelativeFromDir(filename.c_str(), path.c_str());
//std::cout << "Looking for " << newfname <<std::endl;
if (!stat(newfname.c_str(),&s))
{
// File found
//std::cout << "File "<<filename<<" found in "<<path.substr(p0,p1-p0)<<std::endl;
filename = newfname;
return true;
}
return false;
}
bool FileRepository::findFile(std::string& filename, const std::string& basedir, std::ostream* errlog)
{
if (filename.empty()) return false; // no filename
std::string currentDir = SetDirectory::GetCurrentDir();
if (!basedir.empty())
{
currentDir = SetDirectory::GetRelativeFromDir(basedir.c_str(),currentDir.c_str());
}
if (findFileIn(filename, currentDir)) return true;
if (SetDirectory::IsAbsolute(filename)) return false; // absolute file path
if (filename.substr(0,2)=="./" || filename.substr(0,3)=="../")
{
// update filename with current dir
filename = SetDirectory::GetRelativeFromDir(filename.c_str(), currentDir.c_str());
return false; // local file path
}
for (std::vector<std::string>::const_iterator it = vpath.begin(); it != vpath.end(); ++it)
if (findFileIn(filename, *it)) return true;
if (errlog)
{
(*errlog) << "File "<<filename<<" NOT FOUND in "<<basedir;
for (std::vector<std::string>::const_iterator it = vpath.begin(); it != vpath.end(); ++it)
(*errlog) << ':'<<*it;
(*errlog)<<std::endl;
}
return false;
}
bool FileRepository::findFileFromFile(std::string& filename, const std::string& basefile, std::ostream* errlog)
{
return findFile(filename, SetDirectory::GetParentDir(basefile.c_str()), errlog);
}
void FileRepository::print()
{
for (std::vector<std::string>::const_iterator it = vpath.begin(); it != vpath.end(); ++it)
std::cout << *it << std::endl;
}
/*static*/
std::string FileRepository::relativeToPath(std::string path, std::string refPath)
{
#ifdef WIN32
/*
WIN32 is a pain here because of mixed case formatting with randomly
picked slash and backslash to separate dirs.
*/
std::replace(path.begin(),path.end(),'\\' , '/' );
std::replace(refPath.begin(),refPath.end(),'\\' , '/' );
std::transform(path.begin(), path.end(), path.begin(), ::tolower );
std::transform(refPath.begin(), refPath.end(), refPath.begin(), ::tolower );
#endif
std::string::size_type loc = path.find( refPath, 0 );
if (loc==0) path = path.substr(refPath.size()+1);
return path;
}
} // namespace system
} // namespace helper
} // namespace sofa
<commit_msg>r10483/sofa : adding SRC path as a default file repository<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(WIN32)
#include <windows.h>
#include <direct.h>
#elif defined(_XBOX)
#include <xtl.h>
#else
#include <unistd.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
namespace sofa
{
namespace helper
{
namespace system
{
// replacing every occurences of "//" by "/"
std::string cleanPath( const std::string& path )
{
std::string p = path;
size_t pos = p.find("//");
size_t len = p.length();
while( pos != std::string::npos )
{
if ( pos == (len-1))
p.replace( pos, 2, "");
else
p.replace(pos,2,"/");
pos = p.find("//");
}
return p;
}
#define ADD_SOFA_BUILD_DIR( x ) sofa_tostring(SOFA_BUILD_DIR)sofa_tostring(x)
#define ADD_SOFA_SRC_DIR( x ) sofa_tostring(SOFA_SRC_DIR)sofa_tostring(x)
#if defined (WIN32) || defined (_XBOX)
#define SOFA_PLUGIN_SUBDIR /bin
#else
#define SOFA_PLUGIN_SUBDIR /lib
#endif
FileRepository PluginRepository("SOFA_PLUGIN_PATH", ADD_SOFA_BUILD_DIR(SOFA_PLUGIN_SUBDIR));
#undef SOFA_PLUGIN_SUBDIR
static FileRepository createSofaDataPath()
{
FileRepository repository("SOFA_DATA_PATH");
repository.addLastPath( ADD_SOFA_BUILD_DIR( / ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /share ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /examples ) );
#if defined (WIN32) || defined (_XBOX) || defined(PS3)
#elif defined (__APPLE__)
repository.addLastPath( ADD_SOFA_SRC_DIR( /Resources/examples ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /Resources ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /../../../examples ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /../../../share ) );
#else // LINUX
repository.addLastPath( ADD_SOFA_SRC_DIR( /../Verification/data ) );
repository.addLastPath( ADD_SOFA_SRC_DIR( /../Verification/simulation ) );
#endif
repository.addLastPath( ADD_SOFA_SRC_DIR() );
return repository;
}
FileRepository DataRepository = createSofaDataPath();
#undef ADD_SOFA_BUILD_DIR
#undef ADD_SOFA_SRC_DIR
#if defined (_XBOX) || defined(PS3)
char* getenv(const char* varname) { return NULL; } // NOT IMPLEMENTED
#endif
FileRepository::FileRepository(const char* envVar, const char* relativePath)
{
if (envVar != NULL && envVar[0]!='\0')
{
const char* envpath = getenv(envVar);
if (envpath != NULL && envpath[0]!='\0')
addFirstPath(envpath);
}
if (relativePath != NULL && relativePath[0]!='\0')
{
std::string path = relativePath;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
std::string p = path.substr(p0,p1-p0);
addLastPath(SetDirectory::GetRelativeFromProcess(p.c_str()));
}
p0 = p1+1;
}
}
//print();
}
FileRepository::~FileRepository()
{
}
std::string FileRepository::cleanPath( const std::string& path )
{
std::string p = path;
size_t pos = p.find("//");
size_t len = p.length();
while( pos != std::string::npos )
{
if ( pos == (len-2))
p.replace( pos, 2, "");
else
p.replace(pos,2,"/");
pos = p.find("//");
}
return p;
}
void FileRepository::addFirstPath(const std::string& p)
{
// replacing every occurences of "//" by "/"
std::string path = cleanPath( p );
std::vector<std::string> entries;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
entries.push_back(path.substr(p0,p1-p0));
}
p0 = p1+1;
}
vpath.insert(vpath.begin(), entries.begin(), entries.end());
}
void FileRepository::addLastPath(const std::string& p)
{
// replacing every occurences of "//" by "/"
std::string path = cleanPath( p );
std::vector<std::string> entries;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
entries.push_back(path.substr(p0,p1-p0));
}
p0 = p1+1;
}
vpath.insert(vpath.end(), entries.begin(), entries.end());
// std::cout << path << std::endl;
}
void FileRepository::removePath(const std::string& path)
{
std::vector<std::string> entries;
size_t p0 = 0;
size_t p1;
while ( p0 < path.size() )
{
p1 = path.find(entrySeparator(),p0);
if (p1 == std::string::npos) p1 = path.size();
if (p1>p0+1)
{
entries.push_back(path.substr(p0,p1-p0));
}
p0 = p1+1;
}
for(std::vector<std::string>::iterator it=entries.begin();
it!=entries.end(); it++)
{
vpath.erase( find(vpath.begin(), vpath.end(), *it) );
}
// Display
// std::cout<<(*this)<<std::endl;
}
std::string FileRepository::getFirstPath()
{
if (vpath.size() > 0)
return vpath.front();
else return "";
}
bool FileRepository::findFileIn(std::string& filename, const std::string& path)
{
if (filename.empty()) return false; // no filename
struct stat s;
std::string newfname = SetDirectory::GetRelativeFromDir(filename.c_str(), path.c_str());
//std::cout << "Looking for " << newfname <<std::endl;
if (!stat(newfname.c_str(),&s))
{
// File found
//std::cout << "File "<<filename<<" found in "<<path.substr(p0,p1-p0)<<std::endl;
filename = newfname;
return true;
}
return false;
}
bool FileRepository::findFile(std::string& filename, const std::string& basedir, std::ostream* errlog)
{
if (filename.empty()) return false; // no filename
std::string currentDir = SetDirectory::GetCurrentDir();
if (!basedir.empty())
{
currentDir = SetDirectory::GetRelativeFromDir(basedir.c_str(),currentDir.c_str());
}
if (findFileIn(filename, currentDir)) return true;
if (SetDirectory::IsAbsolute(filename)) return false; // absolute file path
if (filename.substr(0,2)=="./" || filename.substr(0,3)=="../")
{
// update filename with current dir
filename = SetDirectory::GetRelativeFromDir(filename.c_str(), currentDir.c_str());
return false; // local file path
}
for (std::vector<std::string>::const_iterator it = vpath.begin(); it != vpath.end(); ++it)
if (findFileIn(filename, *it)) return true;
if (errlog)
{
(*errlog) << "File "<<filename<<" NOT FOUND in "<<basedir;
for (std::vector<std::string>::const_iterator it = vpath.begin(); it != vpath.end(); ++it)
(*errlog) << ':'<<*it;
(*errlog)<<std::endl;
}
return false;
}
bool FileRepository::findFileFromFile(std::string& filename, const std::string& basefile, std::ostream* errlog)
{
return findFile(filename, SetDirectory::GetParentDir(basefile.c_str()), errlog);
}
void FileRepository::print()
{
for (std::vector<std::string>::const_iterator it = vpath.begin(); it != vpath.end(); ++it)
std::cout << *it << std::endl;
}
/*static*/
std::string FileRepository::relativeToPath(std::string path, std::string refPath)
{
#ifdef WIN32
/*
WIN32 is a pain here because of mixed case formatting with randomly
picked slash and backslash to separate dirs.
*/
std::replace(path.begin(),path.end(),'\\' , '/' );
std::replace(refPath.begin(),refPath.end(),'\\' , '/' );
std::transform(path.begin(), path.end(), path.begin(), ::tolower );
std::transform(refPath.begin(), refPath.end(), refPath.begin(), ::tolower );
#endif
std::string::size_type loc = path.find( refPath, 0 );
if (loc==0) path = path.substr(refPath.size()+1);
return path;
}
} // namespace system
} // namespace helper
} // namespace sofa
<|endoftext|> |
<commit_before>/*
ofxTableGestures (formerly OF-TangibleFramework)
Developed for Taller de Sistemes Interactius I
Universitat Pompeu Fabra
Copyright (c) 2010 Daniel Gallardo Grassot <daniel.gallardo@upf.edu>
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 "ofMain.h"
#include "GraphicDispatcher.hpp"
#include <algorithm>
#include <functional>
#include <tr1/functional>
#include <cassert>
GraphicDispatcher::GraphicDispatcher():ngraphics(0) {
}
GraphicDispatcher::~GraphicDispatcher(){
}
void GraphicDispatcher::Draw(){
std::for_each(graphics.begin(),graphics.end(),std::mem_fun(&GraphicSmartContainer::draw));
}
/*struct Deleter
{
void operator()(GraphicSmartContainer * g)
{
delete g;
}
};*/
void GraphicDispatcher::Update(){
for (GraphicsList::iterator it = graphics.begin(); it != graphics.end();)
{
GraphicSmartContainer * g = *it;
if (g->todelete())
{
graphics.erase(it++);
delete g;
}
else
{
++it;
}
}
GraphicsList gr = graphics;
std::for_each(gr.begin(),gr.end(),std::mem_fun(&GraphicSmartContainer::update));
}
void GraphicDispatcher::Resize(int w, int h){
std::for_each(graphics.begin(),graphics.end(),
std::tr1::bind(&GraphicSmartContainer::resize,std::tr1::placeholders::_1,w,h));
}
void GraphicDispatcher::AddGraphic(GraphicSmartContainer* graphic){
graphic->created_time = ngraphics++;
graphics.insert(graphic);
}
/*void GraphicDispatcher::RemoveGraphic(Graphic* graphic){
graphics.erase(graphic);
}*/
void GraphicDispatcher::bring_top(GraphicSmartContainer* graphic){
if(!graphics.erase(graphic)) ofLogError() << "[bring_top] Unable to remove graphic from list!";
graphic->created_time = ngraphics++;
graphics.insert(graphic);
}
void GraphicDispatcher::ChangeLayer(GraphicSmartContainer * graphic, int newlayer){
if(!graphics.erase(graphic)) ofLogError() << "[ChangeLayer] Unable to remove graphic from list!";
graphic->graphic->layer = newlayer;
graphic->created_time = ngraphics++;
graphics.insert(graphic);
}
Graphic * GraphicDispatcher::Collide(ofPoint const & point)
{
GraphicsList::reverse_iterator it = std::find_if(graphics.rbegin(),graphics.rend(),
std::tr1::bind(&GraphicSmartContainer::Collide,std::tr1::placeholders::_1,point));
if (it != graphics.rend())
return (*it)->graphic;
return NULL;
}
/*void GraphicDispatcher::SafeDeleteGraphic(Graphic* graphic)
{
to_delete.push_back(graphic);
}*/
<commit_msg>Remove tr1 from GraphichDispatcher.cpp<commit_after>/*
ofxTableGestures (formerly OF-TangibleFramework)
Developed for Taller de Sistemes Interactius I
Universitat Pompeu Fabra
Copyright (c) 2010 Daniel Gallardo Grassot <daniel.gallardo@upf.edu>
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 "ofMain.h"
#include "GraphicDispatcher.hpp"
#include <algorithm>
#include <functional>
#include <cassert>
GraphicDispatcher::GraphicDispatcher():ngraphics(0) {
}
GraphicDispatcher::~GraphicDispatcher(){
}
void GraphicDispatcher::Draw(){
std::for_each(graphics.begin(),graphics.end(),std::mem_fun(&GraphicSmartContainer::draw));
}
/*struct Deleter
{
void operator()(GraphicSmartContainer * g)
{
delete g;
}
};*/
void GraphicDispatcher::Update(){
for (GraphicsList::iterator it = graphics.begin(); it != graphics.end();)
{
GraphicSmartContainer * g = *it;
if (g->todelete())
{
graphics.erase(it++);
delete g;
}
else
{
++it;
}
}
GraphicsList gr = graphics;
std::for_each(gr.begin(),gr.end(),std::mem_fun(&GraphicSmartContainer::update));
}
void GraphicDispatcher::Resize(int w, int h){
std::for_each(graphics.begin(),graphics.end(),
std::bind(&GraphicSmartContainer::resize,std::placeholders::_1,w,h));
}
void GraphicDispatcher::AddGraphic(GraphicSmartContainer* graphic){
graphic->created_time = ngraphics++;
graphics.insert(graphic);
}
/*void GraphicDispatcher::RemoveGraphic(Graphic* graphic){
graphics.erase(graphic);
}*/
void GraphicDispatcher::bring_top(GraphicSmartContainer* graphic){
if(!graphics.erase(graphic)) ofLogError() << "[bring_top] Unable to remove graphic from list!";
graphic->created_time = ngraphics++;
graphics.insert(graphic);
}
void GraphicDispatcher::ChangeLayer(GraphicSmartContainer * graphic, int newlayer){
if(!graphics.erase(graphic)) ofLogError() << "[ChangeLayer] Unable to remove graphic from list!";
graphic->graphic->layer = newlayer;
graphic->created_time = ngraphics++;
graphics.insert(graphic);
}
Graphic * GraphicDispatcher::Collide(ofPoint const & point)
{
GraphicsList::reverse_iterator it = std::find_if(graphics.rbegin(),graphics.rend(),
std::bind(&GraphicSmartContainer::Collide,std::placeholders::_1,point));
if (it != graphics.rend())
return (*it)->graphic;
return NULL;
}
/*void GraphicDispatcher::SafeDeleteGraphic(Graphic* graphic)
{
to_delete.push_back(graphic);
}*/
<|endoftext|> |
<commit_before>
#include "CCameraController.h"
#include <ionWindow.h>
#include <glm/gtc/matrix_transform.hpp>
namespace ion
{
CCameraController::CCameraController(Scene::ICamera * Camera)
{
this->Camera = Camera;
this->Phi = 0;
this->Theta = 1.5708f;
this->Tracking = false;
this->MoveSpeed = 2.5f;
this->LookSpeed = 0.005f;
this->FocalLengthDelta = 1.1f;
this->MaxAngleEpsilon = 0.01f;
for (int i = 0; i < (int) ECommand::Count; ++ i)
this->Commands[i] = false;
}
void CCameraController::OnEvent(IEvent & Event)
{
if (InstanceOf<SMouseEvent>(Event))
{
SMouseEvent & MouseEvent = As<SMouseEvent>(Event);
if (MouseEvent.Type == SMouseEvent::EType::Click && (MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right)
Tracking = true;
if (MouseEvent.Type == SMouseEvent::EType::Click && (! MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right)
Tracking = false;
if (MouseEvent.Type == SMouseEvent::EType::Move)
{
if (Tracking)
{
Theta += (MouseEvent.Movement.X) * LookSpeed;
Phi -= (MouseEvent.Movement.Y) * LookSpeed;
}
}
if (MouseEvent.Type == SMouseEvent::EType::Scroll)
{
Scene::CPerspectiveCamera * PerspectiveCamera = nullptr;
if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera)))
{
f32 FocalLength = PerspectiveCamera->GetFocalLength();
s32 ticks = (s32) MouseEvent.Movement.Y;
if (ticks > 0)
while (ticks-- > 0)
FocalLength *= FocalLengthDelta;
else if (ticks < 0)
while (ticks++ < 0)
FocalLength /= FocalLengthDelta;
PerspectiveCamera->SetFocalLength(FocalLength);
}
}
}
else if (InstanceOf<SKeyboardEvent>(Event))
{
SKeyboardEvent & KeyboardEvent = As<SKeyboardEvent>(Event);
if (KeyboardEvent.Key == EKey::W || KeyboardEvent.Key == EKey::Up)
Commands[(int) ECommand::Forward] = KeyboardEvent.Pressed;
if (KeyboardEvent.Key == EKey::S || KeyboardEvent.Key == EKey::Down)
Commands[(int) ECommand::Back] = KeyboardEvent.Pressed;
if (KeyboardEvent.Key == EKey::A || KeyboardEvent.Key == EKey::Left)
Commands[(int) ECommand::Left] = KeyboardEvent.Pressed;
if (KeyboardEvent.Key == EKey::D || KeyboardEvent.Key == EKey::Right)
Commands[(int) ECommand::Right] = KeyboardEvent.Pressed;
if (! KeyboardEvent.Pressed)
{
if (KeyboardEvent.Key == EKey::Num0)
SetVelocity(5000000.f);
if (KeyboardEvent.Key == EKey::Num9)
SetVelocity(500000.f);
if (KeyboardEvent.Key == EKey::Num8)
SetVelocity(50000.f);
if (KeyboardEvent.Key == EKey::Num7)
SetVelocity(5000.f);
if (KeyboardEvent.Key == EKey::Num6)
SetVelocity(500.f);
if (KeyboardEvent.Key == EKey::Num5)
SetVelocity(50.f);
if (KeyboardEvent.Key == EKey::Num4)
SetVelocity(10.f);
if (KeyboardEvent.Key == EKey::Num3)
SetVelocity(2.5f);
if (KeyboardEvent.Key == EKey::Num2)
SetVelocity(0.75f);
if (KeyboardEvent.Key == EKey::Num1)
SetVelocity(0.1f);
}
}
else if (InstanceOf<CTimeManager::CUpdateTick>(Event))
{
CTimeManager::CUpdateTick & UpdateTick = As<CTimeManager::CUpdateTick>(Event);
Update(UpdateTick.GetElapsedTime());
}
}
void CCameraController::Update(f64 const TickTime)
{
if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon)
Phi = Constants32::Pi / 2 - MaxAngleEpsilon;
if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon)
Phi = -Constants32::Pi / 2 + MaxAngleEpsilon;
vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi));
vec3f const UpVector = Camera->GetUpVector();
vec3f Translation = Camera->GetPosition();
vec3f const W = -1 * LookDirection;
vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized();
vec3f const U = V.CrossProduct(W).GetNormalized()*-1;
f32 const MoveDelta = MoveSpeed * (f32) TickTime;
if (Commands[(int) ECommand::Forward])
Translation += LookDirection * MoveDelta;
if (Commands[(int) ECommand::Left])
Translation += V * MoveDelta;
if (Commands[(int) ECommand::Right])
Translation -= V * MoveDelta;
if (Commands[(int) ECommand::Back])
Translation -= LookDirection * MoveDelta;
Camera->SetPosition(Translation);
Camera->SetLookDirection(LookDirection);
}
vec3f const & CCameraController::GetPosition() const
{
return Camera->GetPosition();
}
Scene::ICamera const * CCameraController::GetCamera() const
{
return Camera;
}
Scene::ICamera * CCameraController::GetCamera()
{
return Camera;
}
f32 CCameraController::GetVelocity() const
{
return MoveSpeed;
}
void CCameraController::SetVelocity(float const velocity)
{
MoveSpeed = velocity;
}
f32 CCameraController::GetPhi() const
{
return Phi;
}
void CCameraController::SetPhi(f32 const Phi)
{
this->Phi = Phi;
}
f32 CCameraController::GetTheta() const
{
return Theta;
}
void CCameraController::SetTheta(f32 const Theta)
{
this->Theta = Theta;
}
//////////////////////////////
// CGamePadCameraController //
//////////////////////////////
CGamePadCameraController::CGamePadCameraController(Scene::ICamera * Camera)
: CCameraController(Camera)
{}
void CGamePadCameraController::Update(f64 const TickTime)
{
GamePad->UpdateState();
f32 const RightMod = (1.f + 5.f * GamePad->GetRightTrigger());
f32 const LeftMod = (1.f / (1.f + 10.f * GamePad->GetLeftTrigger()));
// Look - Right Axis
f32 const LookMod = 512.f * LeftMod;
Theta += (GamePad->GetRightStick().X) * LookMod * LookSpeed * (f32) TickTime;
Phi += (GamePad->GetRightStick().Y) * LookMod * LookSpeed * (f32) TickTime;
if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon)
Phi = Constants32::Pi / 2 - MaxAngleEpsilon;
if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon)
Phi = -Constants32::Pi / 2 + MaxAngleEpsilon;
vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi));
vec3f const UpVector = Camera->GetUpVector();
vec3f Translation = Camera->GetPosition();
vec3f const W = -1 * LookDirection;
vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized();
vec3f const U = V.CrossProduct(W).GetNormalized()*-1;
// Movement - Left Axis
f32 const MoveDelta = MoveSpeed * (f32) TickTime * RightMod * LeftMod;
Translation += LookDirection * MoveDelta * GamePad->GetLeftStick().Y;
Translation -= V * MoveDelta * GamePad->GetLeftStick().X;
if (GamePad->IsButtonPressed(EGamePadButton::LeftShoulder))
Translation.Y -= MoveDelta;
if (GamePad->IsButtonPressed(EGamePadButton::RightShoulder))
Translation.Y += MoveDelta;
Camera->SetPosition(Translation);
// Focal Length - DPad
f32 const ZoomSpeed = 100.f;
f32 const ZoomMod = 1.01f;
Scene::CPerspectiveCamera * PerspectiveCamera = nullptr;
if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera)))
{
f32 FocalLength = PerspectiveCamera->GetFocalLength();
if (GamePad->IsButtonPressed(EGamePadButton::DPadUp))
FocalLengthAccumulator += ZoomSpeed * (f32) TickTime;
if (GamePad->IsButtonPressed(EGamePadButton::DPadDown))
FocalLengthAccumulator -= ZoomSpeed * (f32) TickTime;
if (FocalLengthAccumulator > 1)
{
while (FocalLengthAccumulator > 1)
{
FocalLengthAccumulator -= 1.f;
FocalLength *= ZoomMod;
}
}
else if (FocalLengthAccumulator < -1)
{
while (FocalLengthAccumulator < -1)
{
FocalLengthAccumulator += 1.f;
FocalLength /= ZoomMod;
}
}
PerspectiveCamera->SetFocalLength(FocalLength);
}
CCameraController::Update(TickTime);
}
}
<commit_msg>[ionApplication] Add buttons to control gamepad camera velocity<commit_after>
#include "CCameraController.h"
#include <ionWindow.h>
#include <glm/gtc/matrix_transform.hpp>
namespace ion
{
CCameraController::CCameraController(Scene::ICamera * Camera)
{
this->Camera = Camera;
this->Phi = 0;
this->Theta = 1.5708f;
this->Tracking = false;
this->MoveSpeed = 2.5f;
this->LookSpeed = 0.005f;
this->FocalLengthDelta = 1.1f;
this->MaxAngleEpsilon = 0.01f;
for (int i = 0; i < (int) ECommand::Count; ++ i)
this->Commands[i] = false;
}
void CCameraController::OnEvent(IEvent & Event)
{
if (InstanceOf<SMouseEvent>(Event))
{
SMouseEvent & MouseEvent = As<SMouseEvent>(Event);
if (MouseEvent.Type == SMouseEvent::EType::Click && (MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right)
Tracking = true;
if (MouseEvent.Type == SMouseEvent::EType::Click && (! MouseEvent.Pressed) && MouseEvent.Button == SMouseEvent::EButton::Right)
Tracking = false;
if (MouseEvent.Type == SMouseEvent::EType::Move)
{
if (Tracking)
{
Theta += (MouseEvent.Movement.X) * LookSpeed;
Phi -= (MouseEvent.Movement.Y) * LookSpeed;
}
}
if (MouseEvent.Type == SMouseEvent::EType::Scroll)
{
Scene::CPerspectiveCamera * PerspectiveCamera = nullptr;
if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera)))
{
f32 FocalLength = PerspectiveCamera->GetFocalLength();
s32 ticks = (s32) MouseEvent.Movement.Y;
if (ticks > 0)
while (ticks-- > 0)
FocalLength *= FocalLengthDelta;
else if (ticks < 0)
while (ticks++ < 0)
FocalLength /= FocalLengthDelta;
PerspectiveCamera->SetFocalLength(FocalLength);
}
}
}
else if (InstanceOf<SKeyboardEvent>(Event))
{
SKeyboardEvent & KeyboardEvent = As<SKeyboardEvent>(Event);
if (KeyboardEvent.Key == EKey::W || KeyboardEvent.Key == EKey::Up)
Commands[(int) ECommand::Forward] = KeyboardEvent.Pressed;
if (KeyboardEvent.Key == EKey::S || KeyboardEvent.Key == EKey::Down)
Commands[(int) ECommand::Back] = KeyboardEvent.Pressed;
if (KeyboardEvent.Key == EKey::A || KeyboardEvent.Key == EKey::Left)
Commands[(int) ECommand::Left] = KeyboardEvent.Pressed;
if (KeyboardEvent.Key == EKey::D || KeyboardEvent.Key == EKey::Right)
Commands[(int) ECommand::Right] = KeyboardEvent.Pressed;
if (! KeyboardEvent.Pressed)
{
if (KeyboardEvent.Key == EKey::Num0)
SetVelocity(5000000.f);
if (KeyboardEvent.Key == EKey::Num9)
SetVelocity(500000.f);
if (KeyboardEvent.Key == EKey::Num8)
SetVelocity(50000.f);
if (KeyboardEvent.Key == EKey::Num7)
SetVelocity(5000.f);
if (KeyboardEvent.Key == EKey::Num6)
SetVelocity(500.f);
if (KeyboardEvent.Key == EKey::Num5)
SetVelocity(50.f);
if (KeyboardEvent.Key == EKey::Num4)
SetVelocity(10.f);
if (KeyboardEvent.Key == EKey::Num3)
SetVelocity(2.5f);
if (KeyboardEvent.Key == EKey::Num2)
SetVelocity(0.75f);
if (KeyboardEvent.Key == EKey::Num1)
SetVelocity(0.1f);
}
}
else if (InstanceOf<CTimeManager::CUpdateTick>(Event))
{
CTimeManager::CUpdateTick & UpdateTick = As<CTimeManager::CUpdateTick>(Event);
Update(UpdateTick.GetElapsedTime());
}
}
void CCameraController::Update(f64 const TickTime)
{
if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon)
Phi = Constants32::Pi / 2 - MaxAngleEpsilon;
if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon)
Phi = -Constants32::Pi / 2 + MaxAngleEpsilon;
vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi));
vec3f const UpVector = Camera->GetUpVector();
vec3f Translation = Camera->GetPosition();
vec3f const W = -1 * LookDirection;
vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized();
vec3f const U = V.CrossProduct(W).GetNormalized()*-1;
f32 const MoveDelta = MoveSpeed * (f32) TickTime;
if (Commands[(int) ECommand::Forward])
Translation += LookDirection * MoveDelta;
if (Commands[(int) ECommand::Left])
Translation += V * MoveDelta;
if (Commands[(int) ECommand::Right])
Translation -= V * MoveDelta;
if (Commands[(int) ECommand::Back])
Translation -= LookDirection * MoveDelta;
Camera->SetPosition(Translation);
Camera->SetLookDirection(LookDirection);
}
vec3f const & CCameraController::GetPosition() const
{
return Camera->GetPosition();
}
Scene::ICamera const * CCameraController::GetCamera() const
{
return Camera;
}
Scene::ICamera * CCameraController::GetCamera()
{
return Camera;
}
f32 CCameraController::GetVelocity() const
{
return MoveSpeed;
}
void CCameraController::SetVelocity(float const velocity)
{
MoveSpeed = velocity;
}
f32 CCameraController::GetPhi() const
{
return Phi;
}
void CCameraController::SetPhi(f32 const Phi)
{
this->Phi = Phi;
}
f32 CCameraController::GetTheta() const
{
return Theta;
}
void CCameraController::SetTheta(f32 const Theta)
{
this->Theta = Theta;
}
//////////////////////////////
// CGamePadCameraController //
//////////////////////////////
CGamePadCameraController::CGamePadCameraController(Scene::ICamera * Camera)
: CCameraController(Camera)
{}
void CGamePadCameraController::Update(f64 const TickTime)
{
GamePad->UpdateState();
f32 const RightMod = (1.f + 5.f * GamePad->GetRightTrigger());
f32 const LeftMod = (1.f / (1.f + 10.f * GamePad->GetLeftTrigger()));
// Look - Right Axis
f32 const LookMod = 512.f * LeftMod;
Theta += (GamePad->GetRightStick().X) * LookMod * LookSpeed * (f32) TickTime;
Phi += (GamePad->GetRightStick().Y) * LookMod * LookSpeed * (f32) TickTime;
if (Phi > Constants32::Pi / 2 - MaxAngleEpsilon)
Phi = Constants32::Pi / 2 - MaxAngleEpsilon;
if (Phi < -Constants32::Pi / 2 + MaxAngleEpsilon)
Phi = -Constants32::Pi / 2 + MaxAngleEpsilon;
vec3f const LookDirection = vec3f(Cos(Theta)*Cos(Phi), Sin(Phi), Sin(Theta)*Cos(Phi));
vec3f const UpVector = Camera->GetUpVector();
vec3f Translation = Camera->GetPosition();
vec3f const W = -1 * LookDirection;
vec3f const V = UpVector.CrossProduct(LookDirection).GetNormalized();
vec3f const U = V.CrossProduct(W).GetNormalized()*-1;
// Movement - Left Axis
f32 const MoveDelta = MoveSpeed * (f32) TickTime * RightMod * LeftMod;
Translation += LookDirection * MoveDelta * GamePad->GetLeftStick().Y;
Translation -= V * MoveDelta * GamePad->GetLeftStick().X;
if (GamePad->IsButtonPressed(EGamePadButton::LeftShoulder))
Translation.Y -= MoveDelta;
if (GamePad->IsButtonPressed(EGamePadButton::RightShoulder))
Translation.Y += MoveDelta;
Camera->SetPosition(Translation);
// Camera Speed
f32 const AccelerateSpeed = 32.f;
if (GamePad->IsButtonPressed(EGamePadButton::DPadRight))
MoveSpeed += AccelerateSpeed * (f32) TickTime;
if (GamePad->IsButtonPressed(EGamePadButton::DPadLeft))
MoveSpeed -= AccelerateSpeed * (f32) TickTime;
// Focal Length - DPad
f32 const ZoomSpeed = 100.f;
f32 const ZoomMod = 1.01f;
Scene::CPerspectiveCamera * PerspectiveCamera = nullptr;
if ((PerspectiveCamera = As<Scene::CPerspectiveCamera>(Camera)))
{
f32 FocalLength = PerspectiveCamera->GetFocalLength();
if (GamePad->IsButtonPressed(EGamePadButton::DPadUp))
FocalLengthAccumulator += ZoomSpeed * (f32) TickTime;
if (GamePad->IsButtonPressed(EGamePadButton::DPadDown))
FocalLengthAccumulator -= ZoomSpeed * (f32) TickTime;
if (FocalLengthAccumulator > 1)
{
while (FocalLengthAccumulator > 1)
{
FocalLengthAccumulator -= 1.f;
FocalLength *= ZoomMod;
}
}
else if (FocalLengthAccumulator < -1)
{
while (FocalLengthAccumulator < -1)
{
FocalLengthAccumulator += 1.f;
FocalLength /= ZoomMod;
}
}
PerspectiveCamera->SetFocalLength(FocalLength);
}
CCameraController::Update(TickTime);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: StreamL.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "StreamL.hh"
vlStreamLine::vlStreamLine()
{
}
// Description:
// Specify the start of the streamline in the cell coordinate system. That is,
// cellId and subId (if composite cell), and parametric coordinates.
void vlStreamLine::SetStartLocation(int cellId, int subId, float pcoords[3])
{
}
// Description:
// Get the starting location of the streamline in the cell corrdinate system.
int vlStreamLine::GetStartLocation(int& subId, float pcoords[3])
{
}
// Description:
// Specify the start of the streamline in the global coordinate system. Search
// must be performed to find initial cell to strart integration from.
void vlStreamLine::SetStartPosition(float x[3])
{
}
// Description:
// Get the start position in global x-y-z coordinates.
float *vlStreamLine::GetStartPosition()
{
}
void vlStreamLine::Execute()
{
}
void vlStreamLine::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlStreamLine::GetClassName()))
{
vlDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "";
}
}
<commit_msg>Will forced me to hack this<commit_after>/*=========================================================================
Program: Visualization Library
Module: StreamL.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "StreamL.hh"
vlStreamLine::vlStreamLine()
{
}
// Description:
// Specify the start of the streamline in the cell coordinate system. That is,
// cellId and subId (if composite cell), and parametric coordinates.
void vlStreamLine::SetStartLocation(int cellId, int subId, float pcoords[3])
{
}
// Description:
// Get the starting location of the streamline in the cell corrdinate system.
int vlStreamLine::GetStartLocation(int& subId, float pcoords[3])
{
return 89;
}
// Description:
// Specify the start of the streamline in the global coordinate system. Search
// must be performed to find initial cell to strart integration from.
void vlStreamLine::SetStartPosition(float x[3])
{
}
// Description:
// Get the start position in global x-y-z coordinates.
float *vlStreamLine::GetStartPosition()
{
static float foo[3];
return foo;
}
void vlStreamLine::Execute()
{
}
void vlStreamLine::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlStreamLine::GetClassName()))
{
vlDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "";
}
}
<|endoftext|> |
<commit_before>// $Id$
//
// Test Suite for geos::operation::polygonize::Polygonizer class.
//
// Port of junit/operation/polygonize/PolygonizeTest.java
//
// tut
#include <tut.hpp>
// geos
#include <geos/operation/polygonize/Polygonizer.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/Point.h>
#include <geos/io/WKTReader.h>
#include <geos/io/WKTWriter.h>
// std
#include <memory>
#include <string>
#include <vector>
#include <iostream>
namespace tut
{
//
// Test Group
//
// Common data used by tests
struct test_polygonizetest_data
{
geos::geom::GeometryFactory gf;
geos::io::WKTReader wktreader;
geos::io::WKTWriter wktwriter;
typedef geos::geom::Geometry::AutoPtr GeomPtr;
typedef geos::geom::Geometry Geom;
typedef geos::geom::Polygon Poly;
typedef geos::operation::polygonize::Polygonizer Polygonizer;
test_polygonizetest_data()
: gf(),
wktreader(&gf)
{
wktwriter.setTrim(true);
}
template <class T>
void delAll(T& cnt)
{
for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) {
delete *i;
}
}
template <class T>
void printAll(std::ostream& os, T& cnt)
{
for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) {
os << **i;
}
}
GeomPtr readWKT(const std::string& inputWKT)
{
return GeomPtr(wktreader.read(inputWKT));
}
void readWKT(const char* const* inputWKT, std::vector<Geom*>& geoms)
{
for (const char* const* ptr=inputWKT; *ptr; ++ptr) {
geoms.push_back(readWKT(*ptr).release());
}
}
template <class T>
bool contains( T& cnt, const Geom* g)
{
for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) {
const Geom* element = *i;
if (element->equalsExact(g)) {
return true;
}
}
return false;
}
template <class T, class S>
bool compare( T& ex, S& ob)
{
using std::cout;
using std::endl;
if ( ex.size() != ob.size() ) {
cout << "Expected " << ex.size() << " polygons, obtained "
<< ob.size() << endl;
return false;
}
for (typename T::iterator i=ex.begin(), e=ex.end(); i!=e; ++i) {
if ( ! contains(ob, *i) ) {
cout << "Expected " << wktwriter.write(*i)
<< " not found" << endl;
return false;
}
}
return true;
}
bool doTest(const char* const* inputWKT, const char* const* expectWKT)
{
using std::cout;
using std::endl;
std::vector<Geom*> inputGeoms, expectGeoms;
readWKT(inputWKT, inputGeoms);
readWKT(expectWKT, expectGeoms);
Polygonizer polygonizer;
polygonizer.add(&inputGeoms);
std::auto_ptr< std::vector<Poly*> > retGeoms;
retGeoms.reset( polygonizer.getPolygons() );
delAll(inputGeoms);
bool ok = compare(expectGeoms, *retGeoms);
if ( ! ok ) {
cout << "OBTAINED(" << retGeoms->size() << "): ";
printAll(cout, *retGeoms);
cout << endl;
ensure( "not all expected geometries in the obtained set", 0 );
}
delAll(expectGeoms);
delAll(*retGeoms);
return ok;
}
};
typedef test_group<test_polygonizetest_data> group;
typedef group::object object;
group test_polygonizetest_group("geos::operation::polygonize::Polygonizer");
template<>
template<>
void object::test<1>()
{
static char const* const inp[] = {
"LINESTRING EMPTY",
"LINESTRING EMPTY",
NULL
};
static char const* const exp[] = {
NULL
};
doTest(inp, exp);
}
template<>
template<>
void object::test<2>()
{
static char const* const inp[] = {
"LINESTRING (100 180, 20 20, 160 20, 100 180)",
"LINESTRING (100 180, 80 60, 120 60, 100 180)",
NULL
};
static char const* const exp[] = {
"POLYGON ((100 180, 120 60, 80 60, 100 180))",
"POLYGON ((100 180, 160 20, 20 20, 100 180), (100 180, 80 60, 120 60, 100 180))",
NULL
};
doTest(inp, exp);
}
} // namespace tut
<commit_msg>Add port info<commit_after>// $Id$
//
// Test Suite for geos::operation::polygonize::Polygonizer class.
//
// Port of junit/operation/polygonize/PolygonizeTest.java
//
// tut
#include <tut.hpp>
// geos
#include <geos/operation/polygonize/Polygonizer.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/Point.h>
#include <geos/io/WKTReader.h>
#include <geos/io/WKTWriter.h>
// std
#include <memory>
#include <string>
#include <vector>
#include <iostream>
namespace tut
{
//
// Test Group
//
// Common data used by tests
struct test_polygonizetest_data
{
geos::geom::GeometryFactory gf;
geos::io::WKTReader wktreader;
geos::io::WKTWriter wktwriter;
typedef geos::geom::Geometry::AutoPtr GeomPtr;
typedef geos::geom::Geometry Geom;
typedef geos::geom::Polygon Poly;
typedef geos::operation::polygonize::Polygonizer Polygonizer;
test_polygonizetest_data()
: gf(),
wktreader(&gf)
{
wktwriter.setTrim(true);
}
template <class T>
void delAll(T& cnt)
{
for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) {
delete *i;
}
}
template <class T>
void printAll(std::ostream& os, T& cnt)
{
for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) {
os << **i;
}
}
GeomPtr readWKT(const std::string& inputWKT)
{
return GeomPtr(wktreader.read(inputWKT));
}
void readWKT(const char* const* inputWKT, std::vector<Geom*>& geoms)
{
for (const char* const* ptr=inputWKT; *ptr; ++ptr) {
geoms.push_back(readWKT(*ptr).release());
}
}
template <class T>
bool contains( T& cnt, const Geom* g)
{
for (typename T::iterator i=cnt.begin(), e=cnt.end(); i!=e; ++i) {
const Geom* element = *i;
if (element->equalsExact(g)) {
return true;
}
}
return false;
}
template <class T, class S>
bool compare( T& ex, S& ob)
{
using std::cout;
using std::endl;
if ( ex.size() != ob.size() ) {
cout << "Expected " << ex.size() << " polygons, obtained "
<< ob.size() << endl;
return false;
}
for (typename T::iterator i=ex.begin(), e=ex.end(); i!=e; ++i) {
if ( ! contains(ob, *i) ) {
cout << "Expected " << wktwriter.write(*i)
<< " not found" << endl;
return false;
}
}
return true;
}
bool doTest(const char* const* inputWKT, const char* const* expectWKT)
{
using std::cout;
using std::endl;
std::vector<Geom*> inputGeoms, expectGeoms;
readWKT(inputWKT, inputGeoms);
readWKT(expectWKT, expectGeoms);
Polygonizer polygonizer;
polygonizer.add(&inputGeoms);
std::auto_ptr< std::vector<Poly*> > retGeoms;
retGeoms.reset( polygonizer.getPolygons() );
delAll(inputGeoms);
bool ok = compare(expectGeoms, *retGeoms);
if ( ! ok ) {
cout << "OBTAINED(" << retGeoms->size() << "): ";
printAll(cout, *retGeoms);
cout << endl;
ensure( "not all expected geometries in the obtained set", 0 );
}
delAll(expectGeoms);
delAll(*retGeoms);
return ok;
}
};
typedef test_group<test_polygonizetest_data> group;
typedef group::object object;
group test_polygonizetest_group("geos::operation::polygonize::Polygonizer");
// test1() in JTS
template<>
template<>
void object::test<1>()
{
static char const* const inp[] = {
"LINESTRING EMPTY",
"LINESTRING EMPTY",
NULL
};
static char const* const exp[] = {
NULL
};
doTest(inp, exp);
}
// test2() in JTS
template<>
template<>
void object::test<2>()
{
static char const* const inp[] = {
"LINESTRING (100 180, 20 20, 160 20, 100 180)",
"LINESTRING (100 180, 80 60, 120 60, 100 180)",
NULL
};
static char const* const exp[] = {
"POLYGON ((100 180, 120 60, 80 60, 100 180))",
"POLYGON ((100 180, 160 20, 20 20, 100 180), (100 180, 80 60, 120 60, 100 180))",
NULL
};
doTest(inp, exp);
}
} // namespace tut
<|endoftext|> |
<commit_before>#ifndef DISSENT_CRYPTO_CPP_DSA_PUBLIC_KEY_H_GUARD
#define DISSENT_CRYPTO_CPP_DSA_PUBLIC_KEY_H_GUARD
#include <stdexcept>
#include <QByteArray>
#include <QDebug>
#include <QFile>
#include <QString>
#include <cryptopp/aes.h>
#include <cryptopp/ccm.h>
#include <cryptopp/des.h>
#include <cryptopp/dsa.h>
#include <cryptopp/osrng.h>
#include <cryptopp/sha.h>
#include "AsymmetricKey.hpp"
#include "Integer.hpp"
namespace Dissent {
namespace Crypto {
/**
* Implementation of KeyBase::PublicKey using CryptoPP
*/
class CppDsaPublicKey : public AsymmetricKey {
public:
typedef CryptoPP::GDSA<CryptoPP::SHA256> KeyBase;
typedef CryptoPP::DL_GroupParameters_GFP Parameters;
typedef CryptoPP::DL_Key<Parameters::Element> Key;
/**
* Reads a key from a file
* @param filename the file storing the key
*/
explicit CppDsaPublicKey(const QString &filename);
/**
* Loads a key from memory
* @param data byte array holding the key
*/
explicit CppDsaPublicKey(const QByteArray &data);
/**
* Creates a public Dsa key given the public parameters
* @param modulus the p of the public key
* @param subgroup the q of the public key
* @param generator the g of the public key
* @param public_element the y of the public key (g^x)
*/
explicit CppDsaPublicKey(const Integer &modulus,
const Integer &subgroup, const Integer &generator,
const Integer &public_element);
/**
* Deconstructor
*/
virtual ~CppDsaPublicKey();
/**
* Creates a public key based upon the seed data, same seed data same
* key. This is mainly used for distributed tests, so other members can
* generate an appropriate public key.
*/
static CppDsaPublicKey *GenerateKey(const QByteArray &data);
/**
* Get a copy of the public key
*/
virtual AsymmetricKey *GetPublicKey() const;
virtual QByteArray GetByteArray() const;
/**
* Returns nothing, not supported for public keys
*/
virtual QByteArray Sign(const QByteArray &data) const;
virtual bool Verify(const QByteArray &data, const QByteArray &sig) const;
/**
* Returns nothing, not supported for DSA
*/
virtual QByteArray Encrypt(const QByteArray &data) const;
/**
* Returns nothing, not supported for DSA
*/
virtual QByteArray Decrypt(const QByteArray &data) const;
inline virtual bool IsPrivateKey() const { return false; }
virtual bool VerifyKey(AsymmetricKey &key) const;
inline virtual bool IsValid() const { return _valid; }
inline virtual int GetKeySize() const { return _key_size; }
/**
* DSA does not explicitly allow encryption
*/
virtual bool SupportsEncryption() { return false; }
/**
* DSA does not work with keys below 1024
*/
static inline int GetMinimumKeySize() { return 1024; }
/**
* Returns the g of the DSA public key
*/
Integer GetGenerator() const;
/**
* Returns the p of the DSA public key
*/
Integer GetModulus() const;
/**
* Returns the q of the DSA public key
*/
Integer GetSubgroup() const;
/**
* Returns the y = g^x mod p of the DSA public key
*/
Integer GetPublicElement() const;
protected:
inline virtual const Parameters &GetGroupParameters() const
{
return GetDsaPublicKey()->GetGroupParameters();
}
/**
* Does not make sense to create random public keys
*/
CppDsaPublicKey() { }
/**
* Used to construct private key
*/
CppDsaPublicKey(Key *key);
/**
* Loads a key from the provided byte array
* @param data key byte array
*/
bool InitFromByteArray(const QByteArray &data);
/**
* Loads a key from the given filename
* @param filename file storing the key
*/
bool InitFromFile(const QString &filename);
/**
* Prevents a remote user from giving a malicious DSA key
*/
inline bool Validate()
{
_valid = false;
_key_size = 0;
if(!_key) {
return false;
}
CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;
if(GetCryptoMaterial()->Validate(rng, 1)) {
_key_size = GetGroupParameters().GetModulus().BitCount();
_valid = true;
return true;
}
return false;
}
/**
* Returns the internal Dsa Public Key
*/
virtual const KeyBase::PublicKey *GetDsaPublicKey() const
{
return dynamic_cast<const KeyBase::PublicKey *>(_key);
}
/**
* Returns the internal cryptomaterial
*/
virtual const CryptoPP::CryptoMaterial *GetCryptoMaterial() const
{
return dynamic_cast<const CryptoPP::CryptoMaterial *>(GetDsaPublicKey());
}
const Key *_key;
bool _valid;
int _key_size;
static QByteArray GetByteArray(const CryptoPP::CryptoMaterial &key);
};
}
}
#endif
<commit_msg>[Crypto] Better logging for DSA key gen<commit_after>#ifndef DISSENT_CRYPTO_CPP_DSA_PUBLIC_KEY_H_GUARD
#define DISSENT_CRYPTO_CPP_DSA_PUBLIC_KEY_H_GUARD
#include <stdexcept>
#include <QByteArray>
#include <QDebug>
#include <QFile>
#include <QString>
#include <cryptopp/aes.h>
#include <cryptopp/ccm.h>
#include <cryptopp/des.h>
#include <cryptopp/dsa.h>
#include <cryptopp/osrng.h>
#include <cryptopp/sha.h>
#include "AsymmetricKey.hpp"
#include "Integer.hpp"
namespace Dissent {
namespace Crypto {
/**
* Implementation of KeyBase::PublicKey using CryptoPP
*/
class CppDsaPublicKey : public AsymmetricKey {
public:
typedef CryptoPP::GDSA<CryptoPP::SHA256> KeyBase;
typedef CryptoPP::DL_GroupParameters_GFP Parameters;
typedef CryptoPP::DL_Key<Parameters::Element> Key;
/**
* Reads a key from a file
* @param filename the file storing the key
*/
explicit CppDsaPublicKey(const QString &filename);
/**
* Loads a key from memory
* @param data byte array holding the key
*/
explicit CppDsaPublicKey(const QByteArray &data);
/**
* Creates a public Dsa key given the public parameters
* @param modulus the p of the public key
* @param subgroup the q of the public key
* @param generator the g of the public key
* @param public_element the y of the public key (g^x)
*/
explicit CppDsaPublicKey(const Integer &modulus,
const Integer &subgroup, const Integer &generator,
const Integer &public_element);
/**
* Deconstructor
*/
virtual ~CppDsaPublicKey();
/**
* Creates a public key based upon the seed data, same seed data same
* key. This is mainly used for distributed tests, so other members can
* generate an appropriate public key.
*/
static CppDsaPublicKey *GenerateKey(const QByteArray &data);
/**
* Get a copy of the public key
*/
virtual AsymmetricKey *GetPublicKey() const;
virtual QByteArray GetByteArray() const;
/**
* Returns nothing, not supported for public keys
*/
virtual QByteArray Sign(const QByteArray &data) const;
virtual bool Verify(const QByteArray &data, const QByteArray &sig) const;
/**
* Returns nothing, not supported for DSA
*/
virtual QByteArray Encrypt(const QByteArray &data) const;
/**
* Returns nothing, not supported for DSA
*/
virtual QByteArray Decrypt(const QByteArray &data) const;
inline virtual bool IsPrivateKey() const { return false; }
virtual bool VerifyKey(AsymmetricKey &key) const;
inline virtual bool IsValid() const { return _valid; }
inline virtual int GetKeySize() const { return _key_size; }
/**
* DSA does not explicitly allow encryption
*/
virtual bool SupportsEncryption() { return false; }
/**
* DSA does not work with keys below 1024
*/
static inline int GetMinimumKeySize() { return 1024; }
/**
* Returns the g of the DSA public key
*/
Integer GetGenerator() const;
/**
* Returns the p of the DSA public key
*/
Integer GetModulus() const;
/**
* Returns the q of the DSA public key
*/
Integer GetSubgroup() const;
/**
* Returns the y = g^x mod p of the DSA public key
*/
Integer GetPublicElement() const;
protected:
inline virtual const Parameters &GetGroupParameters() const
{
return GetDsaPublicKey()->GetGroupParameters();
}
/**
* Does not make sense to create random public keys
*/
CppDsaPublicKey() { }
/**
* Used to construct private key
*/
CppDsaPublicKey(Key *key);
/**
* Loads a key from the provided byte array
* @param data key byte array
*/
bool InitFromByteArray(const QByteArray &data);
/**
* Loads a key from the given filename
* @param filename file storing the key
*/
bool InitFromFile(const QString &filename);
/**
* Prevents a remote user from giving a malicious DSA key
*/
inline bool Validate()
{
_valid = false;
_key_size = 0;
if(!_key) {
qDebug() << "Validate failed: No key";
return false;
}
CryptoPP::AutoSeededX917RNG<CryptoPP::DES_EDE3> rng;
if(GetCryptoMaterial()->Validate(rng, 1)) {
_key_size = GetGroupParameters().GetModulus().BitCount();
_valid = true;
return true;
}
qDebug() << "Validate failed: CryptoPP unable to validate";
return false;
}
/**
* Returns the internal Dsa Public Key
*/
virtual const KeyBase::PublicKey *GetDsaPublicKey() const
{
return dynamic_cast<const KeyBase::PublicKey *>(_key);
}
/**
* Returns the internal cryptomaterial
*/
virtual const CryptoPP::CryptoMaterial *GetCryptoMaterial() const
{
return dynamic_cast<const CryptoPP::CryptoMaterial *>(GetDsaPublicKey());
}
const Key *_key;
bool _valid;
int _key_size;
static QByteArray GetByteArray(const CryptoPP::CryptoMaterial &key);
};
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: statusbarfactory.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:01:05 $
*
* 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 __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_
#include <uifactory/statusbarfactory.hxx>
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_UIELEMENT_STATUSBARWRAPPER_HXX_
#include <uielement/statusbarwrapper.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_
#include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPLLIER_HPP_
#include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
//_________________________________________________________________________________________________________________
// Defines
//_________________________________________________________________________________________________________________
//
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::util;
using namespace ::com::sun::star::ui;
namespace framework
{
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3 ( StatusBarFactory ,
OWeakObject ,
DIRECT_INTERFACE( css::lang::XTypeProvider ),
DIRECT_INTERFACE( css::lang::XServiceInfo ),
DIRECT_INTERFACE( ::com::sun::star::ui::XUIElementFactory )
)
DEFINE_XTYPEPROVIDER_3 ( StatusBarFactory ,
css::lang::XTypeProvider ,
css::lang::XServiceInfo ,
::com::sun::star::ui::XUIElementFactory
)
DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( StatusBarFactory ,
::cppu::OWeakObject ,
SERVICENAME_STATUSBARFACTORY ,
IMPLEMENTATIONNAME_STATUSBARFACTORY
)
DEFINE_INIT_SERVICE ( StatusBarFactory, {} )
StatusBarFactory::StatusBarFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) :
ThreadHelpBase( &Application::GetSolarMutex() )
, m_xServiceManager( xServiceManager )
, m_xModuleManager( xServiceManager->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.ModuleManager" ))),
UNO_QUERY )
{
}
StatusBarFactory::~StatusBarFactory()
{
}
// XUIElementFactory
Reference< XUIElement > SAL_CALL StatusBarFactory::createUIElement(
const ::rtl::OUString& ResourceURL,
const Sequence< PropertyValue >& Args )
throw ( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException )
{
// SAFE
ResetableGuard aLock( m_aLock );
Reference< XUIConfigurationManager > xConfigSource;
Reference< XFrame > xFrame;
rtl::OUString aResourceURL( ResourceURL );
sal_Bool bPersistent( sal_True );
sal_Bool bMenuOnly( sal_False );
for ( sal_Int32 n = 0; n < Args.getLength(); n++ )
{
if ( Args[n].Name.equalsAscii( "ConfigurationSource" ))
Args[n].Value >>= xConfigSource;
else if ( Args[n].Name.equalsAscii( "Frame" ))
Args[n].Value >>= xFrame;
else if ( Args[n].Name.equalsAscii( "ResourceURL" ))
Args[n].Value >>= aResourceURL;
else if ( Args[n].Name.equalsAscii( "Persistent" ))
Args[n].Value >>= bPersistent;
}
Reference< XUIConfigurationManager > xCfgMgr;
if ( aResourceURL.indexOf( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:resource/statusbar/" ))) != 0 )
throw IllegalArgumentException();
else
{
// Identify frame and determine document based ui configuration manager/module ui configuration manager
if ( xFrame.is() && !xConfigSource.is() )
{
bool bHasSettings( false );
Reference< XModel > xModel;
Reference< XController > xController = xFrame->getController();
if ( xController.is() )
xModel = xController->getModel();
if ( xModel.is() )
{
Reference< XUIConfigurationManagerSupplier > xUIConfigurationManagerSupplier( xModel, UNO_QUERY );
if ( xUIConfigurationManagerSupplier.is() )
{
xCfgMgr = xUIConfigurationManagerSupplier->getUIConfigurationManager();
bHasSettings = xCfgMgr->hasSettings( aResourceURL );
}
}
if ( !bHasSettings )
{
rtl::OUString aModuleIdentifier = m_xModuleManager->identify( Reference< XInterface >( xFrame, UNO_QUERY ));
if ( aModuleIdentifier.getLength() )
{
Reference< ::com::sun::star::ui::XModuleUIConfigurationManagerSupplier > xModuleCfgSupplier(
m_xServiceManager->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))),
UNO_QUERY );
xCfgMgr = xModuleCfgSupplier->getUIConfigurationManager( aModuleIdentifier );
bHasSettings = xCfgMgr->hasSettings( aResourceURL );
}
}
}
}
PropertyValue aPropValue;
Sequence< Any > aPropSeq( 4 );
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Frame" ));
aPropValue.Value <<= xFrame;
aPropSeq[0] <<= aPropValue;
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ConfigurationSource" ));
aPropValue.Value <<= xCfgMgr;
aPropSeq[1] <<= aPropValue;
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ResourceURL" ));
aPropValue.Value <<= aResourceURL;
aPropSeq[2] <<= aPropValue;
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Persistent" ));
aPropValue.Value <<= bPersistent;
aPropSeq[3] <<= aPropValue;
vos::OGuard aGuard( Application::GetSolarMutex() );
StatusBarWrapper* pStatusBarWrapper = new StatusBarWrapper( m_xServiceManager );
Reference< ::com::sun::star::ui::XUIElement > xStatusBar( (OWeakObject *)pStatusBarWrapper, UNO_QUERY );
Reference< XInitialization > xInit( xStatusBar, UNO_QUERY );
xInit->initialize( aPropSeq );
return xStatusBar;
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.32); FILE MERGED 2005/10/28 14:48:47 cd 1.4.32.1: #i55991# Warning free code changes for gcc<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: statusbarfactory.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:43:41 $
*
* 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 __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_
#include <uifactory/statusbarfactory.hxx>
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_UIELEMENT_STATUSBARWRAPPER_HXX_
#include <uielement/statusbarwrapper.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_
#include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPLLIER_HPP_
#include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
//_________________________________________________________________________________________________________________
// Defines
//_________________________________________________________________________________________________________________
//
using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using namespace com::sun::star::beans;
using namespace com::sun::star::util;
using namespace ::com::sun::star::ui;
namespace framework
{
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3 ( StatusBarFactory ,
OWeakObject ,
DIRECT_INTERFACE( css::lang::XTypeProvider ),
DIRECT_INTERFACE( css::lang::XServiceInfo ),
DIRECT_INTERFACE( ::com::sun::star::ui::XUIElementFactory )
)
DEFINE_XTYPEPROVIDER_3 ( StatusBarFactory ,
css::lang::XTypeProvider ,
css::lang::XServiceInfo ,
::com::sun::star::ui::XUIElementFactory
)
DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( StatusBarFactory ,
::cppu::OWeakObject ,
SERVICENAME_STATUSBARFACTORY ,
IMPLEMENTATIONNAME_STATUSBARFACTORY
)
DEFINE_INIT_SERVICE ( StatusBarFactory, {} )
StatusBarFactory::StatusBarFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) :
ThreadHelpBase( &Application::GetSolarMutex() )
, m_xServiceManager( xServiceManager )
, m_xModuleManager( xServiceManager->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.ModuleManager" ))),
UNO_QUERY )
{
}
StatusBarFactory::~StatusBarFactory()
{
}
// XUIElementFactory
Reference< XUIElement > SAL_CALL StatusBarFactory::createUIElement(
const ::rtl::OUString& ResourceURL,
const Sequence< PropertyValue >& Args )
throw ( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException )
{
// SAFE
ResetableGuard aLock( m_aLock );
Reference< XUIConfigurationManager > xConfigSource;
Reference< XFrame > xFrame;
rtl::OUString aResourceURL( ResourceURL );
sal_Bool bPersistent( sal_True );
for ( sal_Int32 n = 0; n < Args.getLength(); n++ )
{
if ( Args[n].Name.equalsAscii( "ConfigurationSource" ))
Args[n].Value >>= xConfigSource;
else if ( Args[n].Name.equalsAscii( "Frame" ))
Args[n].Value >>= xFrame;
else if ( Args[n].Name.equalsAscii( "ResourceURL" ))
Args[n].Value >>= aResourceURL;
else if ( Args[n].Name.equalsAscii( "Persistent" ))
Args[n].Value >>= bPersistent;
}
Reference< XUIConfigurationManager > xCfgMgr;
if ( aResourceURL.indexOf( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:resource/statusbar/" ))) != 0 )
throw IllegalArgumentException();
else
{
// Identify frame and determine document based ui configuration manager/module ui configuration manager
if ( xFrame.is() && !xConfigSource.is() )
{
bool bHasSettings( false );
Reference< XModel > xModel;
Reference< XController > xController = xFrame->getController();
if ( xController.is() )
xModel = xController->getModel();
if ( xModel.is() )
{
Reference< XUIConfigurationManagerSupplier > xUIConfigurationManagerSupplier( xModel, UNO_QUERY );
if ( xUIConfigurationManagerSupplier.is() )
{
xCfgMgr = xUIConfigurationManagerSupplier->getUIConfigurationManager();
bHasSettings = xCfgMgr->hasSettings( aResourceURL );
}
}
if ( !bHasSettings )
{
rtl::OUString aModuleIdentifier = m_xModuleManager->identify( Reference< XInterface >( xFrame, UNO_QUERY ));
if ( aModuleIdentifier.getLength() )
{
Reference< ::com::sun::star::ui::XModuleUIConfigurationManagerSupplier > xModuleCfgSupplier(
m_xServiceManager->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))),
UNO_QUERY );
xCfgMgr = xModuleCfgSupplier->getUIConfigurationManager( aModuleIdentifier );
bHasSettings = xCfgMgr->hasSettings( aResourceURL );
}
}
}
}
PropertyValue aPropValue;
Sequence< Any > aPropSeq( 4 );
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Frame" ));
aPropValue.Value <<= xFrame;
aPropSeq[0] <<= aPropValue;
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ConfigurationSource" ));
aPropValue.Value <<= xCfgMgr;
aPropSeq[1] <<= aPropValue;
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ResourceURL" ));
aPropValue.Value <<= aResourceURL;
aPropSeq[2] <<= aPropValue;
aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Persistent" ));
aPropValue.Value <<= bPersistent;
aPropSeq[3] <<= aPropValue;
vos::OGuard aGuard( Application::GetSolarMutex() );
StatusBarWrapper* pStatusBarWrapper = new StatusBarWrapper( m_xServiceManager );
Reference< ::com::sun::star::ui::XUIElement > xStatusBar( (OWeakObject *)pStatusBarWrapper, UNO_QUERY );
Reference< XInitialization > xInit( xStatusBar, UNO_QUERY );
xInit->initialize( aPropSeq );
return xStatusBar;
}
}
<|endoftext|> |
<commit_before>/**
* @file llweb.cpp
* @brief Functions dealing with web browsers
* @author James Cook
*
* $LicenseInfo:firstyear=2006&license=viewergpl$
*
* Copyright (c) 2006-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llweb.h"
// Library includes
#include "llwindow.h" // spawnWebBrowser()
#include "llalertdialog.h"
#include "llappviewer.h"
#include "llfloatermediabrowser.h"
#include "llfloaterreg.h"
#include "lllogininstance.h"
#include "llsd.h"
#include "lltoastalertpanel.h"
#include "llui.h"
#include "lluri.h"
#include "llversioninfo.h"
#include "llviewercontrol.h"
#include "llviewernetwork.h"
#include "llviewerwindow.h"
class URLLoader : public LLToastAlertPanel::URLLoader
{
virtual void load(const std::string& url , bool force_open_externally)
{
if (force_open_externally)
{
LLWeb::loadURLExternal(url);
}
else
{
LLWeb::loadURL(url);
}
}
};
static URLLoader sAlertURLLoader;
// static
void LLWeb::initClass()
{
LLToastAlertPanel::setURLLoader(&sAlertURLLoader);
}
// static
void LLWeb::loadURL(const std::string& url)
{
if (gSavedSettings.getBOOL("UseExternalBrowser"))
{
loadURLExternal(url);
}
else
{
loadURLInternal(url);
}
}
// static
void LLWeb::loadURLInternal(const std::string &url)
{
LLFloaterReg::showInstance("media_browser", url);
}
// static
void LLWeb::loadURLExternal(const std::string& url)
{
std::string escaped_url = escapeURL(url);
gViewerWindow->getWindow()->spawnWebBrowser(escaped_url);
}
// static
std::string LLWeb::escapeURL(const std::string& url)
{
// The CURL curl_escape() function escapes colons, slashes,
// and all characters but A-Z and 0-9. Do a cheesy mini-escape.
std::string escaped_url;
S32 len = url.length();
for (S32 i = 0; i < len; i++)
{
char c = url[i];
if (c == ' ')
{
escaped_url += "%20";
}
else if (c == '\\')
{
escaped_url += "%5C";
}
else
{
escaped_url += c;
}
}
return escaped_url;
}
//static
std::string LLWeb::expandURLSubstitutions(const std::string &url,
const LLSD &default_subs)
{
LLSD substitution = default_subs;
substitution["VERSION"] = LLVersionInfo::getVersion();
substitution["VERSION_MAJOR"] = LLVersionInfo::getMajor();
substitution["VERSION_MINOR"] = LLVersionInfo::getMinor();
substitution["VERSION_PATCH"] = LLVersionInfo::getPatch();
substitution["VERSION_BUILD"] = LLVersionInfo::getBuild();
substitution["CHANNEL"] = LLVersionInfo::getChannel();
substitution["LANGUAGE"] = LLUI::getLanguage();
substitution["GRID"] = LLViewerLogin::getInstance()->getGridLabel();
substitution["OS"] = LLAppViewer::instance()->getOSInfo().getOSStringSimple();
std::string expanded_url = url;
LLStringUtil::format(expanded_url, substitution);
return LLWeb::escapeURL(expanded_url);
}
<commit_msg>fix for post merge compile error (minor)<commit_after>/**
* @file llweb.cpp
* @brief Functions dealing with web browsers
* @author James Cook
*
* $LicenseInfo:firstyear=2006&license=viewergpl$
*
* Copyright (c) 2006-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llweb.h"
// Library includes
#include "llwindow.h" // spawnWebBrowser()
#include "llappviewer.h"
#include "llfloatermediabrowser.h"
#include "llfloaterreg.h"
#include "lllogininstance.h"
#include "llsd.h"
#include "lltoastalertpanel.h"
#include "llui.h"
#include "lluri.h"
#include "llversioninfo.h"
#include "llviewercontrol.h"
#include "llviewernetwork.h"
#include "llviewerwindow.h"
class URLLoader : public LLToastAlertPanel::URLLoader
{
virtual void load(const std::string& url , bool force_open_externally)
{
if (force_open_externally)
{
LLWeb::loadURLExternal(url);
}
else
{
LLWeb::loadURL(url);
}
}
};
static URLLoader sAlertURLLoader;
// static
void LLWeb::initClass()
{
LLToastAlertPanel::setURLLoader(&sAlertURLLoader);
}
// static
void LLWeb::loadURL(const std::string& url)
{
if (gSavedSettings.getBOOL("UseExternalBrowser"))
{
loadURLExternal(url);
}
else
{
loadURLInternal(url);
}
}
// static
void LLWeb::loadURLInternal(const std::string &url)
{
LLFloaterReg::showInstance("media_browser", url);
}
// static
void LLWeb::loadURLExternal(const std::string& url)
{
std::string escaped_url = escapeURL(url);
gViewerWindow->getWindow()->spawnWebBrowser(escaped_url);
}
// static
std::string LLWeb::escapeURL(const std::string& url)
{
// The CURL curl_escape() function escapes colons, slashes,
// and all characters but A-Z and 0-9. Do a cheesy mini-escape.
std::string escaped_url;
S32 len = url.length();
for (S32 i = 0; i < len; i++)
{
char c = url[i];
if (c == ' ')
{
escaped_url += "%20";
}
else if (c == '\\')
{
escaped_url += "%5C";
}
else
{
escaped_url += c;
}
}
return escaped_url;
}
//static
std::string LLWeb::expandURLSubstitutions(const std::string &url,
const LLSD &default_subs)
{
LLSD substitution = default_subs;
substitution["VERSION"] = LLVersionInfo::getVersion();
substitution["VERSION_MAJOR"] = LLVersionInfo::getMajor();
substitution["VERSION_MINOR"] = LLVersionInfo::getMinor();
substitution["VERSION_PATCH"] = LLVersionInfo::getPatch();
substitution["VERSION_BUILD"] = LLVersionInfo::getBuild();
substitution["CHANNEL"] = LLVersionInfo::getChannel();
substitution["LANGUAGE"] = LLUI::getLanguage();
substitution["GRID"] = LLViewerLogin::getInstance()->getGridLabel();
substitution["OS"] = LLAppViewer::instance()->getOSInfo().getOSStringSimple();
std::string expanded_url = url;
LLStringUtil::format(expanded_url, substitution);
return LLWeb::escapeURL(expanded_url);
}
<|endoftext|> |
<commit_before>void input_init() {
}
void input_update(SDL_Event event) {
}
const char *input_event_type_to_string(unsigned int type) {
switch(type) {
case SDL_KEYDOWN:
return "keydown";
case SDL_KEYUP:
return "keyup";
case SDL_MOUSEMOTION:
return "mousemove";
}
return "none";
}<commit_msg>Added SDL_MOUSEBUTTONUP and SDL_MOUSEBUTTONDOWN to input_event_type_to_string<commit_after>void input_init() {
}
void input_update(SDL_Event event) {
}
const char *input_event_type_to_string(unsigned int type) {
switch(type) {
case SDL_KEYDOWN:
return "keydown";
case SDL_KEYUP:
return "keyup";
case SDL_MOUSEMOTION:
return "mousemove";
case SDL_MOUSEBUTTONUP:
return "mouseup";
case SDL_MOUSEBUTTONDOWN:
return "mousedown";
}
return "none";
}<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "SetupOverSamplingAction.h"
#include "MooseApp.h"
#include "Output.h"
#include "FEProblem.h"
#include "OutputProblem.h"
#include "libmesh/exodusII_io.h"
#include "MooseMesh.h"
#include "unistd.h"
template<>
InputParameters validParams<SetupOverSamplingAction>()
{
// Note: I am specifically "skipping" the direct parent here because we want a subset of parameters
// in this block for now. We may make a common ancestor at some point to clean this up
InputParameters params = validParams<Action>();
params.addParam<OutFileBase>("file_base", "The desired oversampled solution output name without an extension. If not supplied, the main file_base will be used with a '_oversample' suffix added.");
params.addParam<unsigned int>("refinements", 1, "The number of refinements to output for the over sampled solution");
params.addParam<bool>("exodus", false, "Specifies that you would like Exodus output solution file(s)");
params.addParam<bool>("nemesis", false, "Specifies that you would like Nemesis output solution file(s)");
params.addParam<bool>("gmv", false, "Specifies that you would like GMV output solution file(s)");
params.addParam<bool>("vtk", false, "Specifies that you would like VTK output solution file(s)");
params.addParam<bool>("tecplot", false, "Specifies that you would like Tecplot output solution files(s)");
params.addParam<bool>("tecplot_binary", false, "Specifies that you would like Tecplot binary output solution files(s)");
params.addParam<bool>("xda", false, "Specifies that you would like xda output solution files(s)");
params.addParam<std::vector<VariableName> >("output_variables", "A list of the variables that should be in the Exodus output file. If this is not provided then all variables will be in the output.");
params.addParam<int>("interval", 1, "The iterval at which timesteps are output to the solution file");
params.addParam<Real>("iteration_plot_start_time", std::numeric_limits<Real>::max(), "Specifies a time after which the solution will be written following each nonlinear iteration");
params.addParam<bool>("output_initial", false, "Requests that the initial condition is output to the solution file");
params.addParam<Point>("position", "Set a positional offset. This vector will get added to the nodal cooardinates to move the domain.");
params.addParam<MeshFileName>("file", "The name of the mesh file to read");
return params;
}
SetupOverSamplingAction::SetupOverSamplingAction(const std::string & name, InputParameters params) :
SetupOutputAction(name, params)
{
}
void
SetupOverSamplingAction::act()
{
if (_problem == NULL)
return;
OutputProblem & out_problem = _problem->getOutputProblem(getParam<unsigned int>("refinements"), getParam<MeshFileName>("file"));
Output & output = out_problem.out(); // can't use use this with coupled problems on different meshes
if(!_pars.isParamValid("output_variables"))
{
_pars.set<std::vector<VariableName> >("output_variables") = _problem->getVariableNames();
}
if(_pars.isParamValid("position"))
out_problem.setPosition(_pars.get<Point>("position"));
_pars.set<OutFileBase>("file_base") = _problem->out().fileBase() + "_oversample";
setupOutputObject(output, _pars);
#ifdef LIBMESH_ENABLE_AMR
Adaptivity & adapt = _problem->adaptivity();
if (adapt.isOn())
output.sequence(true);
#endif //LIBMESH_ENABLE_AMR
// TODO: Need to set these values on the OutputProblem
output.interval(getParam<int>("interval"));
output.iterationPlotStartTime(getParam<Real>("iteration_plot_start_time"));
// Test to make sure that the user can write to the directory specified in file_base
std::string base = "./" + getParam<OutFileBase>("file_base");
base = base.substr(0, base.find_last_of('/'));
if (access(base.c_str(), W_OK) == -1)
mooseError("Can not write to directory: " + base + " for file base: " + getParam<OutFileBase>("file_base"));
}
<commit_msg>Fix for oversampling hack - refs #2243<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "SetupOverSamplingAction.h"
#include "MooseApp.h"
#include "Output.h"
#include "FEProblem.h"
#include "OutputProblem.h"
#include "libmesh/exodusII_io.h"
#include "MooseMesh.h"
#include "unistd.h"
template<>
InputParameters validParams<SetupOverSamplingAction>()
{
// Note: I am specifically "skipping" the direct parent here because we want a subset of parameters
// in this block for now. We may make a common ancestor at some point to clean this up
InputParameters params = validParams<Action>();
params.addParam<OutFileBase>("file_base", "The desired oversampled solution output name without an extension. If not supplied, the main file_base will be used with a '_oversample' suffix added.");
params.addParam<unsigned int>("refinements", 1, "The number of refinements to output for the over sampled solution");
params.addParam<bool>("exodus", false, "Specifies that you would like Exodus output solution file(s)");
params.addParam<bool>("nemesis", false, "Specifies that you would like Nemesis output solution file(s)");
params.addParam<bool>("gmv", false, "Specifies that you would like GMV output solution file(s)");
params.addParam<bool>("vtk", false, "Specifies that you would like VTK output solution file(s)");
params.addParam<bool>("tecplot", false, "Specifies that you would like Tecplot output solution files(s)");
params.addParam<bool>("tecplot_binary", false, "Specifies that you would like Tecplot binary output solution files(s)");
params.addParam<bool>("xda", false, "Specifies that you would like xda output solution files(s)");
params.addParam<bool>("xdr", false, "Specifies that you would like xdr (binary) output solution file(s)");
params.addParam<std::vector<VariableName> >("output_variables", "A list of the variables that should be in the Exodus output file. If this is not provided then all variables will be in the output.");
params.addParam<int>("interval", 1, "The iterval at which timesteps are output to the solution file");
params.addParam<Real>("iteration_plot_start_time", std::numeric_limits<Real>::max(), "Specifies a time after which the solution will be written following each nonlinear iteration");
params.addParam<bool>("output_initial", false, "Requests that the initial condition is output to the solution file");
params.addParam<Point>("position", "Set a positional offset. This vector will get added to the nodal cooardinates to move the domain.");
params.addParam<MeshFileName>("file", "The name of the mesh file to read");
return params;
}
SetupOverSamplingAction::SetupOverSamplingAction(const std::string & name, InputParameters params) :
SetupOutputAction(name, params)
{
}
void
SetupOverSamplingAction::act()
{
if (_problem == NULL)
return;
OutputProblem & out_problem = _problem->getOutputProblem(getParam<unsigned int>("refinements"), getParam<MeshFileName>("file"));
Output & output = out_problem.out(); // can't use use this with coupled problems on different meshes
if(!_pars.isParamValid("output_variables"))
{
_pars.set<std::vector<VariableName> >("output_variables") = _problem->getVariableNames();
}
if(_pars.isParamValid("position"))
out_problem.setPosition(_pars.get<Point>("position"));
_pars.set<OutFileBase>("file_base") = _problem->out().fileBase() + "_oversample";
setupOutputObject(output, _pars);
#ifdef LIBMESH_ENABLE_AMR
Adaptivity & adapt = _problem->adaptivity();
if (adapt.isOn())
output.sequence(true);
#endif //LIBMESH_ENABLE_AMR
// TODO: Need to set these values on the OutputProblem
output.interval(getParam<int>("interval"));
output.iterationPlotStartTime(getParam<Real>("iteration_plot_start_time"));
// Test to make sure that the user can write to the directory specified in file_base
std::string base = "./" + getParam<OutFileBase>("file_base");
base = base.substr(0, base.find_last_of('/'));
if (access(base.c_str(), W_OK) == -1)
mooseError("Can not write to directory: " + base + " for file base: " + getParam<OutFileBase>("file_base"));
}
<|endoftext|> |
<commit_before><commit_msg>Range-based for-loops.<commit_after><|endoftext|> |
<commit_before>#include <vtkSmartPointer.h>
#include <vtkActor.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkLogoRepresentation.h>
#include <vtkLogoWidget.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty2D.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSphereSource.h>
#include <vtkSphereSource.h>
int main(int, char *[])
{
// A sphere
vtkSmartPointer<vtkSphereSource> sphereSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereSource->SetCenter(0.0, 0.0, 0.0);
sphereSource->SetRadius(4.0);
sphereSource->SetPhiResolution(4);
sphereSource->SetThetaResolution(8);
sphereSource->Update();
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(sphereSource->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
// A renderer and render window
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
renderer->AddActor(actor);
// An interactor
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
// Create an image
vtkSmartPointer<vtkImageCanvasSource2D> drawing =
vtkSmartPointer<vtkImageCanvasSource2D>::New();
drawing->SetScalarTypeToUnsignedChar();
drawing->SetNumberOfScalarComponents(3);
drawing->SetExtent(0,200,0,200,0,0);
// Clear the image
drawing->SetDrawColor(255, 127, 100);
drawing->FillBox(0,200,0,200);
drawing->SetDrawColor(0, 0, 0);
drawing->DrawCircle(100, 100, 50);
drawing->Update();
vtkSmartPointer<vtkLogoRepresentation> logoRepresentation =
vtkSmartPointer<vtkLogoRepresentation>::New();
logoRepresentation->SetImage(drawing->GetOutput());
logoRepresentation->SetPosition(0,0);
logoRepresentation->SetPosition2(.4, .4);
logoRepresentation->GetImageProperty()->SetOpacity(.7);
vtkSmartPointer<vtkLogoWidget> logoWidget =
vtkSmartPointer<vtkLogoWidget>::New();
logoWidget->SetInteractor(renderWindowInteractor);
logoWidget->SetRepresentation(logoRepresentation);
renderWindow->Render();
logoWidget->On();
renderer->SetBackground(.2, .3, .4);
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<commit_msg>Using vtkNamedColors<commit_after>#include <vtkActor.h>
#include <vtkImageCanvasSource2D.h>
#include <vtkLogoRepresentation.h>
#include <vtkLogoWidget.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty2D.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
int main(int, char *[]) {
vtkNew<vtkNamedColors> colors;
colors->SetColor("Bkg", 0.2, 0.3, 0.4);
// A sphere
vtkSmartPointer<vtkSphereSource> sphereSource =
vtkSmartPointer<vtkSphereSource>::New();
sphereSource->SetCenter(0.0, 0.0, 0.0);
sphereSource->SetRadius(4.0);
sphereSource->SetPhiResolution(4);
sphereSource->SetThetaResolution(8);
sphereSource->Update();
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(sphereSource->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
// A renderer and render window
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
renderer->AddActor(actor);
// An interactor
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
// Create an image
vtkSmartPointer<vtkImageCanvasSource2D> drawing =
vtkSmartPointer<vtkImageCanvasSource2D>::New();
drawing->SetScalarTypeToUnsignedChar();
drawing->SetNumberOfScalarComponents(3);
drawing->SetExtent(0, 200, 0, 200, 0, 0);
// Clear the image
// Note: SetDrawColour() uses double values of the rgb colors in the
// range [0 ... 255]
// So SetDrawColour(255, 255, 255) is white.
drawing->SetDrawColor(255, 127, 100);
drawing->FillBox(0, 200, 0, 200);
drawing->SetDrawColor(0, 0, 0);
drawing->DrawCircle(100, 100, 50);
drawing->Update();
vtkSmartPointer<vtkLogoRepresentation> logoRepresentation =
vtkSmartPointer<vtkLogoRepresentation>::New();
logoRepresentation->SetImage(drawing->GetOutput());
logoRepresentation->SetPosition(0, 0);
logoRepresentation->SetPosition2(0.4, 0.4);
logoRepresentation->GetImageProperty()->SetOpacity(.7);
vtkSmartPointer<vtkLogoWidget> logoWidget =
vtkSmartPointer<vtkLogoWidget>::New();
logoWidget->SetInteractor(renderWindowInteractor);
logoWidget->SetRepresentation(logoRepresentation);
renderWindow->Render();
logoWidget->On();
renderer->SetBackground(colors->GetColor3d("Bkg").GetData());
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* it->first ==ompanying file Copyright.txt for details.
*
* CompressSZ.cpp
*
* Created on: Jul 24, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#include "CompressSZ.h"
#include <cmath> //std::ceil
#include <ios> //std::ios_base::failure
#include <stdexcept> //std::invalid_argument
extern "C" {
#include <sz.h>
}
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace core
{
namespace compress
{
CompressSZ::CompressSZ(const Params ¶meters) : Operator("sz", parameters) {}
size_t CompressSZ::BufferMaxSize(const size_t sizeIn) const
{
return static_cast<size_t>(std::ceil(1.1 * sizeIn) + 600);
}
size_t CompressSZ::Compress(const void *dataIn, const Dims &dimensions,
const size_t elementSize, DataType varType,
void *bufferOut, const Params ¶meters,
Params &info) const
{
const size_t ndims = dimensions.size();
if (ndims > 5)
{
throw std::invalid_argument("ERROR: ADIOS2 SZ compression: no more "
"than 5 dimension is supported.\n");
}
sz_params sz;
memset(&sz, 0, sizeof(sz_params));
sz.max_quant_intervals = 65536;
sz.quantization_intervals = 0;
// sz.dataEndianType = LITTLE_ENDIAN_DATA;
// sz.sysEndianType = LITTLE_ENDIAN_DATA;
sz.sol_ID = SZ;
// sz.layers = 1;
sz.sampleDistance = 100;
sz.predThreshold = 0.99;
// sz.offset = 0;
sz.szMode = SZ_BEST_COMPRESSION; // SZ_BEST_SPEED; //SZ_BEST_COMPRESSION;
sz.gzipMode = 1;
sz.errorBoundMode = ABS;
sz.absErrBound = 1E-4;
sz.relBoundRatio = 1E-3;
sz.psnr = 80.0;
sz.pw_relBoundRatio = 1E-5;
sz.segment_size =
static_cast<int>(std::pow(5., static_cast<double>(ndims)));
sz.pwr_type = SZ_PWR_MIN_TYPE;
size_t outsize;
size_t r[5] = {0, 0, 0, 0, 0};
/* SZ parameters */
int use_configfile = 0;
std::string sz_configfile = "sz.config";
Params::const_iterator it;
for (it = parameters.begin(); it != parameters.end(); it++)
{
if (it->first == "init")
{
use_configfile = 1;
sz_configfile = std::string(it->second);
}
else if (it->first == "max_quant_intervals")
{
sz.max_quant_intervals = std::stoi(it->second);
}
else if (it->first == "quantization_intervals")
{
sz.quantization_intervals = std::stoi(it->second);
}
else if (it->first == "sol_ID")
{
sz.sol_ID = std::stoi(it->second);
}
else if (it->first == "sampleDistance")
{
sz.sampleDistance = std::stoi(it->second);
}
else if (it->first == "predThreshold")
{
sz.predThreshold = std::stof(it->second);
}
else if (it->first == "szMode")
{
int szMode = SZ_BEST_SPEED;
if (it->second == "SZ_BEST_SPEED")
{
szMode = SZ_BEST_SPEED;
}
else if (it->second == "SZ_BEST_COMPRESSION")
{
szMode = SZ_BEST_COMPRESSION;
}
else if (it->second == "SZ_DEFAULT_COMPRESSION")
{
szMode = SZ_DEFAULT_COMPRESSION;
}
else
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator unknown SZ parameter szMode: " +
it->second + "\n");
}
sz.szMode = szMode;
}
else if (it->first == "gzipMode")
{
sz.gzipMode = std::stoi(it->second);
}
else if (it->first == "errorBoundMode")
{
int errorBoundMode = ABS;
if (it->second == "ABS")
{
errorBoundMode = ABS;
}
else if (it->second == "REL")
{
errorBoundMode = REL;
}
else if (it->second == "ABS_AND_REL")
{
errorBoundMode = ABS_AND_REL;
}
else if (it->second == "ABS_OR_REL")
{
errorBoundMode = ABS_OR_REL;
}
else if (it->second == "PW_REL")
{
errorBoundMode = PW_REL;
}
else
{
throw std::invalid_argument("ERROR: ADIOS2 operator "
"unknown SZ parameter "
"errorBoundMode: " +
it->second + "\n");
}
sz.errorBoundMode = errorBoundMode;
}
else if (it->first == "absErrBound")
{
sz.absErrBound = std::stof(it->second);
}
else if (it->first == "relBoundRatio")
{
sz.relBoundRatio = std::stof(it->second);
}
else if (it->first == "pw_relBoundRatio")
{
sz.pw_relBoundRatio = std::stof(it->second);
}
else if (it->first == "segment_size")
{
sz.segment_size = std::stoi(it->second);
}
else if (it->first == "pwr_type")
{
int pwr_type = SZ_PWR_MIN_TYPE;
if ((it->first == "MIN") || (it->first == "SZ_PWR_MIN_TYPE"))
{
pwr_type = SZ_PWR_MIN_TYPE;
}
else if ((it->first == "AVG") || (it->first == "SZ_PWR_AVG_TYPE"))
{
pwr_type = SZ_PWR_AVG_TYPE;
}
else if ((it->first == "MAX") || (it->first == "SZ_PWR_MAX_TYPE"))
{
pwr_type = SZ_PWR_MAX_TYPE;
}
else
{
throw std::invalid_argument("ERROR: ADIOS2 operator "
"unknown SZ parameter "
"pwr_type: " +
it->second + "\n");
}
sz.pwr_type = pwr_type;
}
else if ((it->first == "abs") || (it->first == "absolute") ||
(it->first == "accuracy"))
{
sz.errorBoundMode = ABS;
sz.absErrBound = std::stod(it->second);
}
else if ((it->first == "rel") || (it->first == "relative"))
{
sz.errorBoundMode = REL;
sz.relBoundRatio = std::stof(it->second);
}
else if ((it->first == "pw") || (it->first == "pwr") ||
(it->first == "pwrel") || (it->first == "pwrelative"))
{
sz.errorBoundMode = PW_REL;
sz.pw_relBoundRatio = std::stof(it->second);
}
else if ((it->first == "zchecker") || (it->first == "zcheck") ||
(it->first == "z-checker") || (it->first == "z-check"))
{
// TODO:
// Z-checker is not currently implemented
// use_zchecker = (it->second == "") ? 1 : std::stof(it->second);
}
else
{
// TODO: ignoring unknown option due to Fortran bindings passing
// empty parameter
}
}
if (use_configfile)
{
SZ_Init((char *)sz_configfile.c_str());
}
else
{
SZ_Init_Params(&sz);
}
// Get type info
int dtype = -1;
if (varType == helper::GetDataType<double>())
{
dtype = SZ_DOUBLE;
}
else if (varType == helper::GetDataType<float>())
{
dtype = SZ_FLOAT;
}
else
{
throw std::invalid_argument("ERROR: ADIOS2 SZ Compression only support "
"double or float, type: " +
ToString(varType) + " is unsupported\n");
}
// r[0] is the fastest changing dimension and r[4] is the lowest changing
// dimension
// In C, r[0] is the last dimension. In Fortran, r[0] is the first dimension
for (size_t i = 0; i < ndims; i++)
{
r[ndims - i - 1] = dimensions[i];
/*
if (fd->group->adios_host_language_fortran == adios_flag_yes)
r[i] = dimensions[i];
else
r[ndims-i-1] = dimensions[i];
d = d->next;
*/
}
unsigned char *bytes = SZ_compress(dtype, (void *)dataIn, &outsize, r[4],
r[3], r[2], r[1], r[0]);
std::memcpy(bufferOut, bytes, outsize);
free(bytes);
bytes = nullptr;
SZ_Finalize();
return static_cast<size_t>(outsize);
}
size_t CompressSZ::Decompress(const void *bufferIn, const size_t sizeIn,
void *dataOut, const Dims &dimensions,
DataType varType,
const Params & /*parameters*/) const
{
if (dimensions.size() > 5)
{
throw std::invalid_argument("ERROR: SZ decompression doesn't support "
"more than 5 dimension variables.\n");
}
// Get type info
int dtype = 0;
size_t typeSizeBytes = 0;
if (varType == helper::GetDataType<double>())
{
dtype = SZ_DOUBLE;
typeSizeBytes = 8;
}
else if (varType == helper::GetDataType<float>())
{
dtype = SZ_FLOAT;
typeSizeBytes = 4;
}
else
{
throw std::runtime_error(
"ERROR: data type must be either double or float in SZ\n");
}
// r[0] is the fastest changing dimension and r[4] is the lowest changing
// dimension
// In C, r[0] is the last dimension. In Fortran, r[0] is the first dimension
std::vector<size_t> rs(5, 0);
const size_t ndims = dimensions.size();
for (size_t i = 0; i < ndims; ++i)
{
rs[ndims - i - 1] = dimensions[i];
}
const size_t dataSizeBytes =
helper::GetTotalSize(dimensions) * typeSizeBytes;
void *result = SZ_decompress(
dtype, reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),
sizeIn, rs[4], rs[3], rs[2], rs[1], rs[0]);
if (result == nullptr)
{
throw std::runtime_error("ERROR: SZ_decompress failed\n");
}
std::memcpy(dataOut, result, dataSizeBytes);
free(result);
result = nullptr;
SZ_Finalize();
return static_cast<size_t>(dataSizeBytes);
}
} // end namespace compress
} // end namespace core
} // end namespace adios2
<commit_msg>removed compressor side memory release as it's done in SZ_Finalize<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* it->first ==ompanying file Copyright.txt for details.
*
* CompressSZ.cpp
*
* Created on: Jul 24, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#include "CompressSZ.h"
#include <cmath> //std::ceil
#include <ios> //std::ios_base::failure
#include <stdexcept> //std::invalid_argument
extern "C" {
#include <sz.h>
}
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace core
{
namespace compress
{
CompressSZ::CompressSZ(const Params ¶meters) : Operator("sz", parameters) {}
size_t CompressSZ::BufferMaxSize(const size_t sizeIn) const
{
return static_cast<size_t>(std::ceil(1.1 * sizeIn) + 600);
}
size_t CompressSZ::Compress(const void *dataIn, const Dims &dimensions,
const size_t elementSize, DataType varType,
void *bufferOut, const Params ¶meters,
Params &info) const
{
const size_t ndims = dimensions.size();
if (ndims > 5)
{
throw std::invalid_argument("ERROR: ADIOS2 SZ compression: no more "
"than 5 dimension is supported.\n");
}
sz_params sz;
memset(&sz, 0, sizeof(sz_params));
sz.max_quant_intervals = 65536;
sz.quantization_intervals = 0;
// sz.dataEndianType = LITTLE_ENDIAN_DATA;
// sz.sysEndianType = LITTLE_ENDIAN_DATA;
sz.sol_ID = SZ;
// sz.layers = 1;
sz.sampleDistance = 100;
sz.predThreshold = 0.99;
// sz.offset = 0;
sz.szMode = SZ_BEST_COMPRESSION; // SZ_BEST_SPEED; //SZ_BEST_COMPRESSION;
sz.gzipMode = 1;
sz.errorBoundMode = ABS;
sz.absErrBound = 1E-4;
sz.relBoundRatio = 1E-3;
sz.psnr = 80.0;
sz.pw_relBoundRatio = 1E-5;
sz.segment_size =
static_cast<int>(std::pow(5., static_cast<double>(ndims)));
sz.pwr_type = SZ_PWR_MIN_TYPE;
size_t outsize;
size_t r[5] = {0, 0, 0, 0, 0};
/* SZ parameters */
int use_configfile = 0;
std::string sz_configfile = "sz.config";
Params::const_iterator it;
for (it = parameters.begin(); it != parameters.end(); it++)
{
if (it->first == "init")
{
use_configfile = 1;
sz_configfile = std::string(it->second);
}
else if (it->first == "max_quant_intervals")
{
sz.max_quant_intervals = std::stoi(it->second);
}
else if (it->first == "quantization_intervals")
{
sz.quantization_intervals = std::stoi(it->second);
}
else if (it->first == "sol_ID")
{
sz.sol_ID = std::stoi(it->second);
}
else if (it->first == "sampleDistance")
{
sz.sampleDistance = std::stoi(it->second);
}
else if (it->first == "predThreshold")
{
sz.predThreshold = std::stof(it->second);
}
else if (it->first == "szMode")
{
int szMode = SZ_BEST_SPEED;
if (it->second == "SZ_BEST_SPEED")
{
szMode = SZ_BEST_SPEED;
}
else if (it->second == "SZ_BEST_COMPRESSION")
{
szMode = SZ_BEST_COMPRESSION;
}
else if (it->second == "SZ_DEFAULT_COMPRESSION")
{
szMode = SZ_DEFAULT_COMPRESSION;
}
else
{
throw std::invalid_argument(
"ERROR: ADIOS2 operator unknown SZ parameter szMode: " +
it->second + "\n");
}
sz.szMode = szMode;
}
else if (it->first == "gzipMode")
{
sz.gzipMode = std::stoi(it->second);
}
else if (it->first == "errorBoundMode")
{
int errorBoundMode = ABS;
if (it->second == "ABS")
{
errorBoundMode = ABS;
}
else if (it->second == "REL")
{
errorBoundMode = REL;
}
else if (it->second == "ABS_AND_REL")
{
errorBoundMode = ABS_AND_REL;
}
else if (it->second == "ABS_OR_REL")
{
errorBoundMode = ABS_OR_REL;
}
else if (it->second == "PW_REL")
{
errorBoundMode = PW_REL;
}
else
{
throw std::invalid_argument("ERROR: ADIOS2 operator "
"unknown SZ parameter "
"errorBoundMode: " +
it->second + "\n");
}
sz.errorBoundMode = errorBoundMode;
}
else if (it->first == "absErrBound")
{
sz.absErrBound = std::stof(it->second);
}
else if (it->first == "relBoundRatio")
{
sz.relBoundRatio = std::stof(it->second);
}
else if (it->first == "pw_relBoundRatio")
{
sz.pw_relBoundRatio = std::stof(it->second);
}
else if (it->first == "segment_size")
{
sz.segment_size = std::stoi(it->second);
}
else if (it->first == "pwr_type")
{
int pwr_type = SZ_PWR_MIN_TYPE;
if ((it->first == "MIN") || (it->first == "SZ_PWR_MIN_TYPE"))
{
pwr_type = SZ_PWR_MIN_TYPE;
}
else if ((it->first == "AVG") || (it->first == "SZ_PWR_AVG_TYPE"))
{
pwr_type = SZ_PWR_AVG_TYPE;
}
else if ((it->first == "MAX") || (it->first == "SZ_PWR_MAX_TYPE"))
{
pwr_type = SZ_PWR_MAX_TYPE;
}
else
{
throw std::invalid_argument("ERROR: ADIOS2 operator "
"unknown SZ parameter "
"pwr_type: " +
it->second + "\n");
}
sz.pwr_type = pwr_type;
}
else if ((it->first == "abs") || (it->first == "absolute") ||
(it->first == "accuracy"))
{
sz.errorBoundMode = ABS;
sz.absErrBound = std::stod(it->second);
}
else if ((it->first == "rel") || (it->first == "relative"))
{
sz.errorBoundMode = REL;
sz.relBoundRatio = std::stof(it->second);
}
else if ((it->first == "pw") || (it->first == "pwr") ||
(it->first == "pwrel") || (it->first == "pwrelative"))
{
sz.errorBoundMode = PW_REL;
sz.pw_relBoundRatio = std::stof(it->second);
}
else if ((it->first == "zchecker") || (it->first == "zcheck") ||
(it->first == "z-checker") || (it->first == "z-check"))
{
// TODO:
// Z-checker is not currently implemented
// use_zchecker = (it->second == "") ? 1 : std::stof(it->second);
}
else
{
// TODO: ignoring unknown option due to Fortran bindings passing
// empty parameter
}
}
if (use_configfile)
{
SZ_Init((char *)sz_configfile.c_str());
}
else
{
SZ_Init_Params(&sz);
}
// Get type info
int dtype = -1;
if (varType == helper::GetDataType<double>())
{
dtype = SZ_DOUBLE;
}
else if (varType == helper::GetDataType<float>())
{
dtype = SZ_FLOAT;
}
else
{
throw std::invalid_argument("ERROR: ADIOS2 SZ Compression only support "
"double or float, type: " +
ToString(varType) + " is unsupported\n");
}
// r[0] is the fastest changing dimension and r[4] is the lowest changing
// dimension
// In C, r[0] is the last dimension. In Fortran, r[0] is the first dimension
for (size_t i = 0; i < ndims; i++)
{
r[ndims - i - 1] = dimensions[i];
/*
if (fd->group->adios_host_language_fortran == adios_flag_yes)
r[i] = dimensions[i];
else
r[ndims-i-1] = dimensions[i];
d = d->next;
*/
}
const unsigned char *bytes = SZ_compress(dtype, (void *)dataIn, &outsize,
r[4], r[3], r[2], r[1], r[0]);
std::memcpy(bufferOut, bytes, outsize);
SZ_Finalize();
return static_cast<size_t>(outsize);
}
size_t CompressSZ::Decompress(const void *bufferIn, const size_t sizeIn,
void *dataOut, const Dims &dimensions,
DataType varType,
const Params & /*parameters*/) const
{
if (dimensions.size() > 5)
{
throw std::invalid_argument("ERROR: SZ decompression doesn't support "
"more than 5 dimension variables.\n");
}
// Get type info
int dtype = 0;
size_t typeSizeBytes = 0;
if (varType == helper::GetDataType<double>())
{
dtype = SZ_DOUBLE;
typeSizeBytes = 8;
}
else if (varType == helper::GetDataType<float>())
{
dtype = SZ_FLOAT;
typeSizeBytes = 4;
}
else
{
throw std::runtime_error(
"ERROR: data type must be either double or float in SZ\n");
}
// r[0] is the fastest changing dimension and r[4] is the lowest changing
// dimension
// In C, r[0] is the last dimension. In Fortran, r[0] is the first dimension
std::vector<size_t> rs(5, 0);
const size_t ndims = dimensions.size();
for (size_t i = 0; i < ndims; ++i)
{
rs[ndims - i - 1] = dimensions[i];
}
const size_t dataSizeBytes =
helper::GetTotalSize(dimensions) * typeSizeBytes;
void *result = SZ_decompress(
dtype, reinterpret_cast<unsigned char *>(const_cast<void *>(bufferIn)),
sizeIn, rs[4], rs[3], rs[2], rs[1], rs[0]);
if (result == nullptr)
{
throw std::runtime_error("ERROR: SZ_decompress failed\n");
}
std::memcpy(dataOut, result, dataSizeBytes);
free(result);
result = nullptr;
SZ_Finalize();
return static_cast<size_t>(dataSizeBytes);
}
} // end namespace compress
} // end namespace core
} // end namespace adios2
<|endoftext|> |
<commit_before>#include "irgen.h"
#include "llvmirgen.h"
#include <llvm/IR/Value.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/BasicBlock.h>
#include <iostream>
#include <string>
#include "astnode.h"
#include "astnodetypes.h"
using namespace llvm;
LLVMContext context;
IRBuilder<> Builder(context);
Module* module;
//TODO(marcus): make this a tree of mapped values.
std::map<std::string, AllocaInst*> varTable;
#define ST SemanticType
Type* getIRType(ST t, std::string ident = "") {
Type* ret;
switch(t) {
case ST::Void:
ret = Type::getVoidTy(context);
break;
case ST::Int:
ret = Type::getInt32Ty(context);
break;
case ST::Float:
ret = Type::getFloatTy(context);
break;
case ST::Double:
ret = Type::getDoubleTy(context);
break;
case ST::Char:
ret = Type::getInt8Ty(context);
break;
case ST::Bool:
ret = Type::getInt1Ty(context);
break;
default:
std::cout << "Type not supported, defaulting to void\n";
ret = Type::getVoidTy(context);
break;
}
return ret;
}
#undef ST
Function* prototypeCodegen(AstNode* n) {
PrototypeNode* protonode = (PrototypeNode*) n;
std::vector<AstNode*>* vec = protonode->getParameters();
std::vector<Type*> parameterTypes;
parameterTypes.reserve(vec->size());
//TODO(marcus): handle user types for return/parameters
for(auto c : (*vec)) {
Type* t = getIRType(c->getType());
parameterTypes.push_back(t);
}
Type* retType = getIRType(protonode->getType());
FunctionType* FT = FunctionType::get(retType, parameterTypes, false);
Function* F = Function::Create(FT, Function::ExternalLinkage, protonode->mfuncname, module);
unsigned int idx = 0;
for(auto &Arg : F->args()) {
std::string name = ((ParamsNode*) (*vec)[idx])->mname;
Arg.setName(name);
++idx;
}
delete vec;
return F;
}
Function* functionCodgen(AstNode* n) {
FuncDefNode* funcnode = (FuncDefNode*) n;
Function* F = module->getFunction(funcnode->mfuncname);
if(!F) {
std::vector<AstNode*>* vec = funcnode->getParameters();
std::vector<Type*> parameterTypes;
parameterTypes.reserve(vec->size());
//TODO(marcus): handle user types for return/parameters
for(auto c : (*vec)) {
Type* t = getIRType(c->getType());
parameterTypes.push_back(t);
}
Type* retType = getIRType(funcnode->getType());
FunctionType* FT = FunctionType::get(retType, parameterTypes, false);
F = Function::Create(FT, Function::ExternalLinkage, funcnode->mfuncname, module);
unsigned int idx = 0;
for(auto &Arg : F->args()) {
std::string name = ((ParamsNode*) (*vec)[idx])->mname;
Arg.setName(name);
++idx;
}
delete vec;
}
//TODO(marcus): what is entry, can it be used for every function?
BasicBlock* BB = BasicBlock::Create(context, "entry", F);
Builder.SetInsertPoint(BB);
//FIXME(marcus): remove void return once expression codegen works
//Builder.CreateRetVoid();
return F;
}
Value* funcCallCodegen(AstNode* n) {
FuncCallNode* callnode = (FuncCallNode*) n;
Function* F = module->getFunction(callnode->mfuncname);
if(!F) {
std::cout << "Function lookup for " << callnode->mfuncname << " not found!\n";
return nullptr;
}
std::vector<Value*> args;
std::vector<AstNode*>* vec = callnode->getChildren();
for(auto c : (*vec)) {
//TODO(marcus): generate code properly for expressions
args.push_back(ConstantInt::get(context, APInt()));
}
return Builder.CreateCall(F, args, "calltemp");
}
Value* retCodegen(AstNode* n) {
ReturnNode* retnode = (ReturnNode*) n;
auto pchildren = retnode->getChildren();
Value* ret = nullptr;
if(pchildren->size() > 0) {
Value* retval = expressionCodegen((*retnode->getChildren())[0]);
ret = Builder.CreateRet(retval);
} else {
ret = Builder.CreateRetVoid();
}
return ret;
}
Value* expressionCodegen(AstNode* n) {
//TODO(marcus): actually fill this in.
Value* val = ConstantInt::get(context, APInt(32,0));
return val;
}
void blockCodegen(AstNode* n) {
std::vector<AstNode*>* vec = n->getChildren();
for(auto c : (*vec)) {
statementCodegen(c);
}
}
//TODO(marcus): see if this code needs to be merged into one function later
void vardecCodegen(AstNode* n) {
auto vardecn = (VarDecNode*) n;
auto varn = (VarNode*)vardecn->mchildren.at(0);
//FIXME(marcus): get the type of the node once type checking works
//TODO(marcus): fix how you access the name of the variable
auto alloc = Builder.CreateAlloca(Type::getInt32Ty(context),0,varn->getVarName());
varTable[varn->getVarName()] = alloc;
return;
}
void vardecassignCodegen(AstNode* n) {
auto vardecan = (VarDecAssignNode*) n;
auto varn = (VarNode*)vardecan->mchildren.at(0);
//FIXME(marcus): get the type of the node once type checking works
//TODO(marcus): fix how you access the name of the variable
AllocaInst* alloca = Builder.CreateAlloca(Type::getInt32Ty(context),0,varn->getVarName());
varTable[varn->getVarName()] = alloca;
//TODO(marcus): don't hardcode child accesses
Value* val = expressionCodegen(vardecan->mchildren.at(1));
Builder.CreateStore(val,alloca);
return;
}
void assignCodegen(AstNode* n) {
std::cout << "Generating assingment\n";
//TODO(marcus): don't hardcode child access
auto assignn = (AssignNode*)n;
auto varn = (VarNode*) assignn->mchildren.at(0);
auto rhs = assignn->mchildren.at(1);
//TODO(marcus): make left hand side work for expressions that yield an address
Value* var = varTable[varn->getVarName()];
Value* val = expressionCodegen(rhs);
Builder.CreateStore(val,var);
return;
}
void ifelseCodegen(AstNode* n) {
auto ifn = (IfNode*) n;
//TODO(marcus): need custom labels for basic blocks?
auto enclosingscope = Builder.GetInsertBlock()->getParent();
BasicBlock* elseBB = nullptr;
BasicBlock* thenBB = BasicBlock::Create(context, "then", enclosingscope);
//TODO(marcus): don't hardcode size values for else check
if(ifn->mstatements.size() == 3) {
elseBB = BasicBlock::Create(context, "else");
}
BasicBlock* mergeBB = BasicBlock::Create(context, "merge");
//TODO(marcus): actually generate conditional expression
auto condv = ConstantInt::get(context, APInt());
//TODO(marcus): is passing nullptr okay here?
Builder.CreateCondBr(condv,thenBB,elseBB);
Builder.SetInsertPoint(thenBB);
//TODO(marcus): don't hardcode child access
statementCodegen(ifn->mstatements.at(1));
Builder.CreateBr(mergeBB);
if(ifn->mstatements.size() == 3) {
enclosingscope->getBasicBlockList().push_back(elseBB);
Builder.SetInsertPoint(elseBB);
auto elsen = (ElseNode*) ifn->mstatements.at(2);
statementCodegen(elsen->mstatements.at(0));
Builder.CreateBr(mergeBB);
}
enclosingscope->getBasicBlockList().push_back(mergeBB);
Builder.SetInsertPoint(mergeBB);
return;
}
void whileloopCodegen(AstNode* n) {
auto whilen = (WhileLoopNode*) n;
auto enclosingscope = Builder.GetInsertBlock()->getParent();
}
#define ANT AstNodeType
void statementCodegen(AstNode* n) {
switch(n->nodeType()) {
case ANT::RetStmnt:
retCodegen(n);
break;
case ANT::Block:
blockCodegen(n);
break;
case ANT::VarDec:
vardecCodegen(n);
break;
case ANT::VarDecAssign:
vardecassignCodegen(n);
break;
case ANT::Assign:
assignCodegen(n);
break;
case ANT::IfStmt:
ifelseCodegen(n);
break;
case ANT::WhileLoop:
whileloopCodegen(n);
break;
default:
break;
}
}
void generateIR_llvm(AstNode* ast) {
//check for null
if(!ast)
return;
//Handle IR gen for each node type
switch(ast->nodeType()) {
case ANT::Prototype:
{
Function* f = prototypeCodegen(ast);
//f->dump();
return;
}
break;
case ANT::FuncDef:
{
Function* F = functionCodgen(ast);
//TODO(marcus): codegen function body
statementCodegen(((FuncDefNode*)ast)->getFunctionBody());
return;
}
break;
case ANT::FuncCall:
{
std::cout << "generating function call\n";
funcCallCodegen(ast);
return;
}
case ANT::RetStmnt:
{
std::cout << "generating return!\n";
retCodegen(ast);
return;
}
case ANT::CompileUnit:
case ANT::Program:
{
std::vector<AstNode*>* vec = ast->getChildren();
for(auto c : (*vec)) {
generateIR_llvm(c);
}
return;
}
default:
break;
}
//recurse
std::vector<AstNode*>* vec = ast->getChildren();
for(auto c : (*vec)) {
generateIR_llvm(c);
}
}
void dumpIR() {
module->dump();
return;
}
void generateIR(AstNode* ast) {
module = new Module("Neuro Program", context);
generateIR_llvm(ast);
}
<commit_msg>While loop code generation and a fix for function call generation.<commit_after>#include "irgen.h"
#include "llvmirgen.h"
#include <llvm/IR/Value.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/BasicBlock.h>
#include <iostream>
#include <string>
#include "astnode.h"
#include "astnodetypes.h"
using namespace llvm;
LLVMContext context;
IRBuilder<> Builder(context);
Module* module;
//TODO(marcus): make this a tree of mapped values.
std::map<std::string, AllocaInst*> varTable;
#define ST SemanticType
Type* getIRType(ST t, std::string ident = "") {
Type* ret;
switch(t) {
case ST::Void:
ret = Type::getVoidTy(context);
break;
case ST::Int:
ret = Type::getInt32Ty(context);
break;
case ST::Float:
ret = Type::getFloatTy(context);
break;
case ST::Double:
ret = Type::getDoubleTy(context);
break;
case ST::Char:
ret = Type::getInt8Ty(context);
break;
case ST::Bool:
ret = Type::getInt1Ty(context);
break;
default:
std::cout << "Type not supported, defaulting to void\n";
ret = Type::getVoidTy(context);
break;
}
return ret;
}
#undef ST
Function* prototypeCodegen(AstNode* n) {
PrototypeNode* protonode = (PrototypeNode*) n;
std::vector<AstNode*>* vec = protonode->getParameters();
std::vector<Type*> parameterTypes;
parameterTypes.reserve(vec->size());
//TODO(marcus): handle user types for return/parameters
for(auto c : (*vec)) {
Type* t = getIRType(c->getType());
parameterTypes.push_back(t);
}
Type* retType = getIRType(protonode->getType());
FunctionType* FT = FunctionType::get(retType, parameterTypes, false);
Function* F = Function::Create(FT, Function::ExternalLinkage, protonode->mfuncname, module);
unsigned int idx = 0;
for(auto &Arg : F->args()) {
std::string name = ((ParamsNode*) (*vec)[idx])->mname;
Arg.setName(name);
++idx;
}
delete vec;
return F;
}
Function* functionCodgen(AstNode* n) {
FuncDefNode* funcnode = (FuncDefNode*) n;
Function* F = module->getFunction(funcnode->mfuncname);
if(!F) {
std::vector<AstNode*>* vec = funcnode->getParameters();
std::vector<Type*> parameterTypes;
parameterTypes.reserve(vec->size());
//TODO(marcus): handle user types for return/parameters
for(auto c : (*vec)) {
Type* t = getIRType(c->getType());
parameterTypes.push_back(t);
}
Type* retType = getIRType(funcnode->getType());
FunctionType* FT = FunctionType::get(retType, parameterTypes, false);
F = Function::Create(FT, Function::ExternalLinkage, funcnode->mfuncname, module);
unsigned int idx = 0;
for(auto &Arg : F->args()) {
std::string name = ((ParamsNode*) (*vec)[idx])->mname;
Arg.setName(name);
++idx;
}
delete vec;
}
//TODO(marcus): what is entry, can it be used for every function?
BasicBlock* BB = BasicBlock::Create(context, "entry", F);
Builder.SetInsertPoint(BB);
//FIXME(marcus): remove void return once expression codegen works
//Builder.CreateRetVoid();
return F;
}
Value* funcCallCodegen(AstNode* n) {
FuncCallNode* callnode = (FuncCallNode*) n;
Function* F = module->getFunction(callnode->mfuncname);
if(!F) {
std::cout << "Function lookup for " << callnode->mfuncname << " not found!\n";
return nullptr;
}
std::vector<Value*> args;
std::vector<AstNode*>* vec = callnode->getChildren();
for(auto c : (*vec)) {
//TODO(marcus): generate code properly for expressions
args.push_back(ConstantInt::get(context, APInt()));
}
return Builder.CreateCall(F, args, "calltemp");
}
Value* retCodegen(AstNode* n) {
ReturnNode* retnode = (ReturnNode*) n;
auto pchildren = retnode->getChildren();
Value* ret = nullptr;
if(pchildren->size() > 0) {
Value* retval = expressionCodegen((*retnode->getChildren())[0]);
ret = Builder.CreateRet(retval);
} else {
ret = Builder.CreateRetVoid();
}
return ret;
}
Value* expressionCodegen(AstNode* n) {
//TODO(marcus): actually fill this in.
Value* val = ConstantInt::get(context, APInt(32,0));
return val;
}
void blockCodegen(AstNode* n) {
std::vector<AstNode*>* vec = n->getChildren();
for(auto c : (*vec)) {
statementCodegen(c);
}
}
//TODO(marcus): see if this code needs to be merged into one function later
void vardecCodegen(AstNode* n) {
auto vardecn = (VarDecNode*) n;
auto varn = (VarNode*)vardecn->mchildren.at(0);
//FIXME(marcus): get the type of the node once type checking works
//TODO(marcus): fix how you access the name of the variable
auto alloc = Builder.CreateAlloca(Type::getInt32Ty(context),0,varn->getVarName());
varTable[varn->getVarName()] = alloc;
return;
}
void vardecassignCodegen(AstNode* n) {
auto vardecan = (VarDecAssignNode*) n;
auto varn = (VarNode*)vardecan->mchildren.at(0);
//FIXME(marcus): get the type of the node once type checking works
//TODO(marcus): fix how you access the name of the variable
AllocaInst* alloca = Builder.CreateAlloca(Type::getInt32Ty(context),0,varn->getVarName());
varTable[varn->getVarName()] = alloca;
//TODO(marcus): don't hardcode child accesses
Value* val = expressionCodegen(vardecan->mchildren.at(1));
Builder.CreateStore(val,alloca);
return;
}
void assignCodegen(AstNode* n) {
std::cout << "Generating assingment\n";
//TODO(marcus): don't hardcode child access
auto assignn = (AssignNode*)n;
auto varn = (VarNode*) assignn->mchildren.at(0);
auto rhs = assignn->mchildren.at(1);
//TODO(marcus): make left hand side work for expressions that yield an address
Value* var = varTable[varn->getVarName()];
Value* val = expressionCodegen(rhs);
Builder.CreateStore(val,var);
return;
}
void ifelseCodegen(AstNode* n) {
auto ifn = (IfNode*) n;
//TODO(marcus): need custom labels for basic blocks?
auto enclosingscope = Builder.GetInsertBlock()->getParent();
BasicBlock* elseBB = nullptr;
BasicBlock* thenBB = BasicBlock::Create(context, "then", enclosingscope);
//TODO(marcus): don't hardcode size values for else check
if(ifn->mstatements.size() == 3) {
elseBB = BasicBlock::Create(context, "else");
}
BasicBlock* mergeBB = BasicBlock::Create(context, "merge");
//TODO(marcus): actually generate conditional expression
auto condv = ConstantInt::get(context, APInt());
//TODO(marcus): is passing nullptr okay here?
Builder.CreateCondBr(condv,thenBB,elseBB);
Builder.SetInsertPoint(thenBB);
//TODO(marcus): don't hardcode child access
statementCodegen(ifn->mstatements.at(1));
Builder.CreateBr(mergeBB);
if(ifn->mstatements.size() == 3) {
enclosingscope->getBasicBlockList().push_back(elseBB);
Builder.SetInsertPoint(elseBB);
auto elsen = (ElseNode*) ifn->mstatements.at(2);
statementCodegen(elsen->mstatements.at(0));
Builder.CreateBr(mergeBB);
}
enclosingscope->getBasicBlockList().push_back(mergeBB);
Builder.SetInsertPoint(mergeBB);
return;
}
void whileloopCodegen(AstNode* n) {
auto whilen = (WhileLoopNode*) n;
auto enclosingscope = Builder.GetInsertBlock()->getParent();
BasicBlock* whileBB = BasicBlock::Create(context,"while",enclosingscope);
BasicBlock* beginBB = BasicBlock::Create(context,"whilebegin",enclosingscope);
BasicBlock* endBB = BasicBlock::Create(context,"whileend",enclosingscope);
Builder.CreateBr(whileBB);
Builder.SetInsertPoint(whileBB);
//TODO(marcus): actually generate the conditional
auto condv = ConstantInt::get(context, APInt());
Builder.CreateCondBr(condv,beginBB,endBB);
Builder.SetInsertPoint(beginBB);
//TODO(marcus): generate whole while loop body
statementCodegen(whilen->mstatements.back());
Builder.CreateBr(whileBB);
Builder.SetInsertPoint(endBB);
return;
}
#define ANT AstNodeType
void statementCodegen(AstNode* n) {
switch(n->nodeType()) {
case ANT::RetStmnt:
retCodegen(n);
break;
case ANT::Block:
blockCodegen(n);
break;
case ANT::VarDec:
vardecCodegen(n);
break;
case ANT::VarDecAssign:
vardecassignCodegen(n);
break;
case ANT::Assign:
assignCodegen(n);
break;
case ANT::IfStmt:
ifelseCodegen(n);
break;
case ANT::WhileLoop:
whileloopCodegen(n);
break;
case ANT::FuncCall:
funcCallCodegen(n);
break;
default:
break;
}
}
void generateIR_llvm(AstNode* ast) {
//check for null
if(!ast)
return;
//Handle IR gen for each node type
switch(ast->nodeType()) {
case ANT::Prototype:
{
Function* f = prototypeCodegen(ast);
//f->dump();
return;
}
break;
case ANT::FuncDef:
{
Function* F = functionCodgen(ast);
//TODO(marcus): codegen function body
statementCodegen(((FuncDefNode*)ast)->getFunctionBody());
return;
}
break;
case ANT::FuncCall:
{
std::cout << "generating function call\n";
funcCallCodegen(ast);
return;
}
case ANT::RetStmnt:
{
std::cout << "generating return!\n";
retCodegen(ast);
return;
}
case ANT::CompileUnit:
case ANT::Program:
{
std::vector<AstNode*>* vec = ast->getChildren();
for(auto c : (*vec)) {
generateIR_llvm(c);
}
return;
}
default:
break;
}
//recurse
std::vector<AstNode*>* vec = ast->getChildren();
for(auto c : (*vec)) {
generateIR_llvm(c);
}
}
void dumpIR() {
module->dump();
return;
}
void generateIR(AstNode* ast) {
module = new Module("Neuro Program", context);
generateIR_llvm(ast);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008-2013, Arvid Norberg
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 its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
EXPORT int run_http_suite(int proxy, char const* protocol, bool test_url_seed, bool chunked_encoding, bool test_ban);
<commit_msg>attempt to fix test link error on windows<commit_after>/*
Copyright (c) 2008-2013, Arvid Norberg
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 its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "test.hpp"
int EXPORT run_http_suite(int proxy, char const* protocol, bool test_url_seed, bool chunked_encoding, bool test_ban);
<|endoftext|> |
<commit_before>/*********************************************************************
* tm700_demo_node.cpp
*
* Copyright 2016 Copyright 2016 Techman Robot Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*********************************************************************
*
* Author: Yun-Hsuan Tsai
*/
#include <ros/ros.h>
#include <ros/console.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/conversions.h>
#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_msgs/AttachedCollisionObject.h>
#include <moveit_msgs/CollisionObject.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
#include "tm_msgs/SetIO.h"
//#include "tm_msgs/SetIORequest.h"
//#include "tm_msgs/SetIOResponse.h"
//get current joint values of TM5
void get_current_joint_values(moveit::planning_interface::MoveGroup& group,
moveit::planning_interface::MoveGroup::Plan& plan,
<<<<<<< HEAD
std::vector<double>& record_joint
){
//if(!ros::ok()) return false;
bool success = false;
std::vector<double> joint_value;
joint_value = group.getCurrentJointValues();
record_joint = group.getCurrentJointValues();
ROS_INFO("In get_current_joint_values()");
for(int i = 0; i<joint_value.size(); i++){
joint_value[i] = joint_value[i]*180/M_PI;
printf("Joint %d: %lf\n",i+1, joint_value[i]);
}
=======
std::vector<double>& record_joint
){
//if(!ros::ok()) return false;
bool success = false;
std::vector<double> joint_value;
joint_value = group.getCurrentJointValues();
record_joint = group.getCurrentJointValues();
ROS_INFO("In get_current_joint_values()");
for(int i = 0; i<joint_value.size(); i++){
joint_value[i] = joint_value[i]*180/M_PI;
printf("Joint %d: %lf\n",i+1, joint_value[i]);
}
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
}
bool try_move_to_named_target(moveit::planning_interface::MoveGroup& group,
moveit::planning_interface::MoveGroup::Plan& plan,
const std::string& target_name,
unsigned int max_try_times = 1
) {
if(!ros::ok()) return false;
bool success = false;
for(unsigned int i = 0; i < max_try_times; i++) {
group.setNamedTarget(target_name);
if(group.move()) {
success = true;
break;
}
else {
if(!ros::ok()) break;
sleep(1);
}
}
return success;
}
bool try_move_to_joint_target(moveit::planning_interface::MoveGroup& group,
moveit::planning_interface::MoveGroup::Plan& plan,
const std::vector<double>& joint_target,
unsigned int max_try_times = 1
) {
if(!ros::ok()) return false;
bool success = false;
for(unsigned int i = 0; i < max_try_times; i++) {
group.setJointValueTarget(joint_target);
if(group.move()) {
success = true;
break;
}
else {
if(!ros::ok()) break;
sleep(1);
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "tm700_demo_test");
ros::NodeHandle node_handle;
ros::ServiceClient set_io_client = node_handle.serviceClient<tm_msgs::SetIO>("tm_driver/set_io");
tm_msgs::SetIO io_srv;
io_srv.request.fun = 2;//tm_msgs::SetIORequest::FUN_SET_EE_DIGITAL_OUT;
io_srv.request.ch = 0;
io_srv.request.value = 0.0;
// start a background "spinner", so our node can process ROS messages
// - this lets us know when the move is completed
ros::AsyncSpinner spinner(1);
spinner.start();
sleep(1);
// Setup
// ^^^^^
// The :move_group_interface:`MoveGroup` class can be easily
// setup using just the name
// of the group you would like to control and plan for.
moveit::planning_interface::MoveGroup group("manipulator");
// We will use the :planning_scene_interface:`PlanningSceneInterface`
// class to deal directly with the world.
moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
// (Optional) Create a publisher for visualizing plans in Rviz.
//ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
//moveit_msgs::DisplayTrajectory display_trajectory;
// Getting Basic Information
// ^^^^^^^^^^^^^^^^^^^^^^^^^
// We can print the name of the reference frame for this robot.
ROS_INFO("Reference frame: %s", group.getPlanningFrame().c_str());
// We can also print the name of the end-effector link for this group.
ROS_INFO("Reference frame: %s", group.getEndEffectorLink().c_str());
moveit::planning_interface::MoveGroup::Plan my_plan;
set_io_client.call(io_srv);
group.setPlanningTime(30.0);
//try_move_to_named_target(group, my_plan, "home", 100);
std::vector<double> joint_target_1;
std::vector<double> joint_target_2;
<<<<<<< HEAD
std::vector<double> record_joint_1;
std::vector<double> record_joint_2;
std::vector<double> record_joint_3;
=======
std::vector<double> record_joint_1;
std::vector<double> record_joint_2;
std::vector<double> record_joint_3;
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
double joint_value = 0;
joint_target_1.assign(6, 0.0f);
joint_target_1[0] = 0.0174533*( 30.0);
joint_target_1[1] = 0.0174533*( 15.0);
joint_target_1[2] = 0.0174533*(105.0);
joint_target_1[3] = 0.0174533*(-30.0);
joint_target_1[4] = 0.0174533*( 90.0);
joint_target_1[5] = 0.0174533*( 30.0);
joint_target_2.assign(6, 0.0f);
joint_target_2[0] = 0.0174533*(-30.0);
joint_target_2[1] = 0.0174533*(-15.0);
joint_target_2[2] = 0.0174533*( 90.0);
joint_target_2[3] = 0.0174533*(-75.0);
joint_target_2[4] = 0.0174533*(120.0);
int step = 0;
int flag = 0;
while (ros::ok()) {
switch (5) {
case 0: //gripper off
<<<<<<< HEAD
io_srv.request.fun = 2;
io_srv.request.ch = 0;
io_srv.request.value = 0.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 1: //move to ready
ROS_INFO("move...");
//try_move_to_named_target(group, my_plan, "ready", 100);
break;
case 2: //light on
/*
io_srv.request.fun = 2;
io_srv.request.ch = 3;
io_srv.request.value = 1.0;
*/
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 3: //wait 3 sec
sleep(3);
break;
case 4: //light off
io_srv.request.fun = 2;
io_srv.request.ch = 3;
io_srv.request.value = 0.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 5: //move 1
//ROS_INFO("move...");
//try_move_to_joint_target(group, my_plan, joint_target_1, 100);
ROS_INFO("Teaching Pose 1...");
=======
io_srv.request.fun = 2;
io_srv.request.ch = 0;
io_srv.request.value = 0.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 1: //move to ready
ROS_INFO("move...");
//try_move_to_named_target(group, my_plan, "ready", 100);
break;
case 2: //light on
/*
io_srv.request.fun = 2;
io_srv.request.ch = 3;
io_srv.request.value = 1.0;
*/
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 3: //wait 3 sec
sleep(3);
break;
case 4: //light off
io_srv.request.fun = 2;
io_srv.request.ch = 3;
io_srv.request.value = 0.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 5: //move 1
//ROS_INFO("move...");
//try_move_to_joint_target(group, my_plan, joint_target_1, 100);
ROS_INFO("Teaching Pose 1...");
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
while(flag == 0){
printf("Finish Teaching? Yes: 1, No:0\n");
scanf("%d", &flag);
get_current_joint_values(group, my_plan, record_joint_1);
}
flag = 0;
ROS_INFO("Teaching Pose 2...");
while(flag == 0){
printf("Finish Teaching? Yes: 1, No:0\n");
scanf("%d", &flag);
get_current_joint_values(group, my_plan, record_joint_2);
}
flag = 0;
ROS_INFO("Teaching Pose 3...");
while(flag == 0){
printf("Finish Teaching? Yes: 1, No:0\n");
scanf("%d", &flag);
get_current_joint_values(group, my_plan, record_joint_3);
}
//ROS_INFO("Teaching Pose 1...");
<<<<<<< HEAD
for(int i = 0; i<record_joint_1.size(); i++){
joint_value = record_joint_1[i]*180/M_PI;
printf("Joint %d: degree: %lf, rad: %lf\n", i+1, joint_value, record_joint_1[i]);
}
=======
for(int i = 0; i<record_joint_1.size(); i++){
joint_value = record_joint_1[i]*180/M_PI;
printf("Joint %d: degree: %lf, rad: %lf\n", i+1, joint_value, record_joint_1[i]);
}
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
while(ros::ok()){
try_move_to_named_target(group, my_plan, "home", 100);
//wait 3 seconds
sleep(3);
try_move_to_joint_target(group, my_plan, record_joint_1, 100);
sleep(3);
try_move_to_joint_target(group, my_plan, record_joint_2, 100);
sleep(3);
try_move_to_joint_target(group, my_plan, record_joint_3, 100);
sleep(3);
}
<<<<<<< HEAD
break;
case 6: //gripper on
io_srv.request.fun = 2;
io_srv.request.ch = 0;
io_srv.request.value = 1.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 7: //wait 1 sec
sleep(1);
break;
case 8: //move 2...
ROS_INFO("move...");
//try_move_to_joint_target(group, my_plan, joint_target_2, 100);
break;
=======
break;
case 6: //gripper on
io_srv.request.fun = 2;
io_srv.request.ch = 0;
io_srv.request.value = 1.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 7: //wait 1 sec
sleep(1);
break;
case 8: //move 2...
ROS_INFO("move...");
//try_move_to_joint_target(group, my_plan, joint_target_2, 100);
break;
>>>>>>> e5e86088216a75c4dc8ce5dc610f4fea4bd2b763
}
step = (step + 1) % 9;
}
return 0;
}
<commit_msg>update merge<commit_after>/*********************************************************************
* tm700_demo_node.cpp
*
* Copyright 2016 Copyright 2016 Techman Robot Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*********************************************************************
*
* Author: Yun-Hsuan Tsai
*/
#include <ros/ros.h>
#include <ros/console.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/robot_state/robot_state.h>
#include <moveit/robot_state/conversions.h>
#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_msgs/AttachedCollisionObject.h>
#include <moveit_msgs/CollisionObject.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
#include "tm_msgs/SetIO.h"
//#include "tm_msgs/SetIORequest.h"
//#include "tm_msgs/SetIOResponse.h"
//get current joint values of TM5
void get_current_joint_values(moveit::planning_interface::MoveGroup& group,
moveit::planning_interface::MoveGroup::Plan& plan,
std::vector<double>& record_joint
){
//if(!ros::ok()) return false;
bool success = false;
std::vector<double> joint_value;
joint_value = group.getCurrentJointValues();
record_joint = group.getCurrentJointValues();
ROS_INFO("In get_current_joint_values()");
for(int i = 0; i<joint_value.size(); i++){
joint_value[i] = joint_value[i]*180/M_PI;
printf("Joint %d: %lf\n",i+1, joint_value[i]);
}
}
bool try_move_to_named_target(moveit::planning_interface::MoveGroup& group,
moveit::planning_interface::MoveGroup::Plan& plan,
const std::string& target_name,
unsigned int max_try_times = 1
) {
if(!ros::ok()) return false;
bool success = false;
for(unsigned int i = 0; i < max_try_times; i++) {
group.setNamedTarget(target_name);
if(group.move()) {
success = true;
break;
}
else {
if(!ros::ok()) break;
sleep(1);
}
}
return success;
}
bool try_move_to_joint_target(moveit::planning_interface::MoveGroup& group,
moveit::planning_interface::MoveGroup::Plan& plan,
const std::vector<double>& joint_target,
unsigned int max_try_times = 1
) {
if(!ros::ok()) return false;
bool success = false;
for(unsigned int i = 0; i < max_try_times; i++) {
group.setJointValueTarget(joint_target);
if(group.move()) {
success = true;
break;
}
else {
if(!ros::ok()) break;
sleep(1);
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "tm700_demo_test");
ros::NodeHandle node_handle;
ros::ServiceClient set_io_client = node_handle.serviceClient<tm_msgs::SetIO>("tm_driver/set_io");
tm_msgs::SetIO io_srv;
io_srv.request.fun = 2;//tm_msgs::SetIORequest::FUN_SET_EE_DIGITAL_OUT;
io_srv.request.ch = 0;
io_srv.request.value = 0.0;
// start a background "spinner", so our node can process ROS messages
// - this lets us know when the move is completed
ros::AsyncSpinner spinner(1);
spinner.start();
sleep(1);
// Setup
// ^^^^^
// The :move_group_interface:`MoveGroup` class can be easily
// setup using just the name
// of the group you would like to control and plan for.
moveit::planning_interface::MoveGroup group("manipulator");
// We will use the :planning_scene_interface:`PlanningSceneInterface`
// class to deal directly with the world.
moveit::planning_interface::PlanningSceneInterface planning_scene_interface;
// (Optional) Create a publisher for visualizing plans in Rviz.
//ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
//moveit_msgs::DisplayTrajectory display_trajectory;
// Getting Basic Information
// ^^^^^^^^^^^^^^^^^^^^^^^^^
// We can print the name of the reference frame for this robot.
ROS_INFO("Reference frame: %s", group.getPlanningFrame().c_str());
// We can also print the name of the end-effector link for this group.
ROS_INFO("Reference frame: %s", group.getEndEffectorLink().c_str());
moveit::planning_interface::MoveGroup::Plan my_plan;
set_io_client.call(io_srv);
group.setPlanningTime(30.0);
//try_move_to_named_target(group, my_plan, "home", 100);
std::vector<double> joint_target_1;
std::vector<double> joint_target_2;
std::vector<double> record_joint_1;
std::vector<double> record_joint_2;
std::vector<double> record_joint_3;
double joint_value = 0;
joint_target_1.assign(6, 0.0f);
joint_target_1[0] = 0.0174533*( 30.0);
joint_target_1[1] = 0.0174533*( 15.0);
joint_target_1[2] = 0.0174533*(105.0);
joint_target_1[3] = 0.0174533*(-30.0);
joint_target_1[4] = 0.0174533*( 90.0);
joint_target_1[5] = 0.0174533*( 30.0);
joint_target_2.assign(6, 0.0f);
joint_target_2[0] = 0.0174533*(-30.0);
joint_target_2[1] = 0.0174533*(-15.0);
joint_target_2[2] = 0.0174533*( 90.0);
joint_target_2[3] = 0.0174533*(-75.0);
joint_target_2[4] = 0.0174533*(120.0);
int step = 0;
int flag = 0;
while (ros::ok()) {
switch (5) {
case 0: //gripper off
io_srv.request.fun = 2;
io_srv.request.ch = 0;
io_srv.request.value = 0.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 1: //move to ready
ROS_INFO("move...");
//try_move_to_named_target(group, my_plan, "ready", 100);
break;
case 2: //light on
/*
io_srv.request.fun = 2;
io_srv.request.ch = 3;
io_srv.request.value = 1.0;
*/
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 3: //wait 3 sec
sleep(3);
break;
case 4: //light off
io_srv.request.fun = 2;
io_srv.request.ch = 3;
io_srv.request.value = 0.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 5: //move 1
//ROS_INFO("move...");
//try_move_to_joint_target(group, my_plan, joint_target_1, 100);
ROS_INFO("Teaching Pose 1...");
while(flag == 0){
printf("Finish Teaching? Yes: 1, No:0\n");
scanf("%d", &flag);
get_current_joint_values(group, my_plan, record_joint_1);
}
flag = 0;
ROS_INFO("Teaching Pose 2...");
while(flag == 0){
printf("Finish Teaching? Yes: 1, No:0\n");
scanf("%d", &flag);
get_current_joint_values(group, my_plan, record_joint_2);
}
flag = 0;
ROS_INFO("Teaching Pose 3...");
while(flag == 0){
printf("Finish Teaching? Yes: 1, No:0\n");
scanf("%d", &flag);
get_current_joint_values(group, my_plan, record_joint_3);
}
//ROS_INFO("Teaching Pose 1...");
for(int i = 0; i<record_joint_1.size(); i++){
joint_value = record_joint_1[i]*180/M_PI;
printf("Joint %d: degree: %lf, rad: %lf\n", i+1, joint_value, record_joint_1[i]);
}
while(ros::ok()){
try_move_to_named_target(group, my_plan, "home", 100);
//wait 3 seconds
sleep(3);
try_move_to_joint_target(group, my_plan, record_joint_1, 100);
sleep(3);
try_move_to_joint_target(group, my_plan, record_joint_2, 100);
sleep(3);
try_move_to_joint_target(group, my_plan, record_joint_3, 100);
sleep(3);
}
break;
case 6: //gripper on
io_srv.request.fun = 2;
io_srv.request.ch = 0;
io_srv.request.value = 1.0;
if (set_io_client.call(io_srv))
ROS_INFO("Set IO success");
else
ROS_WARN("Failed to call service set_io");
break;
case 7: //wait 1 sec
sleep(1);
break;
case 8: //move 2...
ROS_INFO("move...");
//try_move_to_joint_target(group, my_plan, joint_target_2, 100);
break;
}
step = (step + 1) % 9;
}
return 0;
}<|endoftext|> |
<commit_before>
#include <gloperate/rendering/Drawable.h>
#include <cassert>
#include <cppassist/memory/make_unique.h>
#include <glbinding/gl/enum.h>
#include <globjects/VertexArray.h>
#include <globjects/VertexAttributeBinding.h>
namespace gloperate
{
Drawable::Drawable()
: m_vao(cppassist::make_unique<globjects::VertexArray>())
, m_drawMode(DrawMode::Arrays)
, m_size(0)
, m_primitiveMode(gl::GL_TRIANGLES)
, m_indexBufferType(gl::GL_UNSIGNED_INT)
{
}
Drawable::~Drawable()
{
}
globjects::VertexArray * Drawable::vao() const
{
return m_vao.get();
}
DrawMode Drawable::drawMode() const
{
return m_drawMode;
}
void Drawable::setDrawMode(DrawMode drawMode)
{
m_drawMode = drawMode;
}
void Drawable::draw() const
{
draw(m_drawMode);
}
void Drawable::draw(DrawMode drawMode) const
{
switch (drawMode)
{
case DrawMode::ElementsIndices:
case DrawMode::ElementsIndexBuffer:
drawElements();
break;
case DrawMode::Arrays:
default:
drawArrays();
break;
}
}
void Drawable::drawArrays() const
{
drawArrays(m_primitiveMode, 0, m_size);
}
void Drawable::drawArrays(gl::GLenum mode) const
{
drawArrays(mode, 0, m_size);
}
void Drawable::drawArrays(gl::GLint first, gl::GLsizei count) const
{
drawArrays(m_primitiveMode, first, count);
}
void Drawable::drawArrays(gl::GLenum mode, gl::GLint first, gl::GLsizei count) const
{
m_vao->drawArrays(mode, first, count);
}
void Drawable::drawElements() const
{
drawElements(m_primitiveMode);
}
void Drawable::drawElements(gl::GLenum mode) const
{
if (m_drawMode == DrawMode::ElementsIndices)
{
drawElements(mode, m_size, gl::GL_UNSIGNED_INT, m_indices.data());
}
else
{
drawElements(mode, m_size, m_indexBufferType, m_indexBuffer);
}
}
void Drawable::drawElements(gl::GLenum mode, gl::GLsizei count, gl::GLenum type, const void * indices) const
{
// [TODO]: rethink recorded vao state
globjects::Buffer::unbind(gl::GL_ELEMENT_ARRAY_BUFFER);
m_vao->drawElements(mode, count, type, indices);
}
void Drawable::drawElements(gl::GLenum mode, gl::GLsizei count, gl::GLenum type, globjects::Buffer *) const
{
// [TODO]: rethink recorded vao state
m_vao->drawElements(mode, count, type, nullptr);
}
gl::GLsizei Drawable::size() const
{
return m_size;
}
void Drawable::setSize(gl::GLsizei size)
{
m_size = size;
}
gl::GLenum Drawable::primitiveMode() const
{
return m_primitiveMode;
}
void Drawable::setPrimitiveMode(gl::GLenum mode)
{
m_primitiveMode = mode;
}
globjects::Buffer * Drawable::buffer(size_t index)
{
if (m_buffers.count(index) == 0)
{
return nullptr;
}
return m_buffers.at(index);
}
globjects::Buffer * Drawable::buffer(size_t index) const
{
if (m_buffers.count(index) == 0)
{
return nullptr;
}
return m_buffers.at(index);
}
void Drawable::setBuffer(size_t index, globjects::Buffer * buffer)
{
m_buffers[index] = buffer;
}
globjects::Buffer * Drawable::indexBuffer() const
{
return m_indexBuffer;
}
void Drawable::setIndexBuffer(globjects::Buffer * buffer)
{
m_vao->bind();
buffer->bind(gl::GL_ELEMENT_ARRAY_BUFFER);
m_indexBuffer = buffer;
m_vao->unbind();
}
void Drawable::setIndexBuffer(globjects::Buffer * buffer, gl::GLenum bufferType)
{
setIndexBuffer(buffer);
setIndexBufferType(bufferType);
}
gl::GLenum Drawable::indexBufferType() const
{
return m_indexBufferType;
}
void Drawable::setIndexBufferType(gl::GLenum bufferType)
{
m_indexBufferType = bufferType;
}
const std::vector<std::uint32_t> & Drawable::indices() const
{
return m_indices;
}
void Drawable::setIndices(const std::vector<std::uint32_t> & indices)
{
m_indices = indices;
}
globjects::VertexAttributeBinding * Drawable::attributeBinding(size_t index) const
{
return m_vao->binding(index);
}
void Drawable::setAttributeBindingBuffer(size_t bindingIndex, size_t bufferIndex, gl::GLint baseOffset, gl::GLint stride)
{
assert(m_buffers.count(bufferIndex) > 0);
m_vao->binding(bindingIndex)->setBuffer(m_buffers.at(bufferIndex), baseOffset, stride);
}
void Drawable::setAttributeBindingFormat(size_t bindingIndex, gl::GLint size, gl::GLenum type, gl::GLboolean normalized, gl::GLuint relativeOffset)
{
m_vao->binding(bindingIndex)->setFormat(size, type, normalized, relativeOffset);
}
void Drawable::setAttributeBindingFormatI(size_t bindingIndex, gl::GLint size, gl::GLenum type, gl::GLuint relativeOffset)
{
m_vao->binding(bindingIndex)->setIFormat(size, type, relativeOffset);
}
void Drawable::setAttributeBindingFormatL(size_t bindingIndex, gl::GLint size, gl::GLenum type, gl::GLuint relativeOffset)
{
m_vao->binding(bindingIndex)->setLFormat(size, type, relativeOffset);
}
void Drawable::bindAttribute(size_t bindingIndex, gl::GLint attributeIndex)
{
m_vao->binding(bindingIndex)->setAttribute(attributeIndex);
}
void Drawable::bindAttributes(const std::vector<gl::GLint> & attributeIndices)
{
for (size_t i = 0; i < attributeIndices.size(); ++i)
{
m_vao->binding(i)->setAttribute(attributeIndices.at(i));
}
}
void Drawable::enableAttributeBinding(size_t bindingIndex)
{
m_vao->enable(m_vao->binding(bindingIndex)->attributeIndex());
}
void Drawable::enableAllAttributeBindings()
{
for (const globjects::VertexAttributeBinding * binding : m_vao->bindings())
{
m_vao->enable(binding->attributeIndex());
}
}
} // namespace gloperate
<commit_msg>Fix initialization of index buffer in drawable<commit_after>
#include <gloperate/rendering/Drawable.h>
#include <cassert>
#include <cppassist/memory/make_unique.h>
#include <glbinding/gl/enum.h>
#include <globjects/VertexArray.h>
#include <globjects/VertexAttributeBinding.h>
namespace gloperate
{
Drawable::Drawable()
: m_vao(cppassist::make_unique<globjects::VertexArray>())
, m_drawMode(DrawMode::Arrays)
, m_size(0)
, m_primitiveMode(gl::GL_TRIANGLES)
, m_indexBufferType(gl::GL_UNSIGNED_INT)
, m_indexBuffer(nullptr)
{
}
Drawable::~Drawable()
{
}
globjects::VertexArray * Drawable::vao() const
{
return m_vao.get();
}
DrawMode Drawable::drawMode() const
{
return m_drawMode;
}
void Drawable::setDrawMode(DrawMode drawMode)
{
m_drawMode = drawMode;
}
void Drawable::draw() const
{
draw(m_drawMode);
}
void Drawable::draw(DrawMode drawMode) const
{
switch (drawMode)
{
case DrawMode::ElementsIndices:
case DrawMode::ElementsIndexBuffer:
drawElements();
break;
case DrawMode::Arrays:
default:
drawArrays();
break;
}
}
void Drawable::drawArrays() const
{
drawArrays(m_primitiveMode, 0, m_size);
}
void Drawable::drawArrays(gl::GLenum mode) const
{
drawArrays(mode, 0, m_size);
}
void Drawable::drawArrays(gl::GLint first, gl::GLsizei count) const
{
drawArrays(m_primitiveMode, first, count);
}
void Drawable::drawArrays(gl::GLenum mode, gl::GLint first, gl::GLsizei count) const
{
m_vao->drawArrays(mode, first, count);
}
void Drawable::drawElements() const
{
drawElements(m_primitiveMode);
}
void Drawable::drawElements(gl::GLenum mode) const
{
if (m_drawMode == DrawMode::ElementsIndices)
{
drawElements(mode, m_size, gl::GL_UNSIGNED_INT, m_indices.data());
}
else
{
drawElements(mode, m_size, m_indexBufferType, m_indexBuffer);
}
}
void Drawable::drawElements(gl::GLenum mode, gl::GLsizei count, gl::GLenum type, const void * indices) const
{
// [TODO]: rethink recorded vao state
globjects::Buffer::unbind(gl::GL_ELEMENT_ARRAY_BUFFER);
m_vao->drawElements(mode, count, type, indices);
}
void Drawable::drawElements(gl::GLenum mode, gl::GLsizei count, gl::GLenum type, globjects::Buffer *) const
{
// [TODO]: rethink recorded vao state
m_vao->drawElements(mode, count, type, nullptr);
}
gl::GLsizei Drawable::size() const
{
return m_size;
}
void Drawable::setSize(gl::GLsizei size)
{
m_size = size;
}
gl::GLenum Drawable::primitiveMode() const
{
return m_primitiveMode;
}
void Drawable::setPrimitiveMode(gl::GLenum mode)
{
m_primitiveMode = mode;
}
globjects::Buffer * Drawable::buffer(size_t index)
{
if (m_buffers.count(index) == 0)
{
return nullptr;
}
return m_buffers.at(index);
}
globjects::Buffer * Drawable::buffer(size_t index) const
{
if (m_buffers.count(index) == 0)
{
return nullptr;
}
return m_buffers.at(index);
}
void Drawable::setBuffer(size_t index, globjects::Buffer * buffer)
{
m_buffers[index] = buffer;
}
globjects::Buffer * Drawable::indexBuffer() const
{
return m_indexBuffer;
}
void Drawable::setIndexBuffer(globjects::Buffer * buffer)
{
m_vao->bind();
buffer->bind(gl::GL_ELEMENT_ARRAY_BUFFER);
m_indexBuffer = buffer;
m_vao->unbind();
}
void Drawable::setIndexBuffer(globjects::Buffer * buffer, gl::GLenum bufferType)
{
setIndexBuffer(buffer);
setIndexBufferType(bufferType);
}
gl::GLenum Drawable::indexBufferType() const
{
return m_indexBufferType;
}
void Drawable::setIndexBufferType(gl::GLenum bufferType)
{
m_indexBufferType = bufferType;
}
const std::vector<std::uint32_t> & Drawable::indices() const
{
return m_indices;
}
void Drawable::setIndices(const std::vector<std::uint32_t> & indices)
{
m_indices = indices;
}
globjects::VertexAttributeBinding * Drawable::attributeBinding(size_t index) const
{
return m_vao->binding(index);
}
void Drawable::setAttributeBindingBuffer(size_t bindingIndex, size_t bufferIndex, gl::GLint baseOffset, gl::GLint stride)
{
assert(m_buffers.count(bufferIndex) > 0);
m_vao->binding(bindingIndex)->setBuffer(m_buffers.at(bufferIndex), baseOffset, stride);
}
void Drawable::setAttributeBindingFormat(size_t bindingIndex, gl::GLint size, gl::GLenum type, gl::GLboolean normalized, gl::GLuint relativeOffset)
{
m_vao->binding(bindingIndex)->setFormat(size, type, normalized, relativeOffset);
}
void Drawable::setAttributeBindingFormatI(size_t bindingIndex, gl::GLint size, gl::GLenum type, gl::GLuint relativeOffset)
{
m_vao->binding(bindingIndex)->setIFormat(size, type, relativeOffset);
}
void Drawable::setAttributeBindingFormatL(size_t bindingIndex, gl::GLint size, gl::GLenum type, gl::GLuint relativeOffset)
{
m_vao->binding(bindingIndex)->setLFormat(size, type, relativeOffset);
}
void Drawable::bindAttribute(size_t bindingIndex, gl::GLint attributeIndex)
{
m_vao->binding(bindingIndex)->setAttribute(attributeIndex);
}
void Drawable::bindAttributes(const std::vector<gl::GLint> & attributeIndices)
{
for (size_t i = 0; i < attributeIndices.size(); ++i)
{
m_vao->binding(i)->setAttribute(attributeIndices.at(i));
}
}
void Drawable::enableAttributeBinding(size_t bindingIndex)
{
m_vao->enable(m_vao->binding(bindingIndex)->attributeIndex());
}
void Drawable::enableAllAttributeBindings()
{
for (const globjects::VertexAttributeBinding * binding : m_vao->bindings())
{
m_vao->enable(binding->attributeIndex());
}
}
} // namespace gloperate
<|endoftext|> |
<commit_before>#pragma once
#include <glowutils/RawFile.h>
#include <algorithm>
#include <fstream>
#include <glow/logging.h>
namespace glowutils
{
template<typename T>
RawFile<T>::RawFile(const std::string & filePath)
: m_filePath(filePath)
, m_valid(false)
{
read();
}
template<typename T>
RawFile<T>::~RawFile()
{
}
template<typename T>
bool RawFile<T>::valid() const
{
return m_valid;
}
template<typename T>
const T * RawFile<T>::data() const
{
return &m_data.data()[0];
}
template<typename T>
size_t RawFile<T>::size() const
{
return m_data.size();
}
template<typename T>
bool RawFile<T>::read()
{
std::ifstream ifs(m_filePath, std::ios::in | std::ios::binary | std::ios::ate);
if (!ifs)
{
glow::warning() << "Reading from file \"" << m_filePath << "\" failed.";
return false;
}
const std::streampos tmpSize = ifs.tellg();
if (tmpSize > std::numeric_limits<std::streamsize>::max())
{
glow::warning() << "File \"" << m_filePath << "\" is too big to be read in one chunk.";
return false;
}
const std::streamsize size = static_cast<const std::streamsize>(tmpSize);
ifs.seekg(0, std::ios::beg);
m_data.resize(size / sizeof(T));
ifs.read(reinterpret_cast<char*>(&m_data[0]), size);
ifs.close();
m_valid = true;
return true;
}
} // namespace glowutils
<commit_msg>Adjust RawFile<T>::read() for too big files<commit_after>#pragma once
#include <glowutils/RawFile.h>
#include <algorithm>
#include <fstream>
#include <glow/logging.h>
namespace glowutils
{
template<typename T>
RawFile<T>::RawFile(const std::string & filePath)
: m_filePath(filePath)
, m_valid(false)
{
read();
}
template<typename T>
RawFile<T>::~RawFile()
{
}
template<typename T>
bool RawFile<T>::valid() const
{
return m_valid;
}
template<typename T>
const T * RawFile<T>::data() const
{
return &m_data.data()[0];
}
template<typename T>
size_t RawFile<T>::size() const
{
return m_data.size();
}
template<typename T>
bool RawFile<T>::read()
{
std::ifstream ifs(m_filePath, std::ios::in | std::ios::binary | std::ios::ate);
if (!ifs)
{
glow::warning() << "Reading from file \"" << m_filePath << "\" failed.";
return false;
}
const std::streampos tmpSize = ifs.tellg();
if (tmpSize > std::numeric_limits<std::streamsize>::max())
{
glow::warning() << "File \"" << m_filePath << "\" is too big to be read.";
return false;
}
const std::streamsize size = static_cast<const std::streamsize>(tmpSize);
ifs.seekg(0, std::ios::beg);
m_data.resize(size / sizeof(T));
ifs.read(reinterpret_cast<char*>(&m_data[0]), size);
ifs.close();
m_valid = true;
return true;
}
} // namespace glowutils
<|endoftext|> |
<commit_before>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>
#include <ir/index_manager/index/EPostingWriter.h>
#include <ir/index_manager/store/IndexInput.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <util/izene_log.h>
#include <cassert>
using namespace std;
namespace bfs = boost::filesystem;
NS_IZENELIB_IR_BEGIN
namespace indexmanager
{
void writeTermInfo(
IndexOutput* pVocWriter,
termid_t tid,
const TermInfo& termInfo)
{
pVocWriter->writeInt(tid); ///write term id
pVocWriter->writeInt(termInfo.docFreq_); ///write df
pVocWriter->writeInt(termInfo.ctf_); ///write ctf
pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id
pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level
pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset
pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset
pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist)
pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset
pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}
#pragma pack(push,1)
struct Record
{
uint8_t len;
uint32_t tid;
uint32_t docId;
uint32_t offset;
};
#pragma pack(pop)
FieldIndexer::FieldIndexer(
const char* field,
Indexer* pIndexer
)
:field_(field)
,pIndexer_(pIndexer)
,vocFilePointer_(0)
,alloc_(0)
,f_(0)
,termCount_(0)
,iHitsMax_(0)
,recordCount_(0)
,run_num_(0)
,pHits_(0)
,pHitsMax_(0)
,flush_(false)
{
skipInterval_ = pIndexer_->getSkipInterval();
maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
indexLevel_ = pIndexer_->pConfigurationManager_->indexStrategy_.indexLevel_;
sorterFileName_ = field_+".tmp";
bfs::path path(bfs::path(pIndexer_->pConfigurationManager_->indexStrategy_.indexLocation_)
/bfs::path(sorterFileName_));
sorterFullPath_ = path.string();
}
FieldIndexer::~FieldIndexer()
{
if (alloc_) delete alloc_;
if (f_)
{
fclose(f_);
if(! boost::filesystem::remove(sorterFullPath_))
LOG(WARNING) << "FieldIndexer::~FieldIndexer(): failed to remove file " << sorterFullPath_;
}
}
void FieldIndexer::setIndexMode(
boost::shared_ptr<MemCache> pMemCache,
size_t nBatchMemSize,
bool realtime)
{
if(!realtime)
{
if(alloc_)
{
delete alloc_;
alloc_ = 0;
}
pMemCache_.reset(new MemCache(
pIndexer_->getIndexManagerConfig()->mergeStrategy_.memPoolSizeForPostingMerger_));
setHitBuffer_(nBatchMemSize);
}
else
{
hits_.reset();
iHitsMax_ = 0;
pHits_ = pHitsMax_ = 0;
pMemCache_ = pMemCache;
}
reset();
}
bool FieldIndexer::isEmpty()
{
if (pIndexer_->isRealTime())
return postingMap_.size() == 0;
else
return isBatchEmpty_();
}
bool FieldIndexer::isBatchEmpty_()
{
if(hits_.size() == 0) return true;
if(recordCount_ == 0)
{
int iHits = pHits_ - hits_;
if(iHits == 0) return true;
}
return false;
}
void FieldIndexer::setHitBuffer_(size_t size)
{
iHitsMax_ = size;
iHitsMax_ = iHitsMax_/sizeof(TermId) ;
hits_.assign(iHitsMax_);
pHits_ = hits_;
pHitsMax_ = hits_ + iHitsMax_;
}
/***********************************
* Format within single group for merged sort
* uint32 size
* uint32 number
* uint64 nextstart (file offset to location of next group)
* sorted records
************************************/
void FieldIndexer::writeHitBuffer_(int iHits)
{
recordCount_ += iHits;
bufferSort ( &hits_[0], iHits, CmpTermId_fn() );
uint32_t output_buf_size = iHits * (sizeof(TermId)+sizeof(uint8_t));
///buffer size
fwrite(&output_buf_size, sizeof(uint32_t), 1, f_);
///number of hits
fwrite(&iHits, sizeof(uint32_t), 1, f_);
uint64_t nextStart = 0;
uint64_t nextStartPos = ftell(f_);
///next start
fwrite(&nextStart, sizeof(uint64_t), 1, f_);
FieldIndexIO ioStream(f_, "w");
ioStream.writeRecord(&hits_[0], iHits * sizeof(TermId));
nextStart = ftell(f_);
///update next start
fseek(f_, nextStartPos, SEEK_SET);
fwrite(&nextStart, sizeof(uint64_t), 1, f_);
fseek(f_, nextStart, SEEK_SET);
++run_num_;
}
void FieldIndexer::addField(
docid_t docid,
boost::shared_ptr<LAInput> laInput)
{
if(laInput->empty()) return;
if (pIndexer_->isRealTime())
{
if(!alloc_) alloc_ = new boost::scoped_alloc(recycle_);
RTPostingWriter* curPosting;
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termid_);
if (postingIter == postingMap_.end())
{
//curPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_);
assert(alloc_);
curPosting = BOOST_NEW(*alloc_, RTPostingWriter)
(pMemCache_, skipInterval_, maxSkipLevel_, indexLevel_);
postingMap_[iter->termid_] = curPosting;
}
else
curPosting = postingIter->second;
curPosting->add(docid, iter->wordOffset_, true);
}
}
else
{
if(flush_)
{
hits_.assign(iHitsMax_);
pHits_ = hits_;
pHitsMax_ = hits_ + iHitsMax_;
flush_ = false;
}
int iDocHits = laInput->size();
TermId * pDocHits = (TermId*)&(* laInput->begin());
while( iDocHits > 0)
{
int iToCopy = iDocHits < (pHitsMax_ - pHits_) ? iDocHits: (pHitsMax_ - pHits_);
memcpy(pHits_, pDocHits, iToCopy*sizeof(TermId));
pHits_ += iToCopy;
pDocHits += iToCopy;
iDocHits -= iToCopy;
if (pHits_ < pHitsMax_)
continue;
int iHits = pHits_ - hits_;
writeHitBuffer_(iHits);
pHits_ = hits_;
}
}
}
void FieldIndexer::reset()
{
RTPostingWriter* pPosting;
InMemoryPostingMap::iterator iter = postingMap_.begin();
for (; iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
if (!pPosting->isEmpty())
{
pPosting->reset(); ///clear posting data
}
}
postingMap_.clear();
termCount_ = 0;
if (! pIndexer_->isRealTime())
{
f_ = fopen(sorterFullPath_.c_str(),"w");
uint64_t count = 0;
fwrite(&count, sizeof(uint64_t), 1, f_);
}
else
{
if(alloc_) delete alloc_;
alloc_ = new boost::scoped_alloc(recycle_);
}
}
fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();
IndexOutput* pVocWriter = pWriterDesc->getVocOutput();
termid_t tid;
fileoffset_t vocOffset = pVocWriter->getFilePointer();
TermInfo termInfo;
if (pIndexer_->isRealTime())
{
RTPostingWriter* pPosting;
izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
InMemoryPostingMap::iterator iter = postingMap_.begin();
for (; iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
pPosting->setDirty(true);
if (!pPosting->isEmpty())
{
tid = iter->first;
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter,tid,termInfo);
pPosting->reset(); ///clear posting data
termInfo.reset();
termCount_++;
}
//delete pPosting;
//pPosting = NULL;
}
//postingMap_.clear();
}
else
{
if( !boost::filesystem::exists(sorterFullPath_) || isBatchEmpty_())
{
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
int iHits = pHits_ - hits_;
if(iHits > 0)
{
writeHitBuffer_(iHits);
}
fseek(f_, 0, SEEK_SET);
fwrite(&recordCount_, sizeof(uint64_t), 1, f_);
fclose(f_);
f_ = NULL;
hits_.reset();
typedef izenelib::am::SortMerger<uint32_t, uint8_t, true,SortIO<FieldIndexIO> > merge_t;
struct timeval tvafter, tvpre;
struct timezone tz;
gettimeofday (&tvpre , &tz);
merge_t* merger = new merge_t(sorterFullPath_.c_str(), run_num_, 100000000, 2);
merger->run();
gettimeofday (&tvafter , &tz);
LOG(INFO) << "It takes " << ((tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000.)/60000
<< " minutes to sort(" << recordCount_ << ")";
delete merger;
recordCount_ = 0;
run_num_ = 0;
flush_ = true;
FILE* f = fopen(sorterFullPath_.c_str(),"r");
uint64_t count;
FieldIndexIO ioStream(f);
Record r;
ioStream._readBytes((char*)(&count),sizeof(uint64_t));
PostingWriter* pPosting = NULL;
switch(pIndexer_->getIndexCompressType())
{
case BYTEALIGN:
pPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_, indexLevel_);
break;
case BLOCK:
pPosting = new BlockPostingWriter(pMemCache_, indexLevel_);
break;
case CHUNK:
pPosting = new ChunkPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_, indexLevel_);
break;
default:
assert(false);
}
termid_t lastTerm = BAD_DOCID;
try
{
for (uint64_t i = 0; i < count; ++i)
{
ioStream._read((char *)(&r), 13);
if(r.tid != lastTerm && lastTerm != BAD_DOCID)
{
if (!pPosting->isEmpty())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
}
pPosting->add(r.docId, r.offset);
lastTerm = r.tid;
}
}catch(std::exception& e)
{
LOG(WARNING) << e.what();
}
if (!pPosting->isEmpty())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
fclose(f);
boost::filesystem::remove(sorterFullPath_);
delete pPosting;
}
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
///begin write vocabulary descriptor
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
TermReader* FieldIndexer::termReader()
{
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
return new MemTermReader(getField(),this);
}
}
NS_IZENELIB_IR_END
<commit_msg>fix a bug in FieldIndexer::setIndexMode().<commit_after>#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/FieldIndexer.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/TermPositions.h>
#include <ir/index_manager/index/EPostingWriter.h>
#include <ir/index_manager/store/IndexInput.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <util/izene_log.h>
#include <cassert>
using namespace std;
namespace bfs = boost::filesystem;
NS_IZENELIB_IR_BEGIN
namespace indexmanager
{
void writeTermInfo(
IndexOutput* pVocWriter,
termid_t tid,
const TermInfo& termInfo)
{
pVocWriter->writeInt(tid); ///write term id
pVocWriter->writeInt(termInfo.docFreq_); ///write df
pVocWriter->writeInt(termInfo.ctf_); ///write ctf
pVocWriter->writeInt(termInfo.lastDocID_); ///write last doc id
pVocWriter->writeInt(termInfo.skipLevel_); ///write skip level
pVocWriter->writeLong(termInfo.skipPointer_); ///write skip list offset offset
pVocWriter->writeLong(termInfo.docPointer_); ///write document posting offset
pVocWriter->writeInt(termInfo.docPostingLen_); ///write document posting length (without skiplist)
pVocWriter->writeLong(termInfo.positionPointer_); ///write position posting offset
pVocWriter->writeInt(termInfo.positionPostingLen_);///write position posting length
}
#pragma pack(push,1)
struct Record
{
uint8_t len;
uint32_t tid;
uint32_t docId;
uint32_t offset;
};
#pragma pack(pop)
FieldIndexer::FieldIndexer(
const char* field,
Indexer* pIndexer
)
:field_(field)
,pIndexer_(pIndexer)
,vocFilePointer_(0)
,alloc_(0)
,f_(0)
,termCount_(0)
,iHitsMax_(0)
,recordCount_(0)
,run_num_(0)
,pHits_(0)
,pHitsMax_(0)
,flush_(false)
{
skipInterval_ = pIndexer_->getSkipInterval();
maxSkipLevel_ = pIndexer_->getMaxSkipLevel();
indexLevel_ = pIndexer_->pConfigurationManager_->indexStrategy_.indexLevel_;
sorterFileName_ = field_+".tmp";
bfs::path path(bfs::path(pIndexer_->pConfigurationManager_->indexStrategy_.indexLocation_)
/bfs::path(sorterFileName_));
sorterFullPath_ = path.string();
}
FieldIndexer::~FieldIndexer()
{
if (alloc_) delete alloc_;
if (f_)
{
fclose(f_);
if(! boost::filesystem::remove(sorterFullPath_))
LOG(WARNING) << "FieldIndexer::~FieldIndexer(): failed to remove file " << sorterFullPath_;
}
}
void FieldIndexer::setIndexMode(
boost::shared_ptr<MemCache> pMemCache,
size_t nBatchMemSize,
bool realtime)
{
if(!realtime)
{
pMemCache_.reset(new MemCache(
pIndexer_->getIndexManagerConfig()->mergeStrategy_.memPoolSizeForPostingMerger_));
setHitBuffer_(nBatchMemSize);
}
else
{
hits_.reset();
iHitsMax_ = 0;
pHits_ = pHitsMax_ = 0;
pMemCache_ = pMemCache;
}
reset();
}
bool FieldIndexer::isEmpty()
{
if (pIndexer_->isRealTime())
return postingMap_.size() == 0;
else
return isBatchEmpty_();
}
bool FieldIndexer::isBatchEmpty_()
{
if(hits_.size() == 0) return true;
if(recordCount_ == 0)
{
int iHits = pHits_ - hits_;
if(iHits == 0) return true;
}
return false;
}
void FieldIndexer::setHitBuffer_(size_t size)
{
iHitsMax_ = size;
iHitsMax_ = iHitsMax_/sizeof(TermId) ;
hits_.assign(iHitsMax_);
pHits_ = hits_;
pHitsMax_ = hits_ + iHitsMax_;
}
/***********************************
* Format within single group for merged sort
* uint32 size
* uint32 number
* uint64 nextstart (file offset to location of next group)
* sorted records
************************************/
void FieldIndexer::writeHitBuffer_(int iHits)
{
recordCount_ += iHits;
bufferSort ( &hits_[0], iHits, CmpTermId_fn() );
uint32_t output_buf_size = iHits * (sizeof(TermId)+sizeof(uint8_t));
///buffer size
fwrite(&output_buf_size, sizeof(uint32_t), 1, f_);
///number of hits
fwrite(&iHits, sizeof(uint32_t), 1, f_);
uint64_t nextStart = 0;
uint64_t nextStartPos = ftell(f_);
///next start
fwrite(&nextStart, sizeof(uint64_t), 1, f_);
FieldIndexIO ioStream(f_, "w");
ioStream.writeRecord(&hits_[0], iHits * sizeof(TermId));
nextStart = ftell(f_);
///update next start
fseek(f_, nextStartPos, SEEK_SET);
fwrite(&nextStart, sizeof(uint64_t), 1, f_);
fseek(f_, nextStart, SEEK_SET);
++run_num_;
}
void FieldIndexer::addField(
docid_t docid,
boost::shared_ptr<LAInput> laInput)
{
if(laInput->empty()) return;
if (pIndexer_->isRealTime())
{
if(!alloc_) alloc_ = new boost::scoped_alloc(recycle_);
RTPostingWriter* curPosting;
for (LAInput::iterator iter = laInput->begin(); iter != laInput->end(); ++iter)
{
InMemoryPostingMap::iterator postingIter = postingMap_.find(iter->termid_);
if (postingIter == postingMap_.end())
{
//curPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_);
assert(alloc_);
curPosting = BOOST_NEW(*alloc_, RTPostingWriter)
(pMemCache_, skipInterval_, maxSkipLevel_, indexLevel_);
postingMap_[iter->termid_] = curPosting;
}
else
curPosting = postingIter->second;
curPosting->add(docid, iter->wordOffset_, true);
}
}
else
{
if(flush_)
{
hits_.assign(iHitsMax_);
pHits_ = hits_;
pHitsMax_ = hits_ + iHitsMax_;
flush_ = false;
}
int iDocHits = laInput->size();
TermId * pDocHits = (TermId*)&(* laInput->begin());
while( iDocHits > 0)
{
int iToCopy = iDocHits < (pHitsMax_ - pHits_) ? iDocHits: (pHitsMax_ - pHits_);
memcpy(pHits_, pDocHits, iToCopy*sizeof(TermId));
pHits_ += iToCopy;
pDocHits += iToCopy;
iDocHits -= iToCopy;
if (pHits_ < pHitsMax_)
continue;
int iHits = pHits_ - hits_;
writeHitBuffer_(iHits);
pHits_ = hits_;
}
}
}
void FieldIndexer::reset()
{
RTPostingWriter* pPosting;
InMemoryPostingMap::iterator iter = postingMap_.begin();
for (; iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
if (!pPosting->isEmpty())
{
pPosting->reset(); ///clear posting data
}
}
postingMap_.clear();
termCount_ = 0;
if(alloc_)
{
delete alloc_;
alloc_ = 0;
}
if (! pIndexer_->isRealTime())
{
f_ = fopen(sorterFullPath_.c_str(),"w");
uint64_t count = 0;
fwrite(&count, sizeof(uint64_t), 1, f_);
}
else
{
alloc_ = new boost::scoped_alloc(recycle_);
}
}
fileoffset_t FieldIndexer::write(OutputDescriptor* pWriterDesc)
{
vocFilePointer_ = pWriterDesc->getVocOutput()->getFilePointer();
IndexOutput* pVocWriter = pWriterDesc->getVocOutput();
termid_t tid;
fileoffset_t vocOffset = pVocWriter->getFilePointer();
TermInfo termInfo;
if (pIndexer_->isRealTime())
{
RTPostingWriter* pPosting;
izenelib::util::ScopedWriteLock<izenelib::util::ReadWriteLock> lock(rwLock_);
InMemoryPostingMap::iterator iter = postingMap_.begin();
for (; iter !=postingMap_.end(); ++iter)
{
pPosting = iter->second;
pPosting->setDirty(true);
if (!pPosting->isEmpty())
{
tid = iter->first;
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter,tid,termInfo);
pPosting->reset(); ///clear posting data
termInfo.reset();
termCount_++;
}
//delete pPosting;
//pPosting = NULL;
}
//postingMap_.clear();
}
else
{
if( !boost::filesystem::exists(sorterFullPath_) || isBatchEmpty_())
{
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
int iHits = pHits_ - hits_;
if(iHits > 0)
{
writeHitBuffer_(iHits);
}
fseek(f_, 0, SEEK_SET);
fwrite(&recordCount_, sizeof(uint64_t), 1, f_);
fclose(f_);
f_ = NULL;
hits_.reset();
typedef izenelib::am::SortMerger<uint32_t, uint8_t, true,SortIO<FieldIndexIO> > merge_t;
struct timeval tvafter, tvpre;
struct timezone tz;
gettimeofday (&tvpre , &tz);
merge_t* merger = new merge_t(sorterFullPath_.c_str(), run_num_, 100000000, 2);
merger->run();
gettimeofday (&tvafter , &tz);
LOG(INFO) << "It takes " << ((tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000.)/60000
<< " minutes to sort(" << recordCount_ << ")";
delete merger;
recordCount_ = 0;
run_num_ = 0;
flush_ = true;
FILE* f = fopen(sorterFullPath_.c_str(),"r");
uint64_t count;
FieldIndexIO ioStream(f);
Record r;
ioStream._readBytes((char*)(&count),sizeof(uint64_t));
PostingWriter* pPosting = NULL;
switch(pIndexer_->getIndexCompressType())
{
case BYTEALIGN:
pPosting = new RTPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_, indexLevel_);
break;
case BLOCK:
pPosting = new BlockPostingWriter(pMemCache_, indexLevel_);
break;
case CHUNK:
pPosting = new ChunkPostingWriter(pMemCache_, skipInterval_, maxSkipLevel_, indexLevel_);
break;
default:
assert(false);
}
termid_t lastTerm = BAD_DOCID;
try
{
for (uint64_t i = 0; i < count; ++i)
{
ioStream._read((char *)(&r), 13);
if(r.tid != lastTerm && lastTerm != BAD_DOCID)
{
if (!pPosting->isEmpty())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
}
pPosting->add(r.docId, r.offset);
lastTerm = r.tid;
}
}catch(std::exception& e)
{
LOG(WARNING) << e.what();
}
if (!pPosting->isEmpty())
{
pPosting->write(pWriterDesc, termInfo); ///write posting data
writeTermInfo(pVocWriter, lastTerm, termInfo);
pPosting->reset(); ///clear posting data
pMemCache_->flushMem();
termInfo.reset();
termCount_++;
}
fclose(f);
boost::filesystem::remove(sorterFullPath_);
delete pPosting;
}
fileoffset_t vocDescOffset = pVocWriter->getFilePointer();
int64_t vocLength = vocDescOffset - vocOffset;
///begin write vocabulary descriptor
pVocWriter->writeLong(vocLength); ///<VocLength(Int64)>
pVocWriter->writeLong(termCount_); ///<TermCount(Int64)>
///end write vocabulary descriptor
return vocDescOffset;
}
TermReader* FieldIndexer::termReader()
{
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(rwLock_);
return new MemTermReader(getField(),this);
}
}
NS_IZENELIB_IR_END
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software 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 <boost/bind.hpp>
#include "Gaffer/Context.h"
#include "GafferScene/ScenePlug.h"
#include "GafferScene/PathMatcherData.h"
#include "GafferScene/PathFilter.h"
using namespace GafferScene;
using namespace Gaffer;
using namespace IECore;
using namespace std;
IE_CORE_DEFINERUNTIMETYPED( PathFilter );
size_t PathFilter::g_firstPlugIndex = 0;
PathFilter::PathFilter( const std::string &name )
: Filter( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new StringVectorDataPlug( "paths", Plug::In, new StringVectorData ) );
addChild( new ObjectPlug( "__pathMatcher", Plug::Out, new PathMatcherData ) );
plugDirtiedSignal().connect( boost::bind( &PathFilter::plugDirtied, this, ::_1 ) );
}
PathFilter::~PathFilter()
{
}
Gaffer::StringVectorDataPlug *PathFilter::pathsPlug()
{
return getChild<Gaffer::StringVectorDataPlug>( g_firstPlugIndex );
}
const Gaffer::StringVectorDataPlug *PathFilter::pathsPlug() const
{
return getChild<Gaffer::StringVectorDataPlug>( g_firstPlugIndex );
}
Gaffer::ObjectPlug *PathFilter::pathMatcherPlug()
{
return getChild<Gaffer::ObjectPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::ObjectPlug *PathFilter::pathMatcherPlug() const
{
return getChild<Gaffer::ObjectPlug>( g_firstPlugIndex + 1 );
}
void PathFilter::plugDirtied( const Gaffer::Plug *plug )
{
if( plug == pathsPlug() )
{
//\todo: share this logic with Switch::variesWithContext()
Plug* sourcePlug = pathsPlug()->source<Plug>();
if( sourcePlug->direction() == Plug::Out && IECore::runTimeCast<const ComputeNode>( sourcePlug->node() ) )
{
// pathsPlug() is receiving data from a plug whose value is context varying, meaning
// we need to use the intermediate pathMatcherPlug() in computeMatch() instead:
m_pathMatcher = NULL;
}
else
{
// pathsPlug() value is not context varying, meaning we can save on graph evaluations
// by just precomputing it here and directly using it in computeMatch():
ConstStringVectorDataPtr paths = pathsPlug()->getValue();
m_pathMatcher = new PathMatcherData;
m_pathMatcher->writable().init( paths->readable().begin(), paths->readable().end() );
}
}
}
void PathFilter::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
Filter::affects( input, outputs );
if( input == pathsPlug() )
{
outputs.push_back( pathMatcherPlug() );
}
else if( input == pathMatcherPlug() )
{
outputs.push_back( outPlug() );
}
}
void PathFilter::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
Filter::hash( output, context, h );
if( output == pathMatcherPlug() )
{
pathsPlug()->hash( h );
}
}
void PathFilter::compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const
{
if( output == pathMatcherPlug() )
{
ConstStringVectorDataPtr paths = pathsPlug()->getValue();
PathMatcherDataPtr pathMatcherData = new PathMatcherData;
pathMatcherData->writable().init( paths->readable().begin(), paths->readable().end() );
static_cast<ObjectPlug *>( output )->setValue( pathMatcherData );
return;
}
Filter::compute( output, context );
}
void PathFilter::hashMatch( const ScenePlug *scene, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
typedef IECore::TypedData<ScenePlug::ScenePath> ScenePathData;
const ScenePathData *pathData = context->get<ScenePathData>( ScenePlug::scenePathContextName, NULL );
if( pathData )
{
const ScenePlug::ScenePath &path = pathData->readable();
h.append( &(path[0]), path.size() );
}
pathMatcherPlug()->hash( h );
}
unsigned PathFilter::computeMatch( const ScenePlug *scene, const Gaffer::Context *context ) const
{
typedef IECore::TypedData<ScenePlug::ScenePath> ScenePathData;
const ScenePathData *pathData = context->get<ScenePathData>( ScenePlug::scenePathContextName, NULL );
if( pathData )
{
// If we have a precomputed PathMatcher, we use that to compute matches, otherwise
// we grab the PathMatcher from the intermediate plug (which is a bit more expensive
// as it involves graph evaluations):
ConstPathMatcherDataPtr pathMatcher = m_pathMatcher ? m_pathMatcher : boost::static_pointer_cast<const PathMatcherData>( pathMatcherPlug()->getValue() );
return pathMatcher->readable().match( pathData->readable() );
}
return NoMatch;
}
<commit_msg>PathFilter.cpp : Fixed boost include.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012, John Haddon. All rights reserved.
// Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software 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 "boost/bind.hpp"
#include "Gaffer/Context.h"
#include "GafferScene/ScenePlug.h"
#include "GafferScene/PathMatcherData.h"
#include "GafferScene/PathFilter.h"
using namespace GafferScene;
using namespace Gaffer;
using namespace IECore;
using namespace std;
IE_CORE_DEFINERUNTIMETYPED( PathFilter );
size_t PathFilter::g_firstPlugIndex = 0;
PathFilter::PathFilter( const std::string &name )
: Filter( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new StringVectorDataPlug( "paths", Plug::In, new StringVectorData ) );
addChild( new ObjectPlug( "__pathMatcher", Plug::Out, new PathMatcherData ) );
plugDirtiedSignal().connect( boost::bind( &PathFilter::plugDirtied, this, ::_1 ) );
}
PathFilter::~PathFilter()
{
}
Gaffer::StringVectorDataPlug *PathFilter::pathsPlug()
{
return getChild<Gaffer::StringVectorDataPlug>( g_firstPlugIndex );
}
const Gaffer::StringVectorDataPlug *PathFilter::pathsPlug() const
{
return getChild<Gaffer::StringVectorDataPlug>( g_firstPlugIndex );
}
Gaffer::ObjectPlug *PathFilter::pathMatcherPlug()
{
return getChild<Gaffer::ObjectPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::ObjectPlug *PathFilter::pathMatcherPlug() const
{
return getChild<Gaffer::ObjectPlug>( g_firstPlugIndex + 1 );
}
void PathFilter::plugDirtied( const Gaffer::Plug *plug )
{
if( plug == pathsPlug() )
{
//\todo: share this logic with Switch::variesWithContext()
Plug* sourcePlug = pathsPlug()->source<Plug>();
if( sourcePlug->direction() == Plug::Out && IECore::runTimeCast<const ComputeNode>( sourcePlug->node() ) )
{
// pathsPlug() is receiving data from a plug whose value is context varying, meaning
// we need to use the intermediate pathMatcherPlug() in computeMatch() instead:
m_pathMatcher = NULL;
}
else
{
// pathsPlug() value is not context varying, meaning we can save on graph evaluations
// by just precomputing it here and directly using it in computeMatch():
ConstStringVectorDataPtr paths = pathsPlug()->getValue();
m_pathMatcher = new PathMatcherData;
m_pathMatcher->writable().init( paths->readable().begin(), paths->readable().end() );
}
}
}
void PathFilter::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
Filter::affects( input, outputs );
if( input == pathsPlug() )
{
outputs.push_back( pathMatcherPlug() );
}
else if( input == pathMatcherPlug() )
{
outputs.push_back( outPlug() );
}
}
void PathFilter::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
Filter::hash( output, context, h );
if( output == pathMatcherPlug() )
{
pathsPlug()->hash( h );
}
}
void PathFilter::compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const
{
if( output == pathMatcherPlug() )
{
ConstStringVectorDataPtr paths = pathsPlug()->getValue();
PathMatcherDataPtr pathMatcherData = new PathMatcherData;
pathMatcherData->writable().init( paths->readable().begin(), paths->readable().end() );
static_cast<ObjectPlug *>( output )->setValue( pathMatcherData );
return;
}
Filter::compute( output, context );
}
void PathFilter::hashMatch( const ScenePlug *scene, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
typedef IECore::TypedData<ScenePlug::ScenePath> ScenePathData;
const ScenePathData *pathData = context->get<ScenePathData>( ScenePlug::scenePathContextName, NULL );
if( pathData )
{
const ScenePlug::ScenePath &path = pathData->readable();
h.append( &(path[0]), path.size() );
}
pathMatcherPlug()->hash( h );
}
unsigned PathFilter::computeMatch( const ScenePlug *scene, const Gaffer::Context *context ) const
{
typedef IECore::TypedData<ScenePlug::ScenePath> ScenePathData;
const ScenePathData *pathData = context->get<ScenePathData>( ScenePlug::scenePathContextName, NULL );
if( pathData )
{
// If we have a precomputed PathMatcher, we use that to compute matches, otherwise
// we grab the PathMatcher from the intermediate plug (which is a bit more expensive
// as it involves graph evaluations):
ConstPathMatcherDataPtr pathMatcher = m_pathMatcher ? m_pathMatcher : boost::static_pointer_cast<const PathMatcherData>( pathMatcherPlug()->getValue() );
return pathMatcher->readable().match( pathData->readable() );
}
return NoMatch;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <fstream>
#include "../AngelixCommon.h"
#include "SMTLIB2.h"
std::unordered_set<VarDecl*> collectVarsFromScope(const ast_type_traits::DynTypedNode node, ASTContext* context) {
const FunctionDecl* fd;
if ((fd = node.get<FunctionDecl>()) != NULL) {
std::unordered_set<VarDecl*> set;
for (auto it = fd->param_begin(); it != fd->param_end(); ++it) {
auto vd = cast<VarDecl>(*it);
set.insert(vd);
}
return set;
} else {
ArrayRef<ast_type_traits::DynTypedNode> parents = context->getParents(node);
if (parents.size() > 0) {
const ast_type_traits::DynTypedNode parent = *(parents.begin()); // TODO: for now only first
return collectVarsFromScope(parent, context);
} else {
std::unordered_set<VarDecl*> set;
return set;
}
}
}
class CollectVariables : public StmtVisitor<CollectVariables> {
std::unordered_set<VarDecl*> *VSet;
std::unordered_set<MemberExpr*> *MSet;
public:
CollectVariables(std::unordered_set<VarDecl*> *vset, std::unordered_set<MemberExpr*> *mset): VSet(vset), MSet(mset) {}
void Collect(Expr *E) {
if (E)
Visit(E);
}
void Visit(Stmt* S) {
StmtVisitor<CollectVariables>::Visit(S);
}
void VisitBinaryOperator(BinaryOperator *Node) {
Collect(Node->getLHS());
Collect(Node->getRHS());
}
void VisitUnaryOperator(UnaryOperator *Node) {
Collect(Node->getSubExpr());
}
void VisitImplicitCastExpr(ImplicitCastExpr *Node) {
Collect(Node->getSubExpr());
}
void VisitIntegerLiteral(IntegerLiteral *Node) {
}
void VisitCharacterLiteral(CharacterLiteral *Node) {
}
void VisitMemberExpr(MemberExpr *Node) {
if (MSet) {
MSet->insert(Node);
}
}
void VisitDeclRefExpr(DeclRefExpr *Node) {
if (VSet) {
VarDecl* vd;
if ((vd = cast<VarDecl>(Node->getDecl())) != NULL) { // TODO: other kinds of declarations?
VSet->insert(vd);
}
}
}
};
std::unordered_set<VarDecl*> collectVarsFromExpr(const Stmt* stmt) {
std::unordered_set<VarDecl*> set;
CollectVariables T(&set, NULL);
T.Visit(const_cast<Stmt*>(stmt));
return set;
}
std::unordered_set<MemberExpr*> collectMemberExprFromExpr(const Stmt* stmt) {
std::unordered_set<MemberExpr*> set;
CollectVariables T(NULL, &set);
T.Visit(const_cast<Stmt*>(stmt));
return set;
}
bool isSuspicious(int beginLine, int beginColumn, int endLine, int endColumn) {
std::string line;
std::string suspiciousFile(getenv("ANGELIX_SUSPICIOUS"));
std::ifstream infile(suspiciousFile);
int curBeginLine, curBeginColumn, curEndLine, curEndColumn;
while (std::getline(infile, line)) {
std::istringstream iss(line);
iss >> curBeginLine >> curBeginColumn >> curEndLine >> curEndColumn;
if (curBeginLine == beginLine &&
curBeginColumn == beginColumn &&
curEndLine == endLine &&
curEndColumn == endColumn) {
return true;
}
}
return false;
}
class ExpressionHandler : public MatchFinder::MatchCallback {
public:
ExpressionHandler(Rewriter &Rewrite, std::string t) : Rewrite(Rewrite), type(t) {}
virtual void run(const MatchFinder::MatchResult &Result) {
if (const Expr *expr = Result.Nodes.getNodeAs<clang::Expr>("repairable")) {
SourceManager &srcMgr = Rewrite.getSourceMgr();
SourceRange expandedLoc = getExpandedLoc(expr, srcMgr);
unsigned beginLine = srcMgr.getSpellingLineNumber(expandedLoc.getBegin());
unsigned beginColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getBegin());
unsigned endLine = srcMgr.getSpellingLineNumber(expandedLoc.getEnd());
unsigned endColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getEnd());
if (! isSuspicious(beginLine, beginColumn, endLine, endColumn)) {
return;
}
std::cout << beginLine << " " << beginColumn << " " << endLine << " " << endColumn << "\n"
<< toString(expr) << "\n";
std::ostringstream exprId;
exprId << beginLine << "-" << beginColumn << "-" << endLine << "-" << endColumn;
std::string extractedDir(getenv("ANGELIX_EXTRACTED"));
std::ofstream fs(extractedDir + "/" + exprId.str() + ".smt2");
fs << "(assert " << toSMTLIB2(expr) << ")\n";
const ast_type_traits::DynTypedNode node = ast_type_traits::DynTypedNode::create(*expr);
std::unordered_set<VarDecl*> varsFromScope = collectVarsFromScope(node, Result.Context);
std::unordered_set<VarDecl*> varsFromExpr = collectVarsFromExpr(expr);
std::unordered_set<MemberExpr*> memberFromExpr = collectMemberExprFromExpr(expr);
std::unordered_set<VarDecl*> vars;
vars.insert(varsFromScope.begin(), varsFromScope.end());
vars.insert(varsFromExpr.begin(), varsFromExpr.end());
std::ostringstream exprStream;
std::ostringstream nameStream;
bool first = true;
for (auto it = vars.begin(); it != vars.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
VarDecl* var = *it;
exprStream << var->getName().str();
nameStream << "\"" << var->getName().str() << "\"";
}
for (auto it = memberFromExpr.begin(); it != memberFromExpr.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
MemberExpr* me = *it;
exprStream << toString(me);
nameStream << "\"" << toString(me) << "\"";
}
int size = vars.size() + memberFromExpr.size();
std::ostringstream stringStream;
stringStream << "ANGELIX_CHOOSE("
<< type << ", "
<< toString(expr) << ", "
<< beginLine << ", "
<< beginColumn << ", "
<< endLine << ", "
<< endColumn << ", "
<< "((char*[]){" << nameStream.str() << "}), "
<< "((int[]){" << exprStream.str() << "}), "
<< size
<< ")";
std::string replacement = stringStream.str();
Rewrite.ReplaceText(expandedLoc, replacement);
}
}
private:
Rewriter &Rewrite;
std::string type;
};
class SemfixExpressionHandler : public MatchFinder::MatchCallback {
public:
SemfixExpressionHandler(Rewriter &Rewrite, std::string t) : Rewrite(Rewrite), type(t) {}
virtual void run(const MatchFinder::MatchResult &Result) {
if (const Expr *expr = Result.Nodes.getNodeAs<clang::Expr>("repairable")) {
SourceManager &srcMgr = Rewrite.getSourceMgr();
SourceRange expandedLoc = getExpandedLoc(expr, srcMgr);
unsigned beginLine = srcMgr.getSpellingLineNumber(expandedLoc.getBegin());
unsigned beginColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getBegin());
unsigned endLine = srcMgr.getSpellingLineNumber(expandedLoc.getEnd());
unsigned endColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getEnd());
if (! isSuspicious(beginLine, beginColumn, endLine, endColumn)) {
return;
}
std::cout << beginLine << " " << beginColumn << " " << endLine << " " << endColumn << "\n"
<< toString(expr) << "\n";
std::ostringstream exprId;
exprId << beginLine << "-" << beginColumn << "-" << endLine << "-" << endColumn;
std::string extractedDir(getenv("ANGELIX_EXTRACTED"));
std::ofstream fs(extractedDir + "/" + exprId.str() + ".smt2");
fs << "(assert true)\n"; // this is a hack, but not dangerous
const ast_type_traits::DynTypedNode node = ast_type_traits::DynTypedNode::create(*expr);
std::unordered_set<VarDecl*> varsFromScope = collectVarsFromScope(node, Result.Context);
std::unordered_set<VarDecl*> vars;
vars.insert(varsFromScope.begin(), varsFromScope.end());
std::ostringstream exprStream;
std::ostringstream nameStream;
bool first = true;
for (auto it = vars.begin(); it != vars.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
VarDecl* var = *it;
exprStream << var->getName().str();
nameStream << "\"" << var->getName().str() << "\"";
}
int size = vars.size();
std::ostringstream stringStream;
stringStream << "ANGELIX_CHOOSE("
<< type << ", "
<< "1" << ", " // don't execute expression, because it can have side effects
<< beginLine << ", "
<< beginColumn << ", "
<< endLine << ", "
<< endColumn << ", "
<< "((char*[]){" << nameStream.str() << "}), "
<< "((int[]){" << exprStream.str() << "}), "
<< size
<< ")";
std::string replacement = stringStream.str();
Rewrite.ReplaceText(expandedLoc, replacement);
}
}
private:
Rewriter &Rewrite;
std::string type;
};
class StatementHandler : public MatchFinder::MatchCallback {
public:
StatementHandler(Rewriter &Rewrite) : Rewrite(Rewrite) {}
virtual void run(const MatchFinder::MatchResult &Result) {
if (const Stmt *stmt = Result.Nodes.getNodeAs<clang::Stmt>("repairable")) {
SourceManager &srcMgr = Rewrite.getSourceMgr();
SourceRange expandedLoc = getExpandedLoc(stmt, srcMgr);
unsigned beginLine = srcMgr.getSpellingLineNumber(expandedLoc.getBegin());
unsigned beginColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getBegin());
unsigned endLine = srcMgr.getSpellingLineNumber(expandedLoc.getEnd());
unsigned endColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getEnd());
if (! isSuspicious(beginLine, beginColumn, endLine, endColumn)) {
return;
}
std::cout << beginLine << " " << beginColumn << " " << endLine << " " << endColumn << "\n"
<< toString(stmt) << "\n";
std::ostringstream stmtId;
stmtId << beginLine << "-" << beginColumn << "-" << endLine << "-" << endColumn;
std::string extractedDir(getenv("ANGELIX_EXTRACTED"));
std::ofstream fs(extractedDir + "/" + stmtId.str() + ".smt2");
fs << "(assert true)\n";
const ast_type_traits::DynTypedNode node = ast_type_traits::DynTypedNode::create(*stmt);
std::unordered_set<VarDecl*> varsFromScope = collectVarsFromScope(node, Result.Context);
std::unordered_set<VarDecl*> vars;
vars.insert(varsFromScope.begin(), varsFromScope.end());
std::ostringstream exprStream;
std::ostringstream nameStream;
bool first = true;
for (auto it = vars.begin(); it != vars.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
VarDecl* var = *it;
exprStream << var->getName().str();
nameStream << "\"" << var->getName().str() << "\"";
}
int size = vars.size();
std::ostringstream stringStream;
stringStream << "if ("
<< "ANGELIX_CHOOSE("
<< "bool" << ", "
<< 1 << ", "
<< beginLine << ", "
<< beginColumn << ", "
<< endLine << ", "
<< endColumn << ", "
<< "((char*[]){" << nameStream.str() << "}), "
<< "((int[]){" << exprStream.str() << "}), "
<< size
<< ")"
<< ") "
<< toString(stmt);
std::string replacement = stringStream.str();
Rewrite.ReplaceText(expandedLoc, replacement);
}
}
private:
Rewriter &Rewrite;
};
class MyASTConsumer : public ASTConsumer {
public:
MyASTConsumer(Rewriter &R) : HandlerForIntegerExpressions(R, "int"),
HandlerForBooleanExpressions(R, "bool"),
HandlerForStatements(R),
SemfixHandlerForIntegerExpressions(R, "int"),
SemfixHandlerForBooleanExpressions(R, "bool") {
if (getenv("ANGELIX_SEMFIX_MODE")) {
Matcher.addMatcher(InterestingCondition, &SemfixHandlerForBooleanExpressions);
Matcher.addMatcher(InterestingIntegerAssignment, &SemfixHandlerForIntegerExpressions);
} else {
Matcher.addMatcher(RepairableAssignment, &HandlerForIntegerExpressions);
Matcher.addMatcher(InterestingRepairableCondition, &HandlerForBooleanExpressions);
Matcher.addMatcher(InterestingStatement, &HandlerForStatements);
}
}
void HandleTranslationUnit(ASTContext &Context) override {
Matcher.matchAST(Context);
}
private:
ExpressionHandler HandlerForIntegerExpressions;
ExpressionHandler HandlerForBooleanExpressions;
StatementHandler HandlerForStatements;
SemfixExpressionHandler SemfixHandlerForIntegerExpressions;
SemfixExpressionHandler SemfixHandlerForBooleanExpressions;
MatchFinder Matcher;
};
class InstrumentSuspiciousAction : public ASTFrontendAction {
public:
InstrumentSuspiciousAction() {}
void EndSourceFileAction() override {
FileID ID = TheRewriter.getSourceMgr().getMainFileID();
if (INPLACE_MODIFICATION) {
TheRewriter.overwriteChangedFiles();
} else {
TheRewriter.getEditBuffer(ID).write(llvm::outs());
}
}
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) override {
TheRewriter.setSourceMgr(CI.getSourceManager(), CI.getLangOpts());
return llvm::make_unique<MyASTConsumer>(TheRewriter);
}
private:
Rewriter TheRewriter;
};
// Apply a custom category to all command-line options so that they are the only ones displayed.
static llvm::cl::OptionCategory MyToolCategory("angelix options");
int main(int argc, const char **argv) {
// CommonOptionsParser constructor will parse arguments and create a
// CompilationDatabase. In case of error it will terminate the program.
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
// We hand the CompilationDatabase we created and the sources to run over into the tool constructor.
ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
return Tool.run(newFrontendActionFactory<InstrumentSuspiciousAction>().get());
}
<commit_msg>improved variable selection<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <fstream>
#include "../AngelixCommon.h"
#include "SMTLIB2.h"
std::unordered_set<VarDecl*> collectVarsFromScope(const ast_type_traits::DynTypedNode node, ASTContext* context, unsigned line) {
const FunctionDecl* fd;
if ((fd = node.get<FunctionDecl>()) != NULL) {
std::unordered_set<VarDecl*> set;
for (auto it = fd->param_begin(); it != fd->param_end(); ++it) {
auto vd = cast<VarDecl>(*it);
set.insert(vd);
}
if (fd->hasBody()) {
Stmt* body = fd->getBody();
CompoundStmt* cstmt;
if ((cstmt = cast<CompoundStmt>(body)) != NULL) {
for (auto it = cstmt->body_begin(); it != cstmt->body_end(); ++it) {
if (isa<BinaryOperator>(*it)) {
BinaryOperator* op = cast<BinaryOperator>(*it);
SourceRange expandedLoc = getExpandedLoc(op, context->getSourceManager());
unsigned beginLine = context->getSourceManager().getSpellingLineNumber(expandedLoc.getBegin());
if (line > beginLine &&
BinaryOperator::getOpcodeStr(op->getOpcode()).lower() == "=" &&
isa<DeclRefExpr>(op->getLHS())) {
DeclRefExpr* dref = cast<DeclRefExpr>(op->getLHS());
VarDecl* vd;
if ((vd = cast<VarDecl>(dref->getDecl())) != NULL) {
set.insert(vd);
}
}
}
}
}
}
return set;
} else {
ArrayRef<ast_type_traits::DynTypedNode> parents = context->getParents(node);
if (parents.size() > 0) {
const ast_type_traits::DynTypedNode parent = *(parents.begin()); // TODO: for now only first
return collectVarsFromScope(parent, context, line);
} else {
std::unordered_set<VarDecl*> set;
return set;
}
}
}
class CollectVariables : public StmtVisitor<CollectVariables> {
std::unordered_set<VarDecl*> *VSet;
std::unordered_set<MemberExpr*> *MSet;
public:
CollectVariables(std::unordered_set<VarDecl*> *vset, std::unordered_set<MemberExpr*> *mset): VSet(vset), MSet(mset) {}
void Collect(Expr *E) {
if (E)
Visit(E);
}
void Visit(Stmt* S) {
StmtVisitor<CollectVariables>::Visit(S);
}
void VisitBinaryOperator(BinaryOperator *Node) {
Collect(Node->getLHS());
Collect(Node->getRHS());
}
void VisitUnaryOperator(UnaryOperator *Node) {
Collect(Node->getSubExpr());
}
void VisitImplicitCastExpr(ImplicitCastExpr *Node) {
Collect(Node->getSubExpr());
}
void VisitIntegerLiteral(IntegerLiteral *Node) {
}
void VisitCharacterLiteral(CharacterLiteral *Node) {
}
void VisitMemberExpr(MemberExpr *Node) {
if (MSet) {
MSet->insert(Node);
}
}
void VisitDeclRefExpr(DeclRefExpr *Node) {
if (VSet) {
VarDecl* vd;
if ((vd = cast<VarDecl>(Node->getDecl())) != NULL) { // TODO: other kinds of declarations?
VSet->insert(vd);
}
}
}
};
std::unordered_set<VarDecl*> collectVarsFromExpr(const Stmt* stmt) {
std::unordered_set<VarDecl*> set;
CollectVariables T(&set, NULL);
T.Visit(const_cast<Stmt*>(stmt));
return set;
}
std::unordered_set<MemberExpr*> collectMemberExprFromExpr(const Stmt* stmt) {
std::unordered_set<MemberExpr*> set;
CollectVariables T(NULL, &set);
T.Visit(const_cast<Stmt*>(stmt));
return set;
}
bool isSuspicious(int beginLine, int beginColumn, int endLine, int endColumn) {
std::string line;
std::string suspiciousFile(getenv("ANGELIX_SUSPICIOUS"));
std::ifstream infile(suspiciousFile);
int curBeginLine, curBeginColumn, curEndLine, curEndColumn;
while (std::getline(infile, line)) {
std::istringstream iss(line);
iss >> curBeginLine >> curBeginColumn >> curEndLine >> curEndColumn;
if (curBeginLine == beginLine &&
curBeginColumn == beginColumn &&
curEndLine == endLine &&
curEndColumn == endColumn) {
return true;
}
}
return false;
}
class ExpressionHandler : public MatchFinder::MatchCallback {
public:
ExpressionHandler(Rewriter &Rewrite, std::string t) : Rewrite(Rewrite), type(t) {}
virtual void run(const MatchFinder::MatchResult &Result) {
if (const Expr *expr = Result.Nodes.getNodeAs<clang::Expr>("repairable")) {
SourceManager &srcMgr = Rewrite.getSourceMgr();
SourceRange expandedLoc = getExpandedLoc(expr, srcMgr);
unsigned beginLine = srcMgr.getSpellingLineNumber(expandedLoc.getBegin());
unsigned beginColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getBegin());
unsigned endLine = srcMgr.getSpellingLineNumber(expandedLoc.getEnd());
unsigned endColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getEnd());
if (! isSuspicious(beginLine, beginColumn, endLine, endColumn)) {
return;
}
std::cout << beginLine << " " << beginColumn << " " << endLine << " " << endColumn << "\n"
<< toString(expr) << "\n";
std::ostringstream exprId;
exprId << beginLine << "-" << beginColumn << "-" << endLine << "-" << endColumn;
std::string extractedDir(getenv("ANGELIX_EXTRACTED"));
std::ofstream fs(extractedDir + "/" + exprId.str() + ".smt2");
fs << "(assert " << toSMTLIB2(expr) << ")\n";
const ast_type_traits::DynTypedNode node = ast_type_traits::DynTypedNode::create(*expr);
std::unordered_set<VarDecl*> varsFromScope = collectVarsFromScope(node, Result.Context, beginLine);
std::unordered_set<VarDecl*> varsFromExpr = collectVarsFromExpr(expr);
std::unordered_set<MemberExpr*> memberFromExpr = collectMemberExprFromExpr(expr);
std::unordered_set<VarDecl*> vars;
vars.insert(varsFromScope.begin(), varsFromScope.end());
vars.insert(varsFromExpr.begin(), varsFromExpr.end());
std::ostringstream exprStream;
std::ostringstream nameStream;
bool first = true;
for (auto it = vars.begin(); it != vars.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
VarDecl* var = *it;
exprStream << var->getName().str();
nameStream << "\"" << var->getName().str() << "\"";
}
for (auto it = memberFromExpr.begin(); it != memberFromExpr.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
MemberExpr* me = *it;
exprStream << toString(me);
nameStream << "\"" << toString(me) << "\"";
}
int size = vars.size() + memberFromExpr.size();
std::ostringstream stringStream;
stringStream << "ANGELIX_CHOOSE("
<< type << ", "
<< toString(expr) << ", "
<< beginLine << ", "
<< beginColumn << ", "
<< endLine << ", "
<< endColumn << ", "
<< "((char*[]){" << nameStream.str() << "}), "
<< "((int[]){" << exprStream.str() << "}), "
<< size
<< ")";
std::string replacement = stringStream.str();
Rewrite.ReplaceText(expandedLoc, replacement);
}
}
private:
Rewriter &Rewrite;
std::string type;
};
class SemfixExpressionHandler : public MatchFinder::MatchCallback {
public:
SemfixExpressionHandler(Rewriter &Rewrite, std::string t) : Rewrite(Rewrite), type(t) {}
virtual void run(const MatchFinder::MatchResult &Result) {
if (const Expr *expr = Result.Nodes.getNodeAs<clang::Expr>("repairable")) {
SourceManager &srcMgr = Rewrite.getSourceMgr();
SourceRange expandedLoc = getExpandedLoc(expr, srcMgr);
unsigned beginLine = srcMgr.getSpellingLineNumber(expandedLoc.getBegin());
unsigned beginColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getBegin());
unsigned endLine = srcMgr.getSpellingLineNumber(expandedLoc.getEnd());
unsigned endColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getEnd());
if (! isSuspicious(beginLine, beginColumn, endLine, endColumn)) {
return;
}
std::cout << beginLine << " " << beginColumn << " " << endLine << " " << endColumn << "\n"
<< toString(expr) << "\n";
std::ostringstream exprId;
exprId << beginLine << "-" << beginColumn << "-" << endLine << "-" << endColumn;
std::string extractedDir(getenv("ANGELIX_EXTRACTED"));
std::ofstream fs(extractedDir + "/" + exprId.str() + ".smt2");
fs << "(assert true)\n"; // this is a hack, but not dangerous
const ast_type_traits::DynTypedNode node = ast_type_traits::DynTypedNode::create(*expr);
std::unordered_set<VarDecl*> varsFromScope = collectVarsFromScope(node, Result.Context, beginLine);
std::unordered_set<VarDecl*> vars;
vars.insert(varsFromScope.begin(), varsFromScope.end());
std::ostringstream exprStream;
std::ostringstream nameStream;
bool first = true;
for (auto it = vars.begin(); it != vars.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
VarDecl* var = *it;
exprStream << var->getName().str();
nameStream << "\"" << var->getName().str() << "\"";
}
int size = vars.size();
std::ostringstream stringStream;
stringStream << "ANGELIX_CHOOSE("
<< type << ", "
<< "1" << ", " // don't execute expression, because it can have side effects
<< beginLine << ", "
<< beginColumn << ", "
<< endLine << ", "
<< endColumn << ", "
<< "((char*[]){" << nameStream.str() << "}), "
<< "((int[]){" << exprStream.str() << "}), "
<< size
<< ")";
std::string replacement = stringStream.str();
Rewrite.ReplaceText(expandedLoc, replacement);
}
}
private:
Rewriter &Rewrite;
std::string type;
};
class StatementHandler : public MatchFinder::MatchCallback {
public:
StatementHandler(Rewriter &Rewrite) : Rewrite(Rewrite) {}
virtual void run(const MatchFinder::MatchResult &Result) {
if (const Stmt *stmt = Result.Nodes.getNodeAs<clang::Stmt>("repairable")) {
SourceManager &srcMgr = Rewrite.getSourceMgr();
SourceRange expandedLoc = getExpandedLoc(stmt, srcMgr);
unsigned beginLine = srcMgr.getSpellingLineNumber(expandedLoc.getBegin());
unsigned beginColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getBegin());
unsigned endLine = srcMgr.getSpellingLineNumber(expandedLoc.getEnd());
unsigned endColumn = srcMgr.getSpellingColumnNumber(expandedLoc.getEnd());
if (! isSuspicious(beginLine, beginColumn, endLine, endColumn)) {
return;
}
std::cout << beginLine << " " << beginColumn << " " << endLine << " " << endColumn << "\n"
<< toString(stmt) << "\n";
std::ostringstream stmtId;
stmtId << beginLine << "-" << beginColumn << "-" << endLine << "-" << endColumn;
std::string extractedDir(getenv("ANGELIX_EXTRACTED"));
std::ofstream fs(extractedDir + "/" + stmtId.str() + ".smt2");
fs << "(assert true)\n";
const ast_type_traits::DynTypedNode node = ast_type_traits::DynTypedNode::create(*stmt);
std::unordered_set<VarDecl*> varsFromScope = collectVarsFromScope(node, Result.Context, beginLine);
std::unordered_set<VarDecl*> vars;
vars.insert(varsFromScope.begin(), varsFromScope.end());
std::ostringstream exprStream;
std::ostringstream nameStream;
bool first = true;
for (auto it = vars.begin(); it != vars.end(); ++it) {
if (first) {
first = false;
} else {
exprStream << ", ";
nameStream << ", ";
}
VarDecl* var = *it;
exprStream << var->getName().str();
nameStream << "\"" << var->getName().str() << "\"";
}
int size = vars.size();
std::ostringstream stringStream;
stringStream << "if ("
<< "ANGELIX_CHOOSE("
<< "bool" << ", "
<< 1 << ", "
<< beginLine << ", "
<< beginColumn << ", "
<< endLine << ", "
<< endColumn << ", "
<< "((char*[]){" << nameStream.str() << "}), "
<< "((int[]){" << exprStream.str() << "}), "
<< size
<< ")"
<< ") "
<< toString(stmt);
std::string replacement = stringStream.str();
Rewrite.ReplaceText(expandedLoc, replacement);
}
}
private:
Rewriter &Rewrite;
};
class MyASTConsumer : public ASTConsumer {
public:
MyASTConsumer(Rewriter &R) : HandlerForIntegerExpressions(R, "int"),
HandlerForBooleanExpressions(R, "bool"),
HandlerForStatements(R),
SemfixHandlerForIntegerExpressions(R, "int"),
SemfixHandlerForBooleanExpressions(R, "bool") {
if (getenv("ANGELIX_SEMFIX_MODE")) {
Matcher.addMatcher(InterestingCondition, &SemfixHandlerForBooleanExpressions);
Matcher.addMatcher(InterestingIntegerAssignment, &SemfixHandlerForIntegerExpressions);
} else {
Matcher.addMatcher(RepairableAssignment, &HandlerForIntegerExpressions);
Matcher.addMatcher(InterestingRepairableCondition, &HandlerForBooleanExpressions);
Matcher.addMatcher(InterestingStatement, &HandlerForStatements);
}
}
void HandleTranslationUnit(ASTContext &Context) override {
Matcher.matchAST(Context);
}
private:
ExpressionHandler HandlerForIntegerExpressions;
ExpressionHandler HandlerForBooleanExpressions;
StatementHandler HandlerForStatements;
SemfixExpressionHandler SemfixHandlerForIntegerExpressions;
SemfixExpressionHandler SemfixHandlerForBooleanExpressions;
MatchFinder Matcher;
};
class InstrumentSuspiciousAction : public ASTFrontendAction {
public:
InstrumentSuspiciousAction() {}
void EndSourceFileAction() override {
FileID ID = TheRewriter.getSourceMgr().getMainFileID();
if (INPLACE_MODIFICATION) {
TheRewriter.overwriteChangedFiles();
} else {
TheRewriter.getEditBuffer(ID).write(llvm::outs());
}
}
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef file) override {
TheRewriter.setSourceMgr(CI.getSourceManager(), CI.getLangOpts());
return llvm::make_unique<MyASTConsumer>(TheRewriter);
}
private:
Rewriter TheRewriter;
};
// Apply a custom category to all command-line options so that they are the only ones displayed.
static llvm::cl::OptionCategory MyToolCategory("angelix options");
int main(int argc, const char **argv) {
// CommonOptionsParser constructor will parse arguments and create a
// CompilationDatabase. In case of error it will terminate the program.
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
// We hand the CompilationDatabase we created and the sources to run over into the tool constructor.
ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
return Tool.run(newFrontendActionFactory<InstrumentSuspiciousAction>().get());
}
<|endoftext|> |
<commit_before>#include "binlog.h"
#include <assert.h>
#include "common/asm_atomic.h"
#include "common/logging.h"
#include "leveldb/write_batch.h"
#include "utils.h"
namespace galaxy {
namespace ins {
const std::string log_dbname = "#binlog";
const std::string length_tag = "#BINLOG_LEN#";
int32_t LogEntry::Dump(std::string* buf) const {
assert(buf);
int32_t total_len = sizeof(uint8_t) + sizeof(int32_t) + user.size() +
sizeof(int32_t) + key.size() + sizeof(int32_t) +
value.size() + sizeof(int64_t);
buf->resize(total_len);
int32_t user_size = user.size();
int32_t key_size = key.size();
int32_t value_size = value.size();
char* p = reinterpret_cast<char*>(&((*buf)[0]));
p[0] = static_cast<uint8_t>(op);
p += sizeof(uint8_t);
memcpy(p, static_cast<const void*>(&user_size), sizeof(int32_t));
p += sizeof(int32_t);
memcpy(p, static_cast<const void*>(user.data()), user.size());
p += user.size();
memcpy(p, static_cast<const void*>(&key_size), sizeof(int32_t));
p += sizeof(int32_t);
memcpy(p, static_cast<const void*>(key.data()), key.size());
p += key.size();
memcpy(p, static_cast<const void*>(&value_size), sizeof(int32_t));
p += sizeof(int32_t);
memcpy(p, static_cast<const void*>(value.data()), value.size());
p += value.size();
memcpy(p, static_cast<const void*>(&term), sizeof(int64_t));
return total_len;
}
void LogEntry::Load(const std::string& buf) {
const char* p = buf.data();
int32_t user_size = 0;
int32_t key_size = 0;
int32_t value_size = 0;
uint8_t opcode = 0;
memcpy(static_cast<void*>(&opcode), p, sizeof(uint8_t));
op = static_cast<LogOperation>(opcode);
p += sizeof(uint8_t);
memcpy(static_cast<void*>(&user_size), p, sizeof(int32_t));
user.resize(user_size);
p += sizeof(int32_t);
memcpy(static_cast<void*>(&user[0]), p, user_size);
p += user_size;
memcpy(static_cast<void*>(&key_size), p, sizeof(int32_t));
key.resize(key_size);
p += sizeof(int32_t);
memcpy(static_cast<void*>(&key[0]), p, key_size);
p += key_size;
memcpy(static_cast<void*>(&value_size), p, sizeof(int32_t));
value.resize(value_size);
p += sizeof(int32_t);
memcpy(static_cast<void*>(&value[0]), p, value_size);
p += value_size;
memcpy(static_cast<void*>(&term), p, sizeof(int64_t));
}
BinLogger::BinLogger(const std::string& data_dir, bool compress,
int32_t block_size, int32_t write_buffer_size)
: db_(NULL), length_(0), last_log_term_(-1) {
bool ok = ins_common::Mkdirs(data_dir.c_str());
if (!ok) {
LOG(FATAL, "failed to create dir :%s", data_dir.c_str());
abort();
}
std::string full_name = data_dir + "/" + log_dbname;
leveldb::Options options;
options.create_if_missing = true;
if (compress) {
options.compression = leveldb::kSnappyCompression;
LOG(INFO, "enable snappy compress for binlog for %s", full_name.c_str());
}
options.write_buffer_size = write_buffer_size;
options.block_size = block_size;
LOG(INFO, "[binlog]: %s, block_size: %d, writer_buffer_size: %d",
full_name.c_str(), options.block_size, options.write_buffer_size);
leveldb::Status status = leveldb::DB::Open(options, full_name, &db_);
if (!status.ok()) {
LOG(FATAL, "failed to open db %s err %s", full_name.c_str(),
status.ToString().c_str());
assert(status.ok());
}
LOG(INFO, "try to init length & last log term from db");
std::string value;
status = db_->Get(leveldb::ReadOptions(), length_tag, &value);
if (status.ok() && !value.empty()) {
length_ = StringToInt(value);
if (length_ > 0) {
LogEntry log_entry;
bool slot_ok = ReadSlot(length_ - 1, &log_entry);
assert(slot_ok);
last_log_term_ = log_entry.term;
LOG(INFO, "get length: %ld, last log term: %ld", length_, last_log_term_);
}
}
}
BinLogger::~BinLogger() { delete db_; }
int64_t BinLogger::GetLength() {
MutexLock lock(&mu_);
return length_;
}
void BinLogger::GetLastLogIndexAndTerm(int64_t* last_log_index,
int64_t* last_log_term) {
MutexLock lock(&mu_);
*last_log_index = length_ - 1;
*last_log_term = last_log_term_;
}
std::string BinLogger::IntToString(int64_t num) {
std::string key;
key.resize(sizeof(int64_t));
memcpy(&key[0], &num, sizeof(int64_t));
return key;
}
int64_t BinLogger::StringToInt(const std::string& s) {
assert(s.size() == sizeof(int64_t));
int64_t num = 0;
memcpy(&num, &s[0], sizeof(int64_t));
return num;
}
bool BinLogger::RemoveSlot(int64_t slot_index) {
std::string value;
std::string key = IntToString(slot_index);
leveldb::Status status = db_->Get(leveldb::ReadOptions(), key, &value);
if (!status.ok()) {
return false;
}
status = db_->Delete(leveldb::WriteOptions(), key);
if (status.ok()) {
return true;
} else {
return false;
}
}
bool BinLogger::RemoveSlotBefore(int64_t slot_gc_index) {
db_->SetNexusGCKey(slot_gc_index);
return true;
}
bool BinLogger::ReadSlot(int64_t slot_index, LogEntry* log_entry) {
std::string value;
std::string key = IntToString(slot_index);
leveldb::Status status = db_->Get(leveldb::ReadOptions(), key, &value);
if (status.ok()) {
log_entry->Load(value);
return true;
} else if (status.IsNotFound()) {
return false;
} else {
LOG(FATAL, "Read slot fail, %s", status.ToString().c_str());
abort();
}
}
void BinLogger::AppendEntryList(const ::google::protobuf::RepeatedPtrField<
::galaxy::ins::Entry>& entries) {
leveldb::WriteBatch batch;
{
MutexLock lock(&mu_);
int64_t cur_index = length_;
std::string next_index = IntToString(length_ + entries.size());
for (int i = 0; i < entries.size(); i++) {
LogEntry log_entry;
std::string buf;
log_entry.op = entries.Get(i).op();
log_entry.user = entries.Get(i).user();
log_entry.key = entries.Get(i).key();
log_entry.value = entries.Get(i).value();
log_entry.term = entries.Get(i).term();
log_entry.Dump(&buf);
last_log_term_ = log_entry.term;
batch.Put(IntToString(cur_index + i), buf);
}
batch.Put(length_tag, next_index);
leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch);
assert(status.ok());
length_ += entries.size();
}
}
void BinLogger::AppendEntry(const LogEntry& log_entry) {
std::string buf;
log_entry.Dump(&buf);
std::string cur_index;
std::string next_index;
{
MutexLock lock(&mu_);
cur_index = IntToString(length_);
next_index = IntToString(length_ + 1);
leveldb::WriteBatch batch;
batch.Put(cur_index, buf);
batch.Put(length_tag, next_index);
leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch);
assert(status.ok());
length_++;
last_log_term_ = log_entry.term;
}
}
void BinLogger::Truncate(int64_t trunk_slot_index) {
if (trunk_slot_index < -1) {
trunk_slot_index = -1;
}
{
MutexLock lock(&mu_);
length_ = trunk_slot_index + 1;
leveldb::Status status =
db_->Put(leveldb::WriteOptions(), length_tag, IntToString(length_));
assert(status.ok());
if (length_ > 0) {
LogEntry log_entry;
bool slot_ok = ReadSlot(length_ - 1, &log_entry);
assert(slot_ok);
last_log_term_ = log_entry.term;
}
}
}
} // namespace ins
} // namespace galaxy
<commit_msg>局部重构LogEntry代码<commit_after>#include "binlog.h"
#include <assert.h>
#include "common/asm_atomic.h"
#include "common/logging.h"
#include "leveldb/write_batch.h"
#include "utils.h"
namespace galaxy {
namespace ins {
const std::string log_dbname = "#binlog";
const std::string length_tag = "#BINLOG_LEN#";
int32_t LogEntry::Dump(std::string* buf) const {
assert(buf);
int32_t total_len = sizeof(uint8_t) + sizeof(int32_t) + user.size() +
sizeof(int32_t) + key.size() + sizeof(int32_t) +
value.size() + sizeof(int64_t);
buf->resize(total_len);
const int32_t user_size = user.size();
const int32_t key_size = key.size();
const int32_t value_size = value.size();
char *p = const_cast<char *>(buf->data());
// op
p[0] = static_cast<uint8_t>(op);
p += sizeof(uint8_t);
// user length & data
memcpy(p, static_cast<const void*>(&user_size), sizeof(int32_t));
p += sizeof(int32_t);
memcpy(p, static_cast<const void*>(user.data()), user.size());
p += user.size();
// key length & data
memcpy(p, static_cast<const void*>(&key_size), sizeof(int32_t));
p += sizeof(int32_t);
memcpy(p, static_cast<const void*>(key.data()), key.size());
p += key.size();
/// value length & data
memcpy(p, static_cast<const void*>(&value_size), sizeof(int32_t));
p += sizeof(int32_t);
memcpy(p, static_cast<const void*>(value.data()), value.size());
p += value.size();
// term
memcpy(p, static_cast<const void*>(&term), sizeof(int64_t));
return total_len;
}
void LogEntry::Load(const std::string& buf) {
const char* p = buf.data();
int32_t user_size = 0;
int32_t key_size = 0;
int32_t value_size = 0;
// op
uint8_t opcode = 0;
memcpy(static_cast<void*>(&opcode), p, sizeof(uint8_t));
p += sizeof(uint8_t);
op = static_cast<LogOperation>(opcode);
// user
memcpy(static_cast<void*>(&user_size), p, sizeof(int32_t));
user.resize(user_size);
p += sizeof(int32_t);
memcpy(static_cast<void*>(&user[0]), p, user_size);
p += user_size;
// key
memcpy(static_cast<void*>(&key_size), p, sizeof(int32_t));
key.resize(key_size);
p += sizeof(int32_t);
memcpy(static_cast<void*>(&key[0]), p, key_size);
p += key_size;
// value
memcpy(static_cast<void*>(&value_size), p, sizeof(int32_t));
value.resize(value_size);
p += sizeof(int32_t);
memcpy(static_cast<void*>(&value[0]), p, value_size);
p += value_size;
// term
memcpy(static_cast<void*>(&term), p, sizeof(int64_t));
}
BinLogger::BinLogger(const std::string& data_dir, bool compress,
int32_t block_size, int32_t write_buffer_size)
: db_(NULL), length_(0), last_log_term_(-1) {
bool ok = ins_common::Mkdirs(data_dir.c_str());
if (!ok) {
LOG(FATAL, "failed to create dir :%s", data_dir.c_str());
abort();
}
std::string full_name = data_dir + "/" + log_dbname;
leveldb::Options options;
options.create_if_missing = true;
if (compress) {
options.compression = leveldb::kSnappyCompression;
LOG(INFO, "enable snappy compress for binlog for %s", full_name.c_str());
}
options.write_buffer_size = write_buffer_size;
options.block_size = block_size;
LOG(INFO, "[binlog]: %s, block_size: %d, writer_buffer_size: %d",
full_name.c_str(), options.block_size, options.write_buffer_size);
leveldb::Status status = leveldb::DB::Open(options, full_name, &db_);
if (!status.ok()) {
LOG(FATAL, "failed to open db %s err %s", full_name.c_str(),
status.ToString().c_str());
assert(status.ok());
}
LOG(INFO, "try to init length & last log term from db");
std::string value;
status = db_->Get(leveldb::ReadOptions(), length_tag, &value);
if (status.ok() && !value.empty()) {
length_ = StringToInt(value);
if (length_ > 0) {
LogEntry log_entry;
bool slot_ok = ReadSlot(length_ - 1, &log_entry);
assert(slot_ok);
last_log_term_ = log_entry.term;
LOG(INFO, "get length: %ld, last log term: %ld", length_, last_log_term_);
}
}
}
BinLogger::~BinLogger() { delete db_; }
int64_t BinLogger::GetLength() {
MutexLock lock(&mu_);
return length_;
}
void BinLogger::GetLastLogIndexAndTerm(int64_t* last_log_index,
int64_t* last_log_term) {
MutexLock lock(&mu_);
// index从0开始计算
*last_log_index = length_ - 1;
*last_log_term = last_log_term_;
}
std::string BinLogger::IntToString(int64_t num) {
std::string key;
key.resize(sizeof(int64_t));
memcpy(&key[0], &num, sizeof(int64_t));
return key;
}
int64_t BinLogger::StringToInt(const std::string& s) {
assert(s.size() == sizeof(int64_t));
int64_t num = 0;
memcpy(&num, &s[0], sizeof(int64_t));
return num;
}
bool BinLogger::RemoveSlot(int64_t slot_index) {
std::string value;
std::string key = IntToString(slot_index);
leveldb::Status status = db_->Get(leveldb::ReadOptions(), key, &value);
if (!status.ok()) {
return false;
}
status = db_->Delete(leveldb::WriteOptions(), key);
if (status.ok()) {
return true;
} else {
return false;
}
}
bool BinLogger::RemoveSlotBefore(int64_t slot_gc_index) {
db_->SetNexusGCKey(slot_gc_index);
return true;
}
bool BinLogger::ReadSlot(int64_t slot_index, LogEntry* log_entry) {
std::string value;
std::string key = IntToString(slot_index);
leveldb::Status status = db_->Get(leveldb::ReadOptions(), key, &value);
if (status.ok()) {
log_entry->Load(value);
return true;
} else if (status.IsNotFound()) {
return false;
} else {
LOG(FATAL, "Read slot fail, %s", status.ToString().c_str());
abort();
}
}
void BinLogger::AppendEntryList(const ::google::protobuf::RepeatedPtrField<
::galaxy::ins::Entry>& entries) {
leveldb::WriteBatch batch;
{
MutexLock lock(&mu_);
int64_t cur_index = length_;
std::string next_index = IntToString(length_ + entries.size());
for (int i = 0; i < entries.size(); i++) {
LogEntry log_entry;
std::string buf;
log_entry.op = entries.Get(i).op();
log_entry.user = entries.Get(i).user();
log_entry.key = entries.Get(i).key();
log_entry.value = entries.Get(i).value();
log_entry.term = entries.Get(i).term();
log_entry.Dump(&buf);
last_log_term_ = log_entry.term;
batch.Put(IntToString(cur_index + i), buf);
}
batch.Put(length_tag, next_index);
leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch);
assert(status.ok());
length_ += entries.size();
}
}
void BinLogger::AppendEntry(const LogEntry& log_entry) {
std::string buf;
log_entry.Dump(&buf);
std::string cur_index;
std::string next_index;
{
MutexLock lock(&mu_);
cur_index = IntToString(length_);
next_index = IntToString(length_ + 1);
leveldb::WriteBatch batch;
batch.Put(cur_index, buf);
batch.Put(length_tag, next_index);
leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch);
assert(status.ok());
length_++;
last_log_term_ = log_entry.term;
}
}
void BinLogger::Truncate(int64_t trunk_slot_index) {
if (trunk_slot_index < -1) {
trunk_slot_index = -1;
}
{
MutexLock lock(&mu_);
length_ = trunk_slot_index + 1;
leveldb::Status status =
db_->Put(leveldb::WriteOptions(), length_tag, IntToString(length_));
assert(status.ok());
if (length_ > 0) {
LogEntry log_entry;
bool slot_ok = ReadSlot(length_ - 1, &log_entry);
assert(slot_ok);
last_log_term_ = log_entry.term;
}
}
}
} // namespace ins
} // namespace galaxy
<|endoftext|> |
<commit_before>#include <node.h>
#include <v8.h>
#include <git2.h>
#include <map>
#include <algorithm>
#include <set>
#include <openssl/crypto.h>
#include <mutex>
#include "../include/init_ssh2.h"
#include "../include/lock_master.h"
#include "../include/nodegit.h"
#include "../include/context.h"
#include "../include/wrapper.h"
#include "../include/promise_completion.h"
#include "../include/functions/copy.h"
{% each %}
{% if type != "enum" %}
#include "../include/{{ filename }}.h"
{% endif %}
{% endeach %}
#include "../include/convenient_patch.h"
#include "../include/convenient_hunk.h"
#include "../include/filter_registry.h"
using namespace v8;
Local<Value> GetPrivate(Local<Object> object, Local<String> key) {
Local<Value> value;
Nan::Maybe<bool> result = Nan::HasPrivate(object, key);
if (!(result.IsJust() && result.FromJust()))
return Local<Value>();
if (Nan::GetPrivate(object, key).ToLocal(&value))
return value;
return Local<Value>();
}
void SetPrivate(Local<Object> object, Local<String> key, Local<Value> value) {
if (value.IsEmpty())
return;
Nan::SetPrivate(object, key, value);
}
static uv_mutex_t *opensslMutexes;
void OpenSSL_LockingCallback(int mode, int type, const char *, int) {
if (mode & CRYPTO_LOCK) {
uv_mutex_lock(&opensslMutexes[type]);
} else {
uv_mutex_unlock(&opensslMutexes[type]);
}
}
void OpenSSL_IDCallback(CRYPTO_THREADID *id) {
CRYPTO_THREADID_set_numeric(id, (unsigned long)uv_thread_self());
}
void OpenSSL_ThreadSetup() {
opensslMutexes=(uv_mutex_t *)malloc(CRYPTO_num_locks() * sizeof(uv_mutex_t));
for (int i=0; i<CRYPTO_num_locks(); i++) {
uv_mutex_init(&opensslMutexes[i]);
}
CRYPTO_set_locking_callback(OpenSSL_LockingCallback);
CRYPTO_THREADID_set_callback(OpenSSL_IDCallback);
}
static std::once_flag libraryInitializedFlag;
static std::mutex libraryInitializationMutex;
NAN_MODULE_INIT(init) {
{
// We only want to do initialization logic once, and we also want to prevent any thread from completely loading
// the module until initialization has occurred.
// All of this initialization logic ends up being shared.
const std::lock_guard<std::mutex> lock(libraryInitializationMutex);
std::call_once(libraryInitializedFlag, []() {
// Initialize thread safety in openssl and libssh2
OpenSSL_ThreadSetup();
init_ssh2();
// Initialize libgit2.
git_libgit2_init();
// Register thread pool with libgit2
nodegit::ThreadPool::InitializeGlobal();
});
}
Nan::HandleScope scope;
Local<Context> context = Nan::GetCurrentContext();
Isolate *isolate = context->GetIsolate();
nodegit::Context *nodegitContext = new nodegit::Context(isolate);
Wrapper::InitializeComponent(target, nodegitContext);
PromiseCompletion::InitializeComponent(nodegitContext);
{% each %}
{% if type != "enum" %}
{{ cppClassName }}::InitializeComponent(target, nodegitContext);
{% endif %}
{% endeach %}
ConvenientHunk::InitializeComponent(target, nodegitContext);
ConvenientPatch::InitializeComponent(target, nodegitContext);
GitFilterRegistry::InitializeComponent(target, nodegitContext);
nodegit::LockMaster::InitializeContext();
}
NODE_MODULE(nodegit, init)
<commit_msg>Enable module from workers<commit_after>#include <node.h>
#include <v8.h>
#include <git2.h>
#include <map>
#include <algorithm>
#include <set>
#include <openssl/crypto.h>
#include <mutex>
#include "../include/init_ssh2.h"
#include "../include/lock_master.h"
#include "../include/nodegit.h"
#include "../include/context.h"
#include "../include/wrapper.h"
#include "../include/promise_completion.h"
#include "../include/functions/copy.h"
{% each %}
{% if type != "enum" %}
#include "../include/{{ filename }}.h"
{% endif %}
{% endeach %}
#include "../include/convenient_patch.h"
#include "../include/convenient_hunk.h"
#include "../include/filter_registry.h"
using namespace v8;
Local<Value> GetPrivate(Local<Object> object, Local<String> key) {
Local<Value> value;
Nan::Maybe<bool> result = Nan::HasPrivate(object, key);
if (!(result.IsJust() && result.FromJust()))
return Local<Value>();
if (Nan::GetPrivate(object, key).ToLocal(&value))
return value;
return Local<Value>();
}
void SetPrivate(Local<Object> object, Local<String> key, Local<Value> value) {
if (value.IsEmpty())
return;
Nan::SetPrivate(object, key, value);
}
static uv_mutex_t *opensslMutexes;
void OpenSSL_LockingCallback(int mode, int type, const char *, int) {
if (mode & CRYPTO_LOCK) {
uv_mutex_lock(&opensslMutexes[type]);
} else {
uv_mutex_unlock(&opensslMutexes[type]);
}
}
void OpenSSL_IDCallback(CRYPTO_THREADID *id) {
CRYPTO_THREADID_set_numeric(id, (unsigned long)uv_thread_self());
}
void OpenSSL_ThreadSetup() {
opensslMutexes=(uv_mutex_t *)malloc(CRYPTO_num_locks() * sizeof(uv_mutex_t));
for (int i=0; i<CRYPTO_num_locks(); i++) {
uv_mutex_init(&opensslMutexes[i]);
}
CRYPTO_set_locking_callback(OpenSSL_LockingCallback);
CRYPTO_THREADID_set_callback(OpenSSL_IDCallback);
}
static std::once_flag libraryInitializedFlag;
static std::mutex libraryInitializationMutex;
NAN_MODULE_INIT(init) {
{
// We only want to do initialization logic once, and we also want to prevent any thread from completely loading
// the module until initialization has occurred.
// All of this initialization logic ends up being shared.
const std::lock_guard<std::mutex> lock(libraryInitializationMutex);
std::call_once(libraryInitializedFlag, []() {
// Initialize thread safety in openssl and libssh2
OpenSSL_ThreadSetup();
init_ssh2();
// Initialize libgit2.
git_libgit2_init();
// Register thread pool with libgit2
nodegit::ThreadPool::InitializeGlobal();
});
}
Nan::HandleScope scope;
Local<Context> context = Nan::GetCurrentContext();
Isolate *isolate = context->GetIsolate();
nodegit::Context *nodegitContext = new nodegit::Context(isolate);
Wrapper::InitializeComponent(target, nodegitContext);
PromiseCompletion::InitializeComponent(nodegitContext);
{% each %}
{% if type != "enum" %}
{{ cppClassName }}::InitializeComponent(target, nodegitContext);
{% endif %}
{% endeach %}
ConvenientHunk::InitializeComponent(target, nodegitContext);
ConvenientPatch::InitializeComponent(target, nodegitContext);
GitFilterRegistry::InitializeComponent(target, nodegitContext);
nodegit::LockMaster::InitializeContext();
}
NAN_MODULE_WORKER_ENABLED(nodegit, init)
<|endoftext|> |
<commit_before>/*
* Microscope.cpp
*
* Author: Nathan Clack <clackn@janelia.hhmi.org>
* Date: Apr 28, 2010
*/
/*
* Copyright 2010 Howard Hughes Medical Institute.
* All rights reserved.
* Use is subject to Janelia Farm Research Campus Software Copyright 1.1
* license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
#include "Microscope.h"
#include <time.h>
#include <iostream>
#include <fstream>
#include "stack.pb.h"
#include "microscope.pb.h"
#include "google\protobuf\text_format.h"
#define CHKJMP(expr,lbl) \
if(!(expr)) \
{ warning("[MICROSCOPE] %s(%d): "ENDL"\tExpression: %s"ENDL"\tevaluated false."ENDL,__FILE__,__LINE__,#expr); \
goto lbl; \
}
namespace fetch
{ namespace device {
Microscope::Microscope()
:IConfigurableDevice<Config>(&__self_agent)
,__self_agent("Microscope",NULL)
,__scan_agent("Scanner",&scanner)
,__io_agent("IO",&disk)
,__vibratome_agent("Vibratome",&vibratome_)
,scanner(&__scan_agent)
,stage_(&__self_agent)
,vibratome_(&__vibratome_agent)
,fov_(_config->fov())
,disk(&__io_agent)
,frame_averager("FrameAverager")
,pixel_averager("PixelAverager")
,cast_to_i16("i16Cast")
,inverter("inverter")
,wrap()
,frame_formatter("FrameFormatter")
,trash("Trash")
{
set_config(_config);
__common_setup();
}
/*
worker::FrameAverageAgent frame_averager;
worker::HorizontalDownsampleAgent pixel_averager;
worker::FrameCastAgent_i16 cast_to_i16;
worker::FrameInvertAgent inverter;
worker::ResonantWrapAgent wrap;
worker::TerminalAgent trash;
*/
Microscope::Microscope( const Config &cfg )
:IConfigurableDevice<Config>(&__self_agent)
,__self_agent("Microscope",NULL)
,__scan_agent("Scanner",&scanner)
,__io_agent("IO",&disk)
,__vibratome_agent("Vibratome",&vibratome_)
,scanner(&__scan_agent)
,stage_(&__self_agent)
,vibratome_(&__vibratome_agent)
,fov_(cfg.fov())
,disk(&__io_agent)
,frame_averager("FrameAverager")
,pixel_averager("PixelAverager")
,cast_to_i16("i16Cast")
,inverter("inverter")
,wrap()
,frame_formatter("FrameFormatter")
,trash("Trash")
,file_series()
{
set_config(cfg);
__common_setup();
}
Microscope::Microscope(Config *cfg )
:IConfigurableDevice<Config>(&__self_agent,cfg)
,__self_agent("Microscope",NULL)
,__scan_agent("Scanner",&scanner)
,__io_agent("IO",&disk)
,__vibratome_agent("Vibratome",&vibratome_)
,scanner(&__scan_agent,cfg->mutable_scanner3d())
,stage_(&__self_agent,cfg->mutable_stage())
,vibratome_(&__vibratome_agent,cfg->mutable_vibratome())
,fov_(cfg->fov())
,disk(&__io_agent)
,frame_averager(cfg->mutable_frame_average(),"FrameAverager")
,pixel_averager(cfg->mutable_horizontal_downsample(),"PixelAverager")
,cast_to_i16("i16Cast")
,inverter("Inverter")
,wrap(cfg->mutable_resonant_wrap())
,frame_formatter("FrameFormatter")
,trash("Trash")
,file_series(cfg->mutable_file_series())
{
__common_setup();
}
Microscope::~Microscope(void)
{
if(__scan_agent.detach()) warning("Microscope __scan_agent did not detach cleanly\r\n");
if(__self_agent.detach()) warning("Microscope __self_agent did not detach cleanly\r\n");
if( __io_agent.detach()) warning("Microscope __io_agent did not detach cleanly\r\n");
if( __vibratome_agent.detach()) warning("Microscope __vibratome_agent did not detach cleanly\r\n");
}
unsigned int
Microscope::on_attach(void)
{
// argh this is a confusing way to do things. which attach to call when.
//
// on_attach/on_detach only gets called for the owner, so attach/detach events have to be forwarded
// to devices that share the agent. This seems awkward :C
std::string stackname;
CHKJMP( __scan_agent.attach()==0,ESCAN);
CHKJMP( stage_.on_attach()==0,ESTAGE);
CHKJMP(__vibratome_agent.attach()==0,EVIBRATOME);
stackname = _config->file_prefix()+_config->stack_extension();
file_series.ensurePathExists();
return 0; // success
EVIBRATOME:
stage_.on_detach();
ESTAGE:
__scan_agent.detach();
ESCAN:
return 1;
}
unsigned int
Microscope::on_detach(void)
{
int eflag = 0; // 0 success, 1 failure
eflag |= scanner._agent->detach(); //scanner.detach();
eflag |= frame_averager._agent->detach();
eflag |= pixel_averager._agent->detach();
eflag |= inverter._agent->detach();
eflag |= cast_to_i16._agent->detach();
eflag |= wrap._agent->detach();
eflag |= frame_formatter._agent->detach();
eflag |= trash._agent->detach();
eflag |= disk._agent->detach();
eflag |= stage_.on_detach();
eflag |= vibratome_._agent->detach();
return eflag;
}
unsigned int Microscope::on_disarm()
{
unsigned int sts = 1; // success
sts &= scanner._agent->disarm();
sts &= frame_averager._agent->disarm();
sts &= pixel_averager._agent->disarm();
sts &= inverter._agent->disarm();
sts &= cast_to_i16._agent->disarm();
sts &= wrap._agent->disarm();
sts &= frame_formatter._agent->disarm();
sts &= trash._agent->disarm();
sts &= disk._agent->disarm();
sts &= vibratome_._agent->disarm();
return sts;
}
const std::string Microscope::stack_filename()
{
return file_series.getFullPath(_config->file_prefix(),_config->stack_extension());
}
const std::string Microscope::config_filename()
{
return file_series.getFullPath(_config->file_prefix(),_config->config_extension());
}
const std::string Microscope::metadata_filename()
{
return file_series.getFullPath(_config->file_prefix(),_config->metadata_extension());
}
void Microscope::write_stack_metadata()
{
//{ std::ofstream fout(config_filename(),std::ios::out|std::ios::trunc|std::ios::binary);
// get_config().SerializePartialToOstream(&fout);
//}
{ std::ofstream fout(config_filename().c_str(),std::ios::out|std::ios::trunc);
std::string s;
Config c = get_config();
google::protobuf::TextFormat::PrintToString(c,&s);
fout << s;
//get_config().SerializePartialToOstream(&fout);
}
{ float x,y,z;
std::ofstream fout(metadata_filename().c_str(),std::ios::out|std::ios::trunc);
fetch::cfg::data::Acquisition data;
stage_.getPos(&x,&y,&z);
data.set_x_mm(x);
data.set_y_mm(y);
data.set_z_mm(z);
std::string s;
google::protobuf::TextFormat::PrintToString(data,&s);
fout << s;
//get_config().SerializePartialToOstream(&fout);
}
}
void Microscope::_set_config( Config IN *cfg )
{
scanner._set_config(cfg->mutable_scanner3d());
pixel_averager._set_config(cfg->mutable_horizontal_downsample());
frame_averager._set_config(cfg->mutable_frame_average());
wrap._set_config(cfg->mutable_resonant_wrap());
file_series._desc = cfg->mutable_file_series();
}
void Microscope::_set_config( const Config& cfg )
{
*_config=cfg; // Copy
_set_config(_config); // Update
}
void Microscope::onUpdate()
{
scanner.onUpdate();
vibratome_.onUpdate();
fov_.update(_config->fov());
stage_.setFOV(&fov_);
// update microscope's run state based on sub-agents
// require scan agent and vibratome agent to be attached
if( __self_agent.is_attached() && !(__scan_agent.is_attached() && __vibratome_agent.is_attached()))
__self_agent.detach();
}
IDevice* Microscope::configPipeline()
{
//Assemble pipeline here
IDevice *cur;
cur = &scanner;
cur = pixel_averager.apply(cur);
cur = frame_averager.apply(cur);
cur = inverter.apply(cur);
cur = cast_to_i16.apply(cur);
cur = wrap.apply(cur);
cur = frame_formatter.apply(cur);
return cur;
}
void Microscope::__common_setup()
{
__self_agent._owner = this;
stage_.setFOV(&fov_);
//configPipeline();
CHKJMP(_agent->attach()==0,Error);
CHKJMP(_agent->arm(&interaction_task,this,INFINITE)==0,Error);
Error:
return;
}
unsigned int Microscope::runPipeline()
{ int sts = 1;
sts &= frame_formatter._agent->run();
sts &= wrap._agent->run();
sts &= cast_to_i16._agent->run();
sts &= inverter._agent->run();
sts &= frame_averager._agent->run();
sts &= pixel_averager._agent->run();
return (sts!=1); // returns 1 on fail and 0 on success
}
unsigned int Microscope::stopPipeline()
{ int sts = 1;
// These should block till channel's empty
sts &= frame_formatter._agent->stop();
sts &= wrap._agent->stop();
sts &= cast_to_i16._agent->stop();
sts &= inverter._agent->stop();
sts &= frame_averager._agent->stop();
sts &= pixel_averager._agent->stop();
return (sts!=1); // returns 1 on fail and 0 on success
}
///////////////////////////////////////////////////////////////////////
// FileSeries
///////////////////////////////////////////////////////////////////////
#define VALIDATE if(!_is_valid) {warning("(%s:%d) - Invalid location for file series."ENDL,__FILE__,__LINE__);}
FileSeries& FileSeries::inc( void )
{
VALIDATE;
int n = _desc->seriesno();
// reset series number when series path changes
updateDate(); // get the current date
std::string seriespath = _desc->root() + _desc->pathsep() + _desc->date();
if(seriespath.compare(_lastpath)!=0)
{ _desc->set_seriesno(0);
_lastpath = seriespath;
} else
{ _desc->set_seriesno(n+1);
}
return *this;
}
const std::string FileSeries::getFullPath(const std::string& prefix, const std::string& ext)
{
VALIDATE;
char strSeriesNo[32];
renderSeriesNo(strSeriesNo,sizeof(strSeriesNo));
std::string seriespath = _desc->root() + _desc->pathsep() + _desc->date();
std::string part2 = prefix;
if(!part2.empty())
part2 = "-" + prefix;
return seriespath
+ _desc->pathsep()
+ strSeriesNo
+ _desc->pathsep()
+ strSeriesNo + part2 + ext;
}
void FileSeries::updateDate( void )
{
time_t clock = time(NULL);
struct tm *t = localtime(&clock);
char datestr[] = "0000-00-00";
sprintf_s(datestr,sizeof(datestr),"%04d-%02d-%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday);
_desc->set_date(datestr);
}
void FileSeries::ensurePathExists()
{
std::string s,t;
char strSeriesNo[32];
renderSeriesNo(strSeriesNo,sizeof(strSeriesNo));
updateDate();
s = _desc->root()+_desc->pathsep()+_desc->date();
tryCreateDirectory(s.c_str(), "root path", _desc->root().c_str());
t = s + _desc->pathsep()+strSeriesNo;
tryCreateDirectory(t.c_str(), "date path", s.c_str());
}
void FileSeries::renderSeriesNo( char * strSeriesNo,int maxbytes )
{
int n = _desc->seriesno();
if(n>99999)
warning("File series number is greater than the supported number of digits.\r\n");
memset(strSeriesNo,0,maxbytes);
sprintf_s(strSeriesNo,maxbytes,"%05d",n); //limited to 5 digits
}
void FileSeries::tryCreateDirectory( LPCTSTR path, const char* description, LPCTSTR root )
{
_is_valid = true;
if(!CreateDirectory(path,NULL/*default security*/))
{ DWORD err;
switch(err=GetLastError())
{
case ERROR_ALREADY_EXISTS: /*ignore*/
break;
case ERROR_PATH_NOT_FOUND:
case ERROR_NOT_READY:
warning("[FileSeries] %s(%d)"ENDL"\tCould not create %s:"ENDL"\t%s"ENDL,__FILE__,__LINE__,description,root); // [ ] TODO chage this to a warning
_is_valid = false;
break;
default:
_is_valid = false;
warning("[FileSeries] %s(%d)"ENDL"\tUnexpected error returned after call to CreateDirectory()"ENDL"\tFor Path: %s"ENDL,__FILE__,__LINE__,path);
ReportLastWindowsError();
}
}
}
//notes
//-----
// - I can see no reason right now to use transactions
// It would prevent against renaming/deleting dependent directories during the transaction
// Might be interesting in other places to lock files during acquisition. However, I think a little
// discipline from the user(me) can go a long way.
//
// - approach
//
// 1. assert <root> exists
// 2. assert creation or existence of <root>/<date>
// 3. assert creation of <root>/<data>/<seriesno>
// 4. return true on success, fail otherwise.
//see
//---
//
//MSDN CreateDirectory http://msdn.microsoft.com/en-us/library/aa363855(VS.85).aspx
//MSDN CreateDirectoryTransacted http://msdn.microsoft.com/en-us/library/aa363855(VS.85).aspx
//MSDN CreateTransaction http://msdn.microsoft.com/en-us/library/aa366011(v=VS.85).aspx
// handle = CreateTransaction(NULL/*default security*/,0,0,0,0,0/*timeout,0==inf*/,"description");
} // end namespace device
} // end namespace fetch
<commit_msg>Fix: stage and fov weren't being re-config'd<commit_after>/*
* Microscope.cpp
*
* Author: Nathan Clack <clackn@janelia.hhmi.org>
* Date: Apr 28, 2010
*/
/*
* Copyright 2010 Howard Hughes Medical Institute.
* All rights reserved.
* Use is subject to Janelia Farm Research Campus Software Copyright 1.1
* license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
#include "Microscope.h"
#include <time.h>
#include <iostream>
#include <fstream>
#include "stack.pb.h"
#include "microscope.pb.h"
#include "google\protobuf\text_format.h"
#define CHKJMP(expr,lbl) \
if(!(expr)) \
{ warning("[MICROSCOPE] %s(%d): "ENDL"\tExpression: %s"ENDL"\tevaluated false."ENDL,__FILE__,__LINE__,#expr); \
goto lbl; \
}
namespace fetch
{ namespace device {
Microscope::Microscope()
:IConfigurableDevice<Config>(&__self_agent)
,__self_agent("Microscope",NULL)
,__scan_agent("Scanner",&scanner)
,__io_agent("IO",&disk)
,__vibratome_agent("Vibratome",&vibratome_)
,scanner(&__scan_agent)
,stage_(&__self_agent)
,vibratome_(&__vibratome_agent)
,fov_(_config->fov())
,disk(&__io_agent)
,frame_averager("FrameAverager")
,pixel_averager("PixelAverager")
,cast_to_i16("i16Cast")
,inverter("inverter")
,wrap()
,frame_formatter("FrameFormatter")
,trash("Trash")
{
set_config(_config);
__common_setup();
}
/*
worker::FrameAverageAgent frame_averager;
worker::HorizontalDownsampleAgent pixel_averager;
worker::FrameCastAgent_i16 cast_to_i16;
worker::FrameInvertAgent inverter;
worker::ResonantWrapAgent wrap;
worker::TerminalAgent trash;
*/
Microscope::Microscope( const Config &cfg )
:IConfigurableDevice<Config>(&__self_agent)
,__self_agent("Microscope",NULL)
,__scan_agent("Scanner",&scanner)
,__io_agent("IO",&disk)
,__vibratome_agent("Vibratome",&vibratome_)
,scanner(&__scan_agent)
,stage_(&__self_agent)
,vibratome_(&__vibratome_agent)
,fov_(cfg.fov())
,disk(&__io_agent)
,frame_averager("FrameAverager")
,pixel_averager("PixelAverager")
,cast_to_i16("i16Cast")
,inverter("inverter")
,wrap()
,frame_formatter("FrameFormatter")
,trash("Trash")
,file_series()
{
set_config(cfg);
__common_setup();
}
Microscope::Microscope(Config *cfg )
:IConfigurableDevice<Config>(&__self_agent,cfg)
,__self_agent("Microscope",NULL)
,__scan_agent("Scanner",&scanner)
,__io_agent("IO",&disk)
,__vibratome_agent("Vibratome",&vibratome_)
,scanner(&__scan_agent,cfg->mutable_scanner3d())
,stage_(&__self_agent,cfg->mutable_stage())
,vibratome_(&__vibratome_agent,cfg->mutable_vibratome())
,fov_(cfg->fov())
,disk(&__io_agent)
,frame_averager(cfg->mutable_frame_average(),"FrameAverager")
,pixel_averager(cfg->mutable_horizontal_downsample(),"PixelAverager")
,cast_to_i16("i16Cast")
,inverter("Inverter")
,wrap(cfg->mutable_resonant_wrap())
,frame_formatter("FrameFormatter")
,trash("Trash")
,file_series(cfg->mutable_file_series())
{
__common_setup();
}
Microscope::~Microscope(void)
{
if(__scan_agent.detach()) warning("Microscope __scan_agent did not detach cleanly\r\n");
if(__self_agent.detach()) warning("Microscope __self_agent did not detach cleanly\r\n");
if( __io_agent.detach()) warning("Microscope __io_agent did not detach cleanly\r\n");
if( __vibratome_agent.detach()) warning("Microscope __vibratome_agent did not detach cleanly\r\n");
}
unsigned int
Microscope::on_attach(void)
{
// argh this is a confusing way to do things. which attach to call when.
//
// on_attach/on_detach only gets called for the owner, so attach/detach events have to be forwarded
// to devices that share the agent. This seems awkward :C
std::string stackname;
CHKJMP( __scan_agent.attach()==0,ESCAN);
CHKJMP( stage_.on_attach()==0,ESTAGE);
CHKJMP(__vibratome_agent.attach()==0,EVIBRATOME);
stackname = _config->file_prefix()+_config->stack_extension();
file_series.ensurePathExists();
return 0; // success
EVIBRATOME:
stage_.on_detach();
ESTAGE:
__scan_agent.detach();
ESCAN:
return 1;
}
unsigned int
Microscope::on_detach(void)
{
int eflag = 0; // 0 success, 1 failure
eflag |= scanner._agent->detach(); //scanner.detach();
eflag |= frame_averager._agent->detach();
eflag |= pixel_averager._agent->detach();
eflag |= inverter._agent->detach();
eflag |= cast_to_i16._agent->detach();
eflag |= wrap._agent->detach();
eflag |= frame_formatter._agent->detach();
eflag |= trash._agent->detach();
eflag |= disk._agent->detach();
eflag |= stage_.on_detach();
eflag |= vibratome_._agent->detach();
return eflag;
}
unsigned int Microscope::on_disarm()
{
unsigned int sts = 1; // success
sts &= scanner._agent->disarm();
sts &= frame_averager._agent->disarm();
sts &= pixel_averager._agent->disarm();
sts &= inverter._agent->disarm();
sts &= cast_to_i16._agent->disarm();
sts &= wrap._agent->disarm();
sts &= frame_formatter._agent->disarm();
sts &= trash._agent->disarm();
sts &= disk._agent->disarm();
sts &= vibratome_._agent->disarm();
return sts;
}
const std::string Microscope::stack_filename()
{
return file_series.getFullPath(_config->file_prefix(),_config->stack_extension());
}
const std::string Microscope::config_filename()
{
return file_series.getFullPath(_config->file_prefix(),_config->config_extension());
}
const std::string Microscope::metadata_filename()
{
return file_series.getFullPath(_config->file_prefix(),_config->metadata_extension());
}
void Microscope::write_stack_metadata()
{
//{ std::ofstream fout(config_filename(),std::ios::out|std::ios::trunc|std::ios::binary);
// get_config().SerializePartialToOstream(&fout);
//}
{ std::ofstream fout(config_filename().c_str(),std::ios::out|std::ios::trunc);
std::string s;
Config c = get_config();
google::protobuf::TextFormat::PrintToString(c,&s);
fout << s;
//get_config().SerializePartialToOstream(&fout);
}
{ float x,y,z;
std::ofstream fout(metadata_filename().c_str(),std::ios::out|std::ios::trunc);
fetch::cfg::data::Acquisition data;
stage_.getPos(&x,&y,&z);
data.set_x_mm(x);
data.set_y_mm(y);
data.set_z_mm(z);
std::string s;
google::protobuf::TextFormat::PrintToString(data,&s);
fout << s;
//get_config().SerializePartialToOstream(&fout);
}
}
void Microscope::_set_config( Config IN *cfg )
{
scanner._set_config(cfg->mutable_scanner3d());
pixel_averager._set_config(cfg->mutable_horizontal_downsample());
frame_averager._set_config(cfg->mutable_frame_average());
wrap._set_config(cfg->mutable_resonant_wrap());
file_series._desc = cfg->mutable_file_series();
vibratome_._set_config(cfg->mutable_vibratome());
fov_.update(_config->fov());
stage_._set_config(cfg->mutable_stage());
stage_.setFOV(&fov_);
}
void Microscope::_set_config( const Config& cfg )
{
*_config=cfg; // Copy
_set_config(_config); // Update
}
void Microscope::onUpdate()
{
scanner.onUpdate();
vibratome_.onUpdate();
fov_.update(_config->fov());
stage_.setFOV(&fov_);
// update microscope's run state based on sub-agents
// require scan agent and vibratome agent to be attached
if( __self_agent.is_attached() && !(__scan_agent.is_attached() && __vibratome_agent.is_attached()))
__self_agent.detach();
}
IDevice* Microscope::configPipeline()
{
//Assemble pipeline here
IDevice *cur;
cur = &scanner;
cur = pixel_averager.apply(cur);
cur = frame_averager.apply(cur);
cur = inverter.apply(cur);
cur = cast_to_i16.apply(cur);
cur = wrap.apply(cur);
cur = frame_formatter.apply(cur);
return cur;
}
void Microscope::__common_setup()
{
__self_agent._owner = this;
stage_.setFOV(&fov_);
//configPipeline();
CHKJMP(_agent->attach()==0,Error);
CHKJMP(_agent->arm(&interaction_task,this,INFINITE)==0,Error);
Error:
return;
}
unsigned int Microscope::runPipeline()
{ int sts = 1;
sts &= frame_formatter._agent->run();
sts &= wrap._agent->run();
sts &= cast_to_i16._agent->run();
sts &= inverter._agent->run();
sts &= frame_averager._agent->run();
sts &= pixel_averager._agent->run();
return (sts!=1); // returns 1 on fail and 0 on success
}
unsigned int Microscope::stopPipeline()
{ int sts = 1;
// These should block till channel's empty
sts &= frame_formatter._agent->stop();
sts &= wrap._agent->stop();
sts &= cast_to_i16._agent->stop();
sts &= inverter._agent->stop();
sts &= frame_averager._agent->stop();
sts &= pixel_averager._agent->stop();
return (sts!=1); // returns 1 on fail and 0 on success
}
///////////////////////////////////////////////////////////////////////
// FileSeries
///////////////////////////////////////////////////////////////////////
#define VALIDATE if(!_is_valid) {warning("(%s:%d) - Invalid location for file series."ENDL,__FILE__,__LINE__);}
FileSeries& FileSeries::inc( void )
{
VALIDATE;
int n = _desc->seriesno();
// reset series number when series path changes
updateDate(); // get the current date
std::string seriespath = _desc->root() + _desc->pathsep() + _desc->date();
if(seriespath.compare(_lastpath)!=0)
{ _desc->set_seriesno(0);
_lastpath = seriespath;
} else
{ _desc->set_seriesno(n+1);
}
return *this;
}
const std::string FileSeries::getFullPath(const std::string& prefix, const std::string& ext)
{
VALIDATE;
char strSeriesNo[32];
renderSeriesNo(strSeriesNo,sizeof(strSeriesNo));
std::string seriespath = _desc->root() + _desc->pathsep() + _desc->date();
std::string part2 = prefix;
if(!part2.empty())
part2 = "-" + prefix;
return seriespath
+ _desc->pathsep()
+ strSeriesNo
+ _desc->pathsep()
+ strSeriesNo + part2 + ext;
}
void FileSeries::updateDate( void )
{
time_t clock = time(NULL);
struct tm *t = localtime(&clock);
char datestr[] = "0000-00-00";
sprintf_s(datestr,sizeof(datestr),"%04d-%02d-%02d",t->tm_year+1900,t->tm_mon+1,t->tm_mday);
_desc->set_date(datestr);
}
void FileSeries::ensurePathExists()
{
std::string s,t;
char strSeriesNo[32];
renderSeriesNo(strSeriesNo,sizeof(strSeriesNo));
updateDate();
s = _desc->root()+_desc->pathsep()+_desc->date();
tryCreateDirectory(s.c_str(), "root path", _desc->root().c_str());
t = s + _desc->pathsep()+strSeriesNo;
tryCreateDirectory(t.c_str(), "date path", s.c_str());
}
void FileSeries::renderSeriesNo( char * strSeriesNo,int maxbytes )
{
int n = _desc->seriesno();
if(n>99999)
warning("File series number is greater than the supported number of digits.\r\n");
memset(strSeriesNo,0,maxbytes);
sprintf_s(strSeriesNo,maxbytes,"%05d",n); //limited to 5 digits
}
void FileSeries::tryCreateDirectory( LPCTSTR path, const char* description, LPCTSTR root )
{
_is_valid = true;
if(!CreateDirectory(path,NULL/*default security*/))
{ DWORD err;
switch(err=GetLastError())
{
case ERROR_ALREADY_EXISTS: /*ignore*/
break;
case ERROR_PATH_NOT_FOUND:
case ERROR_NOT_READY:
warning("[FileSeries] %s(%d)"ENDL"\tCould not create %s:"ENDL"\t%s"ENDL,__FILE__,__LINE__,description,root); // [ ] TODO chage this to a warning
_is_valid = false;
break;
default:
_is_valid = false;
warning("[FileSeries] %s(%d)"ENDL"\tUnexpected error returned after call to CreateDirectory()"ENDL"\tFor Path: %s"ENDL,__FILE__,__LINE__,path);
ReportLastWindowsError();
}
}
}
//notes
//-----
// - I can see no reason right now to use transactions
// It would prevent against renaming/deleting dependent directories during the transaction
// Might be interesting in other places to lock files during acquisition. However, I think a little
// discipline from the user(me) can go a long way.
//
// - approach
//
// 1. assert <root> exists
// 2. assert creation or existence of <root>/<date>
// 3. assert creation of <root>/<data>/<seriesno>
// 4. return true on success, fail otherwise.
//see
//---
//
//MSDN CreateDirectory http://msdn.microsoft.com/en-us/library/aa363855(VS.85).aspx
//MSDN CreateDirectoryTransacted http://msdn.microsoft.com/en-us/library/aa363855(VS.85).aspx
//MSDN CreateTransaction http://msdn.microsoft.com/en-us/library/aa366011(v=VS.85).aspx
// handle = CreateTransaction(NULL/*default security*/,0,0,0,0,0/*timeout,0==inf*/,"description");
} // end namespace device
} // end namespace fetch
<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2022 Baldur Karlsson
*
* 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 "BufferFormatSpecifier.h"
#include <QFontDatabase>
#include <QKeyEvent>
#include <QScrollBar>
#include <QSignalBlocker>
#include <QTextCursor>
#include <QTextDocument>
#include "Code/QRDUtils.h"
#include "Code/ScintillaSyntax.h"
#include "scintilla/include/SciLexer.h"
#include "scintilla/include/qt/ScintillaEdit.h"
#include "ui_BufferFormatSpecifier.h"
static const int ERROR_STYLE = STYLE_LASTPREDEFINED + 1;
BufferFormatList *globalFormatList = NULL;
BufferFormatList::BufferFormatList(ICaptureContext &ctx, QObject *parent)
: m_Ctx(ctx), QObject(parent)
{
rdcarray<rdcstr> saved = m_Ctx.Config().BufferFormatter_SavedFormats;
for(rdcstr f : saved)
{
int idx = f.indexOf('\n');
formats[QString(f.substr(0, idx))] = QString(f.substr(idx + 1)).trimmed();
}
}
void BufferFormatList::setFormat(QString name, QString format)
{
bool newFmt = !formats.contains(name);
if(format.isEmpty())
formats.remove(name);
else
formats[name] = format;
if(newFmt || (!newFmt && format.isEmpty()))
emit formatListUpdated();
QStringList keys = formats.keys();
keys.sort(Qt::CaseInsensitive);
rdcarray<rdcstr> saved;
for(QString k : keys)
saved.push_back(k + lit("\n") + formats[k]);
m_Ctx.Config().BufferFormatter_SavedFormats = saved;
}
BufferFormatSpecifier::BufferFormatSpecifier(QWidget *parent)
: QWidget(parent), ui(new Ui::BufferFormatSpecifier)
{
ui->setupUi(this);
formatText = new ScintillaEdit(this);
formatText->styleSetFont(STYLE_DEFAULT, Formatter::FixedFont().family().toUtf8().data());
formatText->styleSetSize(STYLE_DEFAULT, Formatter::FixedFont().pointSize());
formatText->styleSetFont(ERROR_STYLE, Formatter::FixedFont().family().toUtf8().data());
formatText->styleSetSize(ERROR_STYLE, Formatter::FixedFont().pointSize());
QColor base = formatText->palette().color(QPalette::Base);
QColor col = QColor::fromHslF(0.0f, 1.0f, qBound(0.1, base.lightnessF(), 0.9));
formatText->styleSetBack(ERROR_STYLE, SCINTILLA_COLOUR(col.red(), col.green(), col.blue()));
ConfigureSyntax(formatText, SCLEX_BUFFER);
formatText->setTabWidth(4);
formatText->setScrollWidth(1);
formatText->setScrollWidthTracking(true);
formatText->annotationSetVisible(ANNOTATION_BOXED);
formatText->colourise(0, -1);
formatText->setMarginWidthN(0, 0);
formatText->setMarginWidthN(1, 0);
formatText->setMarginWidthN(2, 0);
QFrame *formatContainer = new QFrame(this);
QVBoxLayout *layout = new QVBoxLayout;
layout->setContentsMargins(2, 2, 2, 2);
layout->addWidget(formatText);
formatContainer->setLayout(layout);
QPalette pal = formatContainer->palette();
pal.setColor(QPalette::Window, pal.color(QPalette::Base));
formatContainer->setPalette(pal);
formatContainer->setAutoFillBackground(true);
formatContainer->setFrameShape(QFrame::Panel);
formatContainer->setFrameShadow(QFrame::Plain);
QObject::connect(formatText, &ScintillaEdit::modified,
[this](int type, int, int, int, const QByteArray &, int, int, int) {
ui->savedList->clearSelection();
if(!(type & SC_MOD_CHANGEANNOTATION))
formatText->annotationClearAll();
});
ui->mainLayout->insertWidget(0, formatContainer);
ui->savedList->setItemDelegate(new FullEditorDelegate(ui->savedList));
ui->savedList->setFont(Formatter::PreferredFont());
ui->savedList->setColumns({tr("Saved formats")});
setErrors({});
on_showHelp_toggled(false);
}
BufferFormatSpecifier::~BufferFormatSpecifier()
{
delete ui;
}
void BufferFormatSpecifier::setAutoFormat(QString autoFormat)
{
m_AutoFormat = autoFormat;
updateFormatList();
setFormat(autoFormat);
formatText->emptyUndoBuffer();
on_apply_clicked();
}
void BufferFormatSpecifier::setContext(ICaptureContext *ctx)
{
m_Ctx = ctx;
if(!globalFormatList)
globalFormatList = new BufferFormatList(*ctx, ctx->GetMainWindow()->Widget());
QObject::connect(globalFormatList, &BufferFormatList::formatListUpdated, this,
&BufferFormatSpecifier::updateFormatList);
m_Ctx->GetMainWindow()->RegisterShortcut(QKeySequence(QKeySequence::Refresh).toString(), this,
[this](QWidget *) { on_apply_clicked(); });
updateFormatList();
}
void BufferFormatSpecifier::setTitle(QString title)
{
ui->formatGroup->setTitle(title);
}
void BufferFormatSpecifier::setFormat(const QString &format)
{
formatText->setText(format.toUtf8().data());
}
void BufferFormatSpecifier::setErrors(const QMap<int, QString> &errors)
{
formatText->annotationClearAll();
bool first = true;
for(auto err = errors.begin(); err != errors.end(); ++err)
{
int line = err.key();
formatText->annotationSetStyle(line, ERROR_STYLE);
formatText->annotationSetText(line, (tr("Error: %1").arg(err.value())).toUtf8().data());
if(first)
{
int firstLine = formatText->firstVisibleLine();
int linesVisible = formatText->linesOnScreen();
if(line < firstLine || line > (firstLine + linesVisible - 1))
formatText->setFirstVisibleLine(qMax(0, line - linesVisible / 2));
first = false;
}
}
}
void BufferFormatSpecifier::updateFormatList()
{
QString sel;
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(item)
sel = item->text(0);
{
QSignalBlocker block(ui->savedList);
int vs = ui->savedList->verticalScrollBar()->value();
ui->savedList->beginUpdate();
ui->savedList->clear();
int selidx = -1;
if(!m_AutoFormat.isEmpty())
{
item = new RDTreeWidgetItem({tr("<Auto-generated>")});
item->setItalic(true);
ui->savedList->addTopLevelItem(item);
if(item->text(0) == sel)
selidx = 0;
}
QStringList formats = globalFormatList->getFormats();
for(QString f : formats)
{
if(f == sel)
selidx = ui->savedList->topLevelItemCount();
ui->savedList->addTopLevelItem(new RDTreeWidgetItem({f}));
}
{
item = new RDTreeWidgetItem({tr("New...")});
if(item->text(0) == sel)
selidx = ui->savedList->topLevelItemCount();
item->setEditable(0, true);
ui->savedList->addTopLevelItem(item);
}
if(selidx >= 0)
ui->savedList->setSelectedItem(ui->savedList->topLevelItem(selidx));
ui->savedList->resizeColumnToContents(0);
ui->savedList->endUpdate();
ui->savedList->verticalScrollBar()->setValue(vs);
}
on_savedList_itemSelectionChanged();
}
void BufferFormatSpecifier::on_savedList_keyPress(QKeyEvent *event)
{
if(event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)
{
on_delDef_clicked();
}
}
void BufferFormatSpecifier::on_savedList_itemChanged(RDTreeWidgetItem *item, int column)
{
// ignore updates for anything but the last one
if(ui->savedList->indexOfTopLevelItem(item) != ui->savedList->topLevelItemCount() - 1)
return;
QString name = item->text(0);
// prevent recursion
{
QSignalBlocker block(ui->savedList);
// if they didn't actually edit it, ignore
if(name == tr("New..."))
return;
if(globalFormatList->hasFormat(name))
{
RDDialog::critical(this, tr("Name already in use"),
tr("The definition name '%1' is already in used.\n"
"To update this definition, select it and click update."));
item->setText(0, tr("New..."));
return;
}
}
globalFormatList->setFormat(name,
QString::fromUtf8(formatText->getText(formatText->textLength() + 1)));
}
void BufferFormatSpecifier::on_savedList_itemDoubleClicked(RDTreeWidgetItem *item, int column)
{
ui->savedList->setSelectedItem(item);
if(ui->loadDef->isEnabled())
on_loadDef_clicked();
}
void BufferFormatSpecifier::on_savedList_itemSelectionChanged()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
ui->saveDef->setEnabled(item != NULL);
ui->loadDef->setEnabled(item != NULL);
ui->delDef->setEnabled(item != NULL);
// auto format is always the first, and can't be saved to or deleted
if(!m_AutoFormat.isEmpty() && ui->savedList->indexOfTopLevelItem(item) == 0)
{
ui->saveDef->setEnabled(false);
ui->delDef->setEnabled(false);
}
// the 'new' format is always the last, and can't be loaded from or deleted
if(ui->savedList->indexOfTopLevelItem(item) == ui->savedList->topLevelItemCount() - 1)
{
ui->loadDef->setEnabled(false);
ui->delDef->setEnabled(false);
ui->saveDef->setToolTip(tr("Create new current structure definition"));
}
else
{
ui->saveDef->setToolTip(tr("Update selected with current structure definition"));
}
}
void BufferFormatSpecifier::on_showHelp_toggled(bool help)
{
ui->helpText->setVisible(help);
formatText->parentWidget()->setVisible(!help);
}
void BufferFormatSpecifier::on_loadDef_clicked()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(!item)
return;
QString name = item->text(0);
QString format;
if(!m_AutoFormat.isEmpty() && ui->savedList->indexOfTopLevelItem(item) == 0)
format = m_AutoFormat;
else
format = globalFormatList->getFormat(name);
{
QSignalBlocker block(formatText);
formatText->setText(format.toUtf8().data());
}
emit processFormat(format);
}
void BufferFormatSpecifier::on_saveDef_clicked()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(!item)
return;
// for the 'new...' just trigger an edit and let the user do it that way. This reduces
// duplication, avoids need for a prompt for the name, and educates the user that they can edit
// directly
if(ui->savedList->indexOfTopLevelItem(item) == ui->savedList->topLevelItemCount() - 1)
{
ui->savedList->editItem(item);
return;
}
QString name = item->text(0);
QMessageBox::StandardButton res = RDDialog::question(
this, tr("Updating definition"),
tr("Are you sure you wish to overwrite definition '%1'?").arg(name), RDDialog::YesNoCancel);
if(res != QMessageBox::Yes)
return;
globalFormatList->setFormat(name,
QString::fromUtf8(formatText->getText(formatText->textLength() + 1)));
}
void BufferFormatSpecifier::on_delDef_clicked()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(!item)
return;
QString name = item->text(0);
QMessageBox::StandardButton res = RDDialog::question(
this, tr("Deleting definition"),
tr("Are you sure you wish to delete definition '%1'?").arg(name), RDDialog::YesNoCancel);
if(res != QMessageBox::Yes)
return;
ui->savedList->clearSelection();
globalFormatList->setFormat(name, QString());
}
void BufferFormatSpecifier::on_apply_clicked()
{
setErrors({});
emit processFormat(QString::fromUtf8(formatText->getText(formatText->textLength() + 1)));
}
<commit_msg>Unregister F5 shortcut in buffer formatter<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2022 Baldur Karlsson
*
* 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 "BufferFormatSpecifier.h"
#include <QFontDatabase>
#include <QKeyEvent>
#include <QScrollBar>
#include <QSignalBlocker>
#include <QTextCursor>
#include <QTextDocument>
#include "Code/QRDUtils.h"
#include "Code/ScintillaSyntax.h"
#include "scintilla/include/SciLexer.h"
#include "scintilla/include/qt/ScintillaEdit.h"
#include "ui_BufferFormatSpecifier.h"
static const int ERROR_STYLE = STYLE_LASTPREDEFINED + 1;
BufferFormatList *globalFormatList = NULL;
BufferFormatList::BufferFormatList(ICaptureContext &ctx, QObject *parent)
: m_Ctx(ctx), QObject(parent)
{
rdcarray<rdcstr> saved = m_Ctx.Config().BufferFormatter_SavedFormats;
for(rdcstr f : saved)
{
int idx = f.indexOf('\n');
formats[QString(f.substr(0, idx))] = QString(f.substr(idx + 1)).trimmed();
}
}
void BufferFormatList::setFormat(QString name, QString format)
{
bool newFmt = !formats.contains(name);
if(format.isEmpty())
formats.remove(name);
else
formats[name] = format;
if(newFmt || (!newFmt && format.isEmpty()))
emit formatListUpdated();
QStringList keys = formats.keys();
keys.sort(Qt::CaseInsensitive);
rdcarray<rdcstr> saved;
for(QString k : keys)
saved.push_back(k + lit("\n") + formats[k]);
m_Ctx.Config().BufferFormatter_SavedFormats = saved;
}
BufferFormatSpecifier::BufferFormatSpecifier(QWidget *parent)
: QWidget(parent), ui(new Ui::BufferFormatSpecifier)
{
ui->setupUi(this);
formatText = new ScintillaEdit(this);
formatText->styleSetFont(STYLE_DEFAULT, Formatter::FixedFont().family().toUtf8().data());
formatText->styleSetSize(STYLE_DEFAULT, Formatter::FixedFont().pointSize());
formatText->styleSetFont(ERROR_STYLE, Formatter::FixedFont().family().toUtf8().data());
formatText->styleSetSize(ERROR_STYLE, Formatter::FixedFont().pointSize());
QColor base = formatText->palette().color(QPalette::Base);
QColor col = QColor::fromHslF(0.0f, 1.0f, qBound(0.1, base.lightnessF(), 0.9));
formatText->styleSetBack(ERROR_STYLE, SCINTILLA_COLOUR(col.red(), col.green(), col.blue()));
ConfigureSyntax(formatText, SCLEX_BUFFER);
formatText->setTabWidth(4);
formatText->setScrollWidth(1);
formatText->setScrollWidthTracking(true);
formatText->annotationSetVisible(ANNOTATION_BOXED);
formatText->colourise(0, -1);
formatText->setMarginWidthN(0, 0);
formatText->setMarginWidthN(1, 0);
formatText->setMarginWidthN(2, 0);
QFrame *formatContainer = new QFrame(this);
QVBoxLayout *layout = new QVBoxLayout;
layout->setContentsMargins(2, 2, 2, 2);
layout->addWidget(formatText);
formatContainer->setLayout(layout);
QPalette pal = formatContainer->palette();
pal.setColor(QPalette::Window, pal.color(QPalette::Base));
formatContainer->setPalette(pal);
formatContainer->setAutoFillBackground(true);
formatContainer->setFrameShape(QFrame::Panel);
formatContainer->setFrameShadow(QFrame::Plain);
QObject::connect(formatText, &ScintillaEdit::modified,
[this](int type, int, int, int, const QByteArray &, int, int, int) {
ui->savedList->clearSelection();
if(!(type & SC_MOD_CHANGEANNOTATION))
formatText->annotationClearAll();
});
ui->mainLayout->insertWidget(0, formatContainer);
ui->savedList->setItemDelegate(new FullEditorDelegate(ui->savedList));
ui->savedList->setFont(Formatter::PreferredFont());
ui->savedList->setColumns({tr("Saved formats")});
setErrors({});
on_showHelp_toggled(false);
}
BufferFormatSpecifier::~BufferFormatSpecifier()
{
delete ui;
// unregister any shortcuts on this window
if(m_Ctx)
m_Ctx->GetMainWindow()->UnregisterShortcut(QString(), this);
}
void BufferFormatSpecifier::setAutoFormat(QString autoFormat)
{
m_AutoFormat = autoFormat;
updateFormatList();
setFormat(autoFormat);
formatText->emptyUndoBuffer();
on_apply_clicked();
}
void BufferFormatSpecifier::setContext(ICaptureContext *ctx)
{
m_Ctx = ctx;
if(!globalFormatList)
globalFormatList = new BufferFormatList(*ctx, ctx->GetMainWindow()->Widget());
QObject::connect(globalFormatList, &BufferFormatList::formatListUpdated, this,
&BufferFormatSpecifier::updateFormatList);
m_Ctx->GetMainWindow()->RegisterShortcut(QKeySequence(QKeySequence::Refresh).toString(), this,
[this](QWidget *) { on_apply_clicked(); });
updateFormatList();
}
void BufferFormatSpecifier::setTitle(QString title)
{
ui->formatGroup->setTitle(title);
}
void BufferFormatSpecifier::setFormat(const QString &format)
{
formatText->setText(format.toUtf8().data());
}
void BufferFormatSpecifier::setErrors(const QMap<int, QString> &errors)
{
formatText->annotationClearAll();
bool first = true;
for(auto err = errors.begin(); err != errors.end(); ++err)
{
int line = err.key();
formatText->annotationSetStyle(line, ERROR_STYLE);
formatText->annotationSetText(line, (tr("Error: %1").arg(err.value())).toUtf8().data());
if(first)
{
int firstLine = formatText->firstVisibleLine();
int linesVisible = formatText->linesOnScreen();
if(line < firstLine || line > (firstLine + linesVisible - 1))
formatText->setFirstVisibleLine(qMax(0, line - linesVisible / 2));
first = false;
}
}
}
void BufferFormatSpecifier::updateFormatList()
{
QString sel;
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(item)
sel = item->text(0);
{
QSignalBlocker block(ui->savedList);
int vs = ui->savedList->verticalScrollBar()->value();
ui->savedList->beginUpdate();
ui->savedList->clear();
int selidx = -1;
if(!m_AutoFormat.isEmpty())
{
item = new RDTreeWidgetItem({tr("<Auto-generated>")});
item->setItalic(true);
ui->savedList->addTopLevelItem(item);
if(item->text(0) == sel)
selidx = 0;
}
QStringList formats = globalFormatList->getFormats();
for(QString f : formats)
{
if(f == sel)
selidx = ui->savedList->topLevelItemCount();
ui->savedList->addTopLevelItem(new RDTreeWidgetItem({f}));
}
{
item = new RDTreeWidgetItem({tr("New...")});
if(item->text(0) == sel)
selidx = ui->savedList->topLevelItemCount();
item->setEditable(0, true);
ui->savedList->addTopLevelItem(item);
}
if(selidx >= 0)
ui->savedList->setSelectedItem(ui->savedList->topLevelItem(selidx));
ui->savedList->resizeColumnToContents(0);
ui->savedList->endUpdate();
ui->savedList->verticalScrollBar()->setValue(vs);
}
on_savedList_itemSelectionChanged();
}
void BufferFormatSpecifier::on_savedList_keyPress(QKeyEvent *event)
{
if(event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace)
{
on_delDef_clicked();
}
}
void BufferFormatSpecifier::on_savedList_itemChanged(RDTreeWidgetItem *item, int column)
{
// ignore updates for anything but the last one
if(ui->savedList->indexOfTopLevelItem(item) != ui->savedList->topLevelItemCount() - 1)
return;
QString name = item->text(0);
// prevent recursion
{
QSignalBlocker block(ui->savedList);
// if they didn't actually edit it, ignore
if(name == tr("New..."))
return;
if(globalFormatList->hasFormat(name))
{
RDDialog::critical(this, tr("Name already in use"),
tr("The definition name '%1' is already in used.\n"
"To update this definition, select it and click update."));
item->setText(0, tr("New..."));
return;
}
}
globalFormatList->setFormat(name,
QString::fromUtf8(formatText->getText(formatText->textLength() + 1)));
}
void BufferFormatSpecifier::on_savedList_itemDoubleClicked(RDTreeWidgetItem *item, int column)
{
ui->savedList->setSelectedItem(item);
if(ui->loadDef->isEnabled())
on_loadDef_clicked();
}
void BufferFormatSpecifier::on_savedList_itemSelectionChanged()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
ui->saveDef->setEnabled(item != NULL);
ui->loadDef->setEnabled(item != NULL);
ui->delDef->setEnabled(item != NULL);
// auto format is always the first, and can't be saved to or deleted
if(!m_AutoFormat.isEmpty() && ui->savedList->indexOfTopLevelItem(item) == 0)
{
ui->saveDef->setEnabled(false);
ui->delDef->setEnabled(false);
}
// the 'new' format is always the last, and can't be loaded from or deleted
if(ui->savedList->indexOfTopLevelItem(item) == ui->savedList->topLevelItemCount() - 1)
{
ui->loadDef->setEnabled(false);
ui->delDef->setEnabled(false);
ui->saveDef->setToolTip(tr("Create new current structure definition"));
}
else
{
ui->saveDef->setToolTip(tr("Update selected with current structure definition"));
}
}
void BufferFormatSpecifier::on_showHelp_toggled(bool help)
{
ui->helpText->setVisible(help);
formatText->parentWidget()->setVisible(!help);
}
void BufferFormatSpecifier::on_loadDef_clicked()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(!item)
return;
QString name = item->text(0);
QString format;
if(!m_AutoFormat.isEmpty() && ui->savedList->indexOfTopLevelItem(item) == 0)
format = m_AutoFormat;
else
format = globalFormatList->getFormat(name);
{
QSignalBlocker block(formatText);
formatText->setText(format.toUtf8().data());
}
emit processFormat(format);
}
void BufferFormatSpecifier::on_saveDef_clicked()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(!item)
return;
// for the 'new...' just trigger an edit and let the user do it that way. This reduces
// duplication, avoids need for a prompt for the name, and educates the user that they can edit
// directly
if(ui->savedList->indexOfTopLevelItem(item) == ui->savedList->topLevelItemCount() - 1)
{
ui->savedList->editItem(item);
return;
}
QString name = item->text(0);
QMessageBox::StandardButton res = RDDialog::question(
this, tr("Updating definition"),
tr("Are you sure you wish to overwrite definition '%1'?").arg(name), RDDialog::YesNoCancel);
if(res != QMessageBox::Yes)
return;
globalFormatList->setFormat(name,
QString::fromUtf8(formatText->getText(formatText->textLength() + 1)));
}
void BufferFormatSpecifier::on_delDef_clicked()
{
RDTreeWidgetItem *item = ui->savedList->selectedItem();
if(!item)
return;
QString name = item->text(0);
QMessageBox::StandardButton res = RDDialog::question(
this, tr("Deleting definition"),
tr("Are you sure you wish to delete definition '%1'?").arg(name), RDDialog::YesNoCancel);
if(res != QMessageBox::Yes)
return;
ui->savedList->clearSelection();
globalFormatList->setFormat(name, QString());
}
void BufferFormatSpecifier::on_apply_clicked()
{
setErrors({});
emit processFormat(QString::fromUtf8(formatText->getText(formatText->textLength() + 1)));
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#ifdef _WIN32
#include <io.h>
#include <windows.h>
#endif
#include "disk_interface.h"
#include "graph.h"
#include "test.h"
namespace {
class DiskInterfaceTest : public testing::Test {
public:
virtual void SetUp() {
// These tests do real disk accesses, so create a temp dir.
temp_dir_.CreateAndEnter("Ninja-DiskInterfaceTest");
}
virtual void TearDown() {
temp_dir_.Cleanup();
}
bool Touch(const char* path) {
FILE *f = fopen(path, "w");
if (!f)
return false;
return fclose(f) == 0;
}
ScopedTempDir temp_dir_;
RealDiskInterface disk_;
};
TEST_F(DiskInterfaceTest, StatMissingFile) {
EXPECT_EQ(0, disk_.Stat("nosuchfile"));
// On Windows, the errno for a file in a nonexistent directory
// is different.
EXPECT_EQ(0, disk_.Stat("nosuchdir/nosuchfile"));
// On POSIX systems, the errno is different if a component of the
// path prefix is not a directory.
ASSERT_TRUE(Touch("notadir"));
EXPECT_EQ(0, disk_.Stat("notadir/nosuchfile"));
}
TEST_F(DiskInterfaceTest, StatBadPath) {
// To test the error code path, use an overlong file name.
// Both Windows and Linux appear to object to this.
string too_long_name(512, 'x');
EXPECT_EQ(-1, disk_.Stat(too_long_name));
}
TEST_F(DiskInterfaceTest, StatExistingFile) {
ASSERT_TRUE(Touch("file"));
EXPECT_GT(disk_.Stat("file"), 1);
}
TEST_F(DiskInterfaceTest, ReadFile) {
string err;
EXPECT_EQ("", disk_.ReadFile("foobar", &err));
EXPECT_EQ("", err);
const char* kTestFile = "testfile";
FILE* f = fopen(kTestFile, "wb");
ASSERT_TRUE(f);
const char* kTestContent = "test content\nok";
fprintf(f, "%s", kTestContent);
ASSERT_EQ(0, fclose(f));
EXPECT_EQ(kTestContent, disk_.ReadFile(kTestFile, &err));
EXPECT_EQ("", err);
}
TEST_F(DiskInterfaceTest, MakeDirs) {
EXPECT_TRUE(disk_.MakeDirs("path/with/double//slash/"));
}
TEST_F(DiskInterfaceTest, RemoveFile) {
const char* kFileName = "file-to-remove";
ASSERT_TRUE(Touch(kFileName));
EXPECT_EQ(0, disk_.RemoveFile(kFileName));
EXPECT_EQ(1, disk_.RemoveFile(kFileName));
EXPECT_EQ(1, disk_.RemoveFile("does not exist"));
}
struct StatTest : public StateTestWithBuiltinRules,
public DiskInterface {
// DiskInterface implementation.
virtual TimeStamp Stat(const string& path);
virtual bool WriteFile(const string& path, const string & contents) {
assert(false);
return true;
}
virtual bool MakeDir(const string& path) {
assert(false);
return false;
}
virtual string ReadFile(const string& path, string* err) {
assert(false);
return "";
}
virtual int RemoveFile(const string& path) {
assert(false);
return 0;
}
map<string, TimeStamp> mtimes_;
vector<string> stats_;
};
TimeStamp StatTest::Stat(const string& path) {
stats_.push_back(path);
map<string, TimeStamp>::iterator i = mtimes_.find(path);
if (i == mtimes_.end())
return 0; // File not found.
return i->second;
}
TEST_F(StatTest, Simple) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat in\n"));
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_EQ(2u, stats_.size());
ASSERT_EQ("out", stats_[0]);
ASSERT_EQ("in", stats_[1]);
}
TEST_F(StatTest, TwoStep) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n"));
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_EQ(3u, stats_.size());
ASSERT_EQ("out", stats_[0]);
ASSERT_TRUE(GetNode("out")->dirty());
ASSERT_EQ("mid", stats_[1]);
ASSERT_TRUE(GetNode("mid")->dirty());
ASSERT_EQ("in", stats_[2]);
}
TEST_F(StatTest, Tree) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat mid1 mid2\n"
"build mid1: cat in11 in12\n"
"build mid2: cat in21 in22\n"));
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_EQ(1u + 6u, stats_.size());
ASSERT_EQ("mid1", stats_[1]);
ASSERT_TRUE(GetNode("mid1")->dirty());
ASSERT_EQ("in11", stats_[2]);
}
TEST_F(StatTest, Middle) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n"));
mtimes_["in"] = 1;
mtimes_["mid"] = 0; // missing
mtimes_["out"] = 1;
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_FALSE(GetNode("in")->dirty());
ASSERT_TRUE(GetNode("mid")->dirty());
ASSERT_TRUE(GetNode("out")->dirty());
}
} // namespace
<commit_msg>Fix StatBadPath for Windows 7<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#ifdef _WIN32
#include <io.h>
#include <windows.h>
#endif
#include "disk_interface.h"
#include "graph.h"
#include "test.h"
namespace {
class DiskInterfaceTest : public testing::Test {
public:
virtual void SetUp() {
// These tests do real disk accesses, so create a temp dir.
temp_dir_.CreateAndEnter("Ninja-DiskInterfaceTest");
}
virtual void TearDown() {
temp_dir_.Cleanup();
}
bool Touch(const char* path) {
FILE *f = fopen(path, "w");
if (!f)
return false;
return fclose(f) == 0;
}
ScopedTempDir temp_dir_;
RealDiskInterface disk_;
};
TEST_F(DiskInterfaceTest, StatMissingFile) {
EXPECT_EQ(0, disk_.Stat("nosuchfile"));
// On Windows, the errno for a file in a nonexistent directory
// is different.
EXPECT_EQ(0, disk_.Stat("nosuchdir/nosuchfile"));
// On POSIX systems, the errno is different if a component of the
// path prefix is not a directory.
ASSERT_TRUE(Touch("notadir"));
EXPECT_EQ(0, disk_.Stat("notadir/nosuchfile"));
}
TEST_F(DiskInterfaceTest, StatBadPath) {
#ifdef _WIN32
string bad_path("cc:\\foo");
EXPECT_EQ(-1, disk_.Stat(bad_path));
#else
string too_long_name(512, 'x');
EXPECT_EQ(-1, disk_.Stat(too_long_name));
#endif
}
TEST_F(DiskInterfaceTest, StatExistingFile) {
ASSERT_TRUE(Touch("file"));
EXPECT_GT(disk_.Stat("file"), 1);
}
TEST_F(DiskInterfaceTest, ReadFile) {
string err;
EXPECT_EQ("", disk_.ReadFile("foobar", &err));
EXPECT_EQ("", err);
const char* kTestFile = "testfile";
FILE* f = fopen(kTestFile, "wb");
ASSERT_TRUE(f);
const char* kTestContent = "test content\nok";
fprintf(f, "%s", kTestContent);
ASSERT_EQ(0, fclose(f));
EXPECT_EQ(kTestContent, disk_.ReadFile(kTestFile, &err));
EXPECT_EQ("", err);
}
TEST_F(DiskInterfaceTest, MakeDirs) {
EXPECT_TRUE(disk_.MakeDirs("path/with/double//slash/"));
}
TEST_F(DiskInterfaceTest, RemoveFile) {
const char* kFileName = "file-to-remove";
ASSERT_TRUE(Touch(kFileName));
EXPECT_EQ(0, disk_.RemoveFile(kFileName));
EXPECT_EQ(1, disk_.RemoveFile(kFileName));
EXPECT_EQ(1, disk_.RemoveFile("does not exist"));
}
struct StatTest : public StateTestWithBuiltinRules,
public DiskInterface {
// DiskInterface implementation.
virtual TimeStamp Stat(const string& path);
virtual bool WriteFile(const string& path, const string & contents) {
assert(false);
return true;
}
virtual bool MakeDir(const string& path) {
assert(false);
return false;
}
virtual string ReadFile(const string& path, string* err) {
assert(false);
return "";
}
virtual int RemoveFile(const string& path) {
assert(false);
return 0;
}
map<string, TimeStamp> mtimes_;
vector<string> stats_;
};
TimeStamp StatTest::Stat(const string& path) {
stats_.push_back(path);
map<string, TimeStamp>::iterator i = mtimes_.find(path);
if (i == mtimes_.end())
return 0; // File not found.
return i->second;
}
TEST_F(StatTest, Simple) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat in\n"));
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_EQ(2u, stats_.size());
ASSERT_EQ("out", stats_[0]);
ASSERT_EQ("in", stats_[1]);
}
TEST_F(StatTest, TwoStep) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n"));
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_EQ(3u, stats_.size());
ASSERT_EQ("out", stats_[0]);
ASSERT_TRUE(GetNode("out")->dirty());
ASSERT_EQ("mid", stats_[1]);
ASSERT_TRUE(GetNode("mid")->dirty());
ASSERT_EQ("in", stats_[2]);
}
TEST_F(StatTest, Tree) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat mid1 mid2\n"
"build mid1: cat in11 in12\n"
"build mid2: cat in21 in22\n"));
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_EQ(1u + 6u, stats_.size());
ASSERT_EQ("mid1", stats_[1]);
ASSERT_TRUE(GetNode("mid1")->dirty());
ASSERT_EQ("in11", stats_[2]);
}
TEST_F(StatTest, Middle) {
ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n"));
mtimes_["in"] = 1;
mtimes_["mid"] = 0; // missing
mtimes_["out"] = 1;
Node* out = GetNode("out");
out->Stat(this);
ASSERT_EQ(1u, stats_.size());
out->in_edge()->RecomputeDirty(NULL, this, NULL);
ASSERT_FALSE(GetNode("in")->dirty());
ASSERT_TRUE(GetNode("mid")->dirty());
ASSERT_TRUE(GetNode("out")->dirty());
}
} // namespace
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// File: OutputFld.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: FLD file format output.
//
////////////////////////////////////////////////////////////////////////////////
#include <set>
#include <string>
using namespace std;
#include "OutputFld.h"
#include <LibUtilities/BasicUtils/FileSystem.h>
namespace Nektar
{
namespace Utilities
{
ModuleKey OutputFld::m_className[2] = {
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "fld"), OutputFld::create,
"Writes a Fld file."),
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "chk"), OutputFld::create,
"Writes a Fld file."),
};
OutputFld::OutputFld(FieldSharedPtr f) : OutputModule(f)
{
}
OutputFld::~OutputFld()
{
}
void OutputFld::Process(po::variables_map &vm)
{
// Extract the output filename and extension
string filename = m_config["outfile"].as<string>();
if (m_f->m_writeBndFld)
{
ModuleKey module;
// Extract data to boundaryconditions
if (m_f->m_fldToBnd) {
for (int i = 0; i < m_f->m_exp.size(); ++i)
{
m_f->m_exp[i]->FillBndCondFromField();
}
}
if (m_f->m_verbose)
{
cout << "OutputFld: Writing boundary file(s): ";
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
if(i < m_f->m_bndRegionsToWrite.size()-1)
{
cout << ",";
}
}
cout << endl;
}
int nfields = m_f->m_exp.size();
Array<OneD, Array<OneD, const MultiRegions::ExpListSharedPtr> >
BndExp(nfields);
for (int i = 0; i < nfields; ++i)
{
BndExp[i] = m_f->m_exp[i]->GetBndCondExpansions();
}
// get hold of partition boundary regions so we can match it to desired
// region extraction
SpatialDomains::BoundaryConditions bcs(m_f->m_session,
m_f->m_exp[0]->GetGraph());
const SpatialDomains::BoundaryRegionCollection bregions =
bcs.GetBoundaryRegions();
SpatialDomains::BoundaryRegionCollection::const_iterator breg_it;
map<int,int> BndRegionMap;
int cnt =0;
for(breg_it = bregions.begin(); breg_it != bregions.end();
++breg_it, ++cnt)
{
BndRegionMap[breg_it->first] = cnt;
}
// find ending of output file and insert _b1, _b2
int dot = filename.find_last_of('.') + 1;
string ext = filename.substr(dot, filename.length() - dot);
string name = filename.substr(0, dot-1);
LibUtilities::BndRegionOrdering BndOrder =
m_f->m_session->GetBndRegionOrdering();
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
string outname = name + "_b"
+ boost::lexical_cast<string>(m_f->m_bndRegionsToWrite[i])
+ "." + ext;
std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef;
std::vector<std::vector<NekDouble> > FieldData;
if(BndRegionMap.count(m_f->m_bndRegionsToWrite[i]) == 1)
{
int Border = BndRegionMap[m_f->m_bndRegionsToWrite[i]];
FieldDef = BndExp[0][Border]->GetFieldDefinitions();
FieldData.resize(FieldDef.size());
for (int j = 0; j < nfields; ++j)
{
for (int k = 0; k < FieldDef.size(); ++k)
{
BndExp[j][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
if (m_f->m_fielddef.size() > 0)
{
FieldDef[k]->m_fields.push_back(
m_f->m_fielddef[0]->m_fields[j]);
}
else
{
FieldDef[k]->m_fields.push_back(
m_f->m_session->GetVariable(j));
}
}
}
if(m_f->m_addNormals)
{
ASSERTL0(m_f->m_exp[0]->GetCoordim(0) == 3,
"Add normals to extracted boundaries only set up in 3 dimensions");
int normdim = 3; // currently assuming 3D normals;
string normstr[3] = {"Norm_x","Norm_y","Norm_z"};
// Add normal information
StdRegions::StdExpansionSharedPtr elmt;
StdRegions::StdExpansion2DSharedPtr bc;
Array<OneD, int> BoundarytoElmtID, BoundarytoTraceID;
m_f->m_exp[0]->GetBoundaryToElmtMap(BoundarytoElmtID,
BoundarytoTraceID);
// determine offset of this Bnd Expansion Border
int cnt = 0;
for(int n = 0; n < Border; ++n)
{
cnt += BndExp[0][n]->GetExpSize();
}
Array<OneD, NekDouble> tmp_array;
Array<OneD, Array<OneD, NekDouble> > NormCoeff(normdim);
for(int j = 0; j < normdim; ++j)
{
NormCoeff[j] = Array<OneD, NekDouble>(BndExp[0][Border]->GetNcoeffs(),0.0);
}
// setup coeff arrays of normals.
for(int j = 0; j < BndExp[0][Border]->GetExpSize();
++j, cnt++)
{
// find element and face of this expansion.
int elmtid = BoundarytoElmtID[cnt];
elmt = m_f->m_exp[0]->GetExp(elmtid);
// Get face 2D expansion from element expansion
bc = boost::dynamic_pointer_cast<StdRegions::StdExpansion2D> (BndExp[0][Border]->GetExp(j));
//identify boundary of element looking at.
int boundary = BoundarytoTraceID[cnt];
//Get face normals
const Array<OneD, const Array<OneD, NekDouble> > normals = elmt->GetFaceNormal(boundary);
for(int k = 0; k < normdim; ++k)
{
bc->FwdTrans(normals[k],tmp_array = NormCoeff[k]+BndExp[0][Border]->GetCoeff_Offset(j));
}
}
// add normal coefficients to list to be dumped
for (int j = 0; j < normdim; ++j)
{
Vmath::Vcopy(BndExp[0][Border]->GetNcoeffs(),
NormCoeff[j],1,
BndExp[0][Border]->UpdateCoeffs(),1);
for (int k = 0; k < FieldDef.size(); ++k)
{
BndExp[0][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
FieldDef[k]->m_fields.push_back(normstr[j]);
}
}
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < nfields; ++j)
{
BndExp[j][Border]->BwdTrans(BndExp[j][Border]->GetCoeffs(),
BndExp[j][Border]->UpdatePhys());
//Note currently these calls will
//hange since not all partitions will
//call error.
NekDouble l2err = BndExp[j][Border]
->L2(BndExp[j][Border]->GetPhys());
NekDouble linferr = BndExp[j][Border]
->Linf(BndExp[j][Border]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
m_f->m_fld->Write(outname, FieldDef, FieldData,
m_f->m_fieldMetaDataMap);
}
}
else
{
if (m_f->m_verbose)
{
cout << "OutputFld: Writing file..." << endl;
}
fs::path writefile(filename);
bool writefld = true;
if(fs::exists(writefile)&&(vm.count("forceoutput") == 0))
{
string answer;
cout << "Did you wish to overwrite " << filename << " (y/n)? ";
getline(cin,answer);
if(answer.compare("y") != 0)
{
writefld = false;
cout << "Not writing file " << filename << " because it already exists" << endl;
}
}
if(writefld == true)
{
m_f->m_fld->Write(filename, m_f->m_fielddef, m_f->m_data);
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < m_f->m_exp.size(); ++j)
{
if (m_f->m_exp[j]->GetPhysState() == false)
{
m_f->m_exp[j]->BwdTrans(
m_f->m_exp[j]->GetCoeffs(),
m_f->m_exp[j]->UpdatePhys());
}
NekDouble l2err = m_f->m_exp[j]->L2(
m_f->m_exp[j]->GetPhys());
NekDouble linferr = m_f->m_exp[j]->Linf(
m_f->m_exp[j]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
}
}
}
<commit_msg>Added comm::block call around the output check to overwrite an existing fld file<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// File: OutputFld.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: FLD file format output.
//
////////////////////////////////////////////////////////////////////////////////
#include <set>
#include <string>
using namespace std;
#include "OutputFld.h"
#include <LibUtilities/BasicUtils/FileSystem.h>
namespace Nektar
{
namespace Utilities
{
ModuleKey OutputFld::m_className[2] = {
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "fld"), OutputFld::create,
"Writes a Fld file."),
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "chk"), OutputFld::create,
"Writes a Fld file."),
};
OutputFld::OutputFld(FieldSharedPtr f) : OutputModule(f)
{
}
OutputFld::~OutputFld()
{
}
void OutputFld::Process(po::variables_map &vm)
{
// Extract the output filename and extension
string filename = m_config["outfile"].as<string>();
if (m_f->m_writeBndFld)
{
ModuleKey module;
// Extract data to boundaryconditions
if (m_f->m_fldToBnd) {
for (int i = 0; i < m_f->m_exp.size(); ++i)
{
m_f->m_exp[i]->FillBndCondFromField();
}
}
if (m_f->m_verbose)
{
cout << "OutputFld: Writing boundary file(s): ";
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
if(i < m_f->m_bndRegionsToWrite.size()-1)
{
cout << ",";
}
}
cout << endl;
}
int nfields = m_f->m_exp.size();
Array<OneD, Array<OneD, const MultiRegions::ExpListSharedPtr> >
BndExp(nfields);
for (int i = 0; i < nfields; ++i)
{
BndExp[i] = m_f->m_exp[i]->GetBndCondExpansions();
}
// get hold of partition boundary regions so we can match it to desired
// region extraction
SpatialDomains::BoundaryConditions bcs(m_f->m_session,
m_f->m_exp[0]->GetGraph());
const SpatialDomains::BoundaryRegionCollection bregions =
bcs.GetBoundaryRegions();
SpatialDomains::BoundaryRegionCollection::const_iterator breg_it;
map<int,int> BndRegionMap;
int cnt =0;
for(breg_it = bregions.begin(); breg_it != bregions.end();
++breg_it, ++cnt)
{
BndRegionMap[breg_it->first] = cnt;
}
// find ending of output file and insert _b1, _b2
int dot = filename.find_last_of('.') + 1;
string ext = filename.substr(dot, filename.length() - dot);
string name = filename.substr(0, dot-1);
LibUtilities::BndRegionOrdering BndOrder =
m_f->m_session->GetBndRegionOrdering();
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
string outname = name + "_b"
+ boost::lexical_cast<string>(m_f->m_bndRegionsToWrite[i])
+ "." + ext;
std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef;
std::vector<std::vector<NekDouble> > FieldData;
if(BndRegionMap.count(m_f->m_bndRegionsToWrite[i]) == 1)
{
int Border = BndRegionMap[m_f->m_bndRegionsToWrite[i]];
FieldDef = BndExp[0][Border]->GetFieldDefinitions();
FieldData.resize(FieldDef.size());
for (int j = 0; j < nfields; ++j)
{
for (int k = 0; k < FieldDef.size(); ++k)
{
BndExp[j][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
if (m_f->m_fielddef.size() > 0)
{
FieldDef[k]->m_fields.push_back(
m_f->m_fielddef[0]->m_fields[j]);
}
else
{
FieldDef[k]->m_fields.push_back(
m_f->m_session->GetVariable(j));
}
}
}
if(m_f->m_addNormals)
{
ASSERTL0(m_f->m_exp[0]->GetCoordim(0) == 3,
"Add normals to extracted boundaries only set up in 3 dimensions");
int normdim = 3; // currently assuming 3D normals;
string normstr[3] = {"Norm_x","Norm_y","Norm_z"};
// Add normal information
StdRegions::StdExpansionSharedPtr elmt;
StdRegions::StdExpansion2DSharedPtr bc;
Array<OneD, int> BoundarytoElmtID, BoundarytoTraceID;
m_f->m_exp[0]->GetBoundaryToElmtMap(BoundarytoElmtID,
BoundarytoTraceID);
// determine offset of this Bnd Expansion Border
int cnt = 0;
for(int n = 0; n < Border; ++n)
{
cnt += BndExp[0][n]->GetExpSize();
}
Array<OneD, NekDouble> tmp_array;
Array<OneD, Array<OneD, NekDouble> > NormCoeff(normdim);
for(int j = 0; j < normdim; ++j)
{
NormCoeff[j] = Array<OneD, NekDouble>(BndExp[0][Border]->GetNcoeffs(),0.0);
}
// setup coeff arrays of normals.
for(int j = 0; j < BndExp[0][Border]->GetExpSize();
++j, cnt++)
{
// find element and face of this expansion.
int elmtid = BoundarytoElmtID[cnt];
elmt = m_f->m_exp[0]->GetExp(elmtid);
// Get face 2D expansion from element expansion
bc = boost::dynamic_pointer_cast<StdRegions::StdExpansion2D> (BndExp[0][Border]->GetExp(j));
//identify boundary of element looking at.
int boundary = BoundarytoTraceID[cnt];
//Get face normals
const Array<OneD, const Array<OneD, NekDouble> > normals = elmt->GetFaceNormal(boundary);
for(int k = 0; k < normdim; ++k)
{
bc->FwdTrans(normals[k],tmp_array = NormCoeff[k]+BndExp[0][Border]->GetCoeff_Offset(j));
}
}
// add normal coefficients to list to be dumped
for (int j = 0; j < normdim; ++j)
{
Vmath::Vcopy(BndExp[0][Border]->GetNcoeffs(),
NormCoeff[j],1,
BndExp[0][Border]->UpdateCoeffs(),1);
for (int k = 0; k < FieldDef.size(); ++k)
{
BndExp[0][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
FieldDef[k]->m_fields.push_back(normstr[j]);
}
}
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < nfields; ++j)
{
BndExp[j][Border]->BwdTrans(BndExp[j][Border]->GetCoeffs(),
BndExp[j][Border]->UpdatePhys());
//Note currently these calls will
//hange since not all partitions will
//call error.
NekDouble l2err = BndExp[j][Border]
->L2(BndExp[j][Border]->GetPhys());
NekDouble linferr = BndExp[j][Border]
->Linf(BndExp[j][Border]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
m_f->m_fld->Write(outname, FieldDef, FieldData,
m_f->m_fieldMetaDataMap);
}
}
else
{
if (m_f->m_verbose)
{
cout << "OutputFld: Writing file..." << endl;
}
fs::path writefile(filename);
bool writefld = true;
if(fs::exists(writefile)&&(vm.count("forceoutput") == 0))
{
LibUtilities::CommSharedPtr comm = m_f->m_session->GetComm();
int rank = comm->GetRank();
if(rank == 0)
{
string answer;
cout << "Did you wish to overwrite " << filename << " (y/n)? ";
getline(cin,answer);
if(answer.compare("y") != 0)
{
writefld = false;
cout << "Not writing file " << filename << " because it already exists" << endl;
}
}
comm->Block();
}
if(writefld == true)
{
m_f->m_fld->Write(filename, m_f->m_fielddef, m_f->m_data);
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < m_f->m_exp.size(); ++j)
{
if (m_f->m_exp[j]->GetPhysState() == false)
{
m_f->m_exp[j]->BwdTrans(
m_f->m_exp[j]->GetCoeffs(),
m_f->m_exp[j]->UpdatePhys());
}
NekDouble l2err = m_f->m_exp[j]->L2(
m_f->m_exp[j]->GetPhys());
NekDouble linferr = m_f->m_exp[j]->Linf(
m_f->m_exp[j]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
}
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// File: OutputFld.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: FLD file format output.
//
////////////////////////////////////////////////////////////////////////////////
#include <set>
#include <string>
using namespace std;
#include "OutputFld.h"
#include <LibUtilities/BasicUtils/FileSystem.h>
namespace Nektar
{
namespace Utilities
{
ModuleKey OutputFld::m_className[2] = {
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "fld"), OutputFld::create,
"Writes a Fld file."),
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "chk"), OutputFld::create,
"Writes a Fld file."),
};
OutputFld::OutputFld(FieldSharedPtr f) : OutputModule(f)
{
}
OutputFld::~OutputFld()
{
}
void OutputFld::Process(po::variables_map &vm)
{
// Extract the output filename and extension
string filename = m_config["outfile"].as<string>();
if (m_f->m_writeBndFld)
{
ModuleKey module;
// Extract data to boundaryconditions
if (m_f->m_fldToBnd) {
for (int i = 0; i < m_f->m_exp.size(); ++i)
{
m_f->m_exp[i]->FillBndCondFromField();
}
}
if (m_f->m_verbose)
{
cout << "OutputFld: Writing boundary file(s): ";
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
if(i < m_f->m_bndRegionsToWrite.size()-1)
{
cout << ",";
}
}
cout << endl;
}
int nfields = m_f->m_exp.size();
Array<OneD, Array<OneD, const MultiRegions::ExpListSharedPtr> >
BndExp(nfields);
for (int i = 0; i < nfields; ++i)
{
BndExp[i] = m_f->m_exp[i]->GetBndCondExpansions();
}
// get hold of partition boundary regions so we can match it to desired
// region extraction
SpatialDomains::BoundaryConditions bcs(m_f->m_session,
m_f->m_exp[0]->GetGraph());
const SpatialDomains::BoundaryRegionCollection bregions =
bcs.GetBoundaryRegions();
SpatialDomains::BoundaryRegionCollection::const_iterator breg_it;
map<int,int> BndRegionMap;
int cnt =0;
for(breg_it = bregions.begin(); breg_it != bregions.end();
++breg_it, ++cnt)
{
BndRegionMap[breg_it->first] = cnt;
}
// find ending of output file and insert _b1, _b2
int dot = filename.find_last_of('.') + 1;
string ext = filename.substr(dot, filename.length() - dot);
string name = filename.substr(0, dot-1);
LibUtilities::BndRegionOrdering BndOrder =
m_f->m_session->GetBndRegionOrdering();
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
string outname = name + "_b"
+ boost::lexical_cast<string>(m_f->m_bndRegionsToWrite[i])
+ "." + ext;
std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef;
std::vector<std::vector<NekDouble> > FieldData;
if(BndRegionMap.count(m_f->m_bndRegionsToWrite[i]) == 1)
{
int Border = BndRegionMap[m_f->m_bndRegionsToWrite[i]];
FieldDef = BndExp[0][Border]->GetFieldDefinitions();
FieldData.resize(FieldDef.size());
for (int j = 0; j < nfields; ++j)
{
for (int k = 0; k < FieldDef.size(); ++k)
{
BndExp[j][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
FieldDef[k]->m_fields.push_back(m_f->m_fielddef[0]->
m_fields[j]);
}
}
if(m_f->m_addNormals)
{
ASSERTL0(m_f->m_exp[0]->GetCoordim(0) == 3,
"Add normals to extracted boundaries only set up in 3 dimensions");
int normdim = 3; // currently assuming 3D normals;
string normstr[3] = {"Norm_x","Norm_y","Norm_z"};
// Add normal information
StdRegions::StdExpansionSharedPtr elmt;
StdRegions::StdExpansion2DSharedPtr bc;
Array<OneD, int> BoundarytoElmtID, BoundarytoTraceID;
m_f->m_exp[0]->GetBoundaryToElmtMap(BoundarytoElmtID,
BoundarytoTraceID);
// determine offset of this Bnd Expansion Border
int cnt = 0;
for(int n = 0; n < Border; ++n)
{
cnt += BndExp[0][n]->GetExpSize();
}
Array<OneD, NekDouble> tmp_array;
Array<OneD, Array<OneD, NekDouble> > NormCoeff(normdim);
for(int j = 0; j < normdim; ++j)
{
NormCoeff[j] = Array<OneD, NekDouble>(BndExp[0][Border]->GetNcoeffs(),0.0);
}
// setup coeff arrays of normals.
for(int j = 0; j < BndExp[0][Border]->GetExpSize();
++j, cnt++)
{
// find element and face of this expansion.
int elmtid = BoundarytoElmtID[cnt];
elmt = m_f->m_exp[0]->GetExp(elmtid);
// Get face 2D expansion from element expansion
bc = boost::dynamic_pointer_cast<StdRegions::StdExpansion2D> (BndExp[0][Border]->GetExp(j));
//identify boundary of element looking at.
int boundary = BoundarytoTraceID[cnt];
//Get face normals
const Array<OneD, const Array<OneD, NekDouble> > normals = elmt->GetFaceNormal(boundary);
for(int k = 0; k < normdim; ++k)
{
bc->FwdTrans(normals[k],tmp_array = NormCoeff[k]+BndExp[0][Border]->GetCoeff_Offset(j));
}
}
// add normal coefficients to list to be dumped
for (int j = 0; j < normdim; ++j)
{
Vmath::Vcopy(BndExp[0][Border]->GetNcoeffs(),
NormCoeff[j],1,
BndExp[0][Border]->UpdateCoeffs(),1);
for (int k = 0; k < FieldDef.size(); ++k)
{
int st = FieldData[k].size();
BndExp[0][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
FieldDef[k]->m_fields.push_back(normstr[j]);
}
}
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < nfields; ++j)
{
BndExp[j][Border]->BwdTrans(BndExp[j][Border]->GetCoeffs(),
BndExp[j][Border]->UpdatePhys());
//Note currently these calls will
//hange since not all partitions will
//call error.
NekDouble l2err = BndExp[j][Border]
->L2(BndExp[j][Border]->GetPhys());
NekDouble linferr = BndExp[j][Border]
->Linf(BndExp[j][Border]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
m_f->m_fld->Write(outname, FieldDef, FieldData,
m_f->m_fieldMetaDataMap);
}
}
else
{
if (m_f->m_verbose)
{
cout << "OutputFld: Writing file..." << endl;
}
fs::path writefile(filename);
bool writefld = true;
if(fs::exists(writefile)&&(vm.count("forceoutput") == 0))
{
string answer;
cout << "Did you wish to overwrite " << filename << " (y/n)? ";
getline(cin,answer);
if(answer.compare("y") != 0)
{
writefld = false;
cout << "Not writing file " << filename << " because it already exists" << endl;
}
}
if(writefld == true)
{
m_f->m_fld->Write(filename, m_f->m_fielddef, m_f->m_data);
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < m_f->m_exp.size(); ++j)
{
if (m_f->m_exp[j]->GetPhysState() == false)
{
m_f->m_exp[j]->BwdTrans(
m_f->m_exp[j]->GetCoeffs(),
m_f->m_exp[j]->UpdatePhys());
}
NekDouble l2err = m_f->m_exp[j]->L2(
m_f->m_exp[j]->GetPhys());
NekDouble linferr = m_f->m_exp[j]->Linf(
m_f->m_exp[j]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
}
}
}
<commit_msg>Removed unneeded string<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// File: OutputFld.cpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: FLD file format output.
//
////////////////////////////////////////////////////////////////////////////////
#include <set>
#include <string>
using namespace std;
#include "OutputFld.h"
#include <LibUtilities/BasicUtils/FileSystem.h>
namespace Nektar
{
namespace Utilities
{
ModuleKey OutputFld::m_className[2] = {
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "fld"), OutputFld::create,
"Writes a Fld file."),
GetModuleFactory().RegisterCreatorFunction(
ModuleKey(eOutputModule, "chk"), OutputFld::create,
"Writes a Fld file."),
};
OutputFld::OutputFld(FieldSharedPtr f) : OutputModule(f)
{
}
OutputFld::~OutputFld()
{
}
void OutputFld::Process(po::variables_map &vm)
{
// Extract the output filename and extension
string filename = m_config["outfile"].as<string>();
if (m_f->m_writeBndFld)
{
ModuleKey module;
// Extract data to boundaryconditions
if (m_f->m_fldToBnd) {
for (int i = 0; i < m_f->m_exp.size(); ++i)
{
m_f->m_exp[i]->FillBndCondFromField();
}
}
if (m_f->m_verbose)
{
cout << "OutputFld: Writing boundary file(s): ";
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
if(i < m_f->m_bndRegionsToWrite.size()-1)
{
cout << ",";
}
}
cout << endl;
}
int nfields = m_f->m_exp.size();
Array<OneD, Array<OneD, const MultiRegions::ExpListSharedPtr> >
BndExp(nfields);
for (int i = 0; i < nfields; ++i)
{
BndExp[i] = m_f->m_exp[i]->GetBndCondExpansions();
}
// get hold of partition boundary regions so we can match it to desired
// region extraction
SpatialDomains::BoundaryConditions bcs(m_f->m_session,
m_f->m_exp[0]->GetGraph());
const SpatialDomains::BoundaryRegionCollection bregions =
bcs.GetBoundaryRegions();
SpatialDomains::BoundaryRegionCollection::const_iterator breg_it;
map<int,int> BndRegionMap;
int cnt =0;
for(breg_it = bregions.begin(); breg_it != bregions.end();
++breg_it, ++cnt)
{
BndRegionMap[breg_it->first] = cnt;
}
// find ending of output file and insert _b1, _b2
int dot = filename.find_last_of('.') + 1;
string ext = filename.substr(dot, filename.length() - dot);
string name = filename.substr(0, dot-1);
LibUtilities::BndRegionOrdering BndOrder =
m_f->m_session->GetBndRegionOrdering();
for(int i = 0; i < m_f->m_bndRegionsToWrite.size(); ++i)
{
string outname = name + "_b"
+ boost::lexical_cast<string>(m_f->m_bndRegionsToWrite[i])
+ "." + ext;
std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef;
std::vector<std::vector<NekDouble> > FieldData;
if(BndRegionMap.count(m_f->m_bndRegionsToWrite[i]) == 1)
{
int Border = BndRegionMap[m_f->m_bndRegionsToWrite[i]];
FieldDef = BndExp[0][Border]->GetFieldDefinitions();
FieldData.resize(FieldDef.size());
for (int j = 0; j < nfields; ++j)
{
for (int k = 0; k < FieldDef.size(); ++k)
{
BndExp[j][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
FieldDef[k]->m_fields.push_back(m_f->m_fielddef[0]->
m_fields[j]);
}
}
if(m_f->m_addNormals)
{
ASSERTL0(m_f->m_exp[0]->GetCoordim(0) == 3,
"Add normals to extracted boundaries only set up in 3 dimensions");
int normdim = 3; // currently assuming 3D normals;
string normstr[3] = {"Norm_x","Norm_y","Norm_z"};
// Add normal information
StdRegions::StdExpansionSharedPtr elmt;
StdRegions::StdExpansion2DSharedPtr bc;
Array<OneD, int> BoundarytoElmtID, BoundarytoTraceID;
m_f->m_exp[0]->GetBoundaryToElmtMap(BoundarytoElmtID,
BoundarytoTraceID);
// determine offset of this Bnd Expansion Border
int cnt = 0;
for(int n = 0; n < Border; ++n)
{
cnt += BndExp[0][n]->GetExpSize();
}
Array<OneD, NekDouble> tmp_array;
Array<OneD, Array<OneD, NekDouble> > NormCoeff(normdim);
for(int j = 0; j < normdim; ++j)
{
NormCoeff[j] = Array<OneD, NekDouble>(BndExp[0][Border]->GetNcoeffs(),0.0);
}
// setup coeff arrays of normals.
for(int j = 0; j < BndExp[0][Border]->GetExpSize();
++j, cnt++)
{
// find element and face of this expansion.
int elmtid = BoundarytoElmtID[cnt];
elmt = m_f->m_exp[0]->GetExp(elmtid);
// Get face 2D expansion from element expansion
bc = boost::dynamic_pointer_cast<StdRegions::StdExpansion2D> (BndExp[0][Border]->GetExp(j));
//identify boundary of element looking at.
int boundary = BoundarytoTraceID[cnt];
//Get face normals
const Array<OneD, const Array<OneD, NekDouble> > normals = elmt->GetFaceNormal(boundary);
for(int k = 0; k < normdim; ++k)
{
bc->FwdTrans(normals[k],tmp_array = NormCoeff[k]+BndExp[0][Border]->GetCoeff_Offset(j));
}
}
// add normal coefficients to list to be dumped
for (int j = 0; j < normdim; ++j)
{
Vmath::Vcopy(BndExp[0][Border]->GetNcoeffs(),
NormCoeff[j],1,
BndExp[0][Border]->UpdateCoeffs(),1);
for (int k = 0; k < FieldDef.size(); ++k)
{
BndExp[0][Border]->AppendFieldData(FieldDef[k],
FieldData[k]);
FieldDef[k]->m_fields.push_back(normstr[j]);
}
}
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < nfields; ++j)
{
BndExp[j][Border]->BwdTrans(BndExp[j][Border]->GetCoeffs(),
BndExp[j][Border]->UpdatePhys());
//Note currently these calls will
//hange since not all partitions will
//call error.
NekDouble l2err = BndExp[j][Border]
->L2(BndExp[j][Border]->GetPhys());
NekDouble linferr = BndExp[j][Border]
->Linf(BndExp[j][Border]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< FieldDef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
m_f->m_fld->Write(outname, FieldDef, FieldData,
m_f->m_fieldMetaDataMap);
}
}
else
{
if (m_f->m_verbose)
{
cout << "OutputFld: Writing file..." << endl;
}
fs::path writefile(filename);
bool writefld = true;
if(fs::exists(writefile)&&(vm.count("forceoutput") == 0))
{
string answer;
cout << "Did you wish to overwrite " << filename << " (y/n)? ";
getline(cin,answer);
if(answer.compare("y") != 0)
{
writefld = false;
cout << "Not writing file " << filename << " because it already exists" << endl;
}
}
if(writefld == true)
{
m_f->m_fld->Write(filename, m_f->m_fielddef, m_f->m_data);
}
// output error for regression checking.
if (vm.count("error"))
{
int rank = m_f->m_session->GetComm()->GetRank();
for (int j = 0; j < m_f->m_exp.size(); ++j)
{
if (m_f->m_exp[j]->GetPhysState() == false)
{
m_f->m_exp[j]->BwdTrans(
m_f->m_exp[j]->GetCoeffs(),
m_f->m_exp[j]->UpdatePhys());
}
NekDouble l2err = m_f->m_exp[j]->L2(
m_f->m_exp[j]->GetPhys());
NekDouble linferr = m_f->m_exp[j]->Linf(
m_f->m_exp[j]->GetPhys());
if (rank == 0)
{
cout << "L 2 error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << l2err << endl;
cout << "L inf error (variable "
<< m_f->m_fielddef[0]->m_fields[j]
<< ") : " << linferr << endl;
}
}
}
}
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: XglrRen.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <math.h>
#include <iostream.h>
#include "XglrProp.hh"
#include "XglrCam.hh"
#include "XglrLgt.hh"
#include "XglrRenW.hh"
#include "XglrRen.hh"
#include "XglrPoly.hh"
#include "XglrTri.hh"
#include "XglrLine.hh"
#include "XglrPnt.hh"
#include "VolRen.hh"
vlXglrRenderer::vlXglrRenderer()
{
}
// Description:
// Ask actors to build and draw themselves.
int vlXglrRenderer::UpdateActors()
{
vlActor *anActor;
float visibility;
vlMatrix4x4 matrix;
int count = 0;
Xgl_trans model_trans;
// loop through actors
for ( this->Actors.InitTraversal(); anActor = this->Actors.GetNextItem(); )
{
// if it's invisible, we can skip the rest
visibility = anActor->GetVisibility();
if (visibility == 1.0)
{
count++;
// build transformation
anActor->GetMatrix(matrix);
// shold we transpose this matrix ?
matrix.Transpose();
// insert model transformation
xgl_object_get(this->Context,
XGL_CTX_GLOBAL_MODEL_TRANS, &model_trans);
xgl_transform_write(model_trans,(float (*)[4])(matrix[0]));
anActor->Render((vlRenderer *)this);
}
}
return count;
}
// Description:
// Ask active camera to load its view matrix.
int vlXglrRenderer::UpdateCameras ()
{
// update the viewing transformation
if (!this->ActiveCamera) return 0;
this->ActiveCamera->Render((vlRenderer *)this);
return 1;
}
// Description:
// Ask lights to load themselves into graphics pipeline.
int vlXglrRenderer::UpdateLights ()
{
vlLight *light;
short cur_light, idx;
float status;
int count = 0;
Xgl_boolean xglr_switches[MAX_LIGHTS];
Xgl_color light_color;
// first get the lights and switched from the context
xgl_object_get(this->Context,XGL_3D_CTX_LIGHTS, this->XglrLights);
xgl_object_get(this->Context,XGL_3D_CTX_LIGHT_SWITCHES, xglr_switches);
// update the ambient light light# 0
light_color.rgb.r = this->Ambient[0];
light_color.rgb.g = this->Ambient[1];
light_color.rgb.b = this->Ambient[2];
xgl_object_set(this->XglrLights[0],
XGL_LIGHT_TYPE, XGL_LIGHT_AMBIENT,
XGL_LIGHT_COLOR, &light_color,
NULL);
// set all lights off except the ambient light
xglr_switches[0] = TRUE;
for (idx = 1; idx < MAX_LIGHTS; idx++)
{
xglr_switches[idx] = FALSE;
}
cur_light = 1;
for ( this->Lights.InitTraversal(); light = this->Lights.GetNextItem(); )
{
status = light->GetSwitch();
// if the light is on then define it and bind it.
// also make sure we still have room.
if ((status > 0.0)&& (cur_light < MAX_LIGHTS))
{
light->Render((vlRenderer *)this,cur_light);
xglr_switches[cur_light] = TRUE;
// increment the current light by one
cur_light++;
count++;
// and do the same for the mirror source if backlit is on
// and we aren't out of lights
if ((this->BackLight > 0.0) &&
(cur_light < MAX_LIGHTS))
{
xglr_switches[cur_light] = TRUE;
// if backlighting is on then increment the current light again
cur_light++;
}
}
}
// now update the context
xgl_object_set(this->Context,
XGL_3D_CTX_LIGHT_SWITCHES, xglr_switches,
NULL);
this->NumberOfLightsBound = cur_light;
return count;
}
// Description:
// Concrete starbase render method.
void vlXglrRenderer::Render(void)
{
vlXglrRenderWindow *temp;
// update our Context first
temp = (vlXglrRenderWindow *)this->GetRenderWindow();
this->Context = *(temp->GetContext());
// standard render method
this->DoCameras();
this->DoLights();
this->DoActors();
if (this->VolumeRenderer)
{
this->VolumeRenderer->Render((vlRenderer *)this);
}
}
// Description:
// Create particular type of starbase geometry primitive.
vlGeometryPrimitive *vlXglrRenderer::GetPrimitive(char *type)
{
vlGeometryPrimitive *prim;
if (!strcmp(type,"polygons"))
{
prim = new vlXglrPolygons;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"triangle_strips"))
{
prim = new vlXglrTriangleMesh;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"lines"))
{
prim = new vlXglrLines;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"points"))
{
prim = new vlXglrPoints;
return (vlGeometryPrimitive *)prim;
}
return((vlGeometryPrimitive *)NULL);
}
void vlXglrRenderer::PrintSelf(ostream& os, vlIndent indent)
{
this->vlRenderer::PrintSelf(os,indent);
os << indent << "Number Of Lights Bound: " <<
this->NumberOfLightsBound << "\n";
}
<commit_msg>added start and end render methods<commit_after>/*=========================================================================
Program: Visualization Library
Module: XglrRen.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <math.h>
#include <iostream.h>
#include "XglrProp.hh"
#include "XglrCam.hh"
#include "XglrLgt.hh"
#include "XglrRenW.hh"
#include "XglrRen.hh"
#include "XglrPoly.hh"
#include "XglrTri.hh"
#include "XglrLine.hh"
#include "XglrPnt.hh"
#include "VolRen.hh"
vlXglrRenderer::vlXglrRenderer()
{
}
// Description:
// Ask actors to build and draw themselves.
int vlXglrRenderer::UpdateActors()
{
vlActor *anActor;
float visibility;
vlMatrix4x4 matrix;
int count = 0;
Xgl_trans model_trans;
// loop through actors
for ( this->Actors.InitTraversal(); anActor = this->Actors.GetNextItem(); )
{
// if it's invisible, we can skip the rest
visibility = anActor->GetVisibility();
if (visibility == 1.0)
{
count++;
// build transformation
anActor->GetMatrix(matrix);
// shold we transpose this matrix ?
matrix.Transpose();
// insert model transformation
xgl_object_get(this->Context,
XGL_CTX_GLOBAL_MODEL_TRANS, &model_trans);
xgl_transform_write(model_trans,(float (*)[4])(matrix[0]));
anActor->Render((vlRenderer *)this);
}
}
return count;
}
// Description:
// Ask active camera to load its view matrix.
int vlXglrRenderer::UpdateCameras ()
{
// update the viewing transformation
if (!this->ActiveCamera) return 0;
this->ActiveCamera->Render((vlRenderer *)this);
return 1;
}
// Description:
// Ask lights to load themselves into graphics pipeline.
int vlXglrRenderer::UpdateLights ()
{
vlLight *light;
short cur_light, idx;
float status;
int count = 0;
Xgl_boolean xglr_switches[MAX_LIGHTS];
Xgl_color light_color;
// first get the lights and switched from the context
xgl_object_get(this->Context,XGL_3D_CTX_LIGHTS, this->XglrLights);
xgl_object_get(this->Context,XGL_3D_CTX_LIGHT_SWITCHES, xglr_switches);
// update the ambient light light# 0
light_color.rgb.r = this->Ambient[0];
light_color.rgb.g = this->Ambient[1];
light_color.rgb.b = this->Ambient[2];
xgl_object_set(this->XglrLights[0],
XGL_LIGHT_TYPE, XGL_LIGHT_AMBIENT,
XGL_LIGHT_COLOR, &light_color,
NULL);
// set all lights off except the ambient light
xglr_switches[0] = TRUE;
for (idx = 1; idx < MAX_LIGHTS; idx++)
{
xglr_switches[idx] = FALSE;
}
cur_light = 1;
for ( this->Lights.InitTraversal(); light = this->Lights.GetNextItem(); )
{
status = light->GetSwitch();
// if the light is on then define it and bind it.
// also make sure we still have room.
if ((status > 0.0)&& (cur_light < MAX_LIGHTS))
{
light->Render((vlRenderer *)this,cur_light);
xglr_switches[cur_light] = TRUE;
// increment the current light by one
cur_light++;
count++;
// and do the same for the mirror source if backlit is on
// and we aren't out of lights
if ((this->BackLight > 0.0) &&
(cur_light < MAX_LIGHTS))
{
xglr_switches[cur_light] = TRUE;
// if backlighting is on then increment the current light again
cur_light++;
}
}
}
// now update the context
xgl_object_set(this->Context,
XGL_3D_CTX_LIGHT_SWITCHES, xglr_switches,
NULL);
this->NumberOfLightsBound = cur_light;
return count;
}
// Description:
// Concrete starbase render method.
void vlXglrRenderer::Render(void)
{
vlXglrRenderWindow *temp;
if (this->StartRenderMethod)
{
(*this->StartRenderMethod)(this->StartRenderMethodArg);
}
// update our Context first
temp = (vlXglrRenderWindow *)this->GetRenderWindow();
this->Context = *(temp->GetContext());
// standard render method
this->DoCameras();
this->DoLights();
this->DoActors();
if (this->VolumeRenderer)
{
this->VolumeRenderer->Render((vlRenderer *)this);
}
if (this->EndRenderMethod)
{
(*this->EndRenderMethod)(this->EndRenderMethodArg);
}
}
// Description:
// Create particular type of starbase geometry primitive.
vlGeometryPrimitive *vlXglrRenderer::GetPrimitive(char *type)
{
vlGeometryPrimitive *prim;
if (!strcmp(type,"polygons"))
{
prim = new vlXglrPolygons;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"triangle_strips"))
{
prim = new vlXglrTriangleMesh;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"lines"))
{
prim = new vlXglrLines;
return (vlGeometryPrimitive *)prim;
}
if (!strcmp(type,"points"))
{
prim = new vlXglrPoints;
return (vlGeometryPrimitive *)prim;
}
return((vlGeometryPrimitive *)NULL);
}
void vlXglrRenderer::PrintSelf(ostream& os, vlIndent indent)
{
this->vlRenderer::PrintSelf(os,indent);
os << indent << "Number Of Lights Bound: " <<
this->NumberOfLightsBound << "\n";
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "NewRemoteParameterUpdater.h"
#include "Trainer.h"
#include "paddle/utils/Stat.h"
DECLARE_int32(trainer_id);
DECLARE_string(save_dir);
namespace paddle {
NewRemoteParameterUpdater::NewRemoteParameterUpdater(
const OptimizationConfig &config, const std::string pserverSpec)
: trainerConfig_(config),
parameterClient_(-1),
newParameters_(nullptr),
newGradients_(nullptr),
pserverSpec_(pserverSpec) {}
NewRemoteParameterUpdater::NewRemoteParameterUpdater(
const OptimizationConfig &config,
const std::string pserverSpec,
const bool useEtcd)
: trainerConfig_(config),
parameterClient_(-1),
newParameters_(nullptr),
newGradients_(nullptr),
pserverSpec_(pserverSpec),
useEtcd_(useEtcd) {}
void NewRemoteParameterUpdater::init(
const std::vector<ParameterPtr> ¶meters) {
ParameterUpdater::init(parameters);
for (auto ¶ : parameters_) {
para->getBuf(PARAMETER_VALUE)->zeroMem();
para->getBuf(PARAMETER_GRADIENT)->zeroMem();
}
// create parameter server client.
if (useEtcd_) {
parameterClient_ = paddle_new_etcd_pserver_client(
(char *)pserverSpec_.c_str());
} else {
parameterClient_ = paddle_new_pserver_client((char *)pserverSpec_.c_str(),
FLAGS_trainer_id == 0);
}
// init new parameter and gradient.
newParameters_ = initNewParameter(PARAMETER_VALUE);
newGradients_ = initNewParameter(PARAMETER_GRADIENT);
// init parameter, one trainer will get the opportunity to int parameter and
// send them to parameter server. Others will get the initialized parameter
// from parameter server
if (paddle_begin_init_params(parameterClient_)) {
LOG(INFO) << "paddle_begin_init_params start";
for (int i = 0; i < parameterSize(); ++i) {
auto paramConfig = parameters_[i]->getConfig();
LOG(INFO) << "old param config: " << paramConfig.DebugString();
// FIXME(typhoonzero): convert old paramConfig to optimizerConfig
OptimizerConfig optimizeConfigV2;
auto sgdConfigV2 = optimizeConfigV2.mutable_sgd();
sgdConfigV2->set_momentum(paramConfig.momentum());
sgdConfigV2->set_decay(paramConfig.decay_rate());
optimizeConfigV2.set_lr_policy(paddle::OptimizerConfig::Const);
auto constlr = optimizeConfigV2.mutable_const_lr();
if (paramConfig.has_learning_rate()) {
constlr->set_learning_rate(paramConfig.learning_rate());
} else {
constlr->set_learning_rate(trainerConfig_.learning_rate());
}
if (trainerConfig_.algorithm() == "sgd") {
optimizeConfigV2.set_optimizer(paddle::OptimizerConfig::SGD);
// FIXME: config all algorithms
} else {
optimizeConfigV2.set_optimizer(paddle::OptimizerConfig::SGD);
}
std::string bytes = optimizeConfigV2.SerializeAsString();
const char *array = bytes.data();
int size = (int)bytes.size();
paddle_init_param(
parameterClient_, *newParameters_[i], (void *)array, size);
}
paddle_finish_init_params(parameterClient_);
LOG(INFO) << "paddle_begin_init_params done";
} else {
paddle_get_params(parameterClient_, newParameters_, parameterSize());
}
LOG(INFO) << "NewRemoteParameterUpdater initialized";
}
void NewRemoteParameterUpdater::updateImpl(Parameter *para) {}
void NewRemoteParameterUpdater::finishBatch(real cost) {
// send gradient to parameter server.
paddle_send_grads(parameterClient_, newGradients_, parameterSize());
// get the updated parameter from parameterClient.
paddle_get_params(parameterClient_, newParameters_, parameterSize());
// clear gradient after update parameter.
for (auto ¶ : parameters_) {
para->getBuf(PARAMETER_GRADIENT)->zeroMem();
}
}
void NewRemoteParameterUpdater::startPass() {}
bool NewRemoteParameterUpdater::finishPass() { return true; }
} // namespace paddle
<commit_msg>fix style check<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 "NewRemoteParameterUpdater.h"
#include "Trainer.h"
#include "paddle/utils/Stat.h"
DECLARE_int32(trainer_id);
DECLARE_string(save_dir);
namespace paddle {
NewRemoteParameterUpdater::NewRemoteParameterUpdater(
const OptimizationConfig &config, const std::string pserverSpec)
: trainerConfig_(config),
parameterClient_(-1),
newParameters_(nullptr),
newGradients_(nullptr),
pserverSpec_(pserverSpec) {}
NewRemoteParameterUpdater::NewRemoteParameterUpdater(
const OptimizationConfig &config,
const std::string pserverSpec,
const bool useEtcd)
: trainerConfig_(config),
parameterClient_(-1),
newParameters_(nullptr),
newGradients_(nullptr),
pserverSpec_(pserverSpec),
useEtcd_(useEtcd) {}
void NewRemoteParameterUpdater::init(
const std::vector<ParameterPtr> ¶meters) {
ParameterUpdater::init(parameters);
for (auto ¶ : parameters_) {
para->getBuf(PARAMETER_VALUE)->zeroMem();
para->getBuf(PARAMETER_GRADIENT)->zeroMem();
}
// create parameter server client.
if (useEtcd_) {
parameterClient_ =
paddle_new_etcd_pserver_client((char *)pserverSpec_.c_str());
} else {
parameterClient_ = paddle_new_pserver_client((char *)pserverSpec_.c_str(),
FLAGS_trainer_id == 0);
}
// init new parameter and gradient.
newParameters_ = initNewParameter(PARAMETER_VALUE);
newGradients_ = initNewParameter(PARAMETER_GRADIENT);
// init parameter, one trainer will get the opportunity to int parameter and
// send them to parameter server. Others will get the initialized parameter
// from parameter server
if (paddle_begin_init_params(parameterClient_)) {
LOG(INFO) << "paddle_begin_init_params start";
for (int i = 0; i < parameterSize(); ++i) {
auto paramConfig = parameters_[i]->getConfig();
LOG(INFO) << "old param config: " << paramConfig.DebugString();
// FIXME(typhoonzero): convert old paramConfig to optimizerConfig
OptimizerConfig optimizeConfigV2;
auto sgdConfigV2 = optimizeConfigV2.mutable_sgd();
sgdConfigV2->set_momentum(paramConfig.momentum());
sgdConfigV2->set_decay(paramConfig.decay_rate());
optimizeConfigV2.set_lr_policy(paddle::OptimizerConfig::Const);
auto constlr = optimizeConfigV2.mutable_const_lr();
if (paramConfig.has_learning_rate()) {
constlr->set_learning_rate(paramConfig.learning_rate());
} else {
constlr->set_learning_rate(trainerConfig_.learning_rate());
}
if (trainerConfig_.algorithm() == "sgd") {
optimizeConfigV2.set_optimizer(paddle::OptimizerConfig::SGD);
// FIXME: config all algorithms
} else {
optimizeConfigV2.set_optimizer(paddle::OptimizerConfig::SGD);
}
std::string bytes = optimizeConfigV2.SerializeAsString();
const char *array = bytes.data();
int size = (int)bytes.size();
paddle_init_param(
parameterClient_, *newParameters_[i], (void *)array, size);
}
paddle_finish_init_params(parameterClient_);
LOG(INFO) << "paddle_begin_init_params done";
} else {
paddle_get_params(parameterClient_, newParameters_, parameterSize());
}
LOG(INFO) << "NewRemoteParameterUpdater initialized";
}
void NewRemoteParameterUpdater::updateImpl(Parameter *para) {}
void NewRemoteParameterUpdater::finishBatch(real cost) {
// send gradient to parameter server.
paddle_send_grads(parameterClient_, newGradients_, parameterSize());
// get the updated parameter from parameterClient.
paddle_get_params(parameterClient_, newParameters_, parameterSize());
// clear gradient after update parameter.
for (auto ¶ : parameters_) {
para->getBuf(PARAMETER_GRADIENT)->zeroMem();
}
}
void NewRemoteParameterUpdater::startPass() {}
bool NewRemoteParameterUpdater::finishPass() { return true; }
} // namespace paddle
<|endoftext|> |
<commit_before>/*
This file is part of KAddressbook.
Copyright (c) 2003 - 2003 Daniel Molkentin <molkentin@kde.org>
Tobias Koenig <tokoe@kde.org>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qfile.h>
#include <qregexp.h>
#include <kfiledialog.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ktempfile.h>
#include <kurl.h>
#include <kdebug.h>
#include "opera_xxport.h"
class OperaXXPortFactory : public XXPortFactory
{
public:
XXPortObject *xxportObject( KABC::AddressBook *ab, QWidget *parent, const char *name )
{
return new OperaXXPort( ab, parent, name );
}
};
extern "C"
{
void *init_libkaddrbk_opera_xxport()
{
return ( new OperaXXPortFactory() );
}
}
OperaXXPort::OperaXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )
: XXPortObject( ab, parent, name )
{
createImportAction( i18n( "Import Opera Addressbook..." ) );
}
KABC::AddresseeList OperaXXPort::importContacts( const QString& ) const
{
QString source = QDir::homeDirPath() + "/.opera/contacts.adr";
QFile file( source );
// sanity checks
if ( !file.open( IO_ReadOnly ) )
return KABC::AddresseeList();
QTextStream stream( &file );
stream.setEncoding( QTextStream::UnicodeUTF8 );
QString line, key, value;
bool parseContact = false;
KABC::Addressee *addr = 0L;
KABC::AddresseeList addrList;
while ( !stream.atEnd() ) {
line = stream.readLine();
line = line.stripWhiteSpace();
if ( line == QString::fromLatin1( "#CONTACT" ) ) {
parseContact = true;
addr = new KABC::Addressee;
continue;
} else if ( line.isEmpty() ) {
parseContact = false;
if ( addr && !addr->isEmpty() )
addrList.append( *addr );
delete addr;
addr = 0;
continue;
}
if ( parseContact == true ) {
int sep = line.find( '=' );
key = line.left( sep ).lower();
value = line.mid( sep + 1 );
if ( key == QString::fromLatin1( "name" ) )
addr->setNameFromString( value );
else if ( key == QString::fromLatin1( "mail" ) ) {
QStringList emails = QStringList::split( ",", value );
QStringList::Iterator it = emails.begin();
bool preferred = true;
for ( ; it != emails.end(); ++it ) {
addr->insertEmail( *it, preferred );
preferred = false;
}
} else if ( key == QString::fromLatin1( "phone" ) )
addr->insertPhoneNumber( KABC::PhoneNumber( value ) );
else if ( key == QString::fromLatin1( "fax" ) )
addr->insertPhoneNumber( KABC::PhoneNumber( value,
KABC::PhoneNumber::Fax | KABC::PhoneNumber::Home ) );
else if ( key == QString::fromLatin1( "postaladdress" ) ) {
KABC::Address address( KABC::Address::Home );
address.setLabel( value.replace( QRegExp( "\x02\x02" ), "\n" ) );
addr->insertAddress( address );
} else if ( key == QString::fromLatin1( "description" ) )
addr->setNote( value.replace( QRegExp( "\x02\x02" ), "\n" ) );
else if ( key == QString::fromLatin1( "url" ) )
addr->setUrl( value );
}
}
file.close();
return addrList;
}
#include "opera_xxport.moc"
<commit_msg><commit_after>/*
This file is part of KAddressbook.
Copyright (c) 2003 - 2003 Daniel Molkentin <molkentin@kde.org>
Tobias Koenig <tokoe@kde.org>
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qfile.h>
#include <qregexp.h>
#include <kfiledialog.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ktempfile.h>
#include <kurl.h>
#include <kdebug.h>
#include "opera_xxport.h"
class OperaXXPortFactory : public XXPortFactory
{
public:
XXPortObject *xxportObject( KABC::AddressBook *ab, QWidget *parent, const char *name )
{
return new OperaXXPort( ab, parent, name );
}
};
extern "C"
{
void *init_libkaddrbk_opera_xxport()
{
return ( new OperaXXPortFactory() );
}
}
OperaXXPort::OperaXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )
: XXPortObject( ab, parent, name )
{
createImportAction( i18n( "Import Opera Addressbook..." ) );
}
KABC::AddresseeList OperaXXPort::importContacts( const QString& ) const
{
QString source = QDir::homeDirPath() + "/.opera/contacts.adr";
QFile file( source );
// sanity checks
if ( !file.open( IO_ReadOnly ) )
return KABC::AddresseeList();
QTextStream stream( &file );
stream.setEncoding( QTextStream::UnicodeUTF8 );
QString line, key, value;
bool parseContact = false;
KABC::Addressee *addr = 0L;
KABC::AddresseeList addrList;
while ( !stream.atEnd() ) {
line = stream.readLine();
line = line.stripWhiteSpace();
if ( line == QString::fromLatin1( "#CONTACT" ) ) {
parseContact = true;
addr = new KABC::Addressee;
continue;
} else if ( line.isEmpty() ) {
parseContact = false;
if ( addr && !addr->isEmpty() )
addrList.append( *addr );
delete addr;
addr = 0;
continue;
}
if ( parseContact == true ) {
int sep = line.find( '=' );
key = line.left( sep ).lower();
value = line.mid( sep + 1 );
if ( key == QString::fromLatin1( "name" ) )
addr->setNameFromString( value );
else if ( key == QString::fromLatin1( "mail" ) ) {
QStringList emails = QStringList::split( ",", value );
QStringList::Iterator it = emails.begin();
bool preferred = true;
for ( ; it != emails.end(); ++it ) {
addr->insertEmail( *it, preferred );
preferred = false;
}
} else if ( key == QString::fromLatin1( "phone" ) )
addr->insertPhoneNumber( KABC::PhoneNumber( value ) );
else if ( key == QString::fromLatin1( "fax" ) )
addr->insertPhoneNumber( KABC::PhoneNumber( value,
KABC::PhoneNumber::Fax | KABC::PhoneNumber::Home ) );
else if ( key == QString::fromLatin1( "postaladdress" ) ) {
KABC::Address address( KABC::Address::Home );
address.setLabel( value.replace( QRegExp( "\x02\x02" ), "\n" ) );
addr->insertAddress( address );
} else if ( key == QString::fromLatin1( "description" ) )
addr->setNote( value.replace( QRegExp( "\x02\x02" ), "\n" ) );
else if ( key == QString::fromLatin1( "url" ) )
addr->setUrl( value );
else if ( key == QString::fromLatin1( "pictureurl" ) ) {
KABC::Picture pic( value );
addr->setPhoto( pic );
}
}
}
file.close();
return addrList;
}
#include "opera_xxport.moc"
<|endoftext|> |
<commit_before>#include <PCU.h>
#include "parma.h"
#include "diffMC/maximalIndependentSet/mis.h"
#include <parma_dcpart.h>
#include <limits>
namespace {
int numSharedSides(apf::Mesh* m) {
apf::MeshIterator *it = m->begin(m->getDimension()-1);
apf::MeshEntity* e;
int cnt = 0;
while( (e = m->iterate(it)) )
if( m->isShared(e) )
cnt++;
m->end(it);
return cnt;
}
int numBdryVtx(apf::Mesh* m, bool onlyShared=false) {
apf::MeshIterator *it = m->begin(0);
apf::MeshEntity* e;
int cnt = 0;
while( (e = m->iterate(it)) )
if( m->isShared(e) && (onlyShared || m->isOwned(e)) )
cnt++;
m->end(it);
return cnt;
}
int numMdlBdryVtx(apf::Mesh* m) {
const int dim = m->getDimension();
apf::MeshIterator *it = m->begin(0);
apf::MeshEntity* e;
int cnt = 0;
while( (e = m->iterate(it)) )
if( m->getModelType(m->toModel(e)) < dim )
cnt++;
m->end(it);
return cnt;
}
double getEntWeight(apf::Mesh* m, apf::MeshEntity* e, apf::MeshTag* w) {
assert(m->hasTag(e,w));
double weight;
m->getDoubleTag(e,w,&weight);
return weight;
}
void getStats(int& loc, long& tot, int& min, int& max, double& avg) {
min = max = loc;
tot = static_cast<long>(loc);
PCU_Min_Ints(&min, 1);
PCU_Max_Ints(&max, 1);
PCU_Add_Longs(&tot, 1);
avg = static_cast<double>(tot);
avg /= PCU_Comm_Peers();
}
}
void Parma_GetEntImbalance(apf::Mesh* mesh, double (*entImb)[4]) {
int dims;
double tot[4];
dims = mesh->getDimension() + 1;
for(int i=0; i < dims; i++)
tot[i] = (*entImb)[i] = mesh->count(i);
PCU_Add_Doubles(tot, dims);
PCU_Max_Doubles(*entImb, dims);
for(int i=0; i < dims; i++)
(*entImb)[i] /= (tot[i]/PCU_Comm_Peers());
for(int i=dims; i < 4; i++)
(*entImb)[i] = 1.0;
}
double Parma_GetWeightedEntImbalance(apf::Mesh* m, apf::MeshTag* w,
int dim) {
assert(dim >= 0 && dim <= 3);
apf::MeshIterator* it = m->begin(dim);
apf::MeshEntity* e;
double sum = 0;
while ((e = m->iterate(it)))
sum += getEntWeight(m, e, w);
m->end(it);
double max, tot;
max = tot = sum;
PCU_Add_Doubles(&tot, 1);
PCU_Max_Doubles(&max, 1);
return max/(tot/PCU_Comm_Peers());
}
void Parma_GetNeighborStats(apf::Mesh* m, int& max, double& avg, int& loc) {
apf::MeshIterator *it = m->begin(0);
apf::Parts neighbors;
apf::MeshEntity* e;
while ((e = m->iterate(it))) {
apf::Parts sharers;
m->getResidence(e,sharers);
neighbors.insert(sharers.begin(),sharers.end());
}
m->end(it);
loc = static_cast<int>(neighbors.size());
max = loc;
PCU_Max_Ints(&max,1);
double total = loc;
PCU_Add_Doubles(&total,1);
avg = total / PCU_Comm_Peers();
}
void Parma_GetOwnedBdryVtxStats(apf::Mesh* m, int& loc, long& tot, int& min,
int& max, double& avg) {
loc = numBdryVtx(m);
getStats(loc, tot, min, max, avg);
}
void Parma_GetSharedBdryVtxStats(apf::Mesh* m, int& loc, long& tot, int& min,
int& max, double& avg) {
bool onlyShared = true;
loc = numBdryVtx(m,onlyShared);
getStats(loc, tot, min, max, avg);
}
void Parma_GetMdlBdryVtxStats(apf::Mesh* m, int& loc, long& tot, int& min,
int& max, double& avg) {
loc = numMdlBdryVtx(m);
getStats(loc, tot, min, max, avg);
}
void Parma_GetDisconnectedStats(apf::Mesh* m, int& max, double& avg, int& loc) {
dcPart dc(m);
int tot = max = loc = dc.numDisconnectedComps();
PCU_Max_Ints(&max, 1);
PCU_Add_Ints(&tot, 1);
avg = static_cast<double>(tot)/PCU_Comm_Peers();
}
void Parma_ProcessDisconnectedParts(apf::Mesh* m) {
dcPart dc(m);
dc.fix();
}
void Parma_PrintPtnStats(apf::Mesh* m, std::string key, bool fine) {
PCU_Debug_Print("%s vtx %lu\n", key.c_str(), m->count(0));
PCU_Debug_Print("%s edge %lu\n", key.c_str(), m->count(1));
PCU_Debug_Print("%s face %lu\n", key.c_str(), m->count(2));
if( m->getDimension() == 3 )
PCU_Debug_Print("%s rgn %lu\n", key.c_str(), m->count(3));
int maxDc = 0;
double avgDc = 0;
int locDc = 0;
Parma_GetDisconnectedStats(m, maxDc, avgDc, locDc);
PCU_Debug_Print("%s dc %d\n", key.c_str(), locDc);
int maxNb = 0;
double avgNb = 0;
int locNb = 0;
Parma_GetNeighborStats(m, maxNb, avgNb, locNb);
PCU_Debug_Print("%s neighbors %d\n", key.c_str(), locNb);
int locV[3], minV[3], maxV[3];
long totV[3];
double avgV[3];
Parma_GetOwnedBdryVtxStats(m, locV[0], totV[0], minV[0], maxV[0], avgV[0]);
Parma_GetSharedBdryVtxStats(m, locV[1], totV[1], minV[1], maxV[1], avgV[1]);
Parma_GetMdlBdryVtxStats(m, locV[2], totV[2], minV[2], maxV[2], avgV[2]);
PCU_Debug_Print("%s ownedBdryVtx %d\n", key.c_str(), locV[0]);
PCU_Debug_Print("%s sharedBdryVtx %d\n", key.c_str(), locV[1]);
PCU_Debug_Print("%s mdlBdryVtx %d\n", key.c_str(), locV[2]);
int surf = numSharedSides(m);
double vol = static_cast<double>( m->count(m->getDimension()) );
double minSurfToVol, maxSurfToVol, avgSurfToVol, surfToVol;
minSurfToVol = maxSurfToVol = avgSurfToVol = surfToVol = surf/vol;
PCU_Min_Doubles(&minSurfToVol, 1);
PCU_Max_Doubles(&maxSurfToVol, 1);
PCU_Add_Doubles(&avgSurfToVol, 1);
avgSurfToVol /= PCU_Comm_Peers();
PCU_Debug_Print("%s sharedSidesToElements %.3f\n", key.c_str(), surfToVol);
int empty = (m->count(m->getDimension()) == 0 ) ? 1 : 0;
PCU_Add_Ints(&empty, 1);
double imb[4] = {0, 0, 0, 0};
Parma_GetEntImbalance(m, &imb);
if (fine) {
fprintf(stdout, "FINE STATUS %s <Partid vtx rgn dc nb "
"owned_bdry shared_bdry model_bdry shSidesToElm > "
" %d %lu %lu %d %d %d %d %d %.3f\n",
key.c_str(), PCU_Comm_Self()+1, m->count(0), m->count(m->getDimension()),
locDc, locNb, locV[0], locV[1], locV[2], surf/(double)vol);
PCU_Barrier();
}
PCU_Debug_Print("%s vtxAdjacentNeighbors ", key.c_str());
apf::Parts peers;
apf::getPeers(m,0,peers);
APF_ITERATE(apf::Parts,peers,p)
PCU_Debug_Print("%d ", *p);
PCU_Debug_Print("\n");
if( 0 == PCU_Comm_Self() ) {
fprintf(stdout, "STATUS %s disconnected <max avg> %d %.3f\n",
key.c_str(), maxDc, avgDc);
fprintf(stdout, "STATUS %s neighbors <max avg> %d %.3f\n",
key.c_str(), maxNb, avgNb);
fprintf(stdout, "STATUS %s empty parts %d\n",
key.c_str(), empty);
fprintf(stdout, "STATUS %s owned bdry vtx <tot max min avg> "
"%ld %d %d %.3f\n",
key.c_str(), totV[0], maxV[0], minV[0], avgV[0]);
fprintf(stdout, "STATUS %s shared bdry vtx <tot max min avg> "
"%ld %d %d %.3f\n",
key.c_str(), totV[1], maxV[1], minV[1], avgV[1]);
fprintf(stdout, "STATUS %s model bdry vtx <tot max min avg> "
"%ld %d %d %.3f\n",
key.c_str(), totV[2], maxV[2], minV[2], avgV[2]);
fprintf(stdout, "STATUS %s sharedSidesToElements <max min avg> "
"%.3f %.3f %.3f\n",
key.c_str(), maxSurfToVol, minSurfToVol, avgSurfToVol);
fprintf(stdout, "STATUS %s entity imbalance <v e f r>: "
"%.2f %.2f %.2f %.2f\n", key.c_str(), imb[0], imb[1], imb[2], imb[3]);
}
}
apf::MeshTag* Parma_WeighByMemory(apf::Mesh* m) {
apf::MeshIterator* it = m->begin(m->getDimension());
apf::MeshEntity* e;
apf::MeshTag* tag = m->createDoubleTag("parma_bytes", 1);
while ((e = m->iterate(it))) {
double bytes = m->getElementBytes(m->getType(e));
m->setDoubleTag(e, tag, &bytes);
}
m->end(it);
return tag;
}
int Parma_MisNumbering(apf::Mesh* m, int d) {
apf::Parts neighbors;
apf::getPeers(m,d,neighbors);
misLuby::partInfo part;
part.id = m->getId();
part.net.push_back(m->getId());
APF_ITERATE(apf::Parts, neighbors, nItr) {
part.adjPartIds.push_back(*nItr);
part.net.push_back(*nItr);
}
unsigned int seed = static_cast<unsigned int>(part.id+1);
mis_init(seed);
int misNumber=-1;
int iter=0;
int misSize=0;
while( misSize != PCU_Comm_Peers() ) {
if( mis(part, false, true) || 1 == part.net.size() ) {
misNumber = iter;
part.net.clear();
part.adjPartIds.clear();
}
iter++;
misSize = (misNumber != -1);
PCU_Add_Ints(&misSize,1);
}
return misNumber;
}
<commit_msg>vtx stats from Parma_PrintPtnStats<commit_after>#include <PCU.h>
#include "parma.h"
#include "diffMC/maximalIndependentSet/mis.h"
#include <parma_dcpart.h>
#include <limits>
namespace {
int numSharedSides(apf::Mesh* m) {
apf::MeshIterator *it = m->begin(m->getDimension()-1);
apf::MeshEntity* e;
int cnt = 0;
while( (e = m->iterate(it)) )
if( m->isShared(e) )
cnt++;
m->end(it);
return cnt;
}
int numBdryVtx(apf::Mesh* m, bool onlyShared=false) {
apf::MeshIterator *it = m->begin(0);
apf::MeshEntity* e;
int cnt = 0;
while( (e = m->iterate(it)) )
if( m->isShared(e) && (onlyShared || m->isOwned(e)) )
cnt++;
m->end(it);
return cnt;
}
int numMdlBdryVtx(apf::Mesh* m) {
const int dim = m->getDimension();
apf::MeshIterator *it = m->begin(0);
apf::MeshEntity* e;
int cnt = 0;
while( (e = m->iterate(it)) )
if( m->getModelType(m->toModel(e)) < dim )
cnt++;
m->end(it);
return cnt;
}
double getEntWeight(apf::Mesh* m, apf::MeshEntity* e, apf::MeshTag* w) {
assert(m->hasTag(e,w));
double weight;
m->getDoubleTag(e,w,&weight);
return weight;
}
void getStats(int& loc, long& tot, int& min, int& max, double& avg) {
min = max = loc;
tot = static_cast<long>(loc);
PCU_Min_Ints(&min, 1);
PCU_Max_Ints(&max, 1);
PCU_Add_Longs(&tot, 1);
avg = static_cast<double>(tot);
avg /= PCU_Comm_Peers();
}
void vtxStats(apf::Mesh* m, long& tot, int& min, int& max, double& avg) {
int loc = m->count(0);
getStats(loc, tot, min, max, avg);
}
}
void Parma_GetEntImbalance(apf::Mesh* mesh, double (*entImb)[4]) {
int dims;
double tot[4];
dims = mesh->getDimension() + 1;
for(int i=0; i < dims; i++)
tot[i] = (*entImb)[i] = mesh->count(i);
PCU_Add_Doubles(tot, dims);
PCU_Max_Doubles(*entImb, dims);
for(int i=0; i < dims; i++)
(*entImb)[i] /= (tot[i]/PCU_Comm_Peers());
for(int i=dims; i < 4; i++)
(*entImb)[i] = 1.0;
}
double Parma_GetWeightedEntImbalance(apf::Mesh* m, apf::MeshTag* w,
int dim) {
assert(dim >= 0 && dim <= 3);
apf::MeshIterator* it = m->begin(dim);
apf::MeshEntity* e;
double sum = 0;
while ((e = m->iterate(it)))
sum += getEntWeight(m, e, w);
m->end(it);
double max, tot;
max = tot = sum;
PCU_Add_Doubles(&tot, 1);
PCU_Max_Doubles(&max, 1);
return max/(tot/PCU_Comm_Peers());
}
void Parma_GetNeighborStats(apf::Mesh* m, int& max, double& avg, int& loc) {
apf::MeshIterator *it = m->begin(0);
apf::Parts neighbors;
apf::MeshEntity* e;
while ((e = m->iterate(it))) {
apf::Parts sharers;
m->getResidence(e,sharers);
neighbors.insert(sharers.begin(),sharers.end());
}
m->end(it);
loc = static_cast<int>(neighbors.size());
max = loc;
PCU_Max_Ints(&max,1);
double total = loc;
PCU_Add_Doubles(&total,1);
avg = total / PCU_Comm_Peers();
}
void Parma_GetOwnedBdryVtxStats(apf::Mesh* m, int& loc, long& tot, int& min,
int& max, double& avg) {
loc = numBdryVtx(m);
getStats(loc, tot, min, max, avg);
}
void Parma_GetSharedBdryVtxStats(apf::Mesh* m, int& loc, long& tot, int& min,
int& max, double& avg) {
bool onlyShared = true;
loc = numBdryVtx(m,onlyShared);
getStats(loc, tot, min, max, avg);
}
void Parma_GetMdlBdryVtxStats(apf::Mesh* m, int& loc, long& tot, int& min,
int& max, double& avg) {
loc = numMdlBdryVtx(m);
getStats(loc, tot, min, max, avg);
}
void Parma_GetDisconnectedStats(apf::Mesh* m, int& max, double& avg, int& loc) {
dcPart dc(m);
int tot = max = loc = dc.numDisconnectedComps();
PCU_Max_Ints(&max, 1);
PCU_Add_Ints(&tot, 1);
avg = static_cast<double>(tot)/PCU_Comm_Peers();
}
void Parma_ProcessDisconnectedParts(apf::Mesh* m) {
dcPart dc(m);
dc.fix();
}
void Parma_PrintPtnStats(apf::Mesh* m, std::string key, bool fine) {
PCU_Debug_Print("%s vtx %lu\n", key.c_str(), m->count(0));
PCU_Debug_Print("%s edge %lu\n", key.c_str(), m->count(1));
PCU_Debug_Print("%s face %lu\n", key.c_str(), m->count(2));
if( m->getDimension() == 3 )
PCU_Debug_Print("%s rgn %lu\n", key.c_str(), m->count(3));
int maxDc = 0;
double avgDc = 0;
int locDc = 0;
Parma_GetDisconnectedStats(m, maxDc, avgDc, locDc);
PCU_Debug_Print("%s dc %d\n", key.c_str(), locDc);
int maxNb = 0;
double avgNb = 0;
int locNb = 0;
Parma_GetNeighborStats(m, maxNb, avgNb, locNb);
PCU_Debug_Print("%s neighbors %d\n", key.c_str(), locNb);
long totVtx = 0;
int minVtx = 0, maxVtx = 0;
double avgVtx = 0;
vtxStats(m, totVtx, minVtx, maxVtx, avgVtx);
int locV[3], minV[3], maxV[3];
long totV[3];
double avgV[3];
Parma_GetOwnedBdryVtxStats(m, locV[0], totV[0], minV[0], maxV[0], avgV[0]);
Parma_GetSharedBdryVtxStats(m, locV[1], totV[1], minV[1], maxV[1], avgV[1]);
Parma_GetMdlBdryVtxStats(m, locV[2], totV[2], minV[2], maxV[2], avgV[2]);
PCU_Debug_Print("%s ownedBdryVtx %d\n", key.c_str(), locV[0]);
PCU_Debug_Print("%s sharedBdryVtx %d\n", key.c_str(), locV[1]);
PCU_Debug_Print("%s mdlBdryVtx %d\n", key.c_str(), locV[2]);
int surf = numSharedSides(m);
double vol = static_cast<double>( m->count(m->getDimension()) );
double minSurfToVol, maxSurfToVol, avgSurfToVol, surfToVol;
minSurfToVol = maxSurfToVol = avgSurfToVol = surfToVol = surf/vol;
PCU_Min_Doubles(&minSurfToVol, 1);
PCU_Max_Doubles(&maxSurfToVol, 1);
PCU_Add_Doubles(&avgSurfToVol, 1);
avgSurfToVol /= PCU_Comm_Peers();
PCU_Debug_Print("%s sharedSidesToElements %.3f\n", key.c_str(), surfToVol);
int empty = (m->count(m->getDimension()) == 0 ) ? 1 : 0;
PCU_Add_Ints(&empty, 1);
double imb[4] = {0, 0, 0, 0};
Parma_GetEntImbalance(m, &imb);
if (fine) {
fprintf(stdout, "FINE STATUS %s <Partid vtx rgn dc nb "
"owned_bdry shared_bdry model_bdry shSidesToElm > "
" %d %lu %lu %d %d %d %d %d %.3f\n",
key.c_str(), PCU_Comm_Self()+1, m->count(0), m->count(m->getDimension()),
locDc, locNb, locV[0], locV[1], locV[2], surf/(double)vol);
PCU_Barrier();
}
PCU_Debug_Print("%s vtxAdjacentNeighbors ", key.c_str());
apf::Parts peers;
apf::getPeers(m,0,peers);
APF_ITERATE(apf::Parts,peers,p)
PCU_Debug_Print("%d ", *p);
PCU_Debug_Print("\n");
if( 0 == PCU_Comm_Self() ) {
fprintf(stdout, "STATUS %s disconnected <max avg> %d %.3f\n",
key.c_str(), maxDc, avgDc);
fprintf(stdout, "STATUS %s neighbors <max avg> %d %.3f\n",
key.c_str(), maxNb, avgNb);
fprintf(stdout, "STATUS %s empty parts %d\n",
key.c_str(), empty);
fprintf(stdout, "STATUS %s vtx <tot max min avg> "
"%ld %d %d %.3f\n",
key.c_str(), totVtx, maxVtx, minVtx, avgVtx);
fprintf(stdout, "STATUS %s owned bdry vtx <tot max min avg> "
"%ld %d %d %.3f\n",
key.c_str(), totV[0], maxV[0], minV[0], avgV[0]);
fprintf(stdout, "STATUS %s shared bdry vtx <tot max min avg> "
"%ld %d %d %.3f\n",
key.c_str(), totV[1], maxV[1], minV[1], avgV[1]);
fprintf(stdout, "STATUS %s model bdry vtx <tot max min avg> "
"%ld %d %d %.3f\n",
key.c_str(), totV[2], maxV[2], minV[2], avgV[2]);
fprintf(stdout, "STATUS %s sharedSidesToElements <max min avg> "
"%.3f %.3f %.3f\n",
key.c_str(), maxSurfToVol, minSurfToVol, avgSurfToVol);
fprintf(stdout, "STATUS %s entity imbalance <v e f r>: "
"%.2f %.2f %.2f %.2f\n", key.c_str(), imb[0], imb[1], imb[2], imb[3]);
}
}
apf::MeshTag* Parma_WeighByMemory(apf::Mesh* m) {
apf::MeshIterator* it = m->begin(m->getDimension());
apf::MeshEntity* e;
apf::MeshTag* tag = m->createDoubleTag("parma_bytes", 1);
while ((e = m->iterate(it))) {
double bytes = m->getElementBytes(m->getType(e));
m->setDoubleTag(e, tag, &bytes);
}
m->end(it);
return tag;
}
int Parma_MisNumbering(apf::Mesh* m, int d) {
apf::Parts neighbors;
apf::getPeers(m,d,neighbors);
misLuby::partInfo part;
part.id = m->getId();
part.net.push_back(m->getId());
APF_ITERATE(apf::Parts, neighbors, nItr) {
part.adjPartIds.push_back(*nItr);
part.net.push_back(*nItr);
}
unsigned int seed = static_cast<unsigned int>(part.id+1);
mis_init(seed);
int misNumber=-1;
int iter=0;
int misSize=0;
while( misSize != PCU_Comm_Peers() ) {
if( mis(part, false, true) || 1 == part.net.size() ) {
misNumber = iter;
part.net.clear();
part.adjPartIds.clear();
}
iter++;
misSize = (misNumber != -1);
PCU_Add_Ints(&misSize,1);
}
return misNumber;
}
<|endoftext|> |
<commit_before>#include <pqxx/stream_from>
#include <pqxx/transaction>
#include "../test_helpers.hxx"
namespace
{
auto make_focus(pqxx::dbtransaction &tx)
{
return pqxx::stream_from{tx, pqxx::from_query, "SELECT * from generate_series(1, 10)"};
}
void test_cannot_run_statement_during_focus()
{
pqxx::connection conn;
pqxx::transaction tx{conn};
tx.exec("SELECT 1");
auto focus{make_focus(tx)};
PQXX_CHECK_THROWS(
tx.exec("SELECT 1"), pqxx::usage_error,
"Command during focus did not throw expected error.");
}
void test_cannot_run_prepared_statement_during_focus()
{
pqxx::connection conn;
conn.prepare("foo", "SELECT 1");
pqxx::transaction tx{conn};
tx.exec_prepared("foo");
auto focus{make_focus(tx)};
PQXX_CHECK_THROWS(
tx.exec_prepared("foo"), pqxx::usage_error,
"Prepared statement during focus did not throw expected error.");
}
void test_cannot_run_params_statement_during_focus()
{
pqxx::connection conn;
pqxx::transaction tx{conn};
tx.exec_params("select $1", 10);
auto focus{make_focus(tx)};
PQXX_CHECK_THROWS(
tx.exec_params("select $1", 10), pqxx::usage_error,
"Parameterized statement during focus did not throw expected error.");
}
PQXX_REGISTER_TEST(test_cannot_run_statement_during_focus);
PQXX_REGISTER_TEST(test_cannot_run_prepared_statement_during_focus);
PQXX_REGISTER_TEST(test_cannot_run_params_statement_during_focus);
} // namespace
<commit_msg>Reformat.<commit_after>#include <pqxx/stream_from>
#include <pqxx/transaction>
#include "../test_helpers.hxx"
namespace
{
auto make_focus(pqxx::dbtransaction &tx)
{
return pqxx::stream_from{
tx, pqxx::from_query, "SELECT * from generate_series(1, 10)"};
}
void test_cannot_run_statement_during_focus()
{
pqxx::connection conn;
pqxx::transaction tx{conn};
tx.exec("SELECT 1");
auto focus{make_focus(tx)};
PQXX_CHECK_THROWS(
tx.exec("SELECT 1"), pqxx::usage_error,
"Command during focus did not throw expected error.");
}
void test_cannot_run_prepared_statement_during_focus()
{
pqxx::connection conn;
conn.prepare("foo", "SELECT 1");
pqxx::transaction tx{conn};
tx.exec_prepared("foo");
auto focus{make_focus(tx)};
PQXX_CHECK_THROWS(
tx.exec_prepared("foo"), pqxx::usage_error,
"Prepared statement during focus did not throw expected error.");
}
void test_cannot_run_params_statement_during_focus()
{
pqxx::connection conn;
pqxx::transaction tx{conn};
tx.exec_params("select $1", 10);
auto focus{make_focus(tx)};
PQXX_CHECK_THROWS(
tx.exec_params("select $1", 10), pqxx::usage_error,
"Parameterized statement during focus did not throw expected error.");
}
PQXX_REGISTER_TEST(test_cannot_run_statement_during_focus);
PQXX_REGISTER_TEST(test_cannot_run_prepared_statement_during_focus);
PQXX_REGISTER_TEST(test_cannot_run_params_statement_during_focus);
} // namespace
<|endoftext|> |
<commit_before>#include "Todo.h"
#include "TodoConfig.h"
#include "DataTypes.h"
#include "FileIO.h"
#include <rapidjson\document.h>
#include <rapidjson\prettywriter.h>
#include <rapidjson\stringbuffer.h>
Todo::Todo() {
todoConfig = new TodoConfig();
}
Todo::~Todo() {
delete todoConfig;
}
int Todo::getTodoCount(){
return m_todoCollection.size();
}
ToDoCategory Todo::getCategory(int _categoryID){
for (size_t i = 0; i < m_categories.size(); i++){
if (m_categories[i].id == _categoryID){
return m_categories[i];
}
}
throw -1;
}
void Todo::loadToDoFile(){
if (todoConfig == nullptr){
throw -2;
}
std::string fileContents = FileIO::readFile(todoConfig->getToDoFilePath());
rapidjson::Document doc;
doc.Parse(fileContents.c_str());
if (doc.HasParseError()){
throw -1;
}
rapidjson::Value *currJsonObj = &doc;
for (rapidjson::Value::MemberIterator memberItr = currJsonObj->MemberBegin(); memberItr != currJsonObj->MemberEnd(); ++memberItr) {
if (strcmp(memberItr->name.GetString(), "todo") == 0){
ToDoItem toDoItem;
rapidjson::Value *todoVal = &memberItr->value;
for (rapidjson::Value::MemberIterator todoItr = todoVal->MemberBegin(); todoItr != todoVal->MemberEnd(); ++todoItr) {
if (strcmp(todoItr->name.GetString(), "name") == 0 && todoItr->value.IsString()){
toDoItem.name = todoItr->value.GetString();
} else if (strcmp(todoItr->name.GetString(), "description") == 0 && todoItr->value.IsString()){
toDoItem.description = todoItr->value.GetString();
} else if (strcmp(todoItr->name.GetString(), "id") == 0 && todoItr->value.IsInt()){
toDoItem.id = todoItr->value.GetInt();
} else if (strcmp(todoItr->name.GetString(), "category_id") == 0 && todoItr->value.IsInt()){
toDoItem.categoryID = todoItr->value.GetInt();
} else if (strcmp(todoItr->name.GetString(), "completed") == 0 && todoItr->value.IsBool()){
toDoItem.completed = todoItr->value.GetBool();
}
}
m_todoCollection.push_back(toDoItem);
} else if (strcmp(memberItr->name.GetString(), "category") == 0){
ToDoCategory category;
rapidjson::Value *cateVal = &memberItr->value;
for (rapidjson::Value::MemberIterator cateItr = cateVal->MemberBegin(); cateItr != cateVal->MemberEnd(); ++cateItr) {
if (strcmp(cateItr->name.GetString(), "name") == 0 && cateItr->value.IsString()){
category.name = cateItr->value.GetString();
} else if (strcmp(cateItr->name.GetString(), "id") == 0 && cateItr->value.IsInt()){
category.id = cateItr->value.GetInt();
}
}
m_categories.push_back(category);
}
}
}
void Todo::saveToDoFile(){
rapidjson::StringBuffer sb;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
writer.StartObject();
for (size_t i = 0; i < m_todoCollection.size(); i++){
writer.Key("todo");
writer.StartObject();
writer.Key("id");
writer.Int(m_todoCollection[i].id);
writer.Key("category_id");
writer.Int(m_todoCollection[i].categoryID);
writer.Key("name");
writer.String(m_todoCollection[i].name.c_str());
writer.Key("description");
writer.String(m_todoCollection[i].description.c_str());
writer.Key("completed");
writer.Bool(m_todoCollection[i].completed);
writer.EndObject();
}
for (size_t i = 0; i < m_categories.size(); i++){
writer.Key("category");
writer.StartObject();
writer.Key("name");
writer.String(m_categories[i].name.c_str());
writer.Key("id");
writer.Int(m_categories[i].id);
writer.EndObject();
}
writer.EndObject();
FileIO::writeFile("todo.jsondb", sb.GetString(), FileIO::FileWriteType::WRITE);
}
void Todo::createNewToDoFile(std::string _filePath){
rapidjson::StringBuffer sb;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
writer.StartObject();
writer.EndObject();
FileIO::writeFile(_filePath, sb.GetString(), FileIO::FileWriteType::WRITE);
}
void Todo::printToDos(){
printToDos(false);
}
void Todo::printToDos(bool _verbose){
size_t todoSize = m_todoCollection.size();
printf("======= Things to Do ==========\n");
for (size_t i = 0; i < todoSize; i++){
if (i > 0 && i < todoSize) printf("---------------------------\n");
printf("%i. ", i + 1);
printToDoItem(m_todoCollection[i], _verbose);
}
printf("===============================\n");
}
void Todo::printToDos(int _categoryID){
printToDos(_categoryID, false);
}
void Todo::printToDos(int _categoryID, bool _verbose){
size_t todoSize = m_todoCollection.size();
ToDoCategory category;
try{
category = getCategory(_categoryID);
} catch (int e) {
if (e == -1){
printf("ERROR: Could not get category of id %i\n", _categoryID);
} else{
printf("ERROR: Unknown error getting category.\n");
}
return;
}
printf("========== Things to Do in Category: %s ==========\n", category.name.c_str());
int shownAmt = 0;
for (size_t i = 0; i < todoSize; i++){
if (m_todoCollection[i].categoryID == category.id){
if (shownAmt > 0 && i < todoSize) printf("---------------------------\n");
printf("%i. ", i + 1);
printToDoItem(m_todoCollection[i], _verbose);
shownAmt++;
}
}
printf("==================================================\n");
}
void Todo::printToDoItem(const ToDoItem& _toDoItem){
printToDoItem(_toDoItem, false);
}
void Todo::printToDoItem(const ToDoItem& _toDoItem, bool _verbose){
char *nameTag = "", *descriptionTag = "";
if (_verbose){
nameTag = "Name: ";
descriptionTag = "Description: ";
}
printf("[%s] %s%s\n", (_toDoItem.completed) ? "X" : " ", nameTag, _toDoItem.name.c_str());
printf("%s%s\n", descriptionTag, _toDoItem.description.c_str());
if (_verbose){
printf("Category ID: %i\n", _toDoItem.categoryID);
}
}
void Todo::printCategories(){
size_t categoriesSize = m_categories.size();
printf("======== Categories ===========\n");
for (size_t i = 0; i < categoriesSize; i++){
printf("[ID: %i] %s\n", m_categories[i].id, m_categories[i].name.c_str());
}
printf("===============================\n");
}
void Todo::addToDo(ToDoItem _toDoItem){
m_todoCollection.push_back(_toDoItem);
saveToDoFile();
}
void Todo::addCategory(std::string _name){
ToDoCategory categoryToAdd;
categoryToAdd.name = _name;
categoryToAdd.id = m_categories.size();
m_categories.push_back(categoryToAdd);
saveToDoFile();
}
void Todo::removeToDoByIndex(int _index){
if (_index < 0 || _index >= m_todoCollection.size()){
throw -1;
}
m_todoCollection.erase(m_todoCollection.begin() + _index);
saveToDoFile();
}
void Todo::removeAllToDos(){
m_todoCollection.clear();
saveToDoFile();
}
int Todo::removeCategory(int _categoryID){
ToDoCategory category;
try{
category = getCategory(_categoryID);
} catch (int e) {
if (e == -1){
printf("ERROR: Could not get category of id %i\n", _categoryID);
} else{
printf("ERROR: Unknown error getting category.\n");
}
return - 1;
}
for (std::vector<ToDoCategory>::iterator cateItr = m_categories.begin(); cateItr != m_categories.end(); cateItr++){
if (cateItr->id == _categoryID){
m_categories.erase(cateItr);
saveToDoFile();
return 0;
}
}
return -1;
}
void Todo::setToDoToCategory(int _toDoIndex, int _categoryID){
if (_toDoIndex < 0 || _toDoIndex >= m_todoCollection.size()){
throw -1;
}
m_todoCollection[_toDoIndex].categoryID = _categoryID;
saveToDoFile();
}
void Todo::markToDoCompleted(int _toDoIndex, bool _completed){
if (_toDoIndex < 0 || _toDoIndex >= m_todoCollection.size()){
throw -1;
}
m_todoCollection[_toDoIndex].completed = _completed;
saveToDoFile();
}<commit_msg>Fix todo not saving to config filepath.<commit_after>#include "Todo.h"
#include "TodoConfig.h"
#include "DataTypes.h"
#include "FileIO.h"
#include <rapidjson\document.h>
#include <rapidjson\prettywriter.h>
#include <rapidjson\stringbuffer.h>
Todo::Todo() {
todoConfig = new TodoConfig();
}
Todo::~Todo() {
delete todoConfig;
}
int Todo::getTodoCount(){
return m_todoCollection.size();
}
ToDoCategory Todo::getCategory(int _categoryID){
for (size_t i = 0; i < m_categories.size(); i++){
if (m_categories[i].id == _categoryID){
return m_categories[i];
}
}
throw -1;
}
void Todo::loadToDoFile(){
if (todoConfig == nullptr){
throw -2;
}
std::string fileContents = FileIO::readFile(todoConfig->getToDoFilePath());
rapidjson::Document doc;
doc.Parse(fileContents.c_str());
if (doc.HasParseError()){
throw -1;
}
rapidjson::Value *currJsonObj = &doc;
for (rapidjson::Value::MemberIterator memberItr = currJsonObj->MemberBegin(); memberItr != currJsonObj->MemberEnd(); ++memberItr) {
if (strcmp(memberItr->name.GetString(), "todo") == 0){
ToDoItem toDoItem;
rapidjson::Value *todoVal = &memberItr->value;
for (rapidjson::Value::MemberIterator todoItr = todoVal->MemberBegin(); todoItr != todoVal->MemberEnd(); ++todoItr) {
if (strcmp(todoItr->name.GetString(), "name") == 0 && todoItr->value.IsString()){
toDoItem.name = todoItr->value.GetString();
} else if (strcmp(todoItr->name.GetString(), "description") == 0 && todoItr->value.IsString()){
toDoItem.description = todoItr->value.GetString();
} else if (strcmp(todoItr->name.GetString(), "id") == 0 && todoItr->value.IsInt()){
toDoItem.id = todoItr->value.GetInt();
} else if (strcmp(todoItr->name.GetString(), "category_id") == 0 && todoItr->value.IsInt()){
toDoItem.categoryID = todoItr->value.GetInt();
} else if (strcmp(todoItr->name.GetString(), "completed") == 0 && todoItr->value.IsBool()){
toDoItem.completed = todoItr->value.GetBool();
}
}
m_todoCollection.push_back(toDoItem);
} else if (strcmp(memberItr->name.GetString(), "category") == 0){
ToDoCategory category;
rapidjson::Value *cateVal = &memberItr->value;
for (rapidjson::Value::MemberIterator cateItr = cateVal->MemberBegin(); cateItr != cateVal->MemberEnd(); ++cateItr) {
if (strcmp(cateItr->name.GetString(), "name") == 0 && cateItr->value.IsString()){
category.name = cateItr->value.GetString();
} else if (strcmp(cateItr->name.GetString(), "id") == 0 && cateItr->value.IsInt()){
category.id = cateItr->value.GetInt();
}
}
m_categories.push_back(category);
}
}
}
void Todo::saveToDoFile(){
if (todoConfig == nullptr){
throw -2;
}
rapidjson::StringBuffer sb;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
writer.StartObject();
for (size_t i = 0; i < m_todoCollection.size(); i++){
writer.Key("todo");
writer.StartObject();
writer.Key("id");
writer.Int(m_todoCollection[i].id);
writer.Key("category_id");
writer.Int(m_todoCollection[i].categoryID);
writer.Key("name");
writer.String(m_todoCollection[i].name.c_str());
writer.Key("description");
writer.String(m_todoCollection[i].description.c_str());
writer.Key("completed");
writer.Bool(m_todoCollection[i].completed);
writer.EndObject();
}
for (size_t i = 0; i < m_categories.size(); i++){
writer.Key("category");
writer.StartObject();
writer.Key("name");
writer.String(m_categories[i].name.c_str());
writer.Key("id");
writer.Int(m_categories[i].id);
writer.EndObject();
}
writer.EndObject();
FileIO::writeFile(todoConfig->getToDoFilePath(), sb.GetString(), FileIO::FileWriteType::WRITE);
}
void Todo::createNewToDoFile(std::string _filePath){
rapidjson::StringBuffer sb;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(sb);
writer.StartObject();
writer.EndObject();
FileIO::writeFile(_filePath, sb.GetString(), FileIO::FileWriteType::WRITE);
}
void Todo::printToDos(){
printToDos(false);
}
void Todo::printToDos(bool _verbose){
size_t todoSize = m_todoCollection.size();
printf("======= Things to Do ==========\n");
for (size_t i = 0; i < todoSize; i++){
if (i > 0 && i < todoSize) printf("---------------------------\n");
printf("%i. ", i + 1);
printToDoItem(m_todoCollection[i], _verbose);
}
printf("===============================\n");
}
void Todo::printToDos(int _categoryID){
printToDos(_categoryID, false);
}
void Todo::printToDos(int _categoryID, bool _verbose){
size_t todoSize = m_todoCollection.size();
ToDoCategory category;
try{
category = getCategory(_categoryID);
} catch (int e) {
if (e == -1){
printf("ERROR: Could not get category of id %i\n", _categoryID);
} else{
printf("ERROR: Unknown error getting category.\n");
}
return;
}
printf("========== Things to Do in Category: %s ==========\n", category.name.c_str());
int shownAmt = 0;
for (size_t i = 0; i < todoSize; i++){
if (m_todoCollection[i].categoryID == category.id){
if (shownAmt > 0 && i < todoSize) printf("---------------------------\n");
printf("%i. ", i + 1);
printToDoItem(m_todoCollection[i], _verbose);
shownAmt++;
}
}
printf("==================================================\n");
}
void Todo::printToDoItem(const ToDoItem& _toDoItem){
printToDoItem(_toDoItem, false);
}
void Todo::printToDoItem(const ToDoItem& _toDoItem, bool _verbose){
char *nameTag = "", *descriptionTag = "";
if (_verbose){
nameTag = "Name: ";
descriptionTag = "Description: ";
}
printf("[%s] %s%s\n", (_toDoItem.completed) ? "X" : " ", nameTag, _toDoItem.name.c_str());
printf("%s%s\n", descriptionTag, _toDoItem.description.c_str());
if (_verbose){
printf("Category ID: %i\n", _toDoItem.categoryID);
}
}
void Todo::printCategories(){
size_t categoriesSize = m_categories.size();
printf("======== Categories ===========\n");
for (size_t i = 0; i < categoriesSize; i++){
printf("[ID: %i] %s\n", m_categories[i].id, m_categories[i].name.c_str());
}
printf("===============================\n");
}
void Todo::addToDo(ToDoItem _toDoItem){
m_todoCollection.push_back(_toDoItem);
saveToDoFile();
}
void Todo::addCategory(std::string _name){
ToDoCategory categoryToAdd;
categoryToAdd.name = _name;
categoryToAdd.id = m_categories.size();
m_categories.push_back(categoryToAdd);
saveToDoFile();
}
void Todo::removeToDoByIndex(int _index){
if (_index < 0 || _index >= m_todoCollection.size()){
throw -1;
}
m_todoCollection.erase(m_todoCollection.begin() + _index);
saveToDoFile();
}
void Todo::removeAllToDos(){
m_todoCollection.clear();
saveToDoFile();
}
int Todo::removeCategory(int _categoryID){
ToDoCategory category;
try{
category = getCategory(_categoryID);
} catch (int e) {
if (e == -1){
printf("ERROR: Could not get category of id %i\n", _categoryID);
} else{
printf("ERROR: Unknown error getting category.\n");
}
return - 1;
}
for (std::vector<ToDoCategory>::iterator cateItr = m_categories.begin(); cateItr != m_categories.end(); cateItr++){
if (cateItr->id == _categoryID){
m_categories.erase(cateItr);
saveToDoFile();
return 0;
}
}
return -1;
}
void Todo::setToDoToCategory(int _toDoIndex, int _categoryID){
if (_toDoIndex < 0 || _toDoIndex >= m_todoCollection.size()){
throw -1;
}
m_todoCollection[_toDoIndex].categoryID = _categoryID;
saveToDoFile();
}
void Todo::markToDoCompleted(int _toDoIndex, bool _completed){
if (_toDoIndex < 0 || _toDoIndex >= m_todoCollection.size()){
throw -1;
}
m_todoCollection[_toDoIndex].completed = _completed;
saveToDoFile();
}<|endoftext|> |
<commit_before>#include <cstring>
#include <set>
#include <map>
#include <functional>
#include <queue>
#include <unistd.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include "judge.h"
#include "global.h"
#define BSIZ (1 << 18)
using namespace std;
typedef function<char(char, char*, char*, Settings&)> Script;
struct QueueData;
static map<string, Script> scripts;
static queue<QueueData*> jqueue;
static pthread_mutex_t judger_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool instance_exists(char problem, int i) {
FILE* fp = fopen(stringf("problems/%c.in%d", problem, i).c_str(), "r");
if (!fp) return false;
fclose(fp);
return true;
}
static string judge(
int id, const string& team, const string& fno,
const string& path, const string& fn, Settings& settings
) {
// build attempt
Attempt att;
att.id = id;
strcpy(att.team, team.c_str());
att.problem = fno[0]-'A';
char run = scripts[fno.substr(1, fno.size())](
fno[0], (char*)path.c_str(), (char*)fn.c_str(), settings
);
if (run != AC) {
att.verdict = run;
}
else {
att.verdict = AC;
for (int i = 1; instance_exists(fno[0], i) && att.verdict == AC; i++) {
int status = system(
"diff -wB %s%c.out%d problems/%c.sol%d",
path.c_str(), fno[0], i, fno[0], i
);
if (WEXITSTATUS(status)) att.verdict = WA;
else {
status = system(
"diff %s%c.out%d problems/%c.sol%d",
path.c_str(), fno[0], i, fno[0], i
);
if (WEXITSTATUS(status)) att.verdict = PE;
}
}
}
att.when = time(nullptr);
// save attempt info
Global::lock_att_file();
if (Global::alive()) {
FILE* fp = fopen("attempts.bin", "ab");
fwrite(&att, sizeof att, 1, fp);
fclose(fp);
}
Global::unlock_att_file();
// return verdict
static string verdict[] = {"AC", "CE", "RTE", "TLE", "WA", "PE"};
return
att.when < settings.noverdict ?
verdict[int(att.verdict)] :
"The judge is hiding verdicts!"
;
}
struct QueueData {
int id;
string team;
string fno;
string path;
string fn;
Settings settings;
string verdict;
bool done;
QueueData() : done(false) {}
void push() {
pthread_mutex_lock(&judger_mutex);
jqueue.push(this);
pthread_mutex_unlock(&judger_mutex);
while (Global::alive() && !done) usleep(25000);
}
void judge() {
verdict = ::judge(id, team, fno, path, fn, settings);
done = true;
}
};
static bool valid_filename(Settings& settings, const string& fn) {
return
('A' <= fn[0]) && (fn[0] <= ('A' + int(settings.problems.size())-1)) &&
(scripts.find(fn.substr(1, fn.size())) != scripts.end())
;
}
static int genid() {
FILE* fp = fopen("nextid.bin", "rb");
int current, next;
if (!fp) current = 1, next = 2;
else {
fread(¤t, sizeof current, 1, fp);
fclose(fp);
next = current + 1;
}
fp = fopen("nextid.bin", "wb");
fwrite(&next, sizeof next, 1, fp);
fclose(fp);
return current;
}
static __suseconds_t dt(const timeval& start) {
timeval end;
gettimeofday(&end, nullptr);
return
(end.tv_sec*1000000 + end.tv_usec)-
(start.tv_sec*1000000 + start.tv_usec)
;
}
static char run(
int s,
const string& exec_cmd,
char problem,
const string& output_path
) {
__suseconds_t us = s*1000000;
timeval start;
gettimeofday(&start, nullptr);
pid_t proc = fork();
if (!proc) {
// TODO lose root permissions
setpgid(0, 0); // create new process group rooted at proc
for (int i = 1; instance_exists(problem, i); i++) {
int status = system(
"%s < problems/%c.in%d > %s%c.out%d",
exec_cmd.c_str(),
problem, i,
output_path.c_str(), problem, i
);
int exit_code = WEXITSTATUS(status);
if (exit_code) exit(exit_code);
}
exit(0);
}
int status;
while (waitpid(proc, &status, WNOHANG) != proc) {
if (dt(start) > us) {
kill(-proc, SIGKILL); // the minus kills the whole group rooted at proc
waitpid(proc, &status, 0);
return TLE;
}
usleep(10000);
}
if (WEXITSTATUS(status)) return RTE;
return AC;
}
static void load_scripts() {
scripts[".c"] = [](char p, char* path, char* fn, Settings& settings) {
int status = system("gcc -std=c11 %s -o %s%c -lm", fn, path, p);
if (WEXITSTATUS(status)) return char(CE);
return run(
settings.problems[p-'A'],
stringf("%s%c", path, p),
p,
path
);
};
scripts[".cpp"] = [](char p, char* path, char* fn, Settings& settings) {
int status = system("g++ -std=c++1y %s -o %s%c", fn, path, p);
if (WEXITSTATUS(status)) return char(CE);
return run(
settings.problems[p-'A'],
stringf("%s%c", path, p),
p,
path
);
};
scripts[".java"] = [](char p, char* path, char* fn, Settings& settings) {
int status = system("javac %s", fn);
if (WEXITSTATUS(status)) return char(CE);
return run(
settings.problems[p-'A'],
stringf("java -cp %s %c", path, p),
p,
path
);
};
scripts[".py"] = [](char p, char* path, char* fn, Settings& settings) {
return run(
settings.problems[p-'A'],
stringf("python %s", fn),
p,
path
);
};
scripts[".py3"] = [](char p, char* path, char* fn, Settings& settings) {
return run(
settings.problems[p-'A'],
stringf("python3 %s", fn),
p,
path
);
};
}
static void* judger(void*) {
while (Global::alive()) {
pthread_mutex_lock(&judger_mutex);
if (jqueue.empty()) {
pthread_mutex_unlock(&judger_mutex);
usleep(25000);
continue;
}
QueueData* qd = jqueue.front(); jqueue.pop();
pthread_mutex_unlock(&judger_mutex);
qd->judge();
}
return nullptr;
}
namespace Judge {
void fire() {
load_scripts();
Global::fire(judger);
}
void attempt(
int sd,
const string& teamname, const string& team,
const string& file_name, int file_size
) {
Settings settings;
// check time
time_t now = time(nullptr);
if (now < settings.begin || settings.end <= now) {
ignoresd(sd);
write(sd, "The contest is not running.", 27);
return;
}
// check file name
if (!valid_filename(settings, file_name)) {
ignoresd(sd);
write(sd, "Invalid file name!", 18);
return;
}
// check file size
if (file_size > BSIZ) {
string resp =
"Files with more than "+to<string>(BSIZ)+" bytes are not allowed!"
;
ignoresd(sd);
write(sd, resp.c_str(), resp.size());
return;
}
// read data
char* buf = new char[BSIZ];
for (int i = 0, fs = file_size; fs > 0;) {
int rb = read(sd, &buf[i], fs);
if (rb < 0) {
write(sd, "Incomplete request!", 19);
delete[] buf;
return;
}
fs -= rb;
i += rb;
}
// generate id
Global::lock_nextid_file();
if (!Global::alive()) {
Global::unlock_nextid_file();
delete[] buf;
return;
}
int id = genid();
Global::unlock_nextid_file();
// save file
string fn = "attempts/";
mkdir(fn.c_str(), 0777);
fn += (team+"/");
mkdir(fn.c_str(), 0777);
fn += file_name[0]; fn += "/";
mkdir(fn.c_str(), 0777);
fn += (to<string>(id)+"/");
mkdir(fn.c_str(), 0777);
string path = "./"+fn;
fn += file_name;
FILE* fp = fopen(fn.c_str(), "wb");
fwrite(buf, file_size, 1, fp);
fclose(fp);
delete[] buf;
// respond
string response = "Attempt "+to<string>(id)+": ";
QueueData qd;
qd.id = id;
qd.team = teamname;
qd.fno = file_name;
qd.path = path;
qd.fn = fn;
qd.settings = settings;
qd.push();
response += qd.verdict;
write(sd, response.c_str(), response.size());
}
} // namespace Judge
<commit_msg>Now, TLE is per file, not the sum of all files<commit_after>#include <cstring>
#include <set>
#include <map>
#include <functional>
#include <queue>
#include <unistd.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include "judge.h"
#include "global.h"
#define BSIZ (1 << 18)
using namespace std;
typedef function<char(char, char*, char*, Settings&)> Script;
struct QueueData;
static map<string, Script> scripts;
static queue<QueueData*> jqueue;
static pthread_mutex_t judger_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool instance_exists(char problem, int i) {
FILE* fp = fopen(stringf("problems/%c.in%d", problem, i).c_str(), "r");
if (!fp) return false;
fclose(fp);
return true;
}
static string judge(
int id, const string& team, const string& fno,
const string& path, const string& fn, Settings& settings
) {
// build attempt
Attempt att;
att.id = id;
strcpy(att.team, team.c_str());
att.problem = fno[0]-'A';
char run = scripts[fno.substr(1, fno.size())](
fno[0], (char*)path.c_str(), (char*)fn.c_str(), settings
);
if (run != AC) {
att.verdict = run;
}
else {
att.verdict = AC;
for (int i = 1; instance_exists(fno[0], i) && att.verdict == AC; i++) {
int status = system(
"diff -wB %s%c.out%d problems/%c.sol%d",
path.c_str(), fno[0], i, fno[0], i
);
if (WEXITSTATUS(status)) att.verdict = WA;
else {
status = system(
"diff %s%c.out%d problems/%c.sol%d",
path.c_str(), fno[0], i, fno[0], i
);
if (WEXITSTATUS(status)) att.verdict = PE;
}
}
}
att.when = time(nullptr);
// save attempt info
Global::lock_att_file();
if (Global::alive()) {
FILE* fp = fopen("attempts.bin", "ab");
fwrite(&att, sizeof att, 1, fp);
fclose(fp);
}
Global::unlock_att_file();
// return verdict
static string verdict[] = {"AC", "CE", "RTE", "TLE", "WA", "PE"};
return
att.when < settings.noverdict ?
verdict[int(att.verdict)] :
"The judge is hiding verdicts!"
;
}
struct QueueData {
int id;
string team;
string fno;
string path;
string fn;
Settings settings;
string verdict;
bool done;
QueueData() : done(false) {}
void push() {
pthread_mutex_lock(&judger_mutex);
jqueue.push(this);
pthread_mutex_unlock(&judger_mutex);
while (Global::alive() && !done) usleep(25000);
}
void judge() {
verdict = ::judge(id, team, fno, path, fn, settings);
done = true;
}
};
static bool valid_filename(Settings& settings, const string& fn) {
return
('A' <= fn[0]) && (fn[0] <= ('A' + int(settings.problems.size())-1)) &&
(scripts.find(fn.substr(1, fn.size())) != scripts.end())
;
}
static int genid() {
FILE* fp = fopen("nextid.bin", "rb");
int current, next;
if (!fp) current = 1, next = 2;
else {
fread(¤t, sizeof current, 1, fp);
fclose(fp);
next = current + 1;
}
fp = fopen("nextid.bin", "wb");
fwrite(&next, sizeof next, 1, fp);
fclose(fp);
return current;
}
static __suseconds_t dt(const timeval& start) {
timeval end;
gettimeofday(&end, nullptr);
return
(end.tv_sec*1000000 + end.tv_usec)-
(start.tv_sec*1000000 + start.tv_usec)
;
}
static char run(
int s,
const string& exec_cmd,
char problem,
const string& output_path
) {
__suseconds_t us = s*1000000;
for (int i = 1; instance_exists(problem,i); i++) {
timeval start;
gettimeofday(&start, nullptr);
// child
pid_t proc = fork();
if (!proc) {
// TODO lose root permissions
setpgid(0, 0); // create new process group rooted at proc
int status = system(
"%s < problems/%c.in%d > %s%c.out%d",
exec_cmd.c_str(),
problem, i,
output_path.c_str(), problem, i
);
exit(WEXITSTATUS(status));
}
// judge
int status;
while (waitpid(proc, &status, WNOHANG) != proc) {
if (dt(start) > us) {
kill(-proc, SIGKILL); // the minus kills the whole group rooted at proc
waitpid(proc, &status, 0);
return TLE;
}
usleep(10000);
}
if (WEXITSTATUS(status)) return RTE;
}
return AC;
}
static void load_scripts() {
scripts[".c"] = [](char p, char* path, char* fn, Settings& settings) {
int status = system("gcc -std=c11 %s -o %s%c -lm", fn, path, p);
if (WEXITSTATUS(status)) return char(CE);
return run(
settings.problems[p-'A'],
stringf("%s%c", path, p),
p,
path
);
};
scripts[".cpp"] = [](char p, char* path, char* fn, Settings& settings) {
int status = system("g++ -std=c++1y %s -o %s%c", fn, path, p);
if (WEXITSTATUS(status)) return char(CE);
return run(
settings.problems[p-'A'],
stringf("%s%c", path, p),
p,
path
);
};
scripts[".java"] = [](char p, char* path, char* fn, Settings& settings) {
int status = system("javac %s", fn);
if (WEXITSTATUS(status)) return char(CE);
return run(
settings.problems[p-'A'],
stringf("java -cp %s %c", path, p),
p,
path
);
};
scripts[".py"] = [](char p, char* path, char* fn, Settings& settings) {
return run(
settings.problems[p-'A'],
stringf("python %s", fn),
p,
path
);
};
scripts[".py3"] = [](char p, char* path, char* fn, Settings& settings) {
return run(
settings.problems[p-'A'],
stringf("python3 %s", fn),
p,
path
);
};
}
static void* judger(void*) {
while (Global::alive()) {
pthread_mutex_lock(&judger_mutex);
if (jqueue.empty()) {
pthread_mutex_unlock(&judger_mutex);
usleep(25000);
continue;
}
QueueData* qd = jqueue.front(); jqueue.pop();
pthread_mutex_unlock(&judger_mutex);
qd->judge();
}
return nullptr;
}
namespace Judge {
void fire() {
load_scripts();
Global::fire(judger);
}
void attempt(
int sd,
const string& teamname, const string& team,
const string& file_name, int file_size
) {
Settings settings;
// check time
time_t now = time(nullptr);
if (now < settings.begin || settings.end <= now) {
ignoresd(sd);
write(sd, "The contest is not running.", 27);
return;
}
// check file name
if (!valid_filename(settings, file_name)) {
ignoresd(sd);
write(sd, "Invalid file name!", 18);
return;
}
// check file size
if (file_size > BSIZ) {
string resp =
"Files with more than "+to<string>(BSIZ)+" bytes are not allowed!"
;
ignoresd(sd);
write(sd, resp.c_str(), resp.size());
return;
}
// read data
char* buf = new char[BSIZ];
for (int i = 0, fs = file_size; fs > 0;) {
int rb = read(sd, &buf[i], fs);
if (rb < 0) {
write(sd, "Incomplete request!", 19);
delete[] buf;
return;
}
fs -= rb;
i += rb;
}
// generate id
Global::lock_nextid_file();
if (!Global::alive()) {
Global::unlock_nextid_file();
delete[] buf;
return;
}
int id = genid();
Global::unlock_nextid_file();
// save file
string fn = "attempts/";
mkdir(fn.c_str(), 0777);
fn += (team+"/");
mkdir(fn.c_str(), 0777);
fn += file_name[0]; fn += "/";
mkdir(fn.c_str(), 0777);
fn += (to<string>(id)+"/");
mkdir(fn.c_str(), 0777);
string path = "./"+fn;
fn += file_name;
FILE* fp = fopen(fn.c_str(), "wb");
fwrite(buf, file_size, 1, fp);
fclose(fp);
delete[] buf;
// respond
string response = "Attempt "+to<string>(id)+": ";
QueueData qd;
qd.id = id;
qd.team = teamname;
qd.fno = file_name;
qd.path = path;
qd.fn = fn;
qd.settings = settings;
qd.push();
response += qd.verdict;
write(sd, response.c_str(), response.size());
}
} // namespace Judge
<|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
*
*****************************************************************************/
#include "geojson_datasource.hpp"
#include "geojson_featureset.hpp"
#include "large_geojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/interprocess/mapped_region.hpp>
// mapnik
#include <mapnik/boolean.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/feature_kv_iterator.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/util/geometry_to_ds_type.hpp>
#include <mapnik/util/variant.hpp>
#include <mapnik/util/file_io.hpp>
#include <mapnik/make_unique.hpp>
#include <mapnik/json/feature_collection_grammar.hpp>
#include <mapnik/json/extract_bounding_box_grammar_impl.hpp>
#include <mapnik/util/boost_geometry_adapters.hpp> // boost.geometry - register box2d<double>
#include <mapnik/mapped_memory_cache.hpp>
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(geojson_datasource)
struct attr_value_converter
{
mapnik::eAttributeType operator() (mapnik::value_integer) const
{
return mapnik::Integer;
}
mapnik::eAttributeType operator() (double) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (float) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (bool) const
{
return mapnik::Boolean;
}
mapnik::eAttributeType operator() (std::string const& ) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_unicode_string const&) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_null const& ) const
{
return mapnik::String;
}
};
geojson_datasource::geojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(geojson_datasource::name(),
*params.get<std::string>("encoding","utf-8")),
filename_(),
inline_string_(),
extent_(),
features_(),
tree_(nullptr)
{
boost::optional<std::string> inline_string = params.get<std::string>("inline");
if (inline_string)
{
inline_string_ = *inline_string;
}
else
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
filename_ = *base + "/" + *file;
else
filename_ = *file;
}
if (!inline_string_.empty())
{
char const* start = inline_string_.c_str();
char const* end = start + inline_string_.size();
parse_geojson(start, end);
}
else
{
cache_features_ = *params.get<mapnik::boolean_type>("cache_features", true);
#if 0
mapnik::util::file file(filename_);
if (!file.open())
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'");
}
std::string file_buffer;
file_buffer.resize(file.size());
std::fread(&file_buffer[0], file.size(), 1, file.get());
char const* start = file_buffer.c_str();
char const* end = start + file_buffer.length();
if (cache_features_)
{
parse_geojson(start, end);
}
else
{
initialise_index(start, end);
}
#else
boost::optional<mapnik::mapped_region_ptr> mapped_region =
mapnik::mapped_memory_cache::instance().find(filename_, false);
if (!mapped_region)
{
throw std::runtime_error("could not get file mapping for "+ filename_);
}
char const* start = reinterpret_cast<char const*>((*mapped_region)->get_address());
char const* end = start + (*mapped_region)->get_size();
if (cache_features_)
{
parse_geojson(start, end);
}
else
{
initialise_index(start, end);
}
#endif
}
}
namespace {
using base_iterator_type = char const*;
const mapnik::transcoder tr("utf8");
const mapnik::json::feature_collection_grammar<base_iterator_type,mapnik::feature_impl> fc_grammar(tr);
}
template <typename Iterator>
void geojson_datasource::initialise_index(Iterator start, Iterator end)
{
mapnik::json::boxes boxes;
mapnik::json::extract_bounding_box_grammar<Iterator> bbox_grammar;
boost::spirit::ascii::space_type space;
Iterator itr = start;
if (!boost::spirit::qi::phrase_parse(itr, end, (bbox_grammar)(boost::phoenix::ref(boxes)) , space))
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not parse: '" + filename_ + "'");
}
// bulk insert initialise r-tree
tree_ = std::make_unique<spatial_index_type>(boxes);
// calculate total extent
for (auto const& item : boxes)
{
auto const& box = std::get<0>(item);
auto const& geometry_index = std::get<1>(item);
if (!extent_.valid())
{
extent_ = box;
// parse first feature to extract attributes schema.
// NOTE: this doesn't yield correct answer for geoJSON in general, just an indication
Iterator itr = start + geometry_index.first;
Iterator end = itr + geometry_index.second;
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
static const mapnik::transcoder tr("utf8");
static const mapnik::json::feature_grammar<Iterator, mapnik::feature_impl> grammar(tr);
boost::spirit::ascii::space_type space;
if (!boost::spirit::qi::phrase_parse(itr, end, (grammar)(boost::phoenix::ref(*feature)), space))
{
throw std::runtime_error("Failed to parse geojson feature");
}
for ( auto const& kv : *feature)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv),
mapnik::util::apply_visitor(attr_value_converter(),
std::get<1>(kv))));
}
}
else
{
extent_.expand_to_include(box);
}
}
}
template <typename Iterator>
void geojson_datasource::parse_geojson(Iterator start, Iterator end)
{
boost::spirit::ascii::space_type space;
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
std::size_t start_id = 1;
mapnik::json::default_feature_callback callback(features_);
bool result = boost::spirit::qi::phrase_parse(start, end, (fc_grammar)
(boost::phoenix::ref(ctx),boost::phoenix::ref(start_id), boost::phoenix::ref(callback)),
space);
if (!result)
{
if (!inline_string_.empty()) throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file from in-memory string");
else throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + filename_ + "'");
}
using values_container = std::vector< std::pair<box_type, std::pair<std::size_t, std::size_t>>>;
values_container values;
values.reserve(features_.size());
std::size_t geometry_index = 0;
for (mapnik::feature_ptr const& f : features_)
{
mapnik::box2d<double> box = f->envelope();
if (box.valid())
{
if (geometry_index == 0)
{
extent_ = box;
for ( auto const& kv : *f)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv),
mapnik::util::apply_visitor(attr_value_converter(),
std::get<1>(kv))));
}
}
else
{
extent_.expand_to_include(box);
}
}
values.emplace_back(box, std::make_pair(geometry_index,0));
++geometry_index;
}
// packing algorithm
tree_ = std::make_unique<spatial_index_type>(values);
}
geojson_datasource::~geojson_datasource() { }
const char * geojson_datasource::name()
{
return "geojson";
}
boost::optional<mapnik::datasource::geometry_t> geojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
int multi_type = 0;
unsigned num_features = features_.size();
for (unsigned i = 0; i < num_features && i < 5; ++i)
{
mapnik::util::to_ds_type(features_[i]->paths(),result);
if (result)
{
int type = static_cast<int>(*result);
if (multi_type > 0 && multi_type != type)
{
result.reset(mapnik::datasource::Collection);
return result;
}
multi_type = type;
}
}
return result;
}
mapnik::datasource::datasource_t geojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> geojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor geojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const
{
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& box = q.get_bbox();
if (extent_.intersects(box))
{
geojson_featureset::array_type index_array;
if (tree_)
{
tree_->query(boost::geometry::index::intersects(box),std::back_inserter(index_array));
if (cache_features_)
{
return std::make_shared<geojson_featureset>(features_, std::move(index_array));
}
else
{
std::sort(index_array.begin(),index_array.end(),
[] (item_type const& item0, item_type const& item1)
{
return item0.second.first < item1.second.first;
});
return std::make_shared<large_geojson_featureset>(filename_, std::move(index_array));
}
}
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
std::vector<mapnik::attribute_descriptor> const& desc = desc_.get_descriptors();
std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin();
std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end();
for ( ;itr!=end;++itr)
{
q.add_property_name(itr->get_name());
}
return features(q);
}
<commit_msg>only enable geojson memory mapped files if SHAPE_MEMORY_MAPPED_FILE defined (TODO: rename this define) - refs #2698<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
*
*****************************************************************************/
#include "geojson_datasource.hpp"
#include "geojson_featureset.hpp"
#include "large_geojson_featureset.hpp"
#include <fstream>
#include <algorithm>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/spirit/include/qi.hpp>
// mapnik
#include <mapnik/boolean.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/feature_kv_iterator.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/box2d.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/proj_transform.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/util/geometry_to_ds_type.hpp>
#include <mapnik/util/variant.hpp>
#include <mapnik/util/file_io.hpp>
#include <mapnik/make_unique.hpp>
#include <mapnik/json/feature_collection_grammar.hpp>
#include <mapnik/json/extract_bounding_box_grammar_impl.hpp>
#include <mapnik/util/boost_geometry_adapters.hpp> // boost.geometry - register box2d<double>
#if defined(SHAPE_MEMORY_MAPPED_FILE)
#include <boost/interprocess/mapped_region.hpp>
#include <mapnik/mapped_memory_cache.hpp>
#endif
using mapnik::datasource;
using mapnik::parameters;
DATASOURCE_PLUGIN(geojson_datasource)
struct attr_value_converter
{
mapnik::eAttributeType operator() (mapnik::value_integer) const
{
return mapnik::Integer;
}
mapnik::eAttributeType operator() (double) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (float) const
{
return mapnik::Double;
}
mapnik::eAttributeType operator() (bool) const
{
return mapnik::Boolean;
}
mapnik::eAttributeType operator() (std::string const& ) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_unicode_string const&) const
{
return mapnik::String;
}
mapnik::eAttributeType operator() (mapnik::value_null const& ) const
{
return mapnik::String;
}
};
geojson_datasource::geojson_datasource(parameters const& params)
: datasource(params),
type_(datasource::Vector),
desc_(geojson_datasource::name(),
*params.get<std::string>("encoding","utf-8")),
filename_(),
inline_string_(),
extent_(),
features_(),
tree_(nullptr)
{
boost::optional<std::string> inline_string = params.get<std::string>("inline");
if (inline_string)
{
inline_string_ = *inline_string;
}
else
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
filename_ = *base + "/" + *file;
else
filename_ = *file;
}
if (!inline_string_.empty())
{
char const* start = inline_string_.c_str();
char const* end = start + inline_string_.size();
parse_geojson(start, end);
}
else
{
cache_features_ = *params.get<mapnik::boolean_type>("cache_features", true);
#if defined(SHAPE_MEMORY_MAPPED_FILE)
mapnik::util::file file(filename_);
if (!file.open())
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'");
}
std::string file_buffer;
file_buffer.resize(file.size());
std::fread(&file_buffer[0], file.size(), 1, file.get());
char const* start = file_buffer.c_str();
char const* end = start + file_buffer.length();
if (cache_features_)
{
parse_geojson(start, end);
}
else
{
initialise_index(start, end);
}
#else
boost::optional<mapnik::mapped_region_ptr> mapped_region =
mapnik::mapped_memory_cache::instance().find(filename_, false);
if (!mapped_region)
{
throw std::runtime_error("could not get file mapping for "+ filename_);
}
char const* start = reinterpret_cast<char const*>((*mapped_region)->get_address());
char const* end = start + (*mapped_region)->get_size();
if (cache_features_)
{
parse_geojson(start, end);
}
else
{
initialise_index(start, end);
}
#endif
}
}
namespace {
using base_iterator_type = char const*;
const mapnik::transcoder tr("utf8");
const mapnik::json::feature_collection_grammar<base_iterator_type,mapnik::feature_impl> fc_grammar(tr);
}
template <typename Iterator>
void geojson_datasource::initialise_index(Iterator start, Iterator end)
{
mapnik::json::boxes boxes;
mapnik::json::extract_bounding_box_grammar<Iterator> bbox_grammar;
boost::spirit::ascii::space_type space;
Iterator itr = start;
if (!boost::spirit::qi::phrase_parse(itr, end, (bbox_grammar)(boost::phoenix::ref(boxes)) , space))
{
throw mapnik::datasource_exception("GeoJSON Plugin: could not parse: '" + filename_ + "'");
}
// bulk insert initialise r-tree
tree_ = std::make_unique<spatial_index_type>(boxes);
// calculate total extent
for (auto const& item : boxes)
{
auto const& box = std::get<0>(item);
auto const& geometry_index = std::get<1>(item);
if (!extent_.valid())
{
extent_ = box;
// parse first feature to extract attributes schema.
// NOTE: this doesn't yield correct answer for geoJSON in general, just an indication
Iterator itr = start + geometry_index.first;
Iterator end = itr + geometry_index.second;
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1));
static const mapnik::transcoder tr("utf8");
static const mapnik::json::feature_grammar<Iterator, mapnik::feature_impl> grammar(tr);
boost::spirit::ascii::space_type space;
if (!boost::spirit::qi::phrase_parse(itr, end, (grammar)(boost::phoenix::ref(*feature)), space))
{
throw std::runtime_error("Failed to parse geojson feature");
}
for ( auto const& kv : *feature)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv),
mapnik::util::apply_visitor(attr_value_converter(),
std::get<1>(kv))));
}
}
else
{
extent_.expand_to_include(box);
}
}
}
template <typename Iterator>
void geojson_datasource::parse_geojson(Iterator start, Iterator end)
{
boost::spirit::ascii::space_type space;
mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
std::size_t start_id = 1;
mapnik::json::default_feature_callback callback(features_);
bool result = boost::spirit::qi::phrase_parse(start, end, (fc_grammar)
(boost::phoenix::ref(ctx),boost::phoenix::ref(start_id), boost::phoenix::ref(callback)),
space);
if (!result)
{
if (!inline_string_.empty()) throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file from in-memory string");
else throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + filename_ + "'");
}
using values_container = std::vector< std::pair<box_type, std::pair<std::size_t, std::size_t>>>;
values_container values;
values.reserve(features_.size());
std::size_t geometry_index = 0;
for (mapnik::feature_ptr const& f : features_)
{
mapnik::box2d<double> box = f->envelope();
if (box.valid())
{
if (geometry_index == 0)
{
extent_ = box;
for ( auto const& kv : *f)
{
desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv),
mapnik::util::apply_visitor(attr_value_converter(),
std::get<1>(kv))));
}
}
else
{
extent_.expand_to_include(box);
}
}
values.emplace_back(box, std::make_pair(geometry_index,0));
++geometry_index;
}
// packing algorithm
tree_ = std::make_unique<spatial_index_type>(values);
}
geojson_datasource::~geojson_datasource() { }
const char * geojson_datasource::name()
{
return "geojson";
}
boost::optional<mapnik::datasource::geometry_t> geojson_datasource::get_geometry_type() const
{
boost::optional<mapnik::datasource::geometry_t> result;
int multi_type = 0;
unsigned num_features = features_.size();
for (unsigned i = 0; i < num_features && i < 5; ++i)
{
mapnik::util::to_ds_type(features_[i]->paths(),result);
if (result)
{
int type = static_cast<int>(*result);
if (multi_type > 0 && multi_type != type)
{
result.reset(mapnik::datasource::Collection);
return result;
}
multi_type = type;
}
}
return result;
}
mapnik::datasource::datasource_t geojson_datasource::type() const
{
return type_;
}
mapnik::box2d<double> geojson_datasource::envelope() const
{
return extent_;
}
mapnik::layer_descriptor geojson_datasource::get_descriptor() const
{
return desc_;
}
mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const
{
// if the query box intersects our world extent then query for features
mapnik::box2d<double> const& box = q.get_bbox();
if (extent_.intersects(box))
{
geojson_featureset::array_type index_array;
if (tree_)
{
tree_->query(boost::geometry::index::intersects(box),std::back_inserter(index_array));
if (cache_features_)
{
return std::make_shared<geojson_featureset>(features_, std::move(index_array));
}
else
{
std::sort(index_array.begin(),index_array.end(),
[] (item_type const& item0, item_type const& item1)
{
return item0.second.first < item1.second.first;
});
return std::make_shared<large_geojson_featureset>(filename_, std::move(index_array));
}
}
}
// otherwise return an empty featureset pointer
return mapnik::featureset_ptr();
}
mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const
{
mapnik::box2d<double> query_bbox(pt, pt);
query_bbox.pad(tol);
mapnik::query q(query_bbox);
std::vector<mapnik::attribute_descriptor> const& desc = desc_.get_descriptors();
std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin();
std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end();
for ( ;itr!=end;++itr)
{
q.add_property_name(itr->get_name());
}
return features(q);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <pdal/drivers/las/Writer.hpp>
#include "LasHeaderWriter.hpp"
// local
#include "ZipPoint.hpp"
// laszip
#ifdef PDAL_HAVE_LASZIP
#include <laszip/laszipper.hpp>
#endif
#include <pdal/Stage.hpp>
#include <pdal/PointBuffer.hpp>
#include <iostream>
namespace pdal { namespace drivers { namespace las {
Writer::Writer(Stage& prevStage, const Options& options)
: pdal::Writer(prevStage, options)
, m_streamManager(options.getOption("filename").getValue<std::string>())
{
return;
}
Writer::Writer(Stage& prevStage, std::ostream* ostream)
: pdal::Writer(prevStage, Options::none())
, m_streamManager(ostream)
, m_numPointsWritten(0)
{
return;
}
Writer::~Writer()
{
#ifdef PDAL_HAVE_LASZIP
m_zipper.reset();
m_zipPoint.reset();
#endif
m_streamManager.close();
return;
}
void Writer::initialize()
{
pdal::Writer::initialize();
m_streamManager.open();
setCompressed(getOptions().getValueOrDefault("compression", false));
if (getOptions().hasOption("a_srs"))
{
setSpatialReference(getOptions().getValueOrThrow<std::string>("a_srs"));
}
setPointFormat(static_cast<PointFormat>(getOptions().getValueOrDefault<boost::uint32_t>("format", 3)));
setFormatVersion((boost::uint8_t)getOptions().getValueOrDefault<boost::uint32_t>("major_version", 1),
(boost::uint8_t)getOptions().getValueOrDefault<boost::uint32_t>("minor_version", 2));
setDate((boost::uint16_t)getOptions().getValueOrDefault<boost::uint32_t>("year", 0),
(boost::uint16_t)getOptions().getValueOrDefault<boost::uint32_t>("day_of_year", 0));
setHeaderPadding(getOptions().getValueOrDefault<boost::uint32_t>("header_padding", 0));
setSystemIdentifier(getOptions().getValueOrDefault<std::string>("system_id", LasHeader::SystemIdentifier));
setGeneratingSoftware(getOptions().getValueOrDefault<std::string>("software_id", LasHeader::SoftwareIdentifier));
return;
}
const Options Writer::getDefaultOptions() const
{
Options options;
Option filename("filename", "", "file to read from");
Option compression("compression", false, "Do we LASzip-compress the data?");
Option format("format", PointFormat3, "Point format to write");
Option major_version("major_version", 1, "LAS Major version");
Option minor_version("minor_version", 2, "LAS Minor version");
Option day_of_year("day_of_year", 0, "Day of Year for file");
Option year("year", 2011, "4-digit year value for file");
Option system_id("system_id", LasHeader::SystemIdentifier, "System ID for this file");
Option software_id("software_id", LasHeader::SoftwareIdentifier, "Software ID for this file");
Option header_padding("header_padding", 0, "Header padding (space between end of VLRs and beginning of point data)");
options.add(major_version);
options.add(minor_version);
options.add(day_of_year);
options.add(year);
options.add(system_id);
options.add(software_id);
options.add(header_padding);
options.add(format);
options.add(filename);
options.add(compression);
return options;
}
void Writer::setCompressed(bool v)
{
m_lasHeader.SetCompressed(v);
}
void Writer::setFormatVersion(boost::uint8_t majorVersion, boost::uint8_t minorVersion)
{
m_lasHeader.SetVersionMajor(majorVersion);
m_lasHeader.SetVersionMinor(minorVersion);
}
void Writer::setPointFormat(PointFormat pointFormat)
{
m_lasHeader.setPointFormat(pointFormat);
}
void Writer::setDate(boost::uint16_t dayOfYear, boost::uint16_t year)
{
m_lasHeader.SetCreationDOY(dayOfYear);
m_lasHeader.SetCreationYear(year);
}
void Writer::setProjectId(const pdal::external::boost::uuids::uuid& id)
{
m_lasHeader.SetProjectId(id);
}
void Writer::setSystemIdentifier(const std::string& systemId)
{
m_lasHeader.SetSystemId(systemId);
}
void Writer::setGeneratingSoftware(const std::string& softwareId)
{
m_lasHeader.SetSoftwareId(softwareId);
}
void Writer::setHeaderPadding(boost::uint32_t const& v)
{
m_lasHeader.SetHeaderPadding(v);
}
void Writer::writeBegin(boost::uint64_t targetNumPointsToWrite)
{
// need to set properties of the header here, based on prev->getHeader() and on the user's preferences
m_lasHeader.setBounds( getPrevStage().getBounds() );
const Schema& schema = getPrevStage().getSchema();
const Dimension& dimX = schema.getDimension(DimensionId::X_i32);
const Dimension& dimY = schema.getDimension(DimensionId::Y_i32);
const Dimension& dimZ = schema.getDimension(DimensionId::Z_i32);
m_lasHeader.SetScale(dimX.getNumericScale(), dimY.getNumericScale(), dimZ.getNumericScale());
m_lasHeader.SetOffset(dimX.getNumericOffset(), dimY.getNumericOffset(), dimZ.getNumericOffset());
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(8);
boost::uint32_t cnt = static_cast<boost::uint32_t>(targetNumPointsToWrite);
m_lasHeader.SetPointRecordsCount(cnt);
m_lasHeader.setSpatialReference(getSpatialReference());
LasHeaderWriter lasHeaderWriter(m_lasHeader, m_streamManager.ostream());
lasHeaderWriter.write();
m_summaryData.reset();
if (m_lasHeader.Compressed())
{
#ifdef PDAL_HAVE_LASZIP
if (!m_zipPoint)
{
PointFormat format = m_lasHeader.getPointFormat();
boost::scoped_ptr<ZipPoint> z(new ZipPoint(format, m_lasHeader.getVLRs().getAll()));
m_zipPoint.swap(z);
}
if (!m_zipper)
{
boost::scoped_ptr<LASzipper> z(new LASzipper());
m_zipper.swap(z);
bool stat(false);
stat = m_zipper->open(m_streamManager.ostream(), m_zipPoint->GetZipper());
if (!stat)
{
std::ostringstream oss;
const char* err = m_zipper->get_error();
if (err==NULL) err="(unknown error)";
oss << "Error opening LASzipper: " << std::string(err);
throw pdal_error(oss.str());
}
}
#else
throw pdal_error("LASzip compression is not enabled for this compressed file!");
#endif
}
return;
}
void Writer::writeEnd(boost::uint64_t /*actualNumPointsWritten*/)
{
m_lasHeader.SetPointRecordsCount(m_numPointsWritten);
//std::streamsize const dataPos = 107;
//m_ostream.seekp(dataPos, std::ios::beg);
//LasHeaderWriter lasHeaderWriter(m_lasHeader, m_ostream);
//Utils::write_n(m_ostream, m_numPointsWritten, sizeof(m_numPointsWritten));
m_streamManager.ostream().seekp(0);
Support::rewriteHeader(m_streamManager.ostream(), m_summaryData);
return;
}
boost::uint32_t Writer::writeBuffer(const PointBuffer& pointBuffer)
{
const Schema& schema = pointBuffer.getSchema();
PointFormat pointFormat = m_lasHeader.getPointFormat();
const PointIndexes indexes(schema, pointFormat);
boost::uint32_t numValidPoints = 0;
boost::uint8_t buf[1024]; // BUG: fixed size
for (boost::uint32_t pointIndex=0; pointIndex<pointBuffer.getNumPoints(); pointIndex++)
{
boost::uint8_t* p = buf;
// we always write the base fields
const boost::uint32_t x = pointBuffer.getField<boost::uint32_t>(pointIndex, indexes.X);
const boost::uint32_t y = pointBuffer.getField<boost::uint32_t>(pointIndex, indexes.Y);
const boost::uint32_t z = pointBuffer.getField<boost::uint32_t>(pointIndex, indexes.Z);
const boost::uint16_t intensity = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Intensity);
const boost::uint8_t returnNumber = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.ReturnNumber);
const boost::uint8_t numberOfReturns = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.NumberOfReturns);
const boost::uint8_t scanDirectionFlag = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.ScanDirectionFlag);
const boost::uint8_t edgeOfFlightLinet = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.EdgeOfFlightLine);
const boost::uint8_t bits = returnNumber | (numberOfReturns<<3) | (scanDirectionFlag << 6) | (edgeOfFlightLinet << 7);
const boost::uint8_t classification = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.Classification);
const boost::int8_t scanAngleRank = pointBuffer.getField<boost::int8_t>(pointIndex, indexes.ScanAngleRank);
const boost::uint8_t userData = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.UserData);
const boost::uint16_t pointSourceId = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.PointSourceId);
Utils::write_field<boost::uint32_t>(p, x);
Utils::write_field<boost::uint32_t>(p, y);
Utils::write_field<boost::uint32_t>(p, z);
Utils::write_field<boost::uint16_t>(p, intensity);
Utils::write_field<boost::uint8_t>(p, bits);
Utils::write_field<boost::uint8_t>(p, classification);
Utils::write_field<boost::int8_t>(p, scanAngleRank);
Utils::write_field<boost::uint8_t>(p, userData);
Utils::write_field<boost::uint16_t>(p, pointSourceId);
if (Support::hasTime(pointFormat) && indexes.Time != -1)
{
double time(0.0);
if (indexes.Time != -1)
time = pointBuffer.getField<double>(pointIndex, indexes.Time);
Utils::write_field<double>(p, time);
}
if (Support::hasColor(pointFormat))
{
boost::uint16_t red(0);
boost::uint16_t green(0);
boost::uint16_t blue(0);
if (indexes.Red != -1)
red = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Red);
if (indexes.Green != -1)
green = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Green);
if (indexes.Blue != -1)
blue = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Blue);
Utils::write_field<boost::uint16_t>(p, red);
Utils::write_field<boost::uint16_t>(p, green);
Utils::write_field<boost::uint16_t>(p, blue);
}
#ifdef PDAL_HAVE_LASZIP
if (m_zipPoint)
{
for (unsigned int i=0; i<m_zipPoint->m_lz_point_size; i++)
{
m_zipPoint->m_lz_point_data[i] = buf[i];
// printf("%d %d\n", buf[i], i);
}
bool ok = m_zipper->write(m_zipPoint->m_lz_point);
if (!ok)
{
std::ostringstream oss;
const char* err = m_zipper->get_error();
if (err==NULL) err="(unknown error)";
oss << "Error writing point: " << std::string(err);
throw pdal_error(oss.str());
}
}
else
{
Utils::write_n(m_streamManager.ostream(), buf, Support::getPointDataSize(pointFormat));
}
#else
Utils::write_n(m_streamManager.ostream(), buf, Support::getPointDataSize(pointFormat));
#endif
++numValidPoints;
const double xValue = schema.getDimension(DimensionId::X_i32).applyScaling<boost::int32_t>(x);
const double yValue = schema.getDimension(DimensionId::Y_i32).applyScaling<boost::int32_t>(y);
const double zValue = schema.getDimension(DimensionId::Z_i32).applyScaling<boost::int32_t>(z);
m_summaryData.addPoint(xValue, yValue, zValue, returnNumber);
}
m_numPointsWritten = m_numPointsWritten+numValidPoints;
return numValidPoints;
}
boost::property_tree::ptree Writer::toPTree() const
{
boost::property_tree::ptree tree = pdal::Writer::toPTree();
// add stuff here specific to this stage type
return tree;
}
} } } // namespaces
<commit_msg>xyz values are int32_t, not uint32_t for LAS data. We should use a reference to the dimension when applying scaling for the summary data. Only throw exceptions when we don't have XYZ data. Otherwise, write 0's<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <pdal/drivers/las/Writer.hpp>
#include "LasHeaderWriter.hpp"
// local
#include "ZipPoint.hpp"
// laszip
#ifdef PDAL_HAVE_LASZIP
#include <laszip/laszipper.hpp>
#endif
#include <pdal/Stage.hpp>
#include <pdal/PointBuffer.hpp>
#include <iostream>
namespace pdal { namespace drivers { namespace las {
Writer::Writer(Stage& prevStage, const Options& options)
: pdal::Writer(prevStage, options)
, m_streamManager(options.getOption("filename").getValue<std::string>())
{
return;
}
Writer::Writer(Stage& prevStage, std::ostream* ostream)
: pdal::Writer(prevStage, Options::none())
, m_streamManager(ostream)
, m_numPointsWritten(0)
{
return;
}
Writer::~Writer()
{
#ifdef PDAL_HAVE_LASZIP
m_zipper.reset();
m_zipPoint.reset();
#endif
m_streamManager.close();
return;
}
void Writer::initialize()
{
pdal::Writer::initialize();
m_streamManager.open();
setCompressed(getOptions().getValueOrDefault("compression", false));
if (getOptions().hasOption("a_srs"))
{
setSpatialReference(getOptions().getValueOrThrow<std::string>("a_srs"));
}
setPointFormat(static_cast<PointFormat>(getOptions().getValueOrDefault<boost::uint32_t>("format", 3)));
setFormatVersion((boost::uint8_t)getOptions().getValueOrDefault<boost::uint32_t>("major_version", 1),
(boost::uint8_t)getOptions().getValueOrDefault<boost::uint32_t>("minor_version", 2));
setDate((boost::uint16_t)getOptions().getValueOrDefault<boost::uint32_t>("year", 0),
(boost::uint16_t)getOptions().getValueOrDefault<boost::uint32_t>("day_of_year", 0));
setHeaderPadding(getOptions().getValueOrDefault<boost::uint32_t>("header_padding", 0));
setSystemIdentifier(getOptions().getValueOrDefault<std::string>("system_id", LasHeader::SystemIdentifier));
setGeneratingSoftware(getOptions().getValueOrDefault<std::string>("software_id", LasHeader::SoftwareIdentifier));
return;
}
const Options Writer::getDefaultOptions() const
{
Options options;
Option filename("filename", "", "file to read from");
Option compression("compression", false, "Do we LASzip-compress the data?");
Option format("format", PointFormat3, "Point format to write");
Option major_version("major_version", 1, "LAS Major version");
Option minor_version("minor_version", 2, "LAS Minor version");
Option day_of_year("day_of_year", 0, "Day of Year for file");
Option year("year", 2011, "4-digit year value for file");
Option system_id("system_id", LasHeader::SystemIdentifier, "System ID for this file");
Option software_id("software_id", LasHeader::SoftwareIdentifier, "Software ID for this file");
Option header_padding("header_padding", 0, "Header padding (space between end of VLRs and beginning of point data)");
options.add(major_version);
options.add(minor_version);
options.add(day_of_year);
options.add(year);
options.add(system_id);
options.add(software_id);
options.add(header_padding);
options.add(format);
options.add(filename);
options.add(compression);
return options;
}
void Writer::setCompressed(bool v)
{
m_lasHeader.SetCompressed(v);
}
void Writer::setFormatVersion(boost::uint8_t majorVersion, boost::uint8_t minorVersion)
{
m_lasHeader.SetVersionMajor(majorVersion);
m_lasHeader.SetVersionMinor(minorVersion);
}
void Writer::setPointFormat(PointFormat pointFormat)
{
m_lasHeader.setPointFormat(pointFormat);
}
void Writer::setDate(boost::uint16_t dayOfYear, boost::uint16_t year)
{
m_lasHeader.SetCreationDOY(dayOfYear);
m_lasHeader.SetCreationYear(year);
}
void Writer::setProjectId(const pdal::external::boost::uuids::uuid& id)
{
m_lasHeader.SetProjectId(id);
}
void Writer::setSystemIdentifier(const std::string& systemId)
{
m_lasHeader.SetSystemId(systemId);
}
void Writer::setGeneratingSoftware(const std::string& softwareId)
{
m_lasHeader.SetSoftwareId(softwareId);
}
void Writer::setHeaderPadding(boost::uint32_t const& v)
{
m_lasHeader.SetHeaderPadding(v);
}
void Writer::writeBegin(boost::uint64_t targetNumPointsToWrite)
{
// need to set properties of the header here, based on prev->getHeader() and on the user's preferences
m_lasHeader.setBounds( getPrevStage().getBounds() );
const Schema& schema = getPrevStage().getSchema();
const Dimension& dimX = schema.getDimension(DimensionId::X_i32);
const Dimension& dimY = schema.getDimension(DimensionId::Y_i32);
const Dimension& dimZ = schema.getDimension(DimensionId::Z_i32);
m_lasHeader.SetScale(dimX.getNumericScale(), dimY.getNumericScale(), dimZ.getNumericScale());
m_lasHeader.SetOffset(dimX.getNumericOffset(), dimY.getNumericOffset(), dimZ.getNumericOffset());
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(8);
boost::uint32_t cnt = static_cast<boost::uint32_t>(targetNumPointsToWrite);
m_lasHeader.SetPointRecordsCount(cnt);
m_lasHeader.setSpatialReference(getSpatialReference());
LasHeaderWriter lasHeaderWriter(m_lasHeader, m_streamManager.ostream());
lasHeaderWriter.write();
m_summaryData.reset();
if (m_lasHeader.Compressed())
{
#ifdef PDAL_HAVE_LASZIP
if (!m_zipPoint)
{
PointFormat format = m_lasHeader.getPointFormat();
boost::scoped_ptr<ZipPoint> z(new ZipPoint(format, m_lasHeader.getVLRs().getAll()));
m_zipPoint.swap(z);
}
if (!m_zipper)
{
boost::scoped_ptr<LASzipper> z(new LASzipper());
m_zipper.swap(z);
bool stat(false);
stat = m_zipper->open(m_streamManager.ostream(), m_zipPoint->GetZipper());
if (!stat)
{
std::ostringstream oss;
const char* err = m_zipper->get_error();
if (err==NULL) err="(unknown error)";
oss << "Error opening LASzipper: " << std::string(err);
throw pdal_error(oss.str());
}
}
#else
throw pdal_error("LASzip compression is not enabled for this compressed file!");
#endif
}
return;
}
void Writer::writeEnd(boost::uint64_t /*actualNumPointsWritten*/)
{
m_lasHeader.SetPointRecordsCount(m_numPointsWritten);
//std::streamsize const dataPos = 107;
//m_ostream.seekp(dataPos, std::ios::beg);
//LasHeaderWriter lasHeaderWriter(m_lasHeader, m_ostream);
//Utils::write_n(m_ostream, m_numPointsWritten, sizeof(m_numPointsWritten));
m_streamManager.ostream().seekp(0);
Support::rewriteHeader(m_streamManager.ostream(), m_summaryData);
return;
}
boost::uint32_t Writer::writeBuffer(const PointBuffer& pointBuffer)
{
const Schema& schema = getPrevStage().getSchema();
const Dimension& xDim = schema.getDimension(DimensionId::X_i32);
const Dimension& yDim = schema.getDimension(DimensionId::Y_i32);
const Dimension& zDim = schema.getDimension(DimensionId::Z_i32);
PointFormat pointFormat = m_lasHeader.getPointFormat();
const PointIndexes indexes(schema, pointFormat);
boost::uint32_t numValidPoints = 0;
boost::uint8_t buf[1024]; // BUG: fixed size
for (boost::uint32_t pointIndex=0; pointIndex<pointBuffer.getNumPoints(); pointIndex++)
{
boost::uint8_t* p = buf;
// we always write the base fields
const boost::int32_t x = pointBuffer.getField<boost::int32_t>(pointIndex, indexes.X);
const boost::int32_t y = pointBuffer.getField<boost::int32_t>(pointIndex, indexes.Y);
const boost::int32_t z = pointBuffer.getField<boost::int32_t>(pointIndex, indexes.Z);
// std::clog << "x: " << x << " y: " << y << " z: " << z << std::endl;
boost::uint16_t intensity(0);
if (indexes.Intensity != -1)
intensity = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Intensity);
boost::uint8_t returnNumber(0);
if (indexes.ReturnNumber != -1)
returnNumber = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.ReturnNumber);
boost::uint8_t numberOfReturns(0);
if (indexes.NumberOfReturns != -1)
numberOfReturns = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.NumberOfReturns);
boost::uint8_t scanDirectionFlag(0);
if (indexes.ScanDirectionFlag != -1)
scanDirectionFlag = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.ScanDirectionFlag);
boost::uint8_t edgeOfFlightLine(0);
if (indexes.EdgeOfFlightLine != -1)
edgeOfFlightLine = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.EdgeOfFlightLine);
boost::uint8_t bits = returnNumber | (numberOfReturns<<3) | (scanDirectionFlag << 6) | (edgeOfFlightLine << 7);
boost::uint8_t classification(0);
if (indexes.Classification != -1)
classification = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.Classification);
boost::int8_t scanAngleRank(0);
if (indexes.ScanAngleRank != -1)
scanAngleRank = pointBuffer.getField<boost::int8_t>(pointIndex, indexes.ScanAngleRank);
boost::uint8_t userData(0);
if (indexes.UserData != -1)
userData = pointBuffer.getField<boost::uint8_t>(pointIndex, indexes.UserData);
boost::uint16_t pointSourceId(0);
if (indexes.PointSourceId != -1)
pointSourceId = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.PointSourceId);
Utils::write_field<boost::uint32_t>(p, x);
Utils::write_field<boost::uint32_t>(p, y);
Utils::write_field<boost::uint32_t>(p, z);
Utils::write_field<boost::uint16_t>(p, intensity);
Utils::write_field<boost::uint8_t>(p, bits);
Utils::write_field<boost::uint8_t>(p, classification);
Utils::write_field<boost::int8_t>(p, scanAngleRank);
Utils::write_field<boost::uint8_t>(p, userData);
Utils::write_field<boost::uint16_t>(p, pointSourceId);
if (Support::hasTime(pointFormat))
{
double time(0.0);
if (indexes.Time != -1)
time = pointBuffer.getField<double>(pointIndex, indexes.Time);
Utils::write_field<double>(p, time);
}
if (Support::hasColor(pointFormat))
{
boost::uint16_t red(0);
boost::uint16_t green(0);
boost::uint16_t blue(0);
if (indexes.Red != -1)
red = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Red);
if (indexes.Green != -1)
green = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Green);
if (indexes.Blue != -1)
blue = pointBuffer.getField<boost::uint16_t>(pointIndex, indexes.Blue);
Utils::write_field<boost::uint16_t>(p, red);
Utils::write_field<boost::uint16_t>(p, green);
Utils::write_field<boost::uint16_t>(p, blue);
}
#ifdef PDAL_HAVE_LASZIP
if (m_zipPoint)
{
for (unsigned int i=0; i<m_zipPoint->m_lz_point_size; i++)
{
m_zipPoint->m_lz_point_data[i] = buf[i];
// printf("%d %d\n", buf[i], i);
}
bool ok = m_zipper->write(m_zipPoint->m_lz_point);
if (!ok)
{
std::ostringstream oss;
const char* err = m_zipper->get_error();
if (err==NULL) err="(unknown error)";
oss << "Error writing point: " << std::string(err);
throw pdal_error(oss.str());
}
}
else
{
Utils::write_n(m_streamManager.ostream(), buf, Support::getPointDataSize(pointFormat));
}
#else
Utils::write_n(m_streamManager.ostream(), buf, Support::getPointDataSize(pointFormat));
#endif
++numValidPoints;
const double xValue = xDim.applyScaling<boost::int32_t>(x);
const double yValue = yDim.applyScaling<boost::int32_t>(y);
const double zValue = zDim.applyScaling<boost::int32_t>(z);
m_summaryData.addPoint(xValue, yValue, zValue, returnNumber);
}
m_numPointsWritten = m_numPointsWritten+numValidPoints;
return numValidPoints;
}
boost::property_tree::ptree Writer::toPTree() const
{
boost::property_tree::ptree tree = pdal::Writer::toPTree();
// add stuff here specific to this stage type
return tree;
}
} } } // namespaces
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "dll/dyn_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/ocv_visualizer.hpp"
template<typename DBN>
void test_dbn(DBN& dbn){
dbn->display();
std::vector<etl::dyn_vector<float>> images;
dbn->pretrain(images, 10);
}
int main(){
using dbn_t =
dll::dbn_desc<
dll::dbn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t,
dll::dyn_rbm_desc<dll::momentum>::rbm_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t
>, dll::watcher<dll::opencv_dbn_visualizer>
>::dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->template layer_get<0>().init_rbm(28 * 28, 100);
dbn->template layer_get<1>().init_rbm(100, 200);
dbn->template layer_get<2>().init_rbm(200, 10);
test_dbn(dbn);
return 0;
}
<commit_msg>Remove useless test_compile<commit_after><|endoftext|> |
<commit_before>#include <GL/glut.h>
#define X_MAX 50
#define Y_MAX 50
#define dx 5
#define dy 5
GLfloat x[X_MAX] = {0.0};
GLfloat y[X_MAX] = {0.0};
GLfloat x_start = 50, y_start = 50;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
for (int i = 0; i < X_MAX; i++) x[i] = x_start + i * dx;
for (int i = 0; i < Y_MAX; i++) y[i] = y_start + i * dy;
for (int i = 0; i < X_MAX - 1; i++)
{
for (int j = 0; j < Y_MAX - 1; j++)
{
glBegin(GL_LINE_LOOP);
glVertex2f(x[i], y[j]);
glVertex2f(x[i], y[j + 1]);
glVertex2f(x[i + 1], y[j + 1]);
glVertex2f(x[i + 1], y[j]);
glEnd();
}
}
glFlush();
}
void init()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
glPointSize(5.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 499.0, 0.0, 499.0);
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(1000, 1000);
glutInitWindowPosition(0, 0);
glutCreateWindow("Rectangular Mesh");
glutFullScreen();
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
<commit_msg>format<commit_after>#include <GL/glut.h>
#define X_MAX 50
#define Y_MAX 50
#define dx 5
#define dy 5
GLfloat x[X_MAX] = {0.0};
GLfloat y[X_MAX] = {0.0};
GLfloat x_start = 50, y_start = 50;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
for (int i = 0; i < X_MAX; i++) x[i] = x_start + i * dx;
for (int i = 0; i < Y_MAX; i++) y[i] = y_start + i * dy;
for (int i = 0; i < X_MAX - 1; i++)
{
for (int j = 0; j < Y_MAX - 1; j++)
{
glBegin(GL_LINE_LOOP);
glVertex2f(x[i], y[j]);
glVertex2f(x[i], y[j + 1]);
glVertex2f(x[i + 1], y[j + 1]);
glVertex2f(x[i + 1], y[j]);
glEnd();
}
}
glFlush();
}
void init()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
glPointSize(5.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 499.0, 0.0, 499.0);
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(1000, 1000);
glutInitWindowPosition(0, 0);
glutCreateWindow("Rectangular Mesh");
glutFullScreen();
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 "CommonParser.h"
#include <fastrtps/log/Log.h>
#include <cassert>
#if TIXML2_MAJOR_VERSION >= 6
#define PRINTLINE(node) node->GetLineNum()
#define PRINTLINEPLUSONE(node) node->GetLineNum() + 1
#else
#define PRINTLINE(node) ""
#define PRINTLINEPLUSONE(node) ""
#endif
static const char* DomainId_str = "id";
static const char* DomainIdRange_str = "id_range";
static const char* Min_str = "min";
static const char* Max_str = "max";
using namespace eprosima::fastrtps;
using namespace ::rtps::security;
bool eprosima::fastrtps::rtps::security::parse_domain_id_set(tinyxml2::XMLElement* root, Domains& domains)
{
assert(root);
bool returned_value = false;
tinyxml2::XMLElement* node = root->FirstChildElement();
if(node != nullptr)
{
returned_value = true;
do
{
if(strcmp(node->Name(), DomainId_str) == 0)
{
uint32_t domain_id = 0;
if(tinyxml2::XMLError::XML_SUCCESS == node->QueryUnsignedText(&domain_id))
{
domains.ranges.push_back(std::make_pair(domain_id, 0));
}
else
{
logError(XMLPARSER, "Invalid value of " << DomainId_str <<
" tag. Line " << PRINTLINE(node));
returned_value = false;
}
}
else if(strcmp(node->Name() ,DomainIdRange_str) == 0)
{
tinyxml2::XMLElement* subnode = node->FirstChildElement();
if(subnode != nullptr)
{
uint32_t min_domain_id = 0;
if(strcmp(subnode->Name(), Min_str) == 0)
{
if(tinyxml2::XMLError::XML_SUCCESS != subnode->QueryUnsignedText(&min_domain_id))
{
logError(XMLPARSER, "Invalid value of " << DomainId_str <<
" tag. Line " << PRINTLINE(subnode));
returned_value = false;
}
}
else
{
logError(XMLPARSER, "Expected " << Min_str << " tag. Line " <<
PRINTLINE(subnode));
returned_value = false;
}
if(returned_value && (subnode = subnode->NextSiblingElement()) != nullptr)
{
if(strcmp(subnode->Name(), Max_str) == 0)
{
uint32_t max_domain_id = 0;
if(tinyxml2::XMLError::XML_SUCCESS == subnode->QueryUnsignedText(&max_domain_id))
{
domains.ranges.push_back(std::make_pair(min_domain_id, max_domain_id));
}
else
{
logError(XMLPARSER, "Invalid value of " << DomainId_str <<
" tag. Line " << PRINTLINE(subnode));
returned_value = false;
}
}
else
{
logError(XMLPARSER, "Expected " << Max_str << " tag. Line " <<
PRINTLINE(subnode));
returned_value = false;
}
}
else
{
logError(XMLPARSER, "Expected " << Max_str << " tag. Line " <<
PRINTLINE(node));
returned_value = false;
}
}
else
{
logError(XMLPARSER, "Expected " << Min_str << " and " << Max_str << " tags. Line " <<
PRINTLINEPLUSONE(node));
returned_value = false;
}
}
else
{
logError(XMLPARSER, "Not valid tag. Expected " << DomainId_str << " or " << DomainIdRange_str <<
" tag. Line " << PRINTLINE(node));
returned_value = false;
}
}
while(returned_value && (node = node->NextSiblingElement()) != nullptr);
}
else
{
logError(XMLPARSER, "Minimum one " << DomainId_str << " or " << DomainIdRange_str << " tag. Line " <<
PRINTLINEPLUSONE(root));
}
return returned_value;
}
<commit_msg>Refs #3271. Hotfix Github #245 Parser fails on id_range if 'min' tag present but not 'max' tag (#252)<commit_after>// Copyright 2018 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 "CommonParser.h"
#include <fastrtps/log/Log.h>
#include <cassert>
#if TIXML2_MAJOR_VERSION >= 6
#define PRINTLINE(node) node->GetLineNum()
#define PRINTLINEPLUSONE(node) node->GetLineNum() + 1
#else
#define PRINTLINE(node) ""
#define PRINTLINEPLUSONE(node) ""
#endif
static const char* DomainId_str = "id";
static const char* DomainIdRange_str = "id_range";
static const char* Min_str = "min";
static const char* Max_str = "max";
using namespace eprosima::fastrtps;
using namespace ::rtps::security;
bool eprosima::fastrtps::rtps::security::parse_domain_id_set(tinyxml2::XMLElement* root, Domains& domains)
{
assert(root);
bool returned_value = false;
tinyxml2::XMLElement* node = root->FirstChildElement();
if(node != nullptr)
{
returned_value = true;
do
{
if(strcmp(node->Name(), DomainId_str) == 0)
{
uint32_t domain_id = 0;
if(tinyxml2::XMLError::XML_SUCCESS == node->QueryUnsignedText(&domain_id))
{
domains.ranges.push_back(std::make_pair(domain_id, 0));
}
else
{
logError(XMLPARSER, "Invalid value of " << DomainId_str <<
" tag. Line " << PRINTLINE(node));
returned_value = false;
}
}
else if(strcmp(node->Name() ,DomainIdRange_str) == 0)
{
tinyxml2::XMLElement* subnode = node->FirstChildElement();
if(subnode != nullptr)
{
uint32_t min_domain_id = 0;
if(strcmp(subnode->Name(), Min_str) == 0)
{
if(tinyxml2::XMLError::XML_SUCCESS != subnode->QueryUnsignedText(&min_domain_id))
{
logError(XMLPARSER, "Invalid value of " << DomainId_str <<
" tag. Line " << PRINTLINE(subnode));
returned_value = false;
}
}
else
{
logError(XMLPARSER, "Expected " << Min_str << " tag. Line " <<
PRINTLINE(subnode));
returned_value = false;
}
if(returned_value && (subnode = subnode->NextSiblingElement()) != nullptr)
{
// "Max" parameter is optional
if(strcmp(subnode->Name(), Max_str) == 0)
{
uint32_t max_domain_id = 0;
if(tinyxml2::XMLError::XML_SUCCESS == subnode->QueryUnsignedText(&max_domain_id))
{
domains.ranges.push_back(std::make_pair(min_domain_id, max_domain_id));
}
else
{
logError(XMLPARSER, "Invalid max value of " << DomainId_str <<
" tag. Line " << PRINTLINE(subnode));
returned_value = false;
}
}
else
{
domains.ranges.push_back(std::make_pair(min_domain_id, 0));
}
}
else
{
domains.ranges.push_back(std::make_pair(min_domain_id, 0));
}
}
else
{
logError(XMLPARSER, "Expected " << Min_str << " and " << Max_str << " tags. Line " <<
PRINTLINEPLUSONE(node));
returned_value = false;
}
}
else
{
logError(XMLPARSER, "Not valid tag. Expected " << DomainId_str << " or " << DomainIdRange_str <<
" tag. Line " << PRINTLINE(node));
returned_value = false;
}
}
while(returned_value && (node = node->NextSiblingElement()) != nullptr);
}
else
{
logError(XMLPARSER, "Minimum one " << DomainId_str << " or " << DomainIdRange_str << " tag. Line " <<
PRINTLINEPLUSONE(root));
}
return returned_value;
}
<|endoftext|> |
<commit_before>//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// ASTUnit Implementation.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/PCHReader.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Diagnostic.h"
#include "llvm/LLVMContext.h"
#include "llvm/System/Path.h"
using namespace clang;
ASTUnit::ASTUnit(DiagnosticClient *diagClient) : tempFile(false) {
Diags.setClient(diagClient ? diagClient : new TextDiagnosticBuffer());
}
ASTUnit::~ASTUnit() {
if (tempFile)
llvm::sys::Path(getPCHFileName()).eraseFromDisk();
// The ASTUnit object owns the DiagnosticClient.
delete Diags.getClient();
}
namespace {
/// \brief Gathers information from PCHReader that will be used to initialize
/// a Preprocessor.
class PCHInfoCollector : public PCHReaderListener {
LangOptions &LangOpt;
HeaderSearch &HSI;
std::string &TargetTriple;
std::string &Predefines;
unsigned &Counter;
unsigned NumHeaderInfos;
public:
PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
std::string &TargetTriple, std::string &Predefines,
unsigned &Counter)
: LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
LangOpt = LangOpts;
return false;
}
virtual bool ReadTargetTriple(llvm::StringRef Triple) {
TargetTriple = Triple;
return false;
}
virtual bool ReadPredefinesBuffer(llvm::StringRef PCHPredef,
FileID PCHBufferID,
llvm::StringRef OriginalFileName,
std::string &SuggestedPredefines) {
Predefines = PCHPredef;
return false;
}
virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
}
virtual void ReadCounter(unsigned Value) {
Counter = Value;
}
};
} // anonymous namespace
const std::string &ASTUnit::getOriginalSourceFileName() {
return dyn_cast<PCHReader>(Ctx->getExternalSource())->getOriginalSourceFile();
}
const std::string &ASTUnit::getPCHFileName() {
return dyn_cast<PCHReader>(Ctx->getExternalSource())->getFileName();
}
ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
std::string *ErrMsg,
DiagnosticClient *diagClient,
bool OnlyLocalDecls,
bool UseBumpAllocator) {
llvm::OwningPtr<ASTUnit> AST(new ASTUnit(diagClient));
AST->OnlyLocalDecls = OnlyLocalDecls;
AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
// Gather Info for preprocessor construction later on.
LangOptions LangInfo;
HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
std::string TargetTriple;
std::string Predefines;
unsigned Counter;
llvm::OwningPtr<PCHReader> Reader;
llvm::OwningPtr<ExternalASTSource> Source;
Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
AST->Diags));
Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Predefines, Counter));
switch (Reader->ReadPCH(Filename)) {
case PCHReader::Success:
break;
case PCHReader::Failure:
case PCHReader::IgnorePCH:
if (ErrMsg)
*ErrMsg = "Could not load PCH file";
return NULL;
}
// PCH loaded successfully. Now create the preprocessor.
// Get information about the target being compiled for.
//
// FIXME: This is broken, we should store the TargetOptions in the PCH.
TargetOptions TargetOpts;
TargetOpts.ABI = "";
TargetOpts.CPU = "";
TargetOpts.Features.clear();
TargetOpts.Triple = TargetTriple;
AST->Target.reset(TargetInfo::CreateTargetInfo(AST->Diags, TargetOpts));
AST->PP.reset(new Preprocessor(AST->Diags, LangInfo, *AST->Target.get(),
AST->getSourceManager(), HeaderInfo));
Preprocessor &PP = *AST->PP.get();
PP.setPredefines(Reader->getSuggestedPredefines());
PP.setCounterValue(Counter);
Reader->setPreprocessor(PP);
// Create and initialize the ASTContext.
AST->Ctx.reset(new ASTContext(LangInfo,
AST->getSourceManager(),
*AST->Target.get(),
PP.getIdentifierTable(),
PP.getSelectorTable(),
PP.getBuiltinInfo(),
/* FreeMemory = */ !UseBumpAllocator,
/* size_reserve = */0));
ASTContext &Context = *AST->Ctx.get();
Reader->InitializeContext(Context);
// Attach the PCH reader to the AST context as an external AST
// source, so that declarations will be deserialized from the
// PCH file as needed.
Source.reset(Reader.take());
Context.setExternalSource(Source);
return AST.take();
}
namespace {
class NullAction : public ASTFrontendAction {
virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
llvm::StringRef InFile) {
return new ASTConsumer();
}
public:
virtual bool hasCodeCompletionSupport() const { return false; }
};
}
ASTUnit *ASTUnit::LoadFromCompilerInvocation(const CompilerInvocation &CI,
Diagnostic &Diags,
bool OnlyLocalDecls,
bool UseBumpAllocator) {
// Create the compiler instance to use for building the AST.
CompilerInstance Clang(&llvm::getGlobalContext(), false);
llvm::OwningPtr<ASTUnit> AST;
NullAction Act;
Clang.getInvocation() = CI;
Clang.setDiagnostics(&Diags);
Clang.setDiagnosticClient(Diags.getClient());
// Create the target instance.
Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
Clang.getTargetOpts()));
if (!Clang.hasTarget())
goto error;
// Inform the target of the language options.
//
// FIXME: We shouldn't need to do this, the target should be immutable once
// created. This complexity should be lifted elsewhere.
Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
"Invocation must have exactly one source file!");
assert(Clang.getFrontendOpts().Inputs[0].first != FrontendOptions::IK_AST &&
"FIXME: AST inputs not yet supported here!");
// Create the AST unit.
//
// FIXME: Use the provided diagnostic client.
AST.reset(new ASTUnit());
// Create a file manager object to provide access to and cache the filesystem.
Clang.setFileManager(&AST->getFileManager());
// Create the source manager.
Clang.setSourceManager(&AST->getSourceManager());
// Create the preprocessor.
Clang.createPreprocessor();
if (!Act.BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
/*IsAST=*/false))
goto error;
Act.Execute();
// Steal the created context and preprocessor, and take back the source and
// file managers.
AST->Ctx.reset(Clang.takeASTContext());
AST->PP.reset(Clang.takePreprocessor());
Clang.takeSourceManager();
Clang.takeFileManager();
Act.EndSourceFile();
Clang.takeDiagnosticClient();
Clang.takeDiagnostics();
return AST.take();
error:
Clang.takeSourceManager();
Clang.takeFileManager();
Clang.takeDiagnosticClient();
Clang.takeDiagnostics();
return 0;
}
<commit_msg>ASTUnit: Make sure to preserve the TargetInfo for later use.<commit_after>//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// ASTUnit Implementation.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/PCHReader.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Diagnostic.h"
#include "llvm/LLVMContext.h"
#include "llvm/System/Path.h"
using namespace clang;
ASTUnit::ASTUnit(DiagnosticClient *diagClient) : tempFile(false) {
Diags.setClient(diagClient ? diagClient : new TextDiagnosticBuffer());
}
ASTUnit::~ASTUnit() {
if (tempFile)
llvm::sys::Path(getPCHFileName()).eraseFromDisk();
// The ASTUnit object owns the DiagnosticClient.
delete Diags.getClient();
}
namespace {
/// \brief Gathers information from PCHReader that will be used to initialize
/// a Preprocessor.
class PCHInfoCollector : public PCHReaderListener {
LangOptions &LangOpt;
HeaderSearch &HSI;
std::string &TargetTriple;
std::string &Predefines;
unsigned &Counter;
unsigned NumHeaderInfos;
public:
PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
std::string &TargetTriple, std::string &Predefines,
unsigned &Counter)
: LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
LangOpt = LangOpts;
return false;
}
virtual bool ReadTargetTriple(llvm::StringRef Triple) {
TargetTriple = Triple;
return false;
}
virtual bool ReadPredefinesBuffer(llvm::StringRef PCHPredef,
FileID PCHBufferID,
llvm::StringRef OriginalFileName,
std::string &SuggestedPredefines) {
Predefines = PCHPredef;
return false;
}
virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI) {
HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
}
virtual void ReadCounter(unsigned Value) {
Counter = Value;
}
};
} // anonymous namespace
const std::string &ASTUnit::getOriginalSourceFileName() {
return dyn_cast<PCHReader>(Ctx->getExternalSource())->getOriginalSourceFile();
}
const std::string &ASTUnit::getPCHFileName() {
return dyn_cast<PCHReader>(Ctx->getExternalSource())->getFileName();
}
ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
std::string *ErrMsg,
DiagnosticClient *diagClient,
bool OnlyLocalDecls,
bool UseBumpAllocator) {
llvm::OwningPtr<ASTUnit> AST(new ASTUnit(diagClient));
AST->OnlyLocalDecls = OnlyLocalDecls;
AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
// Gather Info for preprocessor construction later on.
LangOptions LangInfo;
HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
std::string TargetTriple;
std::string Predefines;
unsigned Counter;
llvm::OwningPtr<PCHReader> Reader;
llvm::OwningPtr<ExternalASTSource> Source;
Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
AST->Diags));
Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Predefines, Counter));
switch (Reader->ReadPCH(Filename)) {
case PCHReader::Success:
break;
case PCHReader::Failure:
case PCHReader::IgnorePCH:
if (ErrMsg)
*ErrMsg = "Could not load PCH file";
return NULL;
}
// PCH loaded successfully. Now create the preprocessor.
// Get information about the target being compiled for.
//
// FIXME: This is broken, we should store the TargetOptions in the PCH.
TargetOptions TargetOpts;
TargetOpts.ABI = "";
TargetOpts.CPU = "";
TargetOpts.Features.clear();
TargetOpts.Triple = TargetTriple;
AST->Target.reset(TargetInfo::CreateTargetInfo(AST->Diags, TargetOpts));
AST->PP.reset(new Preprocessor(AST->Diags, LangInfo, *AST->Target.get(),
AST->getSourceManager(), HeaderInfo));
Preprocessor &PP = *AST->PP.get();
PP.setPredefines(Reader->getSuggestedPredefines());
PP.setCounterValue(Counter);
Reader->setPreprocessor(PP);
// Create and initialize the ASTContext.
AST->Ctx.reset(new ASTContext(LangInfo,
AST->getSourceManager(),
*AST->Target.get(),
PP.getIdentifierTable(),
PP.getSelectorTable(),
PP.getBuiltinInfo(),
/* FreeMemory = */ !UseBumpAllocator,
/* size_reserve = */0));
ASTContext &Context = *AST->Ctx.get();
Reader->InitializeContext(Context);
// Attach the PCH reader to the AST context as an external AST
// source, so that declarations will be deserialized from the
// PCH file as needed.
Source.reset(Reader.take());
Context.setExternalSource(Source);
return AST.take();
}
namespace {
class NullAction : public ASTFrontendAction {
virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
llvm::StringRef InFile) {
return new ASTConsumer();
}
public:
virtual bool hasCodeCompletionSupport() const { return false; }
};
}
ASTUnit *ASTUnit::LoadFromCompilerInvocation(const CompilerInvocation &CI,
Diagnostic &Diags,
bool OnlyLocalDecls,
bool UseBumpAllocator) {
// Create the compiler instance to use for building the AST.
CompilerInstance Clang(&llvm::getGlobalContext(), false);
llvm::OwningPtr<ASTUnit> AST;
NullAction Act;
Clang.getInvocation() = CI;
Clang.setDiagnostics(&Diags);
Clang.setDiagnosticClient(Diags.getClient());
// Create the target instance.
Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
Clang.getTargetOpts()));
if (!Clang.hasTarget())
goto error;
// Inform the target of the language options.
//
// FIXME: We shouldn't need to do this, the target should be immutable once
// created. This complexity should be lifted elsewhere.
Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
"Invocation must have exactly one source file!");
assert(Clang.getFrontendOpts().Inputs[0].first != FrontendOptions::IK_AST &&
"FIXME: AST inputs not yet supported here!");
// Create the AST unit.
//
// FIXME: Use the provided diagnostic client.
AST.reset(new ASTUnit());
// Create a file manager object to provide access to and cache the filesystem.
Clang.setFileManager(&AST->getFileManager());
// Create the source manager.
Clang.setSourceManager(&AST->getSourceManager());
// Create the preprocessor.
Clang.createPreprocessor();
if (!Act.BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
/*IsAST=*/false))
goto error;
Act.Execute();
// Steal the created target, context, and preprocessor, and take back the
// source and file managers.
AST->Ctx.reset(Clang.takeASTContext());
AST->PP.reset(Clang.takePreprocessor());
Clang.takeSourceManager();
Clang.takeFileManager();
AST->Target.reset(Clang.takeTarget());
Act.EndSourceFile();
Clang.takeDiagnosticClient();
Clang.takeDiagnostics();
return AST.take();
error:
Clang.takeSourceManager();
Clang.takeFileManager();
Clang.takeDiagnosticClient();
Clang.takeDiagnostics();
return 0;
}
<|endoftext|> |
<commit_before>/*
* SessionPdfLatex.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPdfLatex.hpp"
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <core/system/Environment.hpp>
#include <core/FileSerializer.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include "SessionTexUtils.hpp"
using namespace core;
namespace session {
namespace modules {
namespace tex {
namespace pdflatex {
namespace {
class LatexProgramTypes : boost::noncopyable
{
public:
LatexProgramTypes()
{
types_.push_back("pdfLaTeX");
types_.push_back("XeLaTeX");
}
const std::vector<std::string>& allTypes() const
{
return types_;
}
json::Array allTypesAsJson() const
{
json::Array typesJson;
std::transform(types_.begin(),
types_.end(),
std::back_inserter(typesJson),
json::toJsonString);
return typesJson;
}
bool isValidTypeName(const std::string& name) const
{
BOOST_FOREACH(const std::string& type, types_)
{
if (boost::algorithm::iequals(name, type))
return true;
}
return false;
}
std::string printableTypeNames() const
{
if (types_.size() == 1)
return types_[0];
else if (types_.size() == 2)
return types_[0] + " and " + types_[1];
else
{
std::string str;
for (std::size_t i=0; i<types_.size(); i++)
{
str.append(types_[i]);
if (i != (types_.size() - 1))
str.append(", ");
if (i == (types_.size() - 2))
str.append("and ");
}
return str;
}
}
private:
std::vector<std::string> types_;
};
const LatexProgramTypes& programTypes()
{
static LatexProgramTypes instance;
return instance;
}
std::string latexProgramMagicComment(
const core::tex::TexMagicComments& magicComments)
{
BOOST_FOREACH(const core::tex::TexMagicComment& mc, magicComments)
{
if (boost::algorithm::iequals(mc.scope(), "tex") &&
(boost::algorithm::iequals(mc.variable(), "program") ||
boost::algorithm::iequals(mc.variable(), "ts-program")))
{
return mc.value();
}
}
return std::string();
}
void setInvalidProgramTypeMessage(const std::string& program,
std::string* pUserErrMsg)
{
*pUserErrMsg = "Unknown LaTeX program type '" + program +
"' specified (valid types are " +
programTypes().printableTypeNames() + ")";
}
bool validateLatexProgram(const std::string& program,
FilePath* pTexProgramPath,
std::string* pUserErrMsg)
{
// convert to lower case for finding
std::string programName = string_utils::toLower(program);
// try to find on the path
*pTexProgramPath = module_context::findProgram(programName);
if (pTexProgramPath->empty())
{
*pUserErrMsg = "Unabled to find specified LaTeX program '" +
program + "' on the system path";
return false;
}
else
{
return true;
}
}
bool validateLatexProgramType(const std::string& programType,
std::string* pUserErrMsg)
{
if (!programTypes().isValidTypeName(programType))
{
setInvalidProgramTypeMessage(programType, pUserErrMsg);
return false;
}
else
{
return true;
}
}
void appendEnvVarNotice(std::string* pUserErrMsg)
{
pUserErrMsg->append(" (the program was specified using the "
"RSTUDIO_PDFLATEX environment variable)");
}
shell_utils::ShellArgs shellArgs(const PdfLatexOptions& options)
{
shell_utils::ShellArgs args;
if (options.fileLineError)
{
if (options.isMikTeX())
args << kCStyleErrorsOption;
else
args << kFileLineErrorOption;
}
if (options.syncTex)
{
args << kSynctexOption;
}
if (options.shellEscape)
{
if (options.isMikTeX())
args << kEnableWrite18Option;
else
args << kShellEscapeOption;
}
args << "-interaction=nonstopmode";
return args;
}
FilePath programPath(const std::string& name, const std::string& envOverride)
{
std::string envProgram = core::system::getenv(envOverride);
std::string program = envProgram.empty() ? name : envProgram;
return module_context::findProgram(program);
}
bool lineIncludes(const std::string& line, const boost::regex& regex)
{
boost::smatch match;
return boost::regex_search(line, match, regex);
}
int countCitationMisses(const FilePath& logFilePath)
{
// read the log file
std::vector<std::string> lines;
Error error = core::readStringVectorFromFile(logFilePath, &lines);
if (error)
{
LOG_ERROR(error);
return 0;
}
// look for misses
boost::regex missRegex("Warning:.*Citation.*undefined");
int misses = std::count_if(lines.begin(),
lines.end(),
boost::bind(lineIncludes, _1, missRegex));
return misses;
}
bool logIncludesRerun(const FilePath& logFilePath)
{
std::string logContents;
Error error = core::readStringFromFile(logFilePath, &logContents);
if (error)
{
LOG_ERROR(error);
return false;
}
return logContents.find("Rerun to get") != std::string::npos;
}
} // anonymous namespace
const char * const kFileLineErrorOption = "-file-line-error";
const char * const kCStyleErrorsOption = "-c-style-errors";
const char * const kShellEscapeOption = "-shell-escape";
const char * const kEnableWrite18Option = "–enable-write18";
const char * const kSynctexOption = "-synctex=-1";
bool isInstalled()
{
return !module_context::findProgram("pdflatex").empty();
}
core::json::Array supportedTypes()
{
return programTypes().allTypesAsJson();
}
bool latexProgramForFile(const core::tex::TexMagicComments& magicComments,
FilePath* pTexProgramPath,
std::string* pUserErrMsg)
{
// get (optional) magic comments and environment variable override
std::string latexProgramMC = latexProgramMagicComment(magicComments);
std::string pdflatexEnv = core::system::getenv("RSTUDIO_PDFLATEX");
// magic comment always takes highest priority
if (!latexProgramMC.empty())
{
// validate magic comment
if (!validateLatexProgramType(latexProgramMC, pUserErrMsg))
{
return false;
}
else
{
return validateLatexProgram(latexProgramMC,
pTexProgramPath,
pUserErrMsg);
}
}
// next is environment variable
else if (!pdflatexEnv.empty())
{
if (FilePath::isRootPath(pdflatexEnv))
{
FilePath texProgramPath(pdflatexEnv);
if (texProgramPath.exists())
{
*pTexProgramPath = texProgramPath;
return true;
}
else
{
*pUserErrMsg = "Unabled to find specified LaTeX program " +
pdflatexEnv;
appendEnvVarNotice(pUserErrMsg);
return false;
}
}
else
{
bool validated = validateLatexProgram(pdflatexEnv,
pTexProgramPath,
pUserErrMsg);
if (!validated)
appendEnvVarNotice(pUserErrMsg);
return validated;
}
}
// project or global default setting
else
{
std::string defaultProgram = projects::projectContext().hasProject() ?
projects::projectContext().config().defaultLatexProgram :
userSettings().defaultLatexProgram();
if (!validateLatexProgramType(defaultProgram, pUserErrMsg))
{
return false;
}
else
{
return validateLatexProgram(defaultProgram,
pTexProgramPath,
pUserErrMsg);
}
}
}
// this function provides an "emulated" version of texi2dvi for when the
// user has texi2dvi disabled. For example to workaround this bug:
//
// http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458
//
// this code is a port of the simillar logic which exists in the
// tools::texi2dvi function (but the regex for detecting citation
// warnings was made a bit more liberal)
//
core::Error texToPdf(const core::FilePath& texProgramPath,
const core::FilePath& texFilePath,
const tex::pdflatex::PdfLatexOptions& options,
core::system::ProcessResult* pResult)
{
// input file paths
FilePath baseFilePath = texFilePath.parent().complete(texFilePath.stem());
FilePath idxFilePath(baseFilePath.absolutePath() + ".idx");
FilePath logFilePath(baseFilePath.absolutePath() + ".log");
// bibtex and makeindex program paths
FilePath bibtexProgramPath = programPath("bibtex", "BIBTEX");
FilePath makeindexProgramPath = programPath("makeindex", "MAKEINDEX");
// args and process options for running bibtex and makeindex
core::shell_utils::ShellArgs bibtexArgs;
bibtexArgs << string_utils::utf8ToSystem(baseFilePath.filename());
core::shell_utils::ShellArgs makeindexArgs;
makeindexArgs << string_utils::utf8ToSystem(idxFilePath.filename());
core::system::ProcessOptions procOptions;
procOptions.environment = utils::rTexInputsEnvVars();
procOptions.workingDir = texFilePath.parent();
// run the initial compile
Error error = utils::runTexCompile(texProgramPath,
utils::rTexInputsEnvVars(),
shellArgs(options),
texFilePath,
pResult);
if (error)
return error;
// count misses
int misses = countCitationMisses(logFilePath);
int previousMisses = 0;
// resolve citation misses and index
for (int i=0; i<10; i++)
{
// run bibtex if necessary
if (misses > 0 && !bibtexProgramPath.empty())
{
core::system::ProcessResult result;
Error error = core::system::runProgram(
string_utils::utf8ToSystem(bibtexProgramPath.absolutePath()),
bibtexArgs,
"",
procOptions,
pResult);
if (error)
LOG_ERROR(error);
else if (pResult->exitStatus != EXIT_SUCCESS)
return Success(); // pass error state on to caller
}
previousMisses = misses;
// run makeindex if necessary
if (idxFilePath.exists() && !makeindexProgramPath.empty())
{
Error error = core::system::runProgram(
string_utils::utf8ToSystem(makeindexProgramPath.absolutePath()),
makeindexArgs,
"",
procOptions,
pResult);
if (error)
LOG_ERROR(error);
else if (pResult->exitStatus != EXIT_SUCCESS)
return Success(); // pass error state on to caller
}
// re-run latex
Error error = utils::runTexCompile(texProgramPath,
utils::rTexInputsEnvVars(),
shellArgs(options),
texFilePath,
pResult);
if (error)
return error;
// count misses
misses = countCitationMisses(logFilePath);
// if there is no change in misses and there is no "Rerun to get"
// in the log file then break
if ((misses == previousMisses) && !logIncludesRerun(logFilePath))
break;
}
return Success();
}
} // namespace pdflatex
} // namespace tex
} // namespace modules
} // namesapce session
<commit_msg>use compressed synctex<commit_after>/*
* SessionPdfLatex.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPdfLatex.hpp"
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <core/system/Environment.hpp>
#include <core/FileSerializer.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionUserSettings.hpp>
#include <session/SessionModuleContext.hpp>
#include "SessionTexUtils.hpp"
using namespace core;
namespace session {
namespace modules {
namespace tex {
namespace pdflatex {
namespace {
class LatexProgramTypes : boost::noncopyable
{
public:
LatexProgramTypes()
{
types_.push_back("pdfLaTeX");
types_.push_back("XeLaTeX");
}
const std::vector<std::string>& allTypes() const
{
return types_;
}
json::Array allTypesAsJson() const
{
json::Array typesJson;
std::transform(types_.begin(),
types_.end(),
std::back_inserter(typesJson),
json::toJsonString);
return typesJson;
}
bool isValidTypeName(const std::string& name) const
{
BOOST_FOREACH(const std::string& type, types_)
{
if (boost::algorithm::iequals(name, type))
return true;
}
return false;
}
std::string printableTypeNames() const
{
if (types_.size() == 1)
return types_[0];
else if (types_.size() == 2)
return types_[0] + " and " + types_[1];
else
{
std::string str;
for (std::size_t i=0; i<types_.size(); i++)
{
str.append(types_[i]);
if (i != (types_.size() - 1))
str.append(", ");
if (i == (types_.size() - 2))
str.append("and ");
}
return str;
}
}
private:
std::vector<std::string> types_;
};
const LatexProgramTypes& programTypes()
{
static LatexProgramTypes instance;
return instance;
}
std::string latexProgramMagicComment(
const core::tex::TexMagicComments& magicComments)
{
BOOST_FOREACH(const core::tex::TexMagicComment& mc, magicComments)
{
if (boost::algorithm::iequals(mc.scope(), "tex") &&
(boost::algorithm::iequals(mc.variable(), "program") ||
boost::algorithm::iequals(mc.variable(), "ts-program")))
{
return mc.value();
}
}
return std::string();
}
void setInvalidProgramTypeMessage(const std::string& program,
std::string* pUserErrMsg)
{
*pUserErrMsg = "Unknown LaTeX program type '" + program +
"' specified (valid types are " +
programTypes().printableTypeNames() + ")";
}
bool validateLatexProgram(const std::string& program,
FilePath* pTexProgramPath,
std::string* pUserErrMsg)
{
// convert to lower case for finding
std::string programName = string_utils::toLower(program);
// try to find on the path
*pTexProgramPath = module_context::findProgram(programName);
if (pTexProgramPath->empty())
{
*pUserErrMsg = "Unabled to find specified LaTeX program '" +
program + "' on the system path";
return false;
}
else
{
return true;
}
}
bool validateLatexProgramType(const std::string& programType,
std::string* pUserErrMsg)
{
if (!programTypes().isValidTypeName(programType))
{
setInvalidProgramTypeMessage(programType, pUserErrMsg);
return false;
}
else
{
return true;
}
}
void appendEnvVarNotice(std::string* pUserErrMsg)
{
pUserErrMsg->append(" (the program was specified using the "
"RSTUDIO_PDFLATEX environment variable)");
}
shell_utils::ShellArgs shellArgs(const PdfLatexOptions& options)
{
shell_utils::ShellArgs args;
if (options.fileLineError)
{
if (options.isMikTeX())
args << kCStyleErrorsOption;
else
args << kFileLineErrorOption;
}
if (options.syncTex)
{
args << kSynctexOption;
}
if (options.shellEscape)
{
if (options.isMikTeX())
args << kEnableWrite18Option;
else
args << kShellEscapeOption;
}
args << "-interaction=nonstopmode";
return args;
}
FilePath programPath(const std::string& name, const std::string& envOverride)
{
std::string envProgram = core::system::getenv(envOverride);
std::string program = envProgram.empty() ? name : envProgram;
return module_context::findProgram(program);
}
bool lineIncludes(const std::string& line, const boost::regex& regex)
{
boost::smatch match;
return boost::regex_search(line, match, regex);
}
int countCitationMisses(const FilePath& logFilePath)
{
// read the log file
std::vector<std::string> lines;
Error error = core::readStringVectorFromFile(logFilePath, &lines);
if (error)
{
LOG_ERROR(error);
return 0;
}
// look for misses
boost::regex missRegex("Warning:.*Citation.*undefined");
int misses = std::count_if(lines.begin(),
lines.end(),
boost::bind(lineIncludes, _1, missRegex));
return misses;
}
bool logIncludesRerun(const FilePath& logFilePath)
{
std::string logContents;
Error error = core::readStringFromFile(logFilePath, &logContents);
if (error)
{
LOG_ERROR(error);
return false;
}
return logContents.find("Rerun to get") != std::string::npos;
}
} // anonymous namespace
const char * const kFileLineErrorOption = "-file-line-error";
const char * const kCStyleErrorsOption = "-c-style-errors";
const char * const kShellEscapeOption = "-shell-escape";
const char * const kEnableWrite18Option = "–enable-write18";
const char * const kSynctexOption = "-synctex=1";
bool isInstalled()
{
return !module_context::findProgram("pdflatex").empty();
}
core::json::Array supportedTypes()
{
return programTypes().allTypesAsJson();
}
bool latexProgramForFile(const core::tex::TexMagicComments& magicComments,
FilePath* pTexProgramPath,
std::string* pUserErrMsg)
{
// get (optional) magic comments and environment variable override
std::string latexProgramMC = latexProgramMagicComment(magicComments);
std::string pdflatexEnv = core::system::getenv("RSTUDIO_PDFLATEX");
// magic comment always takes highest priority
if (!latexProgramMC.empty())
{
// validate magic comment
if (!validateLatexProgramType(latexProgramMC, pUserErrMsg))
{
return false;
}
else
{
return validateLatexProgram(latexProgramMC,
pTexProgramPath,
pUserErrMsg);
}
}
// next is environment variable
else if (!pdflatexEnv.empty())
{
if (FilePath::isRootPath(pdflatexEnv))
{
FilePath texProgramPath(pdflatexEnv);
if (texProgramPath.exists())
{
*pTexProgramPath = texProgramPath;
return true;
}
else
{
*pUserErrMsg = "Unabled to find specified LaTeX program " +
pdflatexEnv;
appendEnvVarNotice(pUserErrMsg);
return false;
}
}
else
{
bool validated = validateLatexProgram(pdflatexEnv,
pTexProgramPath,
pUserErrMsg);
if (!validated)
appendEnvVarNotice(pUserErrMsg);
return validated;
}
}
// project or global default setting
else
{
std::string defaultProgram = projects::projectContext().hasProject() ?
projects::projectContext().config().defaultLatexProgram :
userSettings().defaultLatexProgram();
if (!validateLatexProgramType(defaultProgram, pUserErrMsg))
{
return false;
}
else
{
return validateLatexProgram(defaultProgram,
pTexProgramPath,
pUserErrMsg);
}
}
}
// this function provides an "emulated" version of texi2dvi for when the
// user has texi2dvi disabled. For example to workaround this bug:
//
// http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=534458
//
// this code is a port of the simillar logic which exists in the
// tools::texi2dvi function (but the regex for detecting citation
// warnings was made a bit more liberal)
//
core::Error texToPdf(const core::FilePath& texProgramPath,
const core::FilePath& texFilePath,
const tex::pdflatex::PdfLatexOptions& options,
core::system::ProcessResult* pResult)
{
// input file paths
FilePath baseFilePath = texFilePath.parent().complete(texFilePath.stem());
FilePath idxFilePath(baseFilePath.absolutePath() + ".idx");
FilePath logFilePath(baseFilePath.absolutePath() + ".log");
// bibtex and makeindex program paths
FilePath bibtexProgramPath = programPath("bibtex", "BIBTEX");
FilePath makeindexProgramPath = programPath("makeindex", "MAKEINDEX");
// args and process options for running bibtex and makeindex
core::shell_utils::ShellArgs bibtexArgs;
bibtexArgs << string_utils::utf8ToSystem(baseFilePath.filename());
core::shell_utils::ShellArgs makeindexArgs;
makeindexArgs << string_utils::utf8ToSystem(idxFilePath.filename());
core::system::ProcessOptions procOptions;
procOptions.environment = utils::rTexInputsEnvVars();
procOptions.workingDir = texFilePath.parent();
// run the initial compile
Error error = utils::runTexCompile(texProgramPath,
utils::rTexInputsEnvVars(),
shellArgs(options),
texFilePath,
pResult);
if (error)
return error;
// count misses
int misses = countCitationMisses(logFilePath);
int previousMisses = 0;
// resolve citation misses and index
for (int i=0; i<10; i++)
{
// run bibtex if necessary
if (misses > 0 && !bibtexProgramPath.empty())
{
core::system::ProcessResult result;
Error error = core::system::runProgram(
string_utils::utf8ToSystem(bibtexProgramPath.absolutePath()),
bibtexArgs,
"",
procOptions,
pResult);
if (error)
LOG_ERROR(error);
else if (pResult->exitStatus != EXIT_SUCCESS)
return Success(); // pass error state on to caller
}
previousMisses = misses;
// run makeindex if necessary
if (idxFilePath.exists() && !makeindexProgramPath.empty())
{
Error error = core::system::runProgram(
string_utils::utf8ToSystem(makeindexProgramPath.absolutePath()),
makeindexArgs,
"",
procOptions,
pResult);
if (error)
LOG_ERROR(error);
else if (pResult->exitStatus != EXIT_SUCCESS)
return Success(); // pass error state on to caller
}
// re-run latex
Error error = utils::runTexCompile(texProgramPath,
utils::rTexInputsEnvVars(),
shellArgs(options),
texFilePath,
pResult);
if (error)
return error;
// count misses
misses = countCitationMisses(logFilePath);
// if there is no change in misses and there is no "Rerun to get"
// in the log file then break
if ((misses == previousMisses) && !logIncludesRerun(logFilePath))
break;
}
return Success();
}
} // namespace pdflatex
} // namespace tex
} // namespace modules
} // namesapce session
<|endoftext|> |
<commit_before><commit_msg>replace auto with type<commit_after><|endoftext|> |
<commit_before>/*!
* \file
* \brief Monitors the simulated frames, tells if there is a frame errors and counts the number of bit errors.
*
* \section LICENSE
* This file is under MIT license (https://opensource.org/licenses/MIT).
*/
#ifndef MONITOR_HPP_
#define MONITOR_HPP_
#include <stdexcept>
#include <csignal>
#include <chrono>
#include <vector>
#include <string>
#include "Tools/Perf/MIPP/mipp.h"
#include "Module/Module.hpp"
namespace aff3ct
{
namespace module
{
/*!
* \class Monitor_i
*
* \brief Monitors the simulated frames, tells if there is a frame errors and counts the number of bit errors.
*
* \tparam B: type of the bits in the frames to compare.
* \tparam R: type of the samples in the channel frame.
*
* Please use Monitor for inheritance (instead of Monitor_i).
*/
template <typename B = int, typename R = float>
class Monitor_i : public Module
{
protected:
static bool interrupt; /*!< True if there is a SIGINT signal (ctrl+C). */
static bool first_interrupt; /*!< True if this is the first time that SIGIN is called. */
static bool over; /*!< True if SIGINT is called twice in the Monitor_i::d_delta_interrupt time */
static std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> t_last_interrupt; /*!< Time point of the last call to SIGINT */
static std::chrono::nanoseconds d_delta_interrupt; /*!< Delta time. */
const int K; /*!< Number of information bits in one frame */
const int N; /*!< Size of one encoded frame (= number of bits in one frame) */
const int N_mod;
public:
/*!
* \brief Constructor.
*
* Registers the SIGINT (signal interrupt or ctrl+C) interruption.
*
* \param K: number of information bits in the frame.
* \param N: size of one frame.
* \param n_frames: number of frames to process in the Monitor.
* \param name: Monitor's name.
*/
Monitor_i(const int& K, const int& N, const int& N_mod, const int& n_frames = 1,
const std::string name = "Monitor_i")
: Module(n_frames, name), K(K), N(N), N_mod(N_mod)
{
if (this->K <= 0)
throw std::invalid_argument("aff3ct::module::Monitor: \"K\" has to be greater than 0.");
if (this->N <= 0)
throw std::invalid_argument("aff3ct::module::Monitor: \"N\" has to be greater than 0.");
if (this->N_mod <= 0)
throw std::invalid_argument("aff3ct::module::Monitor: \"N_mod\" has to be greater than 0.");
if (this->K > this->N)
throw std::invalid_argument("aff3ct::module::Monitor: \"K\" has to be smaller than \"N\".");
Monitor_i<B,R>::interrupt = false;
Monitor_i<B,R>::d_delta_interrupt = std::chrono::nanoseconds(0);
#ifndef ENABLE_MPI
// Install a signal handler
std::signal(SIGINT, Monitor_i<B,R>::signal_interrupt_handler);
#endif
}
/*!
* \brief Destructor.
*/
virtual ~Monitor_i()
{
}
/*!
* \brief Gets the frame size.
*
* \return the frame size.
*/
int get_N() const
{
return N;
}
int get_N_mod() const
{
return N_mod;
}
/*!
* \brief Gets the number of information bits in a frame.
*
* \return the number of information bits.
*/
int get_K() const
{
return K;
}
/*!
* \brief Gets the number of bit errors.
*
* \return the number of bit errors.
*/
virtual unsigned long long get_n_be() const = 0;
/*!
* \brief Gets the number of frame errors.
*
* \return the number of frame errors.
*/
virtual unsigned long long get_n_fe() const = 0;
/*!
* \brief Gets the bit error rate.
*
* \return the bit error rate.
*/
virtual float get_ber() const = 0;
/*!
* \brief Gets the frame error rate.
*
* \return the frame error rate.
*/
virtual float get_fer() const = 0;
/*!
* \brief Gets the number of analyzed frames (analyzed in the Monitor_i::check_errors method).
*
* \return the number of analyzed frames.
*/
virtual unsigned long long get_n_analyzed_fra() const = 0;
/*!
* \brief Gets the frame errors limit (maximal number of frame errors to simulate).
*
* \return the frame errors limit.
*/
virtual unsigned get_fe_limit() const = 0;
/*!
* \brief Tells if the frame errors limit is achieved (in this case the current computations should stop).
*
* \return true if the frame errors limit is achieved.
*/
virtual bool fe_limit_achieved() = 0;
/*!
* \brief Compares two messages and counts the number of frame errors and bit errors.
*
* Typically this method is called at the very end of a communication chain.
*
* \param U: the original message (from the Source or the CRC).
* \param V: the decoded message (from the Decoder).
*/
void check_errors(const mipp::vector<B>& U_K, const mipp::vector<B>& V_K)
{
if ((int)U_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"U_K.size()\" has to be equal to \"K * n_frames\".");
if ((int)V_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"V_K.size()\" has to be equal to \"K * n_frames\".");
this->check_errors(U_K.data(), V_K.data());
}
virtual void check_errors(const B *U_K, const B *V_K)
{
for (auto f = 0; f < this->n_frames; f++)
this->_check_errors(U_K + f * this->K,
V_K + f * this->K);
}
/*!
* \brief Tells if the user asked for stopping the current computations.
*
* \return true if the SIGINT (ctrl+c) is called.
*/
static bool is_interrupt()
{
return Monitor_i<B,R>::interrupt;
}
/*!
* \brief Tells if the user asked for stopping the whole simulation.
*
* \return true if the SIGINT (ctrl+c) is called twice.
*/
static bool is_over()
{
return Monitor_i<B,R>::over;
}
/*!
* \brief Put Monitor_i<B,R>::interrupt and Monitor_i<B,R>::over to true.
*/
static void stop()
{
Monitor_i<B,R>::interrupt = true;
Monitor_i<B,R>::over = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// The following public methods are specific to catch the bad frames and to dump them into files. //
// The proposed default implementation do nothing. //
////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
* \brief Compares two messages and counts the number of frame errors and bit errors.
*
* Typically this method is called at the very end of a communication chain.
*
* \param U: the original message (from the Source or the CRC).
* \param V: the decoded message (from the Decoder).
* \param X: the encoded message (from the Encoder).
* \param X_mod: the modulated message (from the Modulator, the input of the Channel).
* \param Y: the noised message (the output of the Channel).
*/
void check_and_track_errors(const mipp::vector<B>& U_K,
const mipp::vector<B>& V_K,
const mipp::vector<B>& X_N,
const mipp::vector<R>& Y_N_mod)
{
if ((int)U_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"U_K.size()\" has to be equal to \"K * n_frames\".");
if ((int)V_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"V_K.size()\" has to be equal to \"K * n_frames\".");
if ((int)X_N.size() != this->N * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"X_N.size()\" has to be equal to \"N * n_frames\".");
if ((int)Y_N_mod.size() != this->N_mod * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"Y_N_mod.size()\" has to be equal to "
"\"N_mod * n_frames\".");
this->check_and_track_errors(U_K.data(), V_K.data(), X_N.data(), Y_N_mod.data());
}
virtual void check_and_track_errors(const B *U_K, const B *V_K, const B *X_N, const R *Y_N_mod)
{
for (auto f = 0; f < this->n_frames; f++)
this->_check_and_track_errors(U_K + f * this->K,
V_K + f * this->K,
X_N + f * this->N,
Y_N_mod + f * this->N_mod);
}
/*!
* \brief Write the bad frames into files.
*
* \param base_path: base path for files to write the bad frames.
* \param snr: the current SNR.
*/
virtual void dump_bad_frames(const std::string& base_path, const float snr, const mipp::vector<int>& itl_pi = mipp::vector<int>(0))
{
}
/*!
* \brief get the buffer recording the wrong frames from the source
*
* \return a reference to the buffer recording the wrong frames from the source
*/
virtual const std::vector<mipp::vector<B>> get_buff_src() const
{
return std::vector<mipp::vector<B>>(0);
}
/*!
* \brief get the buffer recording the wrong frames from the encoder
*
* \return a reference to the buffer recording the wrong frames from the encoder
*/
virtual const std::vector<mipp::vector<B>> get_buff_enc() const
{
return std::vector<mipp::vector<B>>(0);
}
/*!
* \brief get the buffer recording the noise added to the wrong frames in the channel
*
* \return a reference to the buffer recording the noise added to the wrong frames in the channel
*/
virtual const std::vector<mipp::vector<R>> get_buff_noise() const
{
return std::vector<mipp::vector<R>>(0);
}
protected:
virtual void _check_errors(const B *U, const B *V)
{
throw std::runtime_error("aff3ct::module::Monitor: \"_check_errors\" is unimplemented.");
}
void _check_and_track_errors(const B *U_K, const B *V_K, const B *X_N, const R *Y_N_mod)
{
throw std::runtime_error("aff3ct::module::Monitor: \"_check_and_track_errors\" is unimplemented.");
}
private:
static void signal_interrupt_handler(int signal)
{
auto t_now = std::chrono::steady_clock::now();
if (!Monitor_i<B,R>::first_interrupt)
{
Monitor_i<B,R>::d_delta_interrupt = t_now - Monitor_i<B,R>::t_last_interrupt;
if (Monitor_i<B,R>::d_delta_interrupt < std::chrono::milliseconds(500))
Monitor_i<B,R>::stop();
}
Monitor_i<B,R>::t_last_interrupt = t_now;
Monitor_i<B,R>::first_interrupt = false;
Monitor_i<B,R>::interrupt = true;
}
};
template <typename B, typename R>
bool Monitor_i<B,R>::interrupt = false;
template <typename B, typename R>
bool Monitor_i<B,R>::first_interrupt = true;
template <typename B, typename R>
bool Monitor_i<B,R>::over = false;
template <typename B, typename R>
std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> Monitor_i<B,R>::t_last_interrupt;
template <typename B, typename R>
std::chrono::nanoseconds Monitor_i<B,R>::d_delta_interrupt = std::chrono::nanoseconds(0);
}
}
#include "SC_Monitor.hpp"
#endif /* MONITOR_HPP_ */
<commit_msg>Fix the error tracker.<commit_after>/*!
* \file
* \brief Monitors the simulated frames, tells if there is a frame errors and counts the number of bit errors.
*
* \section LICENSE
* This file is under MIT license (https://opensource.org/licenses/MIT).
*/
#ifndef MONITOR_HPP_
#define MONITOR_HPP_
#include <stdexcept>
#include <csignal>
#include <chrono>
#include <vector>
#include <string>
#include "Tools/Perf/MIPP/mipp.h"
#include "Module/Module.hpp"
namespace aff3ct
{
namespace module
{
/*!
* \class Monitor_i
*
* \brief Monitors the simulated frames, tells if there is a frame errors and counts the number of bit errors.
*
* \tparam B: type of the bits in the frames to compare.
* \tparam R: type of the samples in the channel frame.
*
* Please use Monitor for inheritance (instead of Monitor_i).
*/
template <typename B = int, typename R = float>
class Monitor_i : public Module
{
protected:
static bool interrupt; /*!< True if there is a SIGINT signal (ctrl+C). */
static bool first_interrupt; /*!< True if this is the first time that SIGIN is called. */
static bool over; /*!< True if SIGINT is called twice in the Monitor_i::d_delta_interrupt time */
static std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> t_last_interrupt; /*!< Time point of the last call to SIGINT */
static std::chrono::nanoseconds d_delta_interrupt; /*!< Delta time. */
const int K; /*!< Number of information bits in one frame */
const int N; /*!< Size of one encoded frame (= number of bits in one frame) */
const int N_mod;
public:
/*!
* \brief Constructor.
*
* Registers the SIGINT (signal interrupt or ctrl+C) interruption.
*
* \param K: number of information bits in the frame.
* \param N: size of one frame.
* \param n_frames: number of frames to process in the Monitor.
* \param name: Monitor's name.
*/
Monitor_i(const int& K, const int& N, const int& N_mod, const int& n_frames = 1,
const std::string name = "Monitor_i")
: Module(n_frames, name), K(K), N(N), N_mod(N_mod)
{
if (this->K <= 0)
throw std::invalid_argument("aff3ct::module::Monitor: \"K\" has to be greater than 0.");
if (this->N <= 0)
throw std::invalid_argument("aff3ct::module::Monitor: \"N\" has to be greater than 0.");
if (this->N_mod <= 0)
throw std::invalid_argument("aff3ct::module::Monitor: \"N_mod\" has to be greater than 0.");
if (this->K > this->N)
throw std::invalid_argument("aff3ct::module::Monitor: \"K\" has to be smaller than \"N\".");
Monitor_i<B,R>::interrupt = false;
Monitor_i<B,R>::d_delta_interrupt = std::chrono::nanoseconds(0);
#ifndef ENABLE_MPI
// Install a signal handler
std::signal(SIGINT, Monitor_i<B,R>::signal_interrupt_handler);
#endif
}
/*!
* \brief Destructor.
*/
virtual ~Monitor_i()
{
}
/*!
* \brief Gets the frame size.
*
* \return the frame size.
*/
int get_N() const
{
return N;
}
int get_N_mod() const
{
return N_mod;
}
/*!
* \brief Gets the number of information bits in a frame.
*
* \return the number of information bits.
*/
int get_K() const
{
return K;
}
/*!
* \brief Gets the number of bit errors.
*
* \return the number of bit errors.
*/
virtual unsigned long long get_n_be() const = 0;
/*!
* \brief Gets the number of frame errors.
*
* \return the number of frame errors.
*/
virtual unsigned long long get_n_fe() const = 0;
/*!
* \brief Gets the bit error rate.
*
* \return the bit error rate.
*/
virtual float get_ber() const = 0;
/*!
* \brief Gets the frame error rate.
*
* \return the frame error rate.
*/
virtual float get_fer() const = 0;
/*!
* \brief Gets the number of analyzed frames (analyzed in the Monitor_i::check_errors method).
*
* \return the number of analyzed frames.
*/
virtual unsigned long long get_n_analyzed_fra() const = 0;
/*!
* \brief Gets the frame errors limit (maximal number of frame errors to simulate).
*
* \return the frame errors limit.
*/
virtual unsigned get_fe_limit() const = 0;
/*!
* \brief Tells if the frame errors limit is achieved (in this case the current computations should stop).
*
* \return true if the frame errors limit is achieved.
*/
virtual bool fe_limit_achieved() = 0;
/*!
* \brief Compares two messages and counts the number of frame errors and bit errors.
*
* Typically this method is called at the very end of a communication chain.
*
* \param U: the original message (from the Source or the CRC).
* \param V: the decoded message (from the Decoder).
*/
void check_errors(const mipp::vector<B>& U_K, const mipp::vector<B>& V_K)
{
if ((int)U_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"U_K.size()\" has to be equal to \"K * n_frames\".");
if ((int)V_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"V_K.size()\" has to be equal to \"K * n_frames\".");
this->check_errors(U_K.data(), V_K.data());
}
virtual void check_errors(const B *U_K, const B *V_K)
{
for (auto f = 0; f < this->n_frames; f++)
this->_check_errors(U_K + f * this->K,
V_K + f * this->K);
}
/*!
* \brief Tells if the user asked for stopping the current computations.
*
* \return true if the SIGINT (ctrl+c) is called.
*/
static bool is_interrupt()
{
return Monitor_i<B,R>::interrupt;
}
/*!
* \brief Tells if the user asked for stopping the whole simulation.
*
* \return true if the SIGINT (ctrl+c) is called twice.
*/
static bool is_over()
{
return Monitor_i<B,R>::over;
}
/*!
* \brief Put Monitor_i<B,R>::interrupt and Monitor_i<B,R>::over to true.
*/
static void stop()
{
Monitor_i<B,R>::interrupt = true;
Monitor_i<B,R>::over = true;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// The following public methods are specific to catch the bad frames and to dump them into files. //
// The proposed default implementation do nothing. //
////////////////////////////////////////////////////////////////////////////////////////////////////
/*!
* \brief Compares two messages and counts the number of frame errors and bit errors.
*
* Typically this method is called at the very end of a communication chain.
*
* \param U: the original message (from the Source or the CRC).
* \param V: the decoded message (from the Decoder).
* \param X: the encoded message (from the Encoder).
* \param X_mod: the modulated message (from the Modulator, the input of the Channel).
* \param Y: the noised message (the output of the Channel).
*/
void check_and_track_errors(const mipp::vector<B>& U_K,
const mipp::vector<B>& V_K,
const mipp::vector<B>& X_N,
const mipp::vector<R>& Y_N_mod)
{
if ((int)U_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"U_K.size()\" has to be equal to \"K * n_frames\".");
if ((int)V_K.size() != this->K * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"V_K.size()\" has to be equal to \"K * n_frames\".");
if ((int)X_N.size() != this->N * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"X_N.size()\" has to be equal to \"N * n_frames\".");
if ((int)Y_N_mod.size() != this->N_mod * this->n_frames)
throw std::length_error("aff3ct::module::Monitor: \"Y_N_mod.size()\" has to be equal to "
"\"N_mod * n_frames\".");
this->check_and_track_errors(U_K.data(), V_K.data(), X_N.data(), Y_N_mod.data());
}
virtual void check_and_track_errors(const B *U_K, const B *V_K, const B *X_N, const R *Y_N_mod)
{
for (auto f = 0; f < this->n_frames; f++)
this->_check_and_track_errors(U_K + f * this->K,
V_K + f * this->K,
X_N + f * this->N,
Y_N_mod + f * this->N_mod);
}
/*!
* \brief Write the bad frames into files.
*
* \param base_path: base path for files to write the bad frames.
* \param snr: the current SNR.
*/
virtual void dump_bad_frames(const std::string& base_path, const float snr, const mipp::vector<int>& itl_pi = mipp::vector<int>(0))
{
}
/*!
* \brief get the buffer recording the wrong frames from the source
*
* \return a reference to the buffer recording the wrong frames from the source
*/
virtual const std::vector<mipp::vector<B>> get_buff_src() const
{
return std::vector<mipp::vector<B>>(0);
}
/*!
* \brief get the buffer recording the wrong frames from the encoder
*
* \return a reference to the buffer recording the wrong frames from the encoder
*/
virtual const std::vector<mipp::vector<B>> get_buff_enc() const
{
return std::vector<mipp::vector<B>>(0);
}
/*!
* \brief get the buffer recording the noise added to the wrong frames in the channel
*
* \return a reference to the buffer recording the noise added to the wrong frames in the channel
*/
virtual const std::vector<mipp::vector<R>> get_buff_noise() const
{
return std::vector<mipp::vector<R>>(0);
}
protected:
virtual void _check_errors(const B *U, const B *V)
{
throw std::runtime_error("aff3ct::module::Monitor: \"_check_errors\" is unimplemented.");
}
virtual void _check_and_track_errors(const B *U_K, const B *V_K, const B *X_N, const R *Y_N_mod)
{
throw std::runtime_error("aff3ct::module::Monitor: \"_check_and_track_errors\" is unimplemented.");
}
private:
static void signal_interrupt_handler(int signal)
{
auto t_now = std::chrono::steady_clock::now();
if (!Monitor_i<B,R>::first_interrupt)
{
Monitor_i<B,R>::d_delta_interrupt = t_now - Monitor_i<B,R>::t_last_interrupt;
if (Monitor_i<B,R>::d_delta_interrupt < std::chrono::milliseconds(500))
Monitor_i<B,R>::stop();
}
Monitor_i<B,R>::t_last_interrupt = t_now;
Monitor_i<B,R>::first_interrupt = false;
Monitor_i<B,R>::interrupt = true;
}
};
template <typename B, typename R>
bool Monitor_i<B,R>::interrupt = false;
template <typename B, typename R>
bool Monitor_i<B,R>::first_interrupt = true;
template <typename B, typename R>
bool Monitor_i<B,R>::over = false;
template <typename B, typename R>
std::chrono::time_point<std::chrono::steady_clock, std::chrono::nanoseconds> Monitor_i<B,R>::t_last_interrupt;
template <typename B, typename R>
std::chrono::nanoseconds Monitor_i<B,R>::d_delta_interrupt = std::chrono::nanoseconds(0);
}
}
#include "SC_Monitor.hpp"
#endif /* MONITOR_HPP_ */
<|endoftext|> |
<commit_before>/*
dirservconfigpage.cpp
This file is part of kleopatra
Copyright (c) 2004 Klar�vdalens Datakonsult AB
Libkleopatra is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License,
version 2, as published by the Free Software Foundation.
Libkleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "dirservconfigpage.h"
#include "libkleo/ui/directoryserviceswidget.h"
#include "libkleo/kleo/cryptobackendfactory.h"
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kconfig.h>
#include <knuminput.h>
#include <kdialog.h>
#include <kcomponentdata.h>
#include <khbox.h>
#include <QLabel>
#include <qdatetimeedit.h>
#include <QCheckBox>
#include <QLayout>
#include <kdemacros.h>
#if 0 // disabled, since it is apparently confusing
// For sync'ing kabldaprc
class KABSynchronizer
{
public:
KABSynchronizer()
: mConfig( "kabldaprc" ) {
mConfig.setGroup( "LDAP" );
}
KUrl::List readCurrentList() const {
KUrl::List lst;
// stolen from kabc/ldapclient.cpp
const uint numHosts = mConfig.readEntry( "NumSelectedHosts" );
for ( uint j = 0; j < numHosts; j++ ) {
const QString num = QString::number( j );
KUrl url;
url.setProtocol( "ldap" );
url.setPath( "/" ); // workaround KUrl parsing bug
const QString host = mConfig.readEntry( QString( "SelectedHost" ) + num ).trimmed();
url.setHost( host );
const int port = mConfig.readEntry( QString( "SelectedPort" ) + num );
if ( port != 0 )
url.setPort( port );
const QString base = mConfig.readEntry( QString( "SelectedBase" ) + num ).trimmed();
url.setQuery( base );
const QString bindDN = mConfig.readEntry( QString( "SelectedBind" ) + num ).trimmed();
url.setUser( bindDN );
const QString pwdBindDN = mConfig.readEntry( QString( "SelectedPwdBind" ) + num ).trimmed();
url.setPass( pwdBindDN );
lst.append( url );
}
return lst;
}
void writeList( const KUrl::List& lst ) {
mConfig.writeEntry( "NumSelectedHosts", lst.count() );
KUrl::List::const_iterator it = lst.begin();
KUrl::List::const_iterator end = lst.end();
unsigned j = 0;
for( ; it != end; ++it, ++j ) {
const QString num = QString::number( j );
KUrl url = *it;
Q_ASSERT( url.protocol() == "ldap" );
mConfig.writeEntry( QString( "SelectedHost" ) + num, url.host() );
mConfig.writeEntry( QString( "SelectedPort" ) + num, url.port() );
// KUrl automatically encoded the query (e.g. for spaces inside it),
// so decode it before writing it out
const QString base = KUrl::decode_string( url.query().mid(1) );
mConfig.writeEntry( QString( "SelectedBase" ) + num, base );
mConfig.writeEntry( QString( "SelectedBind" ) + num, url.user() );
mConfig.writeEntry( QString( "SelectedPwdBind" ) + num, url.pass() );
}
mConfig.sync();
}
private:
KConfig mConfig;
};
#endif
static const char s_dirserv_componentName[] = "dirmngr";
static const char s_dirserv_groupName[] = "LDAP";
static const char s_dirserv_entryName[] = "LDAP Server";
static const char s_timeout_componentName[] = "dirmngr";
static const char s_timeout_groupName[] = "LDAP";
static const char s_timeout_entryName[] = "ldaptimeout";
static const char s_maxitems_componentName[] = "dirmngr";
static const char s_maxitems_groupName[] = "LDAP";
static const char s_maxitems_entryName[] = "max-replies";
static const char s_addnewservers_componentName[] = "dirmngr";
static const char s_addnewservers_groupName[] = "LDAP";
static const char s_addnewservers_entryName[] = "add-servers";
DirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( const KComponentData &instance, QWidget *parent, const QVariantList &args )
: KCModule( instance, parent, args )
{
mConfig = Kleo::CryptoBackendFactory::instance()->config();
QVBoxLayout* lay = new QVBoxLayout( this );
lay->setSpacing( KDialog::spacingHint() );
lay->setMargin( 0 );
Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName,
Kleo::CryptoConfigEntry::ArgType_LDAPURL, true );
mWidget = new Kleo::DirectoryServicesWidget( entry, this );
lay->addWidget( mWidget );
connect( mWidget, SIGNAL(changed()), this, SLOT(changed()) );
// LDAP timeout
KHBox* box = new KHBox( this );
box->setSpacing( KDialog::spacingHint() );
lay->addWidget( box );
QLabel* label = new QLabel( i18n( "LDAP &timeout (minutes:seconds):" ), box );
mTimeout = new QTimeEdit( box );
mTimeout->setDisplayFormat( "mm:ss" );
connect( mTimeout, SIGNAL(timeChanged(QTime)), this, SLOT(changed()) );
label->setBuddy( mTimeout );
QWidget* stretch = new QWidget( box );
box->setStretchFactor( stretch, 2 );
// Max number of items returned by queries
box = new KHBox( this );
box->setSpacing( KDialog::spacingHint() );
lay->addWidget( box );
mMaxItems = new KIntNumInput( box );
mMaxItems->setLabel( i18n( "&Maximum number of items returned by query:" ), Qt::AlignLeft | Qt::AlignVCenter );
mMaxItems->setMinimum( 0 );
connect( mMaxItems, SIGNAL(valueChanged(int)), this, SLOT(changed()) );
stretch = new QWidget( box );
box->setStretchFactor( stretch, 2 );
#ifdef NOT_USEFUL_CURRENTLY
mAddNewServersCB = new QCheckBox( i18n( "Automatically add &new servers discovered in CRL distribution points" ), this );
connect( mAddNewServersCB, SIGNAL(clicked()), this, SLOT(changed()) );
lay->addWidget( mAddNewServersCB );
#endif
#ifndef HAVE_UNBROKEN_KCMULTIDIALOG
load();
#endif
}
void DirectoryServicesConfigurationPage::load()
{
mWidget->load();
mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
if ( mTimeoutConfigEntry ) {
QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() );
//kDebug() <<"timeout:" << mTimeoutConfigEntry->uintValue() <<" ->" << time;
mTimeout->setTime( time );
}
mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
if ( mMaxItemsConfigEntry ) {
mMaxItems->blockSignals( true ); // KNumInput emits valueChanged from setValue!
mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() );
mMaxItems->blockSignals( false );
}
#ifdef NOT_USEFUL_CURRENTLY
mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false );
if ( mAddNewServersConfigEntry ) {
mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() );
}
#endif
}
void DirectoryServicesConfigurationPage::save()
{
mWidget->save();
QTime time( mTimeout->time() );
unsigned int timeout = time.minute() * 60 + time.second();
if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout )
mTimeoutConfigEntry->setUIntValue( timeout );
if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() )
mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() );
#ifdef NOT_USEFUL_CURRENTLY
if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() )
mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() );
#endif
mConfig->sync( true );
#if 0
// Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook
KABSynchronizer sync;
const KUrl::List toAdd = mWidget->urlList();
KUrl::List currentList = sync.readCurrentList();
KUrl::List::const_iterator it = toAdd.begin();
KUrl::List::const_iterator end = toAdd.end();
for( ; it != end; ++it ) {
// check if the URL is already in currentList
if ( currentList.find( *it ) == currentList.end() )
// if not, add it
currentList.append( *it );
}
sync.writeList( currentList );
#endif
}
void DirectoryServicesConfigurationPage::defaults()
{
mWidget->defaults();
if ( mTimeoutConfigEntry )
mTimeoutConfigEntry->resetToDefault();
if ( mMaxItemsConfigEntry )
mMaxItemsConfigEntry->resetToDefault();
#ifdef NOT_USEFUL_CURRENTLY
if ( mAddNewServersConfigEntry )
mAddNewServersConfigEntry->resetToDefault();
#endif
load();
}
extern "C"
{
KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent=0, const QVariantList &args=QVariantList() )
{
DirectoryServicesConfigurationPage *page =
new DirectoryServicesConfigurationPage( KComponentData( "kleopatra" ), parent, args );
page->setObjectName( "kleopatra_config_dirserv" );
return page;
}
}
// Find config entry for ldap servers. Implements runtime checks on the configuration option.
Kleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName,
const char* groupName,
const char* entryName,
Kleo::CryptoConfigEntry::ArgType argType,
bool isList )
{
Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName );
if ( !entry ) {
KMessageBox::error( this, i18n( "Backend error: gpgconf does not seem to know the entry for %1/%2/%3", componentName, groupName, entryName ) );
return 0;
}
if( entry->argType() != argType || entry->isList() != isList ) {
KMessageBox::error( this, i18n( "Backend error: gpgconf has wrong type for %1/%2/%3: %4 %5", componentName, groupName, entryName, entry->argType(), entry->isList() ) );
return 0;
}
return entry;
}
#include "dirservconfigpage.moc"
<commit_msg>Clean up user interface and implementation<commit_after>/*
dirservconfigpage.cpp
This file is part of kleopatra
Copyright (c) 2004 Klar�vdalens Datakonsult AB
Libkleopatra is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License,
version 2, as published by the Free Software Foundation.
Libkleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <config-kleopatra.h>
#include "dirservconfigpage.h"
#include "libkleo/ui/directoryserviceswidget.h"
#include "libkleo/kleo/cryptobackendfactory.h"
#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kconfig.h>
#include <knuminput.h>
#include <kdialog.h>
#include <kcomponentdata.h>
#include <khbox.h>
#include <QLabel>
#include <qdatetimeedit.h>
#include <QCheckBox>
#include <QLayout>
#include <kdemacros.h>
#if 0 // disabled, since it is apparently confusing
// For sync'ing kabldaprc
class KABSynchronizer
{
public:
KABSynchronizer()
: mConfig( "kabldaprc" ) {
mConfig.setGroup( "LDAP" );
}
KUrl::List readCurrentList() const {
KUrl::List lst;
// stolen from kabc/ldapclient.cpp
const uint numHosts = mConfig.readEntry( "NumSelectedHosts" );
for ( uint j = 0; j < numHosts; j++ ) {
const QString num = QString::number( j );
KUrl url;
url.setProtocol( "ldap" );
url.setPath( "/" ); // workaround KUrl parsing bug
const QString host = mConfig.readEntry( QString( "SelectedHost" ) + num ).trimmed();
url.setHost( host );
const int port = mConfig.readEntry( QString( "SelectedPort" ) + num );
if ( port != 0 )
url.setPort( port );
const QString base = mConfig.readEntry( QString( "SelectedBase" ) + num ).trimmed();
url.setQuery( base );
const QString bindDN = mConfig.readEntry( QString( "SelectedBind" ) + num ).trimmed();
url.setUser( bindDN );
const QString pwdBindDN = mConfig.readEntry( QString( "SelectedPwdBind" ) + num ).trimmed();
url.setPass( pwdBindDN );
lst.append( url );
}
return lst;
}
void writeList( const KUrl::List& lst ) {
mConfig.writeEntry( "NumSelectedHosts", lst.count() );
KUrl::List::const_iterator it = lst.begin();
KUrl::List::const_iterator end = lst.end();
unsigned j = 0;
for( ; it != end; ++it, ++j ) {
const QString num = QString::number( j );
KUrl url = *it;
Q_ASSERT( url.protocol() == "ldap" );
mConfig.writeEntry( QString( "SelectedHost" ) + num, url.host() );
mConfig.writeEntry( QString( "SelectedPort" ) + num, url.port() );
// KUrl automatically encoded the query (e.g. for spaces inside it),
// so decode it before writing it out
const QString base = KUrl::decode_string( url.query().mid(1) );
mConfig.writeEntry( QString( "SelectedBase" ) + num, base );
mConfig.writeEntry( QString( "SelectedBind" ) + num, url.user() );
mConfig.writeEntry( QString( "SelectedPwdBind" ) + num, url.pass() );
}
mConfig.sync();
}
private:
KConfig mConfig;
};
#endif
static const char s_dirserv_componentName[] = "dirmngr";
static const char s_dirserv_groupName[] = "LDAP";
static const char s_dirserv_entryName[] = "LDAP Server";
static const char s_timeout_componentName[] = "dirmngr";
static const char s_timeout_groupName[] = "LDAP";
static const char s_timeout_entryName[] = "ldaptimeout";
static const char s_maxitems_componentName[] = "dirmngr";
static const char s_maxitems_groupName[] = "LDAP";
static const char s_maxitems_entryName[] = "max-replies";
static const char s_addnewservers_componentName[] = "dirmngr";
static const char s_addnewservers_groupName[] = "LDAP";
static const char s_addnewservers_entryName[] = "add-servers";
DirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( const KComponentData &instance, QWidget *parent, const QVariantList &args )
: KCModule( instance, parent, args )
{
mConfig = Kleo::CryptoBackendFactory::instance()->config();
QGridLayout * glay = new QGridLayout( this );
glay->setSpacing( KDialog::spacingHint() );
glay->setMargin( 0 );
int row = 0;
Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName,
Kleo::CryptoConfigEntry::ArgType_LDAPURL, true );
mWidget = new Kleo::DirectoryServicesWidget( entry, this );
if ( QLayout * l = mWidget->layout() ) {
l->setSpacing( KDialog::spacingHint() );
l->setMargin( 0 );
}
glay->addWidget( mWidget, row, 0, 1, 3 );
connect( mWidget, SIGNAL(changed()), this, SLOT(changed()) );
// LDAP timeout
++row;
QLabel* label = new QLabel( i18n( "LDAP &timeout (minutes:seconds):" ), this );
mTimeout = new QTimeEdit( this );
mTimeout->setDisplayFormat( "mm:ss" );
connect( mTimeout, SIGNAL(timeChanged(QTime)), this, SLOT(changed()) );
label->setBuddy( mTimeout );
glay->addWidget( label, row, 0 );
glay->addWidget( mTimeout, row, 1 );
// Max number of items returned by queries
++row;
label = new QLabel( i18n( "&Maximum number of items returned by query:" ), this );
mMaxItems = new KIntNumInput( this );
mMaxItems->setMinimum( 0 );
label->setBuddy( mMaxItems );
connect( mMaxItems, SIGNAL(valueChanged(int)), this, SLOT(changed()) );
glay->addWidget( label, row, 0 );
glay->addWidget( mMaxItems, row, 1 );
#ifdef NOT_USEFUL_CURRENTLY
++row
mAddNewServersCB = new QCheckBox( i18n( "Automatically add &new servers discovered in CRL distribution points" ), this );
connect( mAddNewServersCB, SIGNAL(clicked()), this, SLOT(changed()) );
glay->addWidget( mAddNewServersCB, row, 0, 1, 3 );
#endif
glay->setRowStretch( ++row, 1 );
glay->setColumnStretch( 2, 1 );
#ifndef HAVE_UNBROKEN_KCMULTIDIALOG
load();
#endif
}
void DirectoryServicesConfigurationPage::load()
{
mWidget->load();
mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
if ( mTimeoutConfigEntry ) {
QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() );
//kDebug() <<"timeout:" << mTimeoutConfigEntry->uintValue() <<" ->" << time;
mTimeout->setTime( time );
}
mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
if ( mMaxItemsConfigEntry ) {
mMaxItems->blockSignals( true ); // KNumInput emits valueChanged from setValue!
mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() );
mMaxItems->blockSignals( false );
}
#ifdef NOT_USEFUL_CURRENTLY
mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false );
if ( mAddNewServersConfigEntry ) {
mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() );
}
#endif
}
void DirectoryServicesConfigurationPage::save()
{
mWidget->save();
QTime time( mTimeout->time() );
unsigned int timeout = time.minute() * 60 + time.second();
if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout )
mTimeoutConfigEntry->setUIntValue( timeout );
if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() )
mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() );
#ifdef NOT_USEFUL_CURRENTLY
if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() )
mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() );
#endif
mConfig->sync( true );
#if 0
// Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook
KABSynchronizer sync;
const KUrl::List toAdd = mWidget->urlList();
KUrl::List currentList = sync.readCurrentList();
KUrl::List::const_iterator it = toAdd.begin();
KUrl::List::const_iterator end = toAdd.end();
for( ; it != end; ++it ) {
// check if the URL is already in currentList
if ( currentList.find( *it ) == currentList.end() )
// if not, add it
currentList.append( *it );
}
sync.writeList( currentList );
#endif
}
void DirectoryServicesConfigurationPage::defaults()
{
mWidget->defaults();
if ( mTimeoutConfigEntry )
mTimeoutConfigEntry->resetToDefault();
if ( mMaxItemsConfigEntry )
mMaxItemsConfigEntry->resetToDefault();
#ifdef NOT_USEFUL_CURRENTLY
if ( mAddNewServersConfigEntry )
mAddNewServersConfigEntry->resetToDefault();
#endif
load();
}
extern "C"
{
KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent=0, const QVariantList &args=QVariantList() )
{
DirectoryServicesConfigurationPage *page =
new DirectoryServicesConfigurationPage( KComponentData( "kleopatra" ), parent, args );
page->setObjectName( "kleopatra_config_dirserv" );
return page;
}
}
// Find config entry for ldap servers. Implements runtime checks on the configuration option.
Kleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName,
const char* groupName,
const char* entryName,
Kleo::CryptoConfigEntry::ArgType argType,
bool isList )
{
Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName );
if ( !entry ) {
KMessageBox::error( this, i18n( "Backend error: gpgconf does not seem to know the entry for %1/%2/%3", componentName, groupName, entryName ) );
return 0;
}
if( entry->argType() != argType || entry->isList() != isList ) {
KMessageBox::error( this, i18n( "Backend error: gpgconf has wrong type for %1/%2/%3: %4 %5", componentName, groupName, entryName, entry->argType(), entry->isList() ) );
return 0;
}
return entry;
}
#include "dirservconfigpage.moc"
<|endoftext|> |
<commit_before>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/Config.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <Nazara/Core/Debug.hpp>
NzHashDigest::NzHashDigest() :
m_digest(nullptr),
m_digestLength(0)
{
}
NzHashDigest::NzHashDigest(const NzString& hashName, const nzUInt8* digest, unsigned int length) :
m_hashName(hashName),
m_digestLength(length)
{
if (m_digestLength > 0)
{
m_digest = new nzUInt8[length];
std::memcpy(m_digest, digest, length);
}
else
m_digest = nullptr;
}
NzHashDigest::NzHashDigest(const NzHashDigest& rhs) :
m_hashName(rhs.m_hashName),
m_digestLength(rhs.m_digestLength)
{
if (m_digestLength > 0)
{
m_digest = new nzUInt8[m_digestLength];
std::memcpy(m_digest, rhs.m_digest, m_digestLength);
}
else
m_digest = nullptr;
}
NzHashDigest::NzHashDigest(NzHashDigest&& rhs) noexcept :
m_hashName(std::move(rhs.m_hashName)),
m_digest(rhs.m_digest),
m_digestLength(rhs.m_digestLength)
{
rhs.m_digest = nullptr;
rhs.m_digestLength = 0;
}
NzHashDigest::~NzHashDigest()
{
delete[] m_digest;
}
bool NzHashDigest::IsValid() const
{
return m_digestLength > 0;
}
const nzUInt8* NzHashDigest::GetDigest() const
{
return m_digest;
}
unsigned int NzHashDigest::GetDigestLength() const
{
return m_digestLength;
}
NzString NzHashDigest::GetHashName() const
{
return m_hashName;
}
NzString NzHashDigest::ToHex() const
{
if (m_digestLength == 0)
return NzString();
unsigned int length = m_digestLength*2;
char* hexOutput = new char[length+1];
for (unsigned int i = 0; i < m_digestLength; ++i)
std::sprintf(hexOutput + i*2, "%02x", m_digest[i]);
return NzString(new NzString::SharedString(1, length, length, hexOutput));
}
nzUInt8 NzHashDigest::operator[](unsigned int pos) const
{
#if NAZARA_CORE_SAFE
if (pos >= m_digestLength)
{
NazaraError("Position out of range");
return 0;
}
#endif
return m_digest[pos];
}
NzHashDigest& NzHashDigest::operator=(const NzHashDigest& rhs)
{
if (this == &rhs)
return *this;
m_hashName = rhs.m_hashName;
m_digestLength = rhs.m_digestLength;
if (m_digestLength > 0)
{
m_digest = new nzUInt8[m_digestLength];
std::memcpy(m_digest, rhs.m_digest, m_digestLength);
}
else
m_digest = nullptr;
return *this;
}
NzHashDigest& NzHashDigest::operator=(NzHashDigest&& rhs) noexcept
{
std::swap(m_hashName, rhs.m_hashName);
std::swap(m_digest, rhs.m_digest);
std::swap(m_digestLength, rhs.m_digestLength);
return *this;
}
bool NzHashDigest::operator==(const NzHashDigest& rhs) const
{
if (m_digest == nullptr || rhs.m_digest == nullptr)
return m_digest == rhs.m_digest;
if (m_digestLength != rhs.m_digestLength)
return false;
return m_hashName == rhs.m_hashName && std::memcmp(m_digest, rhs.m_digest, m_digestLength) == 0;
}
bool NzHashDigest::operator!=(const NzHashDigest& rhs) const
{
return !operator==(rhs);
}
bool NzHashDigest::operator<(const NzHashDigest& rhs) const
{
if (rhs.m_digest == nullptr)
return false;
if (m_digest == nullptr)
return true;
int cmp = NzString::Compare(m_hashName, rhs.m_hashName);
if (cmp == 0)
{
cmp = std::memcmp(m_digest, rhs.m_digest, std::min(m_digestLength, rhs.m_digestLength));
if (cmp == 0)
return m_digestLength < rhs.m_digestLength;
else
return cmp < 0;
}
else
return cmp < 0;
}
bool NzHashDigest::operator<=(const NzHashDigest& rhs) const
{
return !rhs.operator<(*this);
}
bool NzHashDigest::operator>(const NzHashDigest& rhs) const
{
return rhs.operator<(*this);
}
bool NzHashDigest::operator>=(const NzHashDigest& rhs) const
{
return !operator<(rhs);
}
std::ostream& operator<<(std::ostream& out, const NzHashDigest& hashstring)
{
out << hashstring.ToHex();
return out;
}
<commit_msg>Core/HashDigest: Cleanup code<commit_after>// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/Config.hpp>
#include <Nazara/Core/Error.hpp>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <Nazara/Core/Debug.hpp>
NzHashDigest::NzHashDigest() :
m_digest(nullptr),
m_digestLength(0)
{
}
NzHashDigest::NzHashDigest(const NzString& hashName, const nzUInt8* digest, unsigned int length) :
m_hashName(hashName),
m_digestLength(length)
{
if (m_digestLength > 0)
{
m_digest = new nzUInt8[length];
std::memcpy(m_digest, digest, length);
}
else
m_digest = nullptr;
}
NzHashDigest::NzHashDigest(const NzHashDigest& rhs) :
m_hashName(rhs.m_hashName),
m_digestLength(rhs.m_digestLength)
{
if (m_digestLength > 0)
{
m_digest = new nzUInt8[m_digestLength];
std::memcpy(m_digest, rhs.m_digest, m_digestLength);
}
else
m_digest = nullptr;
}
NzHashDigest::NzHashDigest(NzHashDigest&& rhs) noexcept :
m_hashName(std::move(rhs.m_hashName)),
m_digest(rhs.m_digest),
m_digestLength(rhs.m_digestLength)
{
rhs.m_digest = nullptr;
rhs.m_digestLength = 0;
}
NzHashDigest::~NzHashDigest()
{
delete[] m_digest;
}
bool NzHashDigest::IsValid() const
{
return m_digestLength > 0;
}
const nzUInt8* NzHashDigest::GetDigest() const
{
return m_digest;
}
unsigned int NzHashDigest::GetDigestLength() const
{
return m_digestLength;
}
NzString NzHashDigest::GetHashName() const
{
return m_hashName;
}
NzString NzHashDigest::ToHex() const
{
if (m_digestLength == 0)
return NzString();
unsigned int length = m_digestLength*2;
NzString hexOutput(length);
for (unsigned int i = 0; i < m_digestLength; ++i)
std::sprintf(&hexOutput[i*2], "%02x", m_digest[i]);
return hexOutput;
}
nzUInt8 NzHashDigest::operator[](unsigned int pos) const
{
#if NAZARA_CORE_SAFE
if (pos >= m_digestLength)
{
NazaraError("Position out of range");
return 0;
}
#endif
return m_digest[pos];
}
NzHashDigest& NzHashDigest::operator=(const NzHashDigest& rhs)
{
if (this == &rhs)
return *this;
m_hashName = rhs.m_hashName;
m_digestLength = rhs.m_digestLength;
if (m_digestLength > 0)
{
m_digest = new nzUInt8[m_digestLength];
std::memcpy(m_digest, rhs.m_digest, m_digestLength);
}
else
m_digest = nullptr;
return *this;
}
NzHashDigest& NzHashDigest::operator=(NzHashDigest&& rhs) noexcept
{
std::swap(m_hashName, rhs.m_hashName);
std::swap(m_digest, rhs.m_digest);
std::swap(m_digestLength, rhs.m_digestLength);
return *this;
}
bool NzHashDigest::operator==(const NzHashDigest& rhs) const
{
if (m_digest == nullptr || rhs.m_digest == nullptr)
return m_digest == rhs.m_digest;
if (m_digestLength != rhs.m_digestLength)
return false;
return m_hashName == rhs.m_hashName && std::memcmp(m_digest, rhs.m_digest, m_digestLength) == 0;
}
bool NzHashDigest::operator!=(const NzHashDigest& rhs) const
{
return !operator==(rhs);
}
bool NzHashDigest::operator<(const NzHashDigest& rhs) const
{
if (rhs.m_digest == nullptr)
return false;
if (m_digest == nullptr)
return true;
int cmp = NzString::Compare(m_hashName, rhs.m_hashName);
if (cmp == 0)
{
cmp = std::memcmp(m_digest, rhs.m_digest, std::min(m_digestLength, rhs.m_digestLength));
if (cmp == 0)
return m_digestLength < rhs.m_digestLength;
else
return cmp < 0;
}
else
return cmp < 0;
}
bool NzHashDigest::operator<=(const NzHashDigest& rhs) const
{
return !rhs.operator<(*this);
}
bool NzHashDigest::operator>(const NzHashDigest& rhs) const
{
return rhs.operator<(*this);
}
bool NzHashDigest::operator>=(const NzHashDigest& rhs) const
{
return !operator<(rhs);
}
std::ostream& operator<<(std::ostream& out, const NzHashDigest& hashstring)
{
out << hashstring.ToHex();
return out;
}
<|endoftext|> |
<commit_before>/*
* =====================================================================================
*
* Filename: Handler.cpp
*
* Description:
*
* Version: 1.0
* Created: 2013年09月22日 16时53分45秒
* Revision: none
* Compiler: gcc
*
* Author: imane (), imanecr@gmail.com
* Organization:
*
* =====================================================================================
*/
#include "handler.h"
bool HandlerInit(uint8_t process)
{
//to do implementation
// IME_LOG("handler init %u", thread);
return true;
}
bool HandlerFinally(uint8_t process)
{
//to do implementation
// IME_LOG("handler finally %u", thread);
return true;
}
void HandlerWork()
{
//to do implementation
IME_LOG("handler work");
}
<commit_msg>update<commit_after>/*
* =====================================================================================
*
* Filename: Handler.cpp
*
* Description:
*
* Version: 1.0
* Created: 2013年09月22日 16时53分45秒
* Revision: none
* Compiler: gcc
*
* Author: imane (), imanecr@gmail.com
* Organization:
*
* =====================================================================================
*/
#include "handler.h"
bool HandlerInit(uint8_t process)
{
//to do implementation
// IME_LOG("handler init %u", thread);
return true;
}
bool HandlerFinally(uint8_t process)
{
//to do implementation
// IME_LOG("handler finally %u", thread);
return true;
}
void HandlerWork()
{
//to do implementation
//IME_LOG("handler work");
}
<|endoftext|> |
<commit_before>#ifndef ENTT_ENTITY_ENTITY_HPP
#define ENTT_ENTITY_ENTITY_HPP
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include "../config/config.h"
namespace entt {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
namespace internal {
template<typename, typename = void>
struct entt_traits;
template<typename Type>
struct entt_traits<Type, std::enable_if_t<std::is_enum_v<Type>>>
: entt_traits<std::underlying_type_t<Type>>
{};
template<typename Type>
struct entt_traits<Type, std::enable_if_t<std::is_class_v<Type>>>
: entt_traits<typename Type::entity_type>
{};
template<>
struct entt_traits<std::uint32_t> {
using entity_type = std::uint32_t;
using version_type = std::uint16_t;
using difference_type = std::int64_t;
static constexpr entity_type entity_mask = 0xFFFFF;
static constexpr entity_type version_mask = 0xFFF;
static constexpr std::size_t entity_shift = 20u;
};
template<>
struct entt_traits<std::uint64_t> {
using entity_type = std::uint64_t;
using version_type = std::uint32_t;
using difference_type = std::int64_t;
static constexpr entity_type entity_mask = 0xFFFFFFFF;
static constexpr entity_type version_mask = 0xFFFFFFFF;
static constexpr std::size_t entity_shift = 32u;
};
}
/**
* Internal details not to be documented.
* @endcond
*/
/**
* @brief Entity traits.
* @tparam Type Type of identifier.
*/
template<typename Type>
class entt_traits: private internal::entt_traits<Type> {
using traits_type = internal::entt_traits<Type>;
public:
/*! @brief Value type. */
using value_type = Type;
/*! @brief Underlying entity type. */
using entity_type = typename traits_type::entity_type;
/*! @brief Underlying version type. */
using version_type = typename traits_type::version_type;
/*! @brief Difference type. */
using difference_type = typename traits_type::difference_type;
/**
* @brief Converts an entity to its underlying type.
* @param value The value to convert.
* @return The integral representation of the given value.
*/
[[nodiscard]] static constexpr entity_type to_integral(const value_type value) ENTT_NOEXCEPT {
return static_cast<entity_type>(value);
}
/**
* @brief Returns the entity part once converted to the underlying type.
* @param value The value to convert.
* @return The integral representation of the entity part.
*/
[[nodiscard]] static constexpr entity_type to_entity(const value_type value) ENTT_NOEXCEPT {
return (to_integral(value) & traits_type::entity_mask);
}
/**
* @brief Returns the version part once converted to the underlying type.
* @param value The value to convert.
* @return The integral representation of the version part.
*/
[[nodiscard]] static constexpr version_type to_version(const value_type value) ENTT_NOEXCEPT {
constexpr auto mask = (traits_type::version_mask << traits_type::entity_shift);
return ((to_integral(value) & mask) >> traits_type::entity_shift);
}
/**
* @brief Constructs an identifier from its parts.
*
* If the version part is not provided, a tombstone is returned.<br/>
* If the entity part is not provided, a null identifier is returned.
*
* @param entity The entity part of the identifier.
* @param version The version part of the identifier.
* @return A properly constructed identifier.
*/
[[nodiscard]] static constexpr value_type construct(const entity_type entity = traits_type::entity_mask, const version_type version = traits_type::version_mask) ENTT_NOEXCEPT {
return value_type{(entity & traits_type::entity_mask) | (version << traits_type::entity_shift)};
}
};
/**
* @brief Converts an entity to its underlying type.
* @tparam Entity The value type.
* @param entity The value to convert.
* @return The integral representation of the given value.
*/
template<typename Entity>
[[nodiscard]] constexpr auto to_integral(const Entity entity) ENTT_NOEXCEPT {
return entt_traits<Entity>::to_integral(entity);
}
/*! @brief Null object for all entity identifiers. */
struct null_t {
/**
* @brief Converts the null object to identifiers of any type.
* @tparam Entity Type of entity identifier.
* @return The null representation for the given type.
*/
template<typename Entity>
[[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct();
}
/**
* @brief Compares two null objects.
* @param other A null object.
* @return True in all cases.
*/
[[nodiscard]] constexpr bool operator==([[maybe_unused]] const null_t other) const ENTT_NOEXCEPT {
return true;
}
/**
* @brief Compares two null objects.
* @param other A null object.
* @return False in all cases.
*/
[[nodiscard]] constexpr bool operator!=([[maybe_unused]] const null_t other) const ENTT_NOEXCEPT {
return false;
}
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::to_entity(entity) == entt_traits<Entity>::to_entity(*this);
}
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT {
return !(entity == *this);
}
/**
* @brief Creates a null object from an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier to turn into a null object.
* @return The null representation for the given identifier.
*/
template<typename Entity>
[[nodiscard]] constexpr Entity operator|(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct(entt_traits<Entity>::to_entity(*this), entt_traits<Entity>::to_version(entity));
}
};
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A null object yet to be converted.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity, const null_t other) ENTT_NOEXCEPT {
return other.operator==(entity);
}
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A null object yet to be converted.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity, const null_t other) ENTT_NOEXCEPT {
return !(other == entity);
}
/*! @brief Tombstone object for all entity identifiers. */
struct tombstone_t {
/**
* @brief Converts the tombstone object to identifiers of any type.
* @tparam Entity Type of entity identifier.
* @return The tombstone representation for the given type.
*/
template<typename Entity>
[[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct();
}
/**
* @brief Compares two tombstone objects.
* @param other A tombstone object.
* @return True in all cases.
*/
[[nodiscard]] constexpr bool operator==([[maybe_unused]] const tombstone_t other) const ENTT_NOEXCEPT {
return true;
}
/**
* @brief Compares two tombstone objects.
* @param other A tombstone object.
* @return False in all cases.
*/
[[nodiscard]] constexpr bool operator!=([[maybe_unused]] const tombstone_t other) const ENTT_NOEXCEPT {
return false;
}
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::to_version(entity) == entt_traits<Entity>::to_version(*this);
}
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT {
return !(entity == *this);
}
/**
* @brief Creates a tombstone object from an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier to turn into a tombstone object.
* @return The tombstone representation for the given identifier.
*/
template<typename Entity>
[[nodiscard]] constexpr Entity operator|(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct(entt_traits<Entity>::to_entity(entity));
}
};
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A tombstone object yet to be converted.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity, const tombstone_t other) ENTT_NOEXCEPT {
return other.operator==(entity);
}
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A tombstone object yet to be converted.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity, const tombstone_t other) ENTT_NOEXCEPT {
return !(other == entity);
}
/**
* @brief Compile-time constant for null entities.
*
* There exist implicit conversions from this variable to entity identifiers of
* any allowed type. Similarly, there exist comparision operators between the
* null entity and any other entity identifier.
*/
inline constexpr null_t null{};
/**
* @brief Compile-time constant for tombstone entities.
*
* There exist implicit conversions from this variable to entity identifiers of
* any allowed type. Similarly, there exist comparision operators between the
* tombstone entity and any other entity identifier.
*/
inline constexpr tombstone_t tombstone{};
}
#endif
<commit_msg>entity: avoid UBs when id type is std::uint64_t (close #745)<commit_after>#ifndef ENTT_ENTITY_ENTITY_HPP
#define ENTT_ENTITY_ENTITY_HPP
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include "../config/config.h"
namespace entt {
/**
* @cond TURN_OFF_DOXYGEN
* Internal details not to be documented.
*/
namespace internal {
template<typename, typename = void>
struct entt_traits;
template<typename Type>
struct entt_traits<Type, std::enable_if_t<std::is_enum_v<Type>>>
: entt_traits<std::underlying_type_t<Type>>
{};
template<typename Type>
struct entt_traits<Type, std::enable_if_t<std::is_class_v<Type>>>
: entt_traits<typename Type::entity_type>
{};
template<>
struct entt_traits<std::uint32_t> {
using entity_type = std::uint32_t;
using version_type = std::uint16_t;
using difference_type = std::int64_t;
static constexpr entity_type entity_mask = 0xFFFFF;
static constexpr entity_type version_mask = 0xFFF;
static constexpr std::size_t entity_shift = 20u;
};
template<>
struct entt_traits<std::uint64_t> {
using entity_type = std::uint64_t;
using version_type = std::uint32_t;
using difference_type = std::int64_t;
static constexpr entity_type entity_mask = 0xFFFFFFFF;
static constexpr entity_type version_mask = 0xFFFFFFFF;
static constexpr std::size_t entity_shift = 32u;
};
}
/**
* Internal details not to be documented.
* @endcond
*/
/**
* @brief Entity traits.
* @tparam Type Type of identifier.
*/
template<typename Type>
class entt_traits: private internal::entt_traits<Type> {
using traits_type = internal::entt_traits<Type>;
public:
/*! @brief Value type. */
using value_type = Type;
/*! @brief Underlying entity type. */
using entity_type = typename traits_type::entity_type;
/*! @brief Underlying version type. */
using version_type = typename traits_type::version_type;
/*! @brief Difference type. */
using difference_type = typename traits_type::difference_type;
/**
* @brief Converts an entity to its underlying type.
* @param value The value to convert.
* @return The integral representation of the given value.
*/
[[nodiscard]] static constexpr entity_type to_integral(const value_type value) ENTT_NOEXCEPT {
return static_cast<entity_type>(value);
}
/**
* @brief Returns the entity part once converted to the underlying type.
* @param value The value to convert.
* @return The integral representation of the entity part.
*/
[[nodiscard]] static constexpr entity_type to_entity(const value_type value) ENTT_NOEXCEPT {
return (to_integral(value) & traits_type::entity_mask);
}
/**
* @brief Returns the version part once converted to the underlying type.
* @param value The value to convert.
* @return The integral representation of the version part.
*/
[[nodiscard]] static constexpr version_type to_version(const value_type value) ENTT_NOEXCEPT {
constexpr auto mask = (traits_type::version_mask << traits_type::entity_shift);
return ((to_integral(value) & mask) >> traits_type::entity_shift);
}
/**
* @brief Constructs an identifier from its parts.
*
* If the version part is not provided, a tombstone is returned.<br/>
* If the entity part is not provided, a null identifier is returned.
*
* @param entity The entity part of the identifier.
* @param version The version part of the identifier.
* @return A properly constructed identifier.
*/
[[nodiscard]] static constexpr value_type construct(const entity_type entity = traits_type::entity_mask, const version_type version = traits_type::version_mask) ENTT_NOEXCEPT {
return value_type{(entity & traits_type::entity_mask) | (static_cast<entity_type>(version) << traits_type::entity_shift)};
}
};
/**
* @brief Converts an entity to its underlying type.
* @tparam Entity The value type.
* @param entity The value to convert.
* @return The integral representation of the given value.
*/
template<typename Entity>
[[nodiscard]] constexpr auto to_integral(const Entity entity) ENTT_NOEXCEPT {
return entt_traits<Entity>::to_integral(entity);
}
/*! @brief Null object for all entity identifiers. */
struct null_t {
/**
* @brief Converts the null object to identifiers of any type.
* @tparam Entity Type of entity identifier.
* @return The null representation for the given type.
*/
template<typename Entity>
[[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct();
}
/**
* @brief Compares two null objects.
* @param other A null object.
* @return True in all cases.
*/
[[nodiscard]] constexpr bool operator==([[maybe_unused]] const null_t other) const ENTT_NOEXCEPT {
return true;
}
/**
* @brief Compares two null objects.
* @param other A null object.
* @return False in all cases.
*/
[[nodiscard]] constexpr bool operator!=([[maybe_unused]] const null_t other) const ENTT_NOEXCEPT {
return false;
}
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::to_entity(entity) == entt_traits<Entity>::to_entity(*this);
}
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT {
return !(entity == *this);
}
/**
* @brief Creates a null object from an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier to turn into a null object.
* @return The null representation for the given identifier.
*/
template<typename Entity>
[[nodiscard]] constexpr Entity operator|(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct(entt_traits<Entity>::to_entity(*this), entt_traits<Entity>::to_version(entity));
}
};
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A null object yet to be converted.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity, const null_t other) ENTT_NOEXCEPT {
return other.operator==(entity);
}
/**
* @brief Compares a null object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A null object yet to be converted.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity, const null_t other) ENTT_NOEXCEPT {
return !(other == entity);
}
/*! @brief Tombstone object for all entity identifiers. */
struct tombstone_t {
/**
* @brief Converts the tombstone object to identifiers of any type.
* @tparam Entity Type of entity identifier.
* @return The tombstone representation for the given type.
*/
template<typename Entity>
[[nodiscard]] constexpr operator Entity() const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct();
}
/**
* @brief Compares two tombstone objects.
* @param other A tombstone object.
* @return True in all cases.
*/
[[nodiscard]] constexpr bool operator==([[maybe_unused]] const tombstone_t other) const ENTT_NOEXCEPT {
return true;
}
/**
* @brief Compares two tombstone objects.
* @param other A tombstone object.
* @return False in all cases.
*/
[[nodiscard]] constexpr bool operator!=([[maybe_unused]] const tombstone_t other) const ENTT_NOEXCEPT {
return false;
}
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::to_version(entity) == entt_traits<Entity>::to_version(*this);
}
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity) const ENTT_NOEXCEPT {
return !(entity == *this);
}
/**
* @brief Creates a tombstone object from an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier to turn into a tombstone object.
* @return The tombstone representation for the given identifier.
*/
template<typename Entity>
[[nodiscard]] constexpr Entity operator|(const Entity entity) const ENTT_NOEXCEPT {
return entt_traits<Entity>::construct(entt_traits<Entity>::to_entity(entity));
}
};
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A tombstone object yet to be converted.
* @return False if the two elements differ, true otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator==(const Entity entity, const tombstone_t other) ENTT_NOEXCEPT {
return other.operator==(entity);
}
/**
* @brief Compares a tombstone object and an entity identifier of any type.
* @tparam Entity Type of entity identifier.
* @param entity Entity identifier with which to compare.
* @param other A tombstone object yet to be converted.
* @return True if the two elements differ, false otherwise.
*/
template<typename Entity>
[[nodiscard]] constexpr bool operator!=(const Entity entity, const tombstone_t other) ENTT_NOEXCEPT {
return !(other == entity);
}
/**
* @brief Compile-time constant for null entities.
*
* There exist implicit conversions from this variable to entity identifiers of
* any allowed type. Similarly, there exist comparision operators between the
* null entity and any other entity identifier.
*/
inline constexpr null_t null{};
/**
* @brief Compile-time constant for tombstone entities.
*
* There exist implicit conversions from this variable to entity identifiers of
* any allowed type. Similarly, there exist comparision operators between the
* tombstone entity and any other entity identifier.
*/
inline constexpr tombstone_t tombstone{};
}
#endif
<|endoftext|> |
<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Utility.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Core.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/HardwareInfo.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/TaskScheduler.hpp>
#include <Nazara/Core/Thread.hpp>
#include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/Loaders/MD2.hpp>
#include <Nazara/Utility/Loaders/MD5Anim.hpp>
#include <Nazara/Utility/Loaders/MD5Mesh.hpp>
#include <Nazara/Utility/Loaders/PCX.hpp>
#include <Nazara/Utility/Loaders/STB.hpp>
#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Utility/VertexDeclaration.hpp>
#include <Nazara/Utility/Window.hpp>
#include <Nazara/Utility/Debug.hpp>
bool NzUtility::Initialize()
{
if (s_moduleReferenceCounter > 0)
{
s_moduleReferenceCounter++;
return true; // Déjà initialisé
}
// Initialisation des dépendances
if (!NzCore::Initialize())
{
NazaraError("Failed to initialize core module");
return false;
}
s_moduleReferenceCounter++;
// Initialisation du module
NzCallOnExit onExit(NzUtility::Uninitialize);
if (!NzBuffer::Initialize())
{
NazaraError("Failed to initialize buffers");
return false;
}
if (!NzPixelFormat::Initialize())
{
NazaraError("Failed to initialize pixel formats");
return false;
}
if (!NzVertexDeclaration::Initialize())
{
NazaraError("Failed to initialize vertex declarations");
return false;
}
if (!NzWindow::Initialize())
{
NazaraError("Failed to initialize window's system");
return false;
}
// On enregistre les loaders pour les extensions
// Il s'agit ici d'une liste LIFO, le dernier loader enregistré possède la priorité
/// Loaders génériques
// Image
NzLoaders_STB_Register(); // Loader générique (STB)
/// Loaders spécialisés
// Animation
NzLoaders_MD5Anim_Register(); // Loader de fichiers .md5anim (v10)
// Mesh
NzLoaders_MD2_Register(); // Loader de fichiers .md2 (v8)
NzLoaders_MD5Mesh_Register(); // Loader de fichiers .md5mesh (v10)
// Image
NzLoaders_PCX_Register(); // Loader de fichiers .pcx (1, 4, 8, 24 bits)
onExit.Reset();
NazaraNotice("Initialized: Utility module");
return true;
}
bool NzUtility::IsInitialized()
{
return s_moduleReferenceCounter != 0;
}
void NzUtility::Uninitialize()
{
if (s_moduleReferenceCounter != 1)
{
// Le module est soit encore utilisé, soit pas initialisé
if (s_moduleReferenceCounter > 1)
s_moduleReferenceCounter--;
return;
}
// Libération du module
s_moduleReferenceCounter = 0;
NzLoaders_MD2_Unregister();
NzLoaders_MD5Anim_Unregister();
NzLoaders_MD5Mesh_Unregister();
NzLoaders_PCX_Unregister();
NzLoaders_STB_Unregister();
NzWindow::Uninitialize();
NzVertexDeclaration::Uninitialize();
NzPixelFormat::Uninitialize();
NzBuffer::Uninitialize();
NazaraNotice("Uninitialized: Utility module");
// Libération des dépendances
NzCore::Uninitialize();
}
unsigned int NzUtility::ComponentCount[nzComponentType_Max+1] =
{
4, // nzComponentType_Color
1, // nzComponentType_Double1
2, // nzComponentType_Double2
3, // nzComponentType_Double3
4, // nzComponentType_Double4
1, // nzComponentType_Float1
2, // nzComponentType_Float2
3, // nzComponentType_Float3
4, // nzComponentType_Float4
1, // nzComponentType_Int1
2, // nzComponentType_Int2
3, // nzComponentType_Int3
4 // nzComponentType_Int4
};
static_assert(nzComponentType_Max+1 == 13, "Component count array is incomplete");
unsigned int NzUtility::ComponentStride[nzComponentType_Max+1] =
{
4*sizeof(nzUInt8), // nzComponentType_Color
1*sizeof(double), // nzComponentType_Double1
2*sizeof(double), // nzComponentType_Double2
3*sizeof(double), // nzComponentType_Double3
4*sizeof(double), // nzComponentType_Double4
1*sizeof(float), // nzComponentType_Float1
2*sizeof(float), // nzComponentType_Float2
3*sizeof(float), // nzComponentType_Float3
4*sizeof(float), // nzComponentType_Float4
1*sizeof(nzUInt32), // nzComponentType_Int1
2*sizeof(nzUInt32), // nzComponentType_Int2
3*sizeof(nzUInt32), // nzComponentType_Int3
4*sizeof(nzUInt32) // nzComponentType_Int4
};
static_assert(nzComponentType_Max+1 == 13, "Component stride array is incomplete");
unsigned int NzUtility::s_moduleReferenceCounter = 0;
<commit_msg>Fixed missing commit<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Utility.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Core.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/HardwareInfo.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/TaskScheduler.hpp>
#include <Nazara/Core/Thread.hpp>
#include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/Loaders/MD2.hpp>
#include <Nazara/Utility/Loaders/MD5Anim.hpp>
#include <Nazara/Utility/Loaders/MD5Mesh.hpp>
#include <Nazara/Utility/Loaders/PCX.hpp>
#include <Nazara/Utility/Loaders/STB.hpp>
#include <Nazara/Utility/PixelFormat.hpp>
#include <Nazara/Utility/VertexDeclaration.hpp>
#include <Nazara/Utility/Window.hpp>
#include <Nazara/Utility/Debug.hpp>
bool NzUtility::Initialize()
{
if (s_moduleReferenceCounter > 0)
{
s_moduleReferenceCounter++;
return true; // Déjà initialisé
}
// Initialisation des dépendances
if (!NzCore::Initialize())
{
NazaraError("Failed to initialize core module");
return false;
}
s_moduleReferenceCounter++;
// Initialisation du module
NzCallOnExit onExit(NzUtility::Uninitialize);
if (!NzBuffer::Initialize())
{
NazaraError("Failed to initialize buffers");
return false;
}
if (!NzPixelFormat::Initialize())
{
NazaraError("Failed to initialize pixel formats");
return false;
}
if (!NzVertexDeclaration::Initialize())
{
NazaraError("Failed to initialize vertex declarations");
return false;
}
if (!NzWindow::Initialize())
{
NazaraError("Failed to initialize window's system");
return false;
}
// On enregistre les loaders pour les extensions
// Il s'agit ici d'une liste LIFO, le dernier loader enregistré possède la priorité
/// Loaders génériques
// Image
NzLoaders_STB_Register(); // Loader générique (STB)
/// Loaders spécialisés
// Animation
NzLoaders_MD5Anim_Register(); // Loader de fichiers .md5anim (v10)
// Mesh
NzLoaders_MD2_Register(); // Loader de fichiers .md2 (v8)
NzLoaders_MD5Mesh_Register(); // Loader de fichiers .md5mesh (v10)
// Image
NzLoaders_PCX_Register(); // Loader de fichiers .pcx (1, 4, 8, 24 bits)
onExit.Reset();
NazaraNotice("Initialized: Utility module");
return true;
}
bool NzUtility::IsInitialized()
{
return s_moduleReferenceCounter != 0;
}
void NzUtility::Uninitialize()
{
if (s_moduleReferenceCounter != 1)
{
// Le module est soit encore utilisé, soit pas initialisé
if (s_moduleReferenceCounter > 1)
s_moduleReferenceCounter--;
return;
}
// Libération du module
s_moduleReferenceCounter = 0;
NzLoaders_MD2_Unregister();
NzLoaders_MD5Anim_Unregister();
NzLoaders_MD5Mesh_Unregister();
NzLoaders_PCX_Unregister();
NzLoaders_STB_Unregister();
NzWindow::Uninitialize();
NzVertexDeclaration::Uninitialize();
NzPixelFormat::Uninitialize();
NzBuffer::Uninitialize();
NazaraNotice("Uninitialized: Utility module");
// Libération des dépendances
NzCore::Uninitialize();
}
unsigned int NzUtility::ComponentCount[nzComponentType_Max+1] =
{
4, // nzComponentType_Color
1, // nzComponentType_Double1
2, // nzComponentType_Double2
3, // nzComponentType_Double3
4, // nzComponentType_Double4
1, // nzComponentType_Float1
2, // nzComponentType_Float2
3, // nzComponentType_Float3
4, // nzComponentType_Float4
1, // nzComponentType_Int1
2, // nzComponentType_Int2
3, // nzComponentType_Int3
4, // nzComponentType_Int4
4 // nzComponentType_Quaternion
};
static_assert(nzComponentType_Max+1 == 14, "Component count array is incomplete");
unsigned int NzUtility::ComponentStride[nzComponentType_Max+1] =
{
4*sizeof(nzUInt8), // nzComponentType_Color
1*sizeof(double), // nzComponentType_Double1
2*sizeof(double), // nzComponentType_Double2
3*sizeof(double), // nzComponentType_Double3
4*sizeof(double), // nzComponentType_Double4
1*sizeof(float), // nzComponentType_Float1
2*sizeof(float), // nzComponentType_Float2
3*sizeof(float), // nzComponentType_Float3
4*sizeof(float), // nzComponentType_Float4
1*sizeof(nzUInt32), // nzComponentType_Int1
2*sizeof(nzUInt32), // nzComponentType_Int2
3*sizeof(nzUInt32), // nzComponentType_Int3
4*sizeof(nzUInt32), // nzComponentType_Int4
4*sizeof(float) // nzComponentType_Quaternion
};
static_assert(nzComponentType_Max+1 == 14, "Component stride array is incomplete");
unsigned int NzUtility::s_moduleReferenceCounter = 0;
<|endoftext|> |
<commit_before>/*
* phdcontrol.cpp
* PHD Guiding
*
* Created by Andy Galasso
* Copyright (c) 2013 Andy Galasso
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs 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 "phd.h"
enum State
{
STATE_IDLE = 0,
STATE_SETUP,
STATE_ATTEMPT_START,
STATE_SELECT_STAR,
STATE_WAIT_SELECTED,
STATE_CALIBRATE,
STATE_CALIBRATION_WAIT,
STATE_GUIDE,
STATE_SETTLE_BEGIN,
STATE_SETTLE_WAIT,
STATE_FINISH,
};
enum SettleOp
{
OP_DITHER,
OP_GUIDE,
};
struct ControllerState
{
State state;
bool forceCalibration;
bool haveSaveSticky;
bool saveSticky;
int autoFindAttemptsRemaining;
int waitSelectedRemaining;
SettleOp settleOp;
SettleParams settle;
bool settlePriorFrameInRange;
wxStopWatch *settleTimeout;
wxStopWatch *settleInRange;
bool succeeded;
wxString errorMsg;
};
static ControllerState ctrl;
void PhdController::OnAppInit()
{
ctrl.settleTimeout = new wxStopWatch();
ctrl.settleInRange = new wxStopWatch();
}
void PhdController::OnAppExit()
{
delete ctrl.settleTimeout;
ctrl.settleTimeout = NULL;
delete ctrl.settleInRange;
ctrl.settleInRange = NULL;
}
#define SETSTATE(newstate) do { \
Debug.AddLine("PhdController: newstate " #newstate); \
ctrl.state = newstate; \
} while (false)
static wxString ReentrancyError(const char *op)
{
return wxString::Format("Cannot initiate %s while %s is in progress", op, ctrl.settleOp == OP_DITHER ? "dither" : "guide");
}
bool PhdController::Guide(bool recalibrate, const SettleParams& settle, wxString *error)
{
if (ctrl.state != STATE_IDLE)
{
Debug.AddLine("PhdController::Guide reentrancy state = %d op = %d", ctrl.state, ctrl.settleOp);
*error = ReentrancyError("guide");
return false;
}
Debug.AddLine("PhdController::Guide begins");
ctrl.forceCalibration = recalibrate;
ctrl.settleOp = OP_GUIDE;
ctrl.settle = settle;
SETSTATE(STATE_SETUP);
UpdateControllerState();
return true;
}
static void do_fail(const wxString& msg)
{
Debug.AddLine(wxString::Format("PhdController failed: %s", msg));
ctrl.succeeded = false;
ctrl.errorMsg = msg;
SETSTATE(STATE_FINISH);
}
bool PhdController::Dither(double pixels, bool raOnly, const SettleParams& settle, wxString *errMsg)
{
if (ctrl.state != STATE_IDLE)
{
Debug.AddLine("PhdController::Dither reentrancy state = %d op = %d", ctrl.state, ctrl.settleOp);
*errMsg = ReentrancyError("dither");
return false;
}
Debug.AddLine("PhdController::Dither begins");
bool error = pFrame->Dither(pixels, raOnly);
if (error)
{
Debug.AddLine("PhdController::Dither pFrame->Dither failed");
*errMsg = _T("Dither error");
return false;
}
ctrl.settleOp = OP_DITHER;
ctrl.settle = settle;
SETSTATE(STATE_SETTLE_BEGIN);
UpdateControllerState();
return true;
}
void PhdController::AbortController(const wxString& reason)
{
if (ctrl.state != STATE_IDLE)
{
do_fail(reason);
UpdateControllerState();
}
}
static bool all_gear_connected(void)
{
return pCamera && pCamera->Connected &&
(!pMount || pMount->IsConnected()) &&
(!pSecondaryMount || pSecondaryMount->IsConnected());
}
static void do_notify(void)
{
if (ctrl.succeeded)
{
Debug.AddLine("PhdController complete: success");
EvtServer.NotifySettleDone(wxEmptyString);
GuideLog.NotifySettlingStateChange("Settling complete");
}
else
{
Debug.AddLine(wxString::Format("PHDController complete: fail: %s", ctrl.errorMsg));
EvtServer.NotifySettleDone(ctrl.errorMsg);
GuideLog.NotifySettlingStateChange("Settling failed");
}
}
static bool start_capturing(void)
{
if (!pCamera || !pCamera->Connected)
{
return false;
}
pFrame->pGuider->Reset(true); // invalidate current position, etc.
pFrame->pGuider->ForceFullFrame(); // we need a full frame to auto-select a star
pFrame->ResetAutoExposure();
pFrame->StartCapturing();
return true;
}
static bool start_guiding(void)
{
bool error = pFrame->StartGuiding();
return !error;
}
static bool IsAoBumpInProgress()
{
return pMount && pMount->IsStepGuider() && static_cast<StepGuider *>(pMount)->IsBumpInProgress();
}
void PhdController::UpdateControllerState(void)
{
bool done = false;
while (!done)
{
switch (ctrl.state) {
case STATE_IDLE:
done = true;
break;
case STATE_SETUP:
Debug.AddLine("PhdController: setup");
ctrl.haveSaveSticky = false;
ctrl.autoFindAttemptsRemaining = 3;
SETSTATE(STATE_ATTEMPT_START);
break;
case STATE_ATTEMPT_START:
if (!all_gear_connected())
{
do_fail(_T("all equipment must be connected first"));
}
else if (pFrame->pGuider->IsCalibratingOrGuiding())
{
GUIDER_STATE state = pFrame->pGuider->GetState();
Debug.AddLine("PhdController: guider state = %d", state);
if (state == STATE_CALIBRATED || state == STATE_GUIDING)
{
SETSTATE(STATE_SETTLE_BEGIN);
}
else
{
SETSTATE(STATE_CALIBRATION_WAIT);
done = true;
}
}
else if (!pFrame->CaptureActive)
{
Debug.AddLine("PhdController: start capturing");
if (!start_capturing())
{
do_fail(_T("unable to start capturing"));
break;
}
SETSTATE(STATE_SELECT_STAR);
done = true;
}
else if (pFrame->pGuider->GetState() == STATE_SELECTED)
{
SETSTATE(STATE_CALIBRATE);
}
else
{
// capture is active, no star selected
SETSTATE(STATE_SELECT_STAR);
// if auto-exposure is enabled, reset to max exposure duration
// and wait for the next camera frame
if (pFrame->GetAutoExposureCfg().enabled)
{
pFrame->ResetAutoExposure();
done = true;
}
}
break;
case STATE_SELECT_STAR: {
bool error = pFrame->pGuider->AutoSelect();
if (error)
{
Debug.AddLine("auto find star failed, attempts remaining = %d", ctrl.autoFindAttemptsRemaining);
if (--ctrl.autoFindAttemptsRemaining == 0)
{
do_fail(_T("failed to find a suitable guide star"));
}
else
{
pFrame->pGuider->Reset(true);
SETSTATE(STATE_ATTEMPT_START);
done = true;
}
}
else
{
SETSTATE(STATE_WAIT_SELECTED);
ctrl.waitSelectedRemaining = 3;
done = true;
}
break;
}
case STATE_WAIT_SELECTED:
if (pFrame->pGuider->GetState() == STATE_SELECTED)
{
SETSTATE(STATE_CALIBRATE);
}
else
{
Debug.AddLine("waiting for star selected, attempts remaining = %d", ctrl.waitSelectedRemaining);
if (--ctrl.waitSelectedRemaining == 0)
{
SETSTATE(STATE_ATTEMPT_START);
}
done = true;
}
break;
case STATE_CALIBRATE:
if (ctrl.forceCalibration)
{
Debug.AddLine("PhdController: clearing calibration");
if (pMount)
pMount->ClearCalibration();
if (pSecondaryMount)
pSecondaryMount->ClearCalibration();
}
if ((pMount && !pMount->IsCalibrated()) ||
(pSecondaryMount && !pSecondaryMount->IsCalibrated()))
{
Debug.AddLine("PhdController: start calibration");
ctrl.saveSticky = pFrame->pGuider->LockPosIsSticky();
ctrl.haveSaveSticky = true;
pFrame->pGuider->SetLockPosIsSticky(true);
if (!start_guiding())
{
pFrame->pGuider->SetLockPosIsSticky(ctrl.saveSticky);
do_fail(_T("could not start calibration"));
break;
}
SETSTATE(STATE_CALIBRATION_WAIT);
done = true;
}
else
{
SETSTATE(STATE_GUIDE);
}
break;
case STATE_CALIBRATION_WAIT:
if ((!pMount || pMount->IsCalibrated()) &&
(!pSecondaryMount || pSecondaryMount->IsCalibrated()))
{
if (ctrl.haveSaveSticky)
pFrame->pGuider->SetLockPosIsSticky(ctrl.saveSticky);
SETSTATE(STATE_SETTLE_BEGIN);
}
else
done = true;
break;
case STATE_GUIDE:
if (!start_guiding())
{
do_fail(_T("could not start guiding"));
break;
}
SETSTATE(STATE_SETTLE_BEGIN);
done = true;
break;
case STATE_SETTLE_BEGIN:
ctrl.settlePriorFrameInRange = false;
ctrl.settleTimeout->Start();
SETSTATE(STATE_SETTLE_WAIT);
GuideLog.NotifySettlingStateChange("Settling started");
done = true;
break;
case STATE_SETTLE_WAIT: {
bool lockedOnStar = pFrame->pGuider->IsLocked();
double currentError = pFrame->pGuider->CurrentError();
bool inRange = lockedOnStar && currentError <= ctrl.settle.tolerancePx;
bool aoBumpInProgress = IsAoBumpInProgress();
long timeInRange = 0;
Debug.AddLine("PhdController: settling, locked = %d, distance = %.2f (%.2f) aobump = %d", lockedOnStar, currentError,
ctrl.settle.tolerancePx, aoBumpInProgress);
if (inRange)
{
if (!ctrl.settlePriorFrameInRange)
{
ctrl.settleInRange->Start();
}
else if (((timeInRange = ctrl.settleInRange->Time()) / 1000) >= ctrl.settle.settleTimeSec && !aoBumpInProgress)
{
ctrl.succeeded = true;
SETSTATE(STATE_FINISH);
break;
}
}
if ((ctrl.settleTimeout->Time() / 1000) >= ctrl.settle.timeoutSec)
{
do_fail(_T("timed-out waiting for guider to settle"));
break;
}
EvtServer.NotifySettling(currentError, (double) timeInRange / 1000., ctrl.settle.settleTimeSec);
ctrl.settlePriorFrameInRange = inRange;
done = true;
break;
}
case STATE_FINISH:
do_notify();
SETSTATE(STATE_IDLE);
done = true;
break;
}
}
}
<commit_msg>server api: if requested settle time is 0, only require a singe frame to settle<commit_after>/*
* phdcontrol.cpp
* PHD Guiding
*
* Created by Andy Galasso
* Copyright (c) 2013 Andy Galasso
* All rights reserved.
*
* This source code is distributed under the following "BSD" license
* 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 Craig Stark, Stark Labs 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 "phd.h"
enum State
{
STATE_IDLE = 0,
STATE_SETUP,
STATE_ATTEMPT_START,
STATE_SELECT_STAR,
STATE_WAIT_SELECTED,
STATE_CALIBRATE,
STATE_CALIBRATION_WAIT,
STATE_GUIDE,
STATE_SETTLE_BEGIN,
STATE_SETTLE_WAIT,
STATE_FINISH,
};
enum SettleOp
{
OP_DITHER,
OP_GUIDE,
};
struct ControllerState
{
State state;
bool forceCalibration;
bool haveSaveSticky;
bool saveSticky;
int autoFindAttemptsRemaining;
int waitSelectedRemaining;
SettleOp settleOp;
SettleParams settle;
bool settlePriorFrameInRange;
wxStopWatch *settleTimeout;
wxStopWatch *settleInRange;
bool succeeded;
wxString errorMsg;
};
static ControllerState ctrl;
void PhdController::OnAppInit()
{
ctrl.settleTimeout = new wxStopWatch();
ctrl.settleInRange = new wxStopWatch();
}
void PhdController::OnAppExit()
{
delete ctrl.settleTimeout;
ctrl.settleTimeout = NULL;
delete ctrl.settleInRange;
ctrl.settleInRange = NULL;
}
#define SETSTATE(newstate) do { \
Debug.AddLine("PhdController: newstate " #newstate); \
ctrl.state = newstate; \
} while (false)
static wxString ReentrancyError(const char *op)
{
return wxString::Format("Cannot initiate %s while %s is in progress", op, ctrl.settleOp == OP_DITHER ? "dither" : "guide");
}
bool PhdController::Guide(bool recalibrate, const SettleParams& settle, wxString *error)
{
if (ctrl.state != STATE_IDLE)
{
Debug.AddLine("PhdController::Guide reentrancy state = %d op = %d", ctrl.state, ctrl.settleOp);
*error = ReentrancyError("guide");
return false;
}
Debug.AddLine("PhdController::Guide begins");
ctrl.forceCalibration = recalibrate;
ctrl.settleOp = OP_GUIDE;
ctrl.settle = settle;
SETSTATE(STATE_SETUP);
UpdateControllerState();
return true;
}
static void do_fail(const wxString& msg)
{
Debug.AddLine(wxString::Format("PhdController failed: %s", msg));
ctrl.succeeded = false;
ctrl.errorMsg = msg;
SETSTATE(STATE_FINISH);
}
bool PhdController::Dither(double pixels, bool raOnly, const SettleParams& settle, wxString *errMsg)
{
if (ctrl.state != STATE_IDLE)
{
Debug.AddLine("PhdController::Dither reentrancy state = %d op = %d", ctrl.state, ctrl.settleOp);
*errMsg = ReentrancyError("dither");
return false;
}
Debug.AddLine("PhdController::Dither begins");
bool error = pFrame->Dither(pixels, raOnly);
if (error)
{
Debug.AddLine("PhdController::Dither pFrame->Dither failed");
*errMsg = _T("Dither error");
return false;
}
ctrl.settleOp = OP_DITHER;
ctrl.settle = settle;
SETSTATE(STATE_SETTLE_BEGIN);
UpdateControllerState();
return true;
}
void PhdController::AbortController(const wxString& reason)
{
if (ctrl.state != STATE_IDLE)
{
do_fail(reason);
UpdateControllerState();
}
}
static bool all_gear_connected(void)
{
return pCamera && pCamera->Connected &&
(!pMount || pMount->IsConnected()) &&
(!pSecondaryMount || pSecondaryMount->IsConnected());
}
static void do_notify(void)
{
if (ctrl.succeeded)
{
Debug.AddLine("PhdController complete: success");
EvtServer.NotifySettleDone(wxEmptyString);
GuideLog.NotifySettlingStateChange("Settling complete");
}
else
{
Debug.AddLine(wxString::Format("PhdController complete: fail: %s", ctrl.errorMsg));
EvtServer.NotifySettleDone(ctrl.errorMsg);
GuideLog.NotifySettlingStateChange("Settling failed");
}
}
static bool start_capturing(void)
{
if (!pCamera || !pCamera->Connected)
{
return false;
}
pFrame->pGuider->Reset(true); // invalidate current position, etc.
pFrame->pGuider->ForceFullFrame(); // we need a full frame to auto-select a star
pFrame->ResetAutoExposure();
pFrame->StartCapturing();
return true;
}
static bool start_guiding(void)
{
bool error = pFrame->StartGuiding();
return !error;
}
static bool IsAoBumpInProgress()
{
return pMount && pMount->IsStepGuider() && static_cast<StepGuider *>(pMount)->IsBumpInProgress();
}
void PhdController::UpdateControllerState(void)
{
bool done = false;
while (!done)
{
switch (ctrl.state) {
case STATE_IDLE:
done = true;
break;
case STATE_SETUP:
Debug.AddLine("PhdController: setup");
ctrl.haveSaveSticky = false;
ctrl.autoFindAttemptsRemaining = 3;
SETSTATE(STATE_ATTEMPT_START);
break;
case STATE_ATTEMPT_START:
if (!all_gear_connected())
{
do_fail(_T("all equipment must be connected first"));
}
else if (pFrame->pGuider->IsCalibratingOrGuiding())
{
GUIDER_STATE state = pFrame->pGuider->GetState();
Debug.AddLine("PhdController: guider state = %d", state);
if (state == STATE_CALIBRATED || state == STATE_GUIDING)
{
SETSTATE(STATE_SETTLE_BEGIN);
}
else
{
SETSTATE(STATE_CALIBRATION_WAIT);
done = true;
}
}
else if (!pFrame->CaptureActive)
{
Debug.AddLine("PhdController: start capturing");
if (!start_capturing())
{
do_fail(_T("unable to start capturing"));
break;
}
SETSTATE(STATE_SELECT_STAR);
done = true;
}
else if (pFrame->pGuider->GetState() == STATE_SELECTED)
{
SETSTATE(STATE_CALIBRATE);
}
else
{
// capture is active, no star selected
SETSTATE(STATE_SELECT_STAR);
// if auto-exposure is enabled, reset to max exposure duration
// and wait for the next camera frame
if (pFrame->GetAutoExposureCfg().enabled)
{
pFrame->ResetAutoExposure();
done = true;
}
}
break;
case STATE_SELECT_STAR: {
bool error = pFrame->pGuider->AutoSelect();
if (error)
{
Debug.AddLine("auto find star failed, attempts remaining = %d", ctrl.autoFindAttemptsRemaining);
if (--ctrl.autoFindAttemptsRemaining == 0)
{
do_fail(_T("failed to find a suitable guide star"));
}
else
{
pFrame->pGuider->Reset(true);
SETSTATE(STATE_ATTEMPT_START);
done = true;
}
}
else
{
SETSTATE(STATE_WAIT_SELECTED);
ctrl.waitSelectedRemaining = 3;
done = true;
}
break;
}
case STATE_WAIT_SELECTED:
if (pFrame->pGuider->GetState() == STATE_SELECTED)
{
SETSTATE(STATE_CALIBRATE);
}
else
{
Debug.AddLine("waiting for star selected, attempts remaining = %d", ctrl.waitSelectedRemaining);
if (--ctrl.waitSelectedRemaining == 0)
{
SETSTATE(STATE_ATTEMPT_START);
}
done = true;
}
break;
case STATE_CALIBRATE:
if (ctrl.forceCalibration)
{
Debug.AddLine("PhdController: clearing calibration");
if (pMount)
pMount->ClearCalibration();
if (pSecondaryMount)
pSecondaryMount->ClearCalibration();
}
if ((pMount && !pMount->IsCalibrated()) ||
(pSecondaryMount && !pSecondaryMount->IsCalibrated()))
{
Debug.AddLine("PhdController: start calibration");
ctrl.saveSticky = pFrame->pGuider->LockPosIsSticky();
ctrl.haveSaveSticky = true;
pFrame->pGuider->SetLockPosIsSticky(true);
if (!start_guiding())
{
pFrame->pGuider->SetLockPosIsSticky(ctrl.saveSticky);
do_fail(_T("could not start calibration"));
break;
}
SETSTATE(STATE_CALIBRATION_WAIT);
done = true;
}
else
{
SETSTATE(STATE_GUIDE);
}
break;
case STATE_CALIBRATION_WAIT:
if ((!pMount || pMount->IsCalibrated()) &&
(!pSecondaryMount || pSecondaryMount->IsCalibrated()))
{
if (ctrl.haveSaveSticky)
pFrame->pGuider->SetLockPosIsSticky(ctrl.saveSticky);
SETSTATE(STATE_SETTLE_BEGIN);
}
else
done = true;
break;
case STATE_GUIDE:
if (!start_guiding())
{
do_fail(_T("could not start guiding"));
break;
}
SETSTATE(STATE_SETTLE_BEGIN);
done = true;
break;
case STATE_SETTLE_BEGIN:
ctrl.settlePriorFrameInRange = false;
ctrl.settleTimeout->Start();
SETSTATE(STATE_SETTLE_WAIT);
GuideLog.NotifySettlingStateChange("Settling started");
done = true;
break;
case STATE_SETTLE_WAIT: {
bool lockedOnStar = pFrame->pGuider->IsLocked();
double currentError = pFrame->pGuider->CurrentError();
bool inRange = lockedOnStar && currentError <= ctrl.settle.tolerancePx;
bool aoBumpInProgress = IsAoBumpInProgress();
long timeInRange = 0;
Debug.AddLine("PhdController: settling, locked = %d, distance = %.2f (%.2f) aobump = %d", lockedOnStar, currentError,
ctrl.settle.tolerancePx, aoBumpInProgress);
if (inRange)
{
if (!ctrl.settlePriorFrameInRange)
{
// first frame
if (ctrl.settle.settleTimeSec <= 0)
{
ctrl.succeeded = true;
SETSTATE(STATE_FINISH);
break;
}
ctrl.settleInRange->Start();
}
else if (((timeInRange = ctrl.settleInRange->Time()) / 1000) >= ctrl.settle.settleTimeSec && !aoBumpInProgress)
{
ctrl.succeeded = true;
SETSTATE(STATE_FINISH);
break;
}
}
if ((ctrl.settleTimeout->Time() / 1000) >= ctrl.settle.timeoutSec)
{
do_fail(_T("timed-out waiting for guider to settle"));
break;
}
EvtServer.NotifySettling(currentError, (double) timeInRange / 1000., ctrl.settle.settleTimeSec);
ctrl.settlePriorFrameInRange = inRange;
done = true;
break;
}
case STATE_FINISH:
do_notify();
SETSTATE(STATE_IDLE);
done = true;
break;
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <sstream>
#include <sys/stat.h>
using namespace std;
void help() {
cout << "xxd: make a hexdump" << endl;
cout << "visit https://HelloACM.com" << endl;
cout << "-u uppercase" << endl;
cout << "-c column" << endl;
cout << "-h help" << endl;
}
inline bool file_exists(const string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
string tohex(int x, int w = 7, bool upper = false) {
stringstream stream;
stream << std::hex << (x & 0xFF);
string result(stream.str());
if (upper) {
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
}
int j = w - result.length();
while (j-- > 0) { // zero padding
result = '0' + result;
}
return result;
}
void print_xxd(string content, int w = 16, bool upper = false) {
int len = content.size();
int num = 0;
string curline = "";
int width = 9 + (w / 2) * 5 + 1;
if (w & 1 == 1) {
width += 3;
}
int cw = 1;
int kk = 1;
for (int i = 0; i < len ; i ++) {
if ((i % w) == 0) {
cout << tohex(num) << ": ";
cw = 9;
}
char t = content[i];
cout << tohex((int)t, 2, upper);
cw += 2;
curline += t;
if ((i & 1) == kk) {
cout << " ";
cw += 1;
}
if ((i % w) == (w - 1)) {
num += w;
cout << " ";
cw += 2;
int k = i - w + 1;
for (int j = 0; j < w; j ++) {
t = content[k ++];
if ((int)t < 32) { // non-printable characters
t = '.';
}
cout << t;
cw ++;
}
cout << "\n\r";
curline = "";
cw = 0;
if (w & 1 == 1) {
kk = kk == 1 ? 0 : 1;
}
}
}
// remaining characters;
int j = width - cw + 1;
while (j-- > 0) {
cout << " ";
}
for (int i = 0; i < curline.size(); i ++) {
char t = content[i ++];
if ((int)t < 32) { // non-printable characters
t = '.';
}
cout << t;
}
}
std::string get_file_contents(const char *filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
}
void xxd(string filename, int w = 16, bool upper = false) {
if (!file_exists(filename)) {
cout << "xxd: " << filename << ": No such file or directory" << endl;
return;
}
print_xxd(get_file_contents(filename.c_str()), w, upper);
}
int main(int argc, char ** argv)
{
bool upper = false;
int w = 16;
bool io = true;
for (int i = 2; i <= argc; i ++) {
string cur = argv[i - 1];
if (cur == "-h") {
help();
return 0;
}
if (cur == "-u") {
upper = true;
}
else if ((cur[0] == '-') && (cur.length() > 1)) {
if (cur[1] == 'c') {
if (cur.length() > 2) {
string num = cur.substr(2);
std::stringstream str(num);
int x;
str >> x;
if (str) {
if (x > 0) {
w = x;
}
}
} else {
if (i != argc) {
string num = string(argv[i]);
std::stringstream str(num);
int x;
str >> x;
if (str) {
if (x > 0) {
w = x;
}
}
i ++;
}
}
}
}
else {
xxd(cur, w, upper);
io = false;
}
}
if (io) {
// standard input
std::string line;
std::string all = "";
while (std::getline(std::cin, line))
{
all += line;
}
print_xxd(all, w, upper);
}
return 0;
}
<commit_msg>Fix bugs<commit_after>#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <sstream>
#include <sys/stat.h>
using namespace std;
void help() {
cout << "xxd: make a hexdump" << endl;
cout << "visit https://HelloACM.com" << endl;
cout << "-u uppercase" << endl;
cout << "-c column" << endl;
cout << "-h help" << endl;
}
inline bool file_exists(const string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
string tohex(int x, int w = 8, bool upper = false) {
stringstream stream;
stream << std::hex << (x & 0xFF);
string result(stream.str());
if (upper) {
std::transform(result.begin(), result.end(), result.begin(), ::toupper);
}
int j = w - result.length();
while (j-- > 0) { // zero padding
result = '0' + result;
}
return result;
}
void print_xxd(string content, int w = 16, bool upper = false) {
int len = static_cast<int>(content.size());
int num = 0;
string curline = "";
int width = 9 + (w / 2) * 5 + 1;
if (w & 1 == 1) {
width += 3;
}
int cw = 1;
int kk = 1;
for (int i = 0; i < len ; i ++) {
if ((i % w) == 0) {
cout << tohex(num) << ": ";
cw = 9;
}
char t = content[i];
cout << tohex((int)t, 2, upper);
cw += 2;
curline += t;
if ((i & 1) == kk) {
cout << " ";
cw += 1;
}
if ((i % w) == (w - 1)) {
num += w;
cout << " ";
cw += 2;
int k = i - w + 1;
for (int j = 0; j < w; j ++) {
t = content[k ++];
if ((int)t < 32) { // non-printable characters
t = '.';
}
cout << t;
cw ++;
}
cout << "\n\r";
curline = "";
cw = 0;
if (w & 1 == 1) {
kk = kk == 1 ? 0 : 1;
}
}
}
// remaining characters;
int j = width - cw;
while (j-- > 0) {
cout << " ";
}
for (int i = 0; i < static_cast<int>(curline.size()); i ++) {
char t = content[i];
if ((int)t < 32) { // non-printable characters
t = '.';
}
cout << t;
}
}
std::string get_file_contents(const char *filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in) {
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
}
void xxd(string filename, int w = 16, bool upper = false) {
if (!file_exists(filename)) {
cout << "xxd: " << filename << ": No such file or directory" << endl;
return;
}
print_xxd(get_file_contents(filename.c_str()), w, upper);
}
int main(int argc, char ** argv)
{
bool upper = false;
int w = 16;
bool io = true;
for (int i = 2; i <= argc; i ++) {
string cur = argv[i - 1];
if (cur == "-h") {
help();
return 0;
}
if (cur == "-u") {
upper = true;
}
else if ((cur[0] == '-') && (cur.length() > 1)) {
if (cur[1] == 'c') {
if (cur.length() > 2) {
string num = cur.substr(2);
std::stringstream str(num);
int x;
str >> x;
if (str) {
if (x > 0) {
w = x;
}
}
} else {
if (i != argc) {
string num = string(argv[i]);
std::stringstream str(num);
int x;
str >> x;
if (str) {
if (x > 0) {
w = x;
}
}
i ++;
}
}
}
}
else {
xxd(cur, w, upper);
io = false;
}
}
if (io) {
// standard input
std::string line;
std::string all = "";
while (std::getline(std::cin, line))
{
all += line + "\n";
}
print_xxd(all, w, upper);
cout << endl;
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Minor fix for GLES2<commit_after><|endoftext|> |
<commit_before>#include "StdInc.h"
#include "Diagnostic.hpp"
#include "ConsoleColors.h"
#include "StringRef.h"
#include <Frontend/SourceCode.h>
#include <Frontend/LocationSer.h>
static int _reportingEnabled = 1;
static int _numErrors = 0;
static int _numSupppresedErrors = 0;
namespace
{
void doReport(const Location& loc, DiagnosticSeverity severity, const string& message)
{
// Write location: 'filename(line:col) : '
if ( !Nest_isLocEmpty(&loc) )
{
cerr << loc << " : ";
}
// Write the severity
switch ( severity )
{
case diagInternalError: cerr << ConsoleColors::fgHiMagenta << "INTERNAL ERROR : "; break;
case diagError: cerr << ConsoleColors::fgLoRed << "ERROR : "; break;
case diagWarning: cerr << ConsoleColors::fgHiYellow << "WARNING : "; break;
case diagInfo:
default: break;
}
// Write the diagnostic text
cerr << ConsoleColors::stClear << ConsoleColors::stBold << message << ConsoleColors::stClear << endl;
// Try to write the source line no in which the diagnostic occurred
if ( !Nest_isLocEmpty(&loc) )
{
// Get the actual source line
StringRef sourceLine = Nest_getSourceCodeLine(loc.sourceCode, loc.start.line);
size_t sourceLineLen = sourceLine.end - sourceLine.begin;
if ( sourceLineLen > 0 )
{
char lastChar = *(sourceLine.end-1);
// Add the source line
cerr << "> " << string(sourceLine.begin, sourceLine.end);
if ( lastChar != '\n' )
cerr << "\n";
// Add the pointer to the output string
int count = loc.end.line == loc.start.line
? loc.end.col - loc.start.col
: sourceLineLen - loc.start.col+1;
if ( count <= 1 )
count = 1;
cerr << " ";
cerr << string(loc.start.col-1, ' '); // spaces used for alignment
cerr << ConsoleColors::fgLoRed;
cerr << string(count, '~'); // arrow to underline the whole location range
cerr << ConsoleColors::stClear << endl;
}
}
}
}
void Nest_reportDiagnostic(Location loc, DiagnosticSeverity severity, const char* message)
{
// If error reporting is paused, allow only internal errors
if ( severity != diagInternalError && !_reportingEnabled )
{
if ( severity == diagError )
++_numSupppresedErrors;
return;
}
if ( severity == diagError )
++_numErrors;
// Show the diagnostic
doReport(loc, severity, message);
// Old mechanism of throwing exceptions on errors
if ( severity == diagError || severity == diagInternalError )
throw Nest::Common::CompilationError(severity, message);
if ( severity == diagInternalError )
exit(-1);
}
void Nest_reportFmt(Location loc, DiagnosticSeverity severity, const char* fmt, ...)
{
static const int maxMessageLen = 1024;
char buffer[maxMessageLen];
va_list args;
va_start(args, fmt);
vsnprintf(buffer, maxMessageLen, fmt, args);
Nest_reportDiagnostic(loc, severity, buffer);
va_end(args);
}
void Nest_enableReporting(int enable)
{
if ( !enable )
_numSupppresedErrors = 0; // Reset the counter when disabling errors
_reportingEnabled = enable;
}
int Nest_isReportingEnabled()
{
return _reportingEnabled;
}
int Nest_getErrorsNum()
{
return _numErrors;
}
int Nest_getSuppressedErrorsNum()
{
return _numSupppresedErrors;
}
<commit_msg>Problem: Some Internal errors were visible on the screen<commit_after>#include "StdInc.h"
#include "Diagnostic.hpp"
#include "ConsoleColors.h"
#include "StringRef.h"
#include <Frontend/SourceCode.h>
#include <Frontend/LocationSer.h>
static int _reportingEnabled = 1;
static int _numErrors = 0;
static int _numSupppresedErrors = 0;
namespace
{
void doReport(const Location& loc, DiagnosticSeverity severity, const string& message)
{
// Write location: 'filename(line:col) : '
if ( !Nest_isLocEmpty(&loc) )
{
cerr << loc << " : ";
}
// Write the severity
switch ( severity )
{
case diagInternalError: cerr << ConsoleColors::fgHiMagenta << "INTERNAL ERROR : "; break;
case diagError: cerr << ConsoleColors::fgLoRed << "ERROR : "; break;
case diagWarning: cerr << ConsoleColors::fgHiYellow << "WARNING : "; break;
case diagInfo:
default: break;
}
// Write the diagnostic text
cerr << ConsoleColors::stClear << ConsoleColors::stBold << message << ConsoleColors::stClear << endl;
// Try to write the source line no in which the diagnostic occurred
if ( !Nest_isLocEmpty(&loc) )
{
// Get the actual source line
StringRef sourceLine = Nest_getSourceCodeLine(loc.sourceCode, loc.start.line);
size_t sourceLineLen = sourceLine.end - sourceLine.begin;
if ( sourceLineLen > 0 )
{
char lastChar = *(sourceLine.end-1);
// Add the source line
cerr << "> " << string(sourceLine.begin, sourceLine.end);
if ( lastChar != '\n' )
cerr << "\n";
// Add the pointer to the output string
int count = loc.end.line == loc.start.line
? loc.end.col - loc.start.col
: sourceLineLen - loc.start.col+1;
if ( count <= 1 )
count = 1;
cerr << " ";
cerr << string(loc.start.col-1, ' '); // spaces used for alignment
cerr << ConsoleColors::fgLoRed;
cerr << string(count, '~'); // arrow to underline the whole location range
cerr << ConsoleColors::stClear << endl;
}
}
}
}
void Nest_reportDiagnostic(Location loc, DiagnosticSeverity severity, const char* message)
{
// If error reporting is paused, allow only internal errors
if ( severity != diagInternalError && !_reportingEnabled )
{
if ( severity == diagError )
{
++_numSupppresedErrors;
throw Nest::Common::CompilationError(severity, message);
}
return;
}
if ( severity == diagError )
++_numErrors;
// Show the diagnostic
doReport(loc, severity, message);
// Old mechanism of throwing exceptions on errors
if ( severity == diagError )
throw Nest::Common::CompilationError(severity, message);
if ( severity == diagInternalError )
exit(-1);
}
void Nest_reportFmt(Location loc, DiagnosticSeverity severity, const char* fmt, ...)
{
static const int maxMessageLen = 1024;
char buffer[maxMessageLen];
va_list args;
va_start(args, fmt);
vsnprintf(buffer, maxMessageLen, fmt, args);
Nest_reportDiagnostic(loc, severity, buffer);
va_end(args);
}
void Nest_enableReporting(int enable)
{
if ( !enable )
_numSupppresedErrors = 0; // Reset the counter when disabling errors
_reportingEnabled = enable;
}
int Nest_isReportingEnabled()
{
return _reportingEnabled;
}
int Nest_getErrorsNum()
{
return _numErrors;
}
int Nest_getSuppressedErrorsNum()
{
return _numSupppresedErrors;
}
<|endoftext|> |
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
adapted for karm 2005 by Thorsten Staerk <kde@staerk.de>
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <kgenericfactory.h>
#include <kparts/componentfactory.h>
#include <kicon.h>
#include "core.h"
#include "plugin.h"
#include "karm_plugin.h"
#include "karminterface.h"
typedef KGenericFactory<KarmPlugin, Kontact::Core> KarmPluginFactory;
K_EXPORT_COMPONENT_FACTORY( libkontact_karm,
KarmPluginFactory( "kontact_karm" ) )
KarmPlugin::KarmPlugin( Kontact::Core *core, const QStringList& )
: Kontact::Plugin( core, core, "KArm" )
{
setInstance( KarmPluginFactory::instance() );
KAction *action = new KAction( KIcon("karm"), i18n( "New Task" ), actionCollection(), "new_task" );
action->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_W));
connect(action, SIGNAL(triggered(bool)), SLOT( newTask() ));
insertNewAction(action);
}
KarmPlugin::~KarmPlugin()
{
}
QString KarmPlugin::tipFile() const
{
// TODO: tips file
//QString file = KStandardDirs::locate("data", "karm/tips");
QString file;
return file;
}
KParts::ReadOnlyPart* KarmPlugin::createPart()
{
KParts::ReadOnlyPart * part = loadPart();
if ( !part ) return 0;
// this calls a DCOP interface from karm via the lib KarmDCOPIface_stub that is generated automatically
mInterface = new OrgKdeKarmKarmInterface( "/Karm", "org.kde.karm.Karm", QDBusConnection::sessionBus() );
return part;
}
void KarmPlugin::newTask()
{
kDebug() << "Entering newTask" << endl;
mInterface->addTask("New Task");
}
#include "karm_plugin.moc"
<commit_msg>Not sure that it will work<commit_after>/*
This file is part of Kontact.
Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
adapted for karm 2005 by Thorsten Staerk <kde@staerk.de>
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <kgenericfactory.h>
#include <kparts/componentfactory.h>
#include <kicon.h>
#include "core.h"
#include "plugin.h"
#include "karm_plugin.h"
#include "karminterface.h"
typedef KGenericFactory<KarmPlugin, Kontact::Core> KarmPluginFactory;
K_EXPORT_COMPONENT_FACTORY( libkontact_karm,
KarmPluginFactory( "kontact_karm" ) )
KarmPlugin::KarmPlugin( Kontact::Core *core, const QStringList& )
: Kontact::Plugin( core, core, "KArm" )
{
setInstance( KarmPluginFactory::instance() );
KAction *action = new KAction( KIcon("karm"), i18n( "New Task" ), actionCollection(), "new_task" );
action->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_W));
connect(action, SIGNAL(triggered(bool)), SLOT( newTask() ));
insertNewAction(action);
}
KarmPlugin::~KarmPlugin()
{
}
QString KarmPlugin::tipFile() const
{
// TODO: tips file
//QString file = KStandardDirs::locate("data", "karm/tips");
QString file;
return file;
}
KParts::ReadOnlyPart* KarmPlugin::createPart()
{
KParts::ReadOnlyPart * part = loadPart();
if ( !part ) return 0;
// this calls a DCOP interface from karm via the lib KarmDCOPIface_stub that is generated automatically
mInterface = new OrgKdeKarmKarmInterface( "org.kde.karm", "/Karm", QDBusConnection::sessionBus() );
return part;
}
void KarmPlugin::newTask()
{
kDebug() << "Entering newTask" << endl;
mInterface->addTask("New Task");
}
#include "karm_plugin.moc"
<|endoftext|> |
<commit_before>//===--- RawSyntax.cpp - Swift Raw Syntax Implementation ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/ColorUtils.h"
#include "swift/Syntax/RawSyntax.h"
#include "swift/Syntax/SyntaxArena.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using llvm::dyn_cast;
using namespace swift;
using namespace swift::syntax;
namespace {
static bool isTrivialSyntaxKind(SyntaxKind Kind) {
if (isUnknownKind(Kind))
return true;
if (isCollectionKind(Kind))
return true;
switch(Kind) {
case SyntaxKind::SourceFile:
case SyntaxKind::CodeBlockItem:
case SyntaxKind::ExpressionStmt:
case SyntaxKind::DeclarationStmt:
return true;
default:
return false;
}
}
static void printSyntaxKind(SyntaxKind Kind, llvm::raw_ostream &OS,
SyntaxPrintOptions Opts, bool Open) {
std::unique_ptr<swift::OSColor> Color;
if (Opts.Visual) {
Color.reset(new swift::OSColor(OS, llvm::raw_ostream::GREEN));
}
OS << "<";
if (!Open)
OS << "/";
dumpSyntaxKind(OS, Kind);
OS << ">";
}
} // end of anonymous namespace
void swift::dumpTokenKind(llvm::raw_ostream &OS, tok Kind) {
switch (Kind) {
#define TOKEN(X) \
case tok::X: \
OS << #X; \
break;
#include "swift/Syntax/TokenKinds.def"
case tok::NUM_TOKENS:
OS << "NUM_TOKENS (unset)";
break;
}
}
unsigned RawSyntax::NextFreeNodeId = 1;
RawSyntax::RawSyntax(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout,
SourcePresence Presence, const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
assert(Kind != SyntaxKind::Token &&
"'token' syntax node must be constructed with dedicated constructor");
RefCount = 0;
if (NodeId.hasValue()) {
this->NodeId = NodeId.getValue();
NextFreeNodeId = std::max(this->NodeId + 1, NextFreeNodeId);
} else {
this->NodeId = NextFreeNodeId++;
}
Bits.Common.Kind = unsigned(Kind);
Bits.Common.Presence = unsigned(Presence);
Bits.Layout.NumChildren = Layout.size();
Bits.Layout.TextLength = UINT32_MAX;
this->Arena = Arena;
// Initialize layout data.
std::uninitialized_copy(Layout.begin(), Layout.end(),
getTrailingObjects<RC<RawSyntax>>());
}
RawSyntax::RawSyntax(tok TokKind, OwnedString Text,
ArrayRef<TriviaPiece> LeadingTrivia,
ArrayRef<TriviaPiece> TrailingTrivia,
SourcePresence Presence, const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
RefCount = 0;
if (NodeId.hasValue()) {
this->NodeId = NodeId.getValue();
NextFreeNodeId = std::max(this->NodeId + 1, NextFreeNodeId);
} else {
this->NodeId = NextFreeNodeId++;
}
Bits.Common.Kind = unsigned(SyntaxKind::Token);
Bits.Common.Presence = unsigned(Presence);
Bits.Token.TokenKind = unsigned(TokKind);
Bits.Token.NumLeadingTrivia = LeadingTrivia.size();
Bits.Token.NumTrailingTrivia = TrailingTrivia.size();
this->Arena = Arena;
// Initialize token text.
::new (static_cast<void *>(getTrailingObjects<OwnedString>()))
OwnedString(Text);
// Initialize leading trivia.
std::uninitialized_copy(LeadingTrivia.begin(), LeadingTrivia.end(),
getTrailingObjects<TriviaPiece>());
// Initialize trailing trivia.
std::uninitialized_copy(TrailingTrivia.begin(), TrailingTrivia.end(),
getTrailingObjects<TriviaPiece>() +
Bits.Token.NumLeadingTrivia);
}
RawSyntax::~RawSyntax() {
if (isToken()) {
getTrailingObjects<OwnedString>()->~OwnedString();
for (auto &trivia : getLeadingTrivia())
trivia.~TriviaPiece();
for (auto &trivia : getTrailingTrivia())
trivia.~TriviaPiece();
} else {
for (auto &child : getLayout())
child.~RC<RawSyntax>();
}
}
RC<RawSyntax> RawSyntax::make(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout,
SourcePresence Presence,
const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>(
Layout.size(), 0, 0);
void *data = Arena ? Arena->Allocate(size, alignof(RawSyntax))
: ::operator new(size);
return RC<RawSyntax>(
new (data) RawSyntax(Kind, Layout, Presence, Arena, NodeId));
}
RC<RawSyntax> RawSyntax::make(tok TokKind, OwnedString Text,
ArrayRef<TriviaPiece> LeadingTrivia,
ArrayRef<TriviaPiece> TrailingTrivia,
SourcePresence Presence,
const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>(
0, 1, LeadingTrivia.size() + TrailingTrivia.size());
void *data = Arena ? Arena->Allocate(size, alignof(RawSyntax))
: ::operator new(size);
return RC<RawSyntax>(new (data) RawSyntax(TokKind, Text, LeadingTrivia,
TrailingTrivia, Presence,
Arena, NodeId));
}
RC<RawSyntax> RawSyntax::append(RC<RawSyntax> NewLayoutElement) const {
auto Layout = getLayout();
std::vector<RC<RawSyntax>> NewLayout;
NewLayout.reserve(Layout.size() + 1);
std::copy(Layout.begin(), Layout.end(), std::back_inserter(NewLayout));
NewLayout.push_back(NewLayoutElement);
return RawSyntax::make(getKind(), NewLayout, SourcePresence::Present);
}
RC<RawSyntax> RawSyntax::replaceChild(CursorIndex Index,
RC<RawSyntax> NewLayoutElement) const {
auto Layout = getLayout();
std::vector<RC<RawSyntax>> NewLayout;
NewLayout.reserve(Layout.size());
std::copy(Layout.begin(), Layout.begin() + Index,
std::back_inserter(NewLayout));
NewLayout.push_back(NewLayoutElement);
std::copy(Layout.begin() + Index + 1, Layout.end(),
std::back_inserter(NewLayout));
return RawSyntax::make(getKind(), NewLayout, getPresence());
}
llvm::Optional<AbsolutePosition>
RawSyntax::accumulateAbsolutePosition(AbsolutePosition &Pos) const {
llvm::Optional<AbsolutePosition> Ret;
if (isToken()) {
if (isMissing())
return None;
for (auto &Leader : getLeadingTrivia())
Leader.accumulateAbsolutePosition(Pos);
Ret = Pos;
Pos.addText(getTokenText());
for (auto &Trailer : getTrailingTrivia())
Trailer.accumulateAbsolutePosition(Pos);
} else {
for (auto &Child : getLayout()) {
if (!Child)
continue;
auto Result = Child->accumulateAbsolutePosition(Pos);
if (!Ret && Result)
Ret = Result;
}
}
return Ret;
}
bool RawSyntax::accumulateLeadingTrivia(AbsolutePosition &Pos) const {
if (isToken()) {
if (!isMissing()) {
for (auto &Leader: getLeadingTrivia())
Leader.accumulateAbsolutePosition(Pos);
return true;
}
} else {
for (auto &Child: getLayout()) {
if (!Child || Child->isMissing())
continue;
if (Child->accumulateLeadingTrivia(Pos))
return true;
}
}
return false;
}
void RawSyntax::print(llvm::raw_ostream &OS, SyntaxPrintOptions Opts) const {
if (isMissing())
return;
if (isToken()) {
for (const auto &Leader : getLeadingTrivia())
Leader.print(OS);
OS << getTokenText();
for (const auto &Trailer : getTrailingTrivia())
Trailer.print(OS);
} else {
auto Kind = getKind();
const bool PrintKind = Opts.PrintSyntaxKind && (Opts.PrintTrivialNodeKind ||
!isTrivialSyntaxKind(Kind));
if (PrintKind)
printSyntaxKind(Kind, OS, Opts, true);
for (const auto &LE : getLayout())
if (LE)
LE->print(OS, Opts);
if (PrintKind)
printSyntaxKind(Kind, OS, Opts, false);
}
}
void RawSyntax::dump() const {
dump(llvm::errs(), /*Indent*/ 0);
llvm::errs() << '\n';
}
void RawSyntax::dump(llvm::raw_ostream &OS, unsigned Indent) const {
auto indent = [&](unsigned Amount) {
for (decltype(Amount) i = 0; i < Amount; ++i) {
OS << ' ';
}
};
indent(Indent);
OS << '(';
dumpSyntaxKind(OS, getKind());
if (isMissing())
OS << " [missing] ";
if (isToken()) {
OS << " ";
dumpTokenKind(OS, getTokenKind());
for (auto &Leader : getLeadingTrivia()) {
OS << "\n";
Leader.dump(OS, Indent + 1);
}
OS << "\n";
indent(Indent + 1);
OS << "(text=\"";
OS.write_escaped(getTokenText(), /*UseHexEscapes=*/true);
OS << "\")";
for (auto &Trailer : getTrailingTrivia()) {
OS << "\n";
Trailer.dump(OS, Indent + 1);
}
} else {
for (auto &Child : getLayout()) {
if (!Child)
continue;
OS << "\n";
Child->dump(OS, Indent + 1);
}
}
OS << ')';
}
void AbsolutePosition::printLineAndColumn(llvm::raw_ostream &OS) const {
OS << getLine() << ':' << getColumn();
}
void AbsolutePosition::dump(llvm::raw_ostream &OS) const {
OS << "(absolute_position ";
OS << "offset=" << getOffset() << " ";
OS << "line=" << getLine() << " ";
OS << "column=" << getColumn();
OS << ')';
}
void RawSyntax::Profile(llvm::FoldingSetNodeID &ID, tok TokKind,
OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia,
ArrayRef<TriviaPiece> TrailingTrivia) {
ID.AddInteger(unsigned(TokKind));
switch (TokKind) {
#define TOKEN_DEFAULT(NAME) case tok::NAME:
#define PUNCTUATOR(NAME, X) TOKEN_DEFAULT(NAME)
#define KEYWORD(KW) TOKEN_DEFAULT(kw_##KW)
#define POUND_KEYWORD(KW) TOKEN_DEFAULT(pound_##KW)
#include "swift/Syntax/TokenKinds.def"
break;
default:
ID.AddString(Text.str());
break;
}
for (auto &Piece : LeadingTrivia)
Piece.Profile(ID);
for (auto &Piece : TrailingTrivia)
Piece.Profile(ID);
}
llvm::raw_ostream &llvm::operator<<(raw_ostream &OS, AbsolutePosition Pos) {
Pos.printLineAndColumn(OS);
return OS;
}
<commit_msg>[Syntax] Include leading/trailing trivia size to the cache ID<commit_after>//===--- RawSyntax.cpp - Swift Raw Syntax Implementation ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/ColorUtils.h"
#include "swift/Syntax/RawSyntax.h"
#include "swift/Syntax/SyntaxArena.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using llvm::dyn_cast;
using namespace swift;
using namespace swift::syntax;
namespace {
static bool isTrivialSyntaxKind(SyntaxKind Kind) {
if (isUnknownKind(Kind))
return true;
if (isCollectionKind(Kind))
return true;
switch(Kind) {
case SyntaxKind::SourceFile:
case SyntaxKind::CodeBlockItem:
case SyntaxKind::ExpressionStmt:
case SyntaxKind::DeclarationStmt:
return true;
default:
return false;
}
}
static void printSyntaxKind(SyntaxKind Kind, llvm::raw_ostream &OS,
SyntaxPrintOptions Opts, bool Open) {
std::unique_ptr<swift::OSColor> Color;
if (Opts.Visual) {
Color.reset(new swift::OSColor(OS, llvm::raw_ostream::GREEN));
}
OS << "<";
if (!Open)
OS << "/";
dumpSyntaxKind(OS, Kind);
OS << ">";
}
} // end of anonymous namespace
void swift::dumpTokenKind(llvm::raw_ostream &OS, tok Kind) {
switch (Kind) {
#define TOKEN(X) \
case tok::X: \
OS << #X; \
break;
#include "swift/Syntax/TokenKinds.def"
case tok::NUM_TOKENS:
OS << "NUM_TOKENS (unset)";
break;
}
}
unsigned RawSyntax::NextFreeNodeId = 1;
RawSyntax::RawSyntax(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout,
SourcePresence Presence, const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
assert(Kind != SyntaxKind::Token &&
"'token' syntax node must be constructed with dedicated constructor");
RefCount = 0;
if (NodeId.hasValue()) {
this->NodeId = NodeId.getValue();
NextFreeNodeId = std::max(this->NodeId + 1, NextFreeNodeId);
} else {
this->NodeId = NextFreeNodeId++;
}
Bits.Common.Kind = unsigned(Kind);
Bits.Common.Presence = unsigned(Presence);
Bits.Layout.NumChildren = Layout.size();
Bits.Layout.TextLength = UINT32_MAX;
this->Arena = Arena;
// Initialize layout data.
std::uninitialized_copy(Layout.begin(), Layout.end(),
getTrailingObjects<RC<RawSyntax>>());
}
RawSyntax::RawSyntax(tok TokKind, OwnedString Text,
ArrayRef<TriviaPiece> LeadingTrivia,
ArrayRef<TriviaPiece> TrailingTrivia,
SourcePresence Presence, const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
RefCount = 0;
if (NodeId.hasValue()) {
this->NodeId = NodeId.getValue();
NextFreeNodeId = std::max(this->NodeId + 1, NextFreeNodeId);
} else {
this->NodeId = NextFreeNodeId++;
}
Bits.Common.Kind = unsigned(SyntaxKind::Token);
Bits.Common.Presence = unsigned(Presence);
Bits.Token.TokenKind = unsigned(TokKind);
Bits.Token.NumLeadingTrivia = LeadingTrivia.size();
Bits.Token.NumTrailingTrivia = TrailingTrivia.size();
this->Arena = Arena;
// Initialize token text.
::new (static_cast<void *>(getTrailingObjects<OwnedString>()))
OwnedString(Text);
// Initialize leading trivia.
std::uninitialized_copy(LeadingTrivia.begin(), LeadingTrivia.end(),
getTrailingObjects<TriviaPiece>());
// Initialize trailing trivia.
std::uninitialized_copy(TrailingTrivia.begin(), TrailingTrivia.end(),
getTrailingObjects<TriviaPiece>() +
Bits.Token.NumLeadingTrivia);
}
RawSyntax::~RawSyntax() {
if (isToken()) {
getTrailingObjects<OwnedString>()->~OwnedString();
for (auto &trivia : getLeadingTrivia())
trivia.~TriviaPiece();
for (auto &trivia : getTrailingTrivia())
trivia.~TriviaPiece();
} else {
for (auto &child : getLayout())
child.~RC<RawSyntax>();
}
}
RC<RawSyntax> RawSyntax::make(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout,
SourcePresence Presence,
const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>(
Layout.size(), 0, 0);
void *data = Arena ? Arena->Allocate(size, alignof(RawSyntax))
: ::operator new(size);
return RC<RawSyntax>(
new (data) RawSyntax(Kind, Layout, Presence, Arena, NodeId));
}
RC<RawSyntax> RawSyntax::make(tok TokKind, OwnedString Text,
ArrayRef<TriviaPiece> LeadingTrivia,
ArrayRef<TriviaPiece> TrailingTrivia,
SourcePresence Presence,
const RC<SyntaxArena> &Arena,
llvm::Optional<unsigned> NodeId) {
auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>(
0, 1, LeadingTrivia.size() + TrailingTrivia.size());
void *data = Arena ? Arena->Allocate(size, alignof(RawSyntax))
: ::operator new(size);
return RC<RawSyntax>(new (data) RawSyntax(TokKind, Text, LeadingTrivia,
TrailingTrivia, Presence,
Arena, NodeId));
}
RC<RawSyntax> RawSyntax::append(RC<RawSyntax> NewLayoutElement) const {
auto Layout = getLayout();
std::vector<RC<RawSyntax>> NewLayout;
NewLayout.reserve(Layout.size() + 1);
std::copy(Layout.begin(), Layout.end(), std::back_inserter(NewLayout));
NewLayout.push_back(NewLayoutElement);
return RawSyntax::make(getKind(), NewLayout, SourcePresence::Present);
}
RC<RawSyntax> RawSyntax::replaceChild(CursorIndex Index,
RC<RawSyntax> NewLayoutElement) const {
auto Layout = getLayout();
std::vector<RC<RawSyntax>> NewLayout;
NewLayout.reserve(Layout.size());
std::copy(Layout.begin(), Layout.begin() + Index,
std::back_inserter(NewLayout));
NewLayout.push_back(NewLayoutElement);
std::copy(Layout.begin() + Index + 1, Layout.end(),
std::back_inserter(NewLayout));
return RawSyntax::make(getKind(), NewLayout, getPresence());
}
llvm::Optional<AbsolutePosition>
RawSyntax::accumulateAbsolutePosition(AbsolutePosition &Pos) const {
llvm::Optional<AbsolutePosition> Ret;
if (isToken()) {
if (isMissing())
return None;
for (auto &Leader : getLeadingTrivia())
Leader.accumulateAbsolutePosition(Pos);
Ret = Pos;
Pos.addText(getTokenText());
for (auto &Trailer : getTrailingTrivia())
Trailer.accumulateAbsolutePosition(Pos);
} else {
for (auto &Child : getLayout()) {
if (!Child)
continue;
auto Result = Child->accumulateAbsolutePosition(Pos);
if (!Ret && Result)
Ret = Result;
}
}
return Ret;
}
bool RawSyntax::accumulateLeadingTrivia(AbsolutePosition &Pos) const {
if (isToken()) {
if (!isMissing()) {
for (auto &Leader: getLeadingTrivia())
Leader.accumulateAbsolutePosition(Pos);
return true;
}
} else {
for (auto &Child: getLayout()) {
if (!Child || Child->isMissing())
continue;
if (Child->accumulateLeadingTrivia(Pos))
return true;
}
}
return false;
}
void RawSyntax::print(llvm::raw_ostream &OS, SyntaxPrintOptions Opts) const {
if (isMissing())
return;
if (isToken()) {
for (const auto &Leader : getLeadingTrivia())
Leader.print(OS);
OS << getTokenText();
for (const auto &Trailer : getTrailingTrivia())
Trailer.print(OS);
} else {
auto Kind = getKind();
const bool PrintKind = Opts.PrintSyntaxKind && (Opts.PrintTrivialNodeKind ||
!isTrivialSyntaxKind(Kind));
if (PrintKind)
printSyntaxKind(Kind, OS, Opts, true);
for (const auto &LE : getLayout())
if (LE)
LE->print(OS, Opts);
if (PrintKind)
printSyntaxKind(Kind, OS, Opts, false);
}
}
void RawSyntax::dump() const {
dump(llvm::errs(), /*Indent*/ 0);
llvm::errs() << '\n';
}
void RawSyntax::dump(llvm::raw_ostream &OS, unsigned Indent) const {
auto indent = [&](unsigned Amount) {
for (decltype(Amount) i = 0; i < Amount; ++i) {
OS << ' ';
}
};
indent(Indent);
OS << '(';
dumpSyntaxKind(OS, getKind());
if (isMissing())
OS << " [missing] ";
if (isToken()) {
OS << " ";
dumpTokenKind(OS, getTokenKind());
for (auto &Leader : getLeadingTrivia()) {
OS << "\n";
Leader.dump(OS, Indent + 1);
}
OS << "\n";
indent(Indent + 1);
OS << "(text=\"";
OS.write_escaped(getTokenText(), /*UseHexEscapes=*/true);
OS << "\")";
for (auto &Trailer : getTrailingTrivia()) {
OS << "\n";
Trailer.dump(OS, Indent + 1);
}
} else {
for (auto &Child : getLayout()) {
if (!Child)
continue;
OS << "\n";
Child->dump(OS, Indent + 1);
}
}
OS << ')';
}
void AbsolutePosition::printLineAndColumn(llvm::raw_ostream &OS) const {
OS << getLine() << ':' << getColumn();
}
void AbsolutePosition::dump(llvm::raw_ostream &OS) const {
OS << "(absolute_position ";
OS << "offset=" << getOffset() << " ";
OS << "line=" << getLine() << " ";
OS << "column=" << getColumn();
OS << ')';
}
void RawSyntax::Profile(llvm::FoldingSetNodeID &ID, tok TokKind,
OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia,
ArrayRef<TriviaPiece> TrailingTrivia) {
ID.AddInteger(unsigned(TokKind));
ID.AddInteger(LeadingTrivia.size());
ID.AddInteger(TrailingTrivia.size());
switch (TokKind) {
#define TOKEN_DEFAULT(NAME) case tok::NAME:
#define PUNCTUATOR(NAME, X) TOKEN_DEFAULT(NAME)
#define KEYWORD(KW) TOKEN_DEFAULT(kw_##KW)
#define POUND_KEYWORD(KW) TOKEN_DEFAULT(pound_##KW)
#include "swift/Syntax/TokenKinds.def"
break;
default:
ID.AddString(Text.str());
break;
}
for (auto &Piece : LeadingTrivia)
Piece.Profile(ID);
for (auto &Piece : TrailingTrivia)
Piece.Profile(ID);
}
llvm::raw_ostream &llvm::operator<<(raw_ostream &OS, AbsolutePosition Pos) {
Pos.printLineAndColumn(OS);
return OS;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
using namespace std;
typedef chrono::system_clock Clock;
typedef chrono::nanoseconds ClockResolution;
#include <boost/format.hpp>
boost::format log_fmt;
#include <mpi.h>
#define WITH_MPI
#include "../logging.hpp"
#define MAX_ITER 5
#define BASE_DELAY 1000 // nanoseconds
#define FINE_MULTIPLIER 100000
#define COARSE_MULTIPLIER 1
#define STATE_MULTIPLIER 100
#define TOTAL_STEPS 4
#define RESIDUAL_TOL 2 // seconds
enum class PState : int {
// overall state
CONVERGED = 0,
FAILED = 1,
// iterating states
ITERATING = 10,
PRE_ITER_COARSE = 20,
ITER_COARSE = 21,
POST_ITER_COARSE = 22,
PRE_ITER_FINE = 30,
ITER_FINE = 31,
POST_ITER_FINE = 32,
// last
UNKNOWN = 99,
};
struct ProcessState
{
PState state= PState::UNKNOWN;
int iter = -1;
double residual = numeric_limits<double>::max();
};
int block_length[3] = {1, 1, 1};
MPI_Aint block_displace[3] = {
0,
sizeof(int),
sizeof(int) + sizeof(int)
};
MPI_Datatype block_types[3] = {
MPI_INT, MPI_INT, MPI_DOUBLE
};
MPI_Datatype process_state_type;
int process_state_type_size;
struct ProcessData
{
int size = -1;
int rank = -1;
bool iam_first;
bool iam_last;
int prev = -1;
int next = -1;
double coarse_val_in, coarse_val, coarse_val_out;
double fine_val_in, fine_val, fine_val_out;
double mpi_start;
ProcessState state;
MPI_Win coarse_win;
MPI_Win fine_win;
MPI_Win state_win;
void init(const double start_time) {
assert(rank >= 0 && size > 0);
this->mpi_start = start_time;
this->iam_first = (rank == 0);
this->iam_last = (rank == size - 1);
if (!this->iam_first) { this->prev = this->rank - 1; }
if (!this->iam_last) { this->next = this->rank + 1; }
}
void create_windows()
{
if (this->size > 1) {
VLOG(6) << "creating windows";
MPI_Win_create(&fine_val_out, sizeof(double), MPI_DOUBLE, MPI_INFO_NULL, MPI_COMM_WORLD, &fine_win);
MPI_Win_create(&coarse_val_out, sizeof(double), MPI_DOUBLE, MPI_INFO_NULL, MPI_COMM_WORLD, &coarse_win);
MPI_Win_create(&state, 1, process_state_type_size, MPI_INFO_NULL, MPI_COMM_WORLD, &state_win);
} else {
VLOG(6) << "no need for communication";
}
}
void free_windows()
{
if (this->size > 1) {
VLOG(6) << "freeing windows";
MPI_Win_free(&fine_win);
MPI_Win_free(&coarse_win);
MPI_Win_free(&state_win);
} else {
VLOG(6) << "no need for communication";
}
}
};
static int fine_tag(const int iter) { return (iter + 1) * FINE_MULTIPLIER; }
static int coarse_tag(const int iter) { return (iter + 1) * COARSE_MULTIPLIER; }
static int state_tag(const int iter) { return (iter + 1) * STATE_MULTIPLIER; }
void update_state(ProcessData &data, const PState &new_state, const int iter=-1) {
int mpi_err = MPI_SUCCESS;
if (data.size > 1) {
VLOG(5) << "locking local state window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.state_win);
assert(mpi_err == MPI_SUCCESS);
}
data.state.state = new_state;
if (iter != -1) {
data.state.iter = iter;
}
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.state_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local state window";
}
}
void doing_pre_fine(ProcessData &data) {
update_state(data, PState::PRE_ITER_FINE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1 && !data.iam_first) {
VLOG(5) << "locking fine window to rank " << data.prev;
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.prev, 0, data.fine_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(4) << "getting fine value from " << data.prev;
mpi_err = MPI_Get(&(data.fine_val_in), 1, MPI_DOUBLE, data.prev, 0, 1, MPI_DOUBLE, data.fine_win);
assert(mpi_err == MPI_SUCCESS);
mpi_err = MPI_Win_unlock(data.prev, data.fine_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked fine window to rank " << data.prev;
}
}
void doing_fine(ProcessData &data, const int iter) {
update_state(data, PState::ITER_FINE);
VLOG(2) << "start computation";
data.fine_val = data.fine_val_in + (data.state.iter + 1) * FINE_MULTIPLIER + iter * 0.001;
VLOG(3) << data.fine_val << " = " << data.fine_val_in << " + " << ((data.rank + 1) * FINE_MULTIPLIER) << " + " << (iter * 0.001);
chrono::time_point<Clock> start, end;
ClockResolution duration;
start = Clock::now();
do {
end = Clock::now();
duration = end - start;
} while(duration.count() < BASE_DELAY * FINE_MULTIPLIER);
VLOG(2) << "done computation";
}
void doing_post_fine(ProcessData &data) {
update_state(data, PState::POST_ITER_FINE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1) {
VLOG(5) << "locking local fine window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.fine_win);
assert(mpi_err == MPI_SUCCESS);
}
data.fine_val_out = data.fine_val;
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.fine_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local fine window";
}
}
void doing_pre_coarse(ProcessData &data) {
update_state(data, PState::PRE_ITER_COARSE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1 && !data.iam_first) {
VLOG(5) << "locking coarse window to rank " << data.prev;
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.prev, 0, data.coarse_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(4) << "getting coarse value from " << data.prev;
mpi_err = MPI_Get(&(data.coarse_val_in), 1, MPI_DOUBLE, data.prev, 0, 1, MPI_DOUBLE, data.coarse_win);
assert(mpi_err == MPI_SUCCESS);
mpi_err = MPI_Win_unlock(data.prev, data.coarse_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked coarse window to rank " << data.prev;
}
}
void doing_coarse(ProcessData &data, const int iter) {
update_state(data, PState::ITER_COARSE);
VLOG(2) << "start computation";
data.coarse_val = data.coarse_val_in + (data.state.iter + 1) * COARSE_MULTIPLIER + iter * 0.001;
VLOG(3) << data.coarse_val << " = " << data.coarse_val_in << " + " << ((data.rank + 1) * COARSE_MULTIPLIER) << " + " << (iter * 0.001);
chrono::time_point<Clock> start, end;
ClockResolution duration;
start = Clock::now();
do {
end = Clock::now();
duration = end - start;
} while(duration.count() < BASE_DELAY * COARSE_MULTIPLIER);
VLOG(2) << "done computation";
}
void doing_post_coarse(ProcessData &data) {
update_state(data, PState::POST_ITER_COARSE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1) {
VLOG(5) << "locking local coarse window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.coarse_win);
assert(mpi_err == MPI_SUCCESS);
}
data.coarse_val_out = data.coarse_val;
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.coarse_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local coarse window";
}
}
void check_finished(ProcessData &data, const int iter) {
int mpi_err = MPI_SUCCESS;
ProcessState other_state;
if (data.size > 1 && !data.iam_first) {
VLOG(5) << "locking state window to rank " << data.prev;
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.prev, 0, data.state_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(4) << "getting state from " << data.prev;
mpi_err = MPI_Get(&other_state, 1, process_state_type, data.prev, 0, 1, process_state_type, data.state_win);
assert(mpi_err == MPI_SUCCESS);
mpi_err = MPI_Win_unlock(data.prev, data.state_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked state window to rank " << data.prev;
} else {
other_state.state = PState::CONVERGED;
}
if (data.size > 1) {
VLOG(5) << "locking local state window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.state_win);
assert(mpi_err == MPI_SUCCESS);
}
double curr_time = MPI_Wtime();
data.state.residual = curr_time - data.mpi_start;
switch (other_state.state) {
case PState::FAILED:
data.state.state = PState::FAILED;
break;
case PState::CONVERGED:
if (data.state.residual > RESIDUAL_TOL) {
data.state.state = PState::CONVERGED;
}
break;
}
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.state_win);
assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local state window";
}
}
int main(int argn, char** argv) {
// iter residual coarse fine
log_fmt = boost::format("%4.d %12.3f %12.3f %12.3f");
MPI_Init(&argn, &argv);
init_log(argn, argv);
int size = -1;
int rank = -1;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Type_create_struct(3, block_length, block_displace, block_types, &process_state_type);
MPI_Type_commit(&process_state_type);
MPI_Type_size(process_state_type, &process_state_type_size);
int curr_step_start = 0;
double initial_value = 1.0;
do {
double mpi_start = MPI_Wtime();
int mpi_err = MPI_SUCCESS;
ProcessData myself;
myself.rank = rank;
int working_size = (curr_step_start + size - 1 < TOTAL_STEPS) ? size : TOTAL_STEPS % size;
LOG(INFO) << working_size << " processes will work now";
myself.size = working_size;
if (rank < working_size) {
LOG(INFO) << "doing step " << (curr_step_start + rank);
myself.init(mpi_start);
myself.create_windows();
myself.fine_val_in = initial_value;
myself.coarse_val_in = initial_value / FINE_MULTIPLIER;
LOG(INFO) << "inital values:\tcoarse=" << std::fixed << std::setprecision(3) << myself.coarse_val_in << "\tfine=" << myself.fine_val_in;
for(int iter = 0; myself.state.state > PState::FAILED; ++iter) {
update_state(myself, PState::ITERATING, iter);
doing_pre_coarse(myself);
doing_coarse(myself, iter);
doing_post_coarse(myself);
doing_pre_fine(myself);
doing_fine(myself, iter);
doing_post_fine(myself);
update_state(myself, PState::ITERATING);
check_finished(myself, iter);
log_fmt % iter % myself.state.residual % myself.coarse_val_out % myself.fine_val_out;
LOG(INFO) << log_fmt;
}
myself.free_windows();
} else {
// this rank hasn't to do anything anymore
LOG(WARNING) << "hasn't work anymore";
}
VLOG(4) << "broadcasting final value to all";
MPI_Bcast(&(myself.fine_val_out), 1, MPI_DOUBLE, working_size - 1, MPI_COMM_WORLD);
initial_value = myself.fine_val_out;
curr_step_start += size;
} while (curr_step_start < TOTAL_STEPS);
MPI_Type_free(&process_state_type);
VLOG(6) << "finalizing";
MPI_Finalize();
}
<commit_msg>intel compiler sucks<commit_after>#include <cassert>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
using namespace std;
typedef chrono::system_clock Clock;
typedef chrono::nanoseconds ClockResolution;
#include <boost/format.hpp>
boost::format log_fmt;
#include <mpi.h>
#define WITH_MPI
#include "../logging.hpp"
#define MAX_ITER 5
#define BASE_DELAY 1000 // nanoseconds
#define FINE_MULTIPLIER 100000
#define COARSE_MULTIPLIER 1
#define STATE_MULTIPLIER 100
#define TOTAL_STEPS 4
#define RESIDUAL_TOL 2 // seconds
enum class PState : int {
// overall state
CONVERGED = 0,
FAILED = 1,
// iterating states
ITERATING = 10,
PRE_ITER_COARSE = 20,
ITER_COARSE = 21,
POST_ITER_COARSE = 22,
PRE_ITER_FINE = 30,
ITER_FINE = 31,
POST_ITER_FINE = 32,
// last
UNKNOWN = 99,
};
struct ProcessState
{
PState state= PState::UNKNOWN;
int iter = -1;
double residual = numeric_limits<double>::max();
};
int block_length[3] = {1, 1, 1};
MPI_Aint block_displace[3] = {
0,
sizeof(int),
sizeof(int) + sizeof(int)
};
MPI_Datatype block_types[3] = {
MPI_INT, MPI_INT, MPI_DOUBLE
};
MPI_Datatype process_state_type;
int process_state_type_size;
struct ProcessData
{
int size = -1;
int rank = -1;
bool iam_first;
bool iam_last;
int prev = -1;
int next = -1;
double coarse_val_in, coarse_val, coarse_val_out;
double fine_val_in, fine_val, fine_val_out;
double mpi_start;
ProcessState state;
MPI_Win coarse_win;
MPI_Win fine_win;
MPI_Win state_win;
void init(const double start_time) {
assert(rank >= 0 && size > 0);
this->mpi_start = start_time;
this->iam_first = (rank == 0);
this->iam_last = (rank == size - 1);
if (!this->iam_first) { this->prev = this->rank - 1; }
if (!this->iam_last) { this->next = this->rank + 1; }
}
void create_windows()
{
if (this->size > 1) {
VLOG(6) << "creating windows";
MPI_Win_create(&fine_val_out, sizeof(double), MPI_DOUBLE, MPI_INFO_NULL, MPI_COMM_WORLD, &fine_win);
MPI_Win_create(&coarse_val_out, sizeof(double), MPI_DOUBLE, MPI_INFO_NULL, MPI_COMM_WORLD, &coarse_win);
MPI_Win_create(&state, 1, process_state_type_size, MPI_INFO_NULL, MPI_COMM_WORLD, &state_win);
} else {
VLOG(6) << "no need for communication";
}
}
void free_windows()
{
if (this->size > 1) {
VLOG(6) << "freeing windows";
MPI_Win_free(&fine_win);
MPI_Win_free(&coarse_win);
MPI_Win_free(&state_win);
} else {
VLOG(6) << "no need for communication";
}
}
};
static int fine_tag(const int iter) { return (iter + 1) * FINE_MULTIPLIER; }
static int coarse_tag(const int iter) { return (iter + 1) * COARSE_MULTIPLIER; }
static int state_tag(const int iter) { return (iter + 1) * STATE_MULTIPLIER; }
void update_state(ProcessData &data, const PState &new_state, const int iter=-1) {
int mpi_err = MPI_SUCCESS;
if (data.size > 1) {
VLOG(5) << "locking local state window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.state_win); assert(mpi_err == MPI_SUCCESS);
}
data.state.state = new_state;
if (iter != -1) {
data.state.iter = iter;
}
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.state_win); assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local state window";
}
}
void doing_pre_fine(ProcessData &data) {
update_state(data, PState::PRE_ITER_FINE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1 && !data.iam_first) {
VLOG(5) << "locking fine window to rank " << data.prev;
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.prev, 0, data.fine_win); assert(mpi_err == MPI_SUCCESS);
VLOG(4) << "getting fine value from " << data.prev;
mpi_err = MPI_Get(&(data.fine_val_in), 1, MPI_DOUBLE, data.prev, 0, 1, MPI_DOUBLE, data.fine_win); assert(mpi_err == MPI_SUCCESS);
mpi_err = MPI_Win_unlock(data.prev, data.fine_win); assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked fine window to rank " << data.prev;
}
}
void doing_fine(ProcessData &data, const int iter) {
update_state(data, PState::ITER_FINE);
VLOG(2) << "start computation";
data.fine_val = data.fine_val_in + (data.state.iter + 1) * FINE_MULTIPLIER + iter * 0.001;
VLOG(3) << data.fine_val << " = " << data.fine_val_in << " + " << ((data.rank + 1) * FINE_MULTIPLIER) << " + " << (iter * 0.001);
chrono::time_point<Clock> start, end;
ClockResolution duration;
start = Clock::now();
do {
end = Clock::now();
duration = end - start;
} while(duration.count() < BASE_DELAY * FINE_MULTIPLIER);
VLOG(2) << "done computation";
}
void doing_post_fine(ProcessData &data) {
update_state(data, PState::POST_ITER_FINE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1) {
VLOG(5) << "locking local fine window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.fine_win); assert(mpi_err == MPI_SUCCESS);
}
data.fine_val_out = data.fine_val;
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.fine_win); assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local fine window";
}
}
void doing_pre_coarse(ProcessData &data) {
update_state(data, PState::PRE_ITER_COARSE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1 && !data.iam_first) {
VLOG(5) << "locking coarse window to rank " << data.prev;
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.prev, 0, data.coarse_win); assert(mpi_err == MPI_SUCCESS);
VLOG(4) << "getting coarse value from " << data.prev;
mpi_err = MPI_Get(&(data.coarse_val_in), 1, MPI_DOUBLE, data.prev, 0, 1, MPI_DOUBLE, data.coarse_win); assert(mpi_err == MPI_SUCCESS);
mpi_err = MPI_Win_unlock(data.prev, data.coarse_win); assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked coarse window to rank " << data.prev;
}
}
void doing_coarse(ProcessData &data, const int iter) {
update_state(data, PState::ITER_COARSE);
VLOG(2) << "start computation";
data.coarse_val = data.coarse_val_in + (data.state.iter + 1) * COARSE_MULTIPLIER + iter * 0.001;
VLOG(3) << data.coarse_val << " = " << data.coarse_val_in << " + " << ((data.rank + 1) * COARSE_MULTIPLIER) << " + " << (iter * 0.001);
chrono::time_point<Clock> start, end;
ClockResolution duration;
start = Clock::now();
do {
end = Clock::now();
duration = end - start;
} while(duration.count() < BASE_DELAY * COARSE_MULTIPLIER);
VLOG(2) << "done computation";
}
void doing_post_coarse(ProcessData &data) {
update_state(data, PState::POST_ITER_COARSE);
int mpi_err = MPI_SUCCESS;
if (data.size > 1) {
VLOG(5) << "locking local coarse window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.coarse_win); assert(mpi_err == MPI_SUCCESS);
}
data.coarse_val_out = data.coarse_val;
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.coarse_win); assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local coarse window";
}
}
void check_finished(ProcessData &data, const int iter) {
int mpi_err = MPI_SUCCESS;
ProcessState other_state;
if (data.size > 1 && !data.iam_first) {
VLOG(5) << "locking state window to rank " << data.prev;
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.prev, 0, data.state_win); assert(mpi_err == MPI_SUCCESS);
VLOG(4) << "getting state from " << data.prev;
mpi_err = MPI_Get(&other_state, 1, process_state_type, data.prev, 0, 1, process_state_type, data.state_win); assert(mpi_err == MPI_SUCCESS);
mpi_err = MPI_Win_unlock(data.prev, data.state_win); assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked state window to rank " << data.prev;
} else {
other_state.state = PState::CONVERGED;
}
if (data.size > 1) {
VLOG(5) << "locking local state window";
mpi_err = MPI_Win_lock(MPI_LOCK_EXCLUSIVE, data.rank, 0, data.state_win); assert(mpi_err == MPI_SUCCESS);
}
double curr_time = MPI_Wtime();
data.state.residual = curr_time - data.mpi_start;
if (other_state.state == PState::FAILED) {
data.state.state = PState::FAILED;
} else if (other_state.state == PState::CONVERGED && data.state.residual > RESIDUAL_TOL) {
data.state.state = PState::CONVERGED;
}
if (data.size > 1) {
mpi_err = MPI_Win_unlock(data.rank, data.state_win); assert(mpi_err == MPI_SUCCESS);
VLOG(5) << "unlocked local state window";
}
}
int main(int argn, char** argv) {
// iter residual coarse fine
log_fmt = boost::format("%4.d %12.3f %12.3f %12.3f");
MPI_Init(&argn, &argv);
init_log(argn, argv);
int size = -1;
int rank = -1;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
assert(size <= TOTAL_STEPS);
MPI_Type_create_struct(3, block_length, block_displace, block_types, &process_state_type);
MPI_Type_commit(&process_state_type);
MPI_Type_size(process_state_type, &process_state_type_size);
int curr_step_start = 0;
double initial_value = 1.0;
do {
double mpi_start = MPI_Wtime();
int mpi_err = MPI_SUCCESS;
ProcessData myself;
myself.rank = rank;
int working_size = (curr_step_start + size - 1 < TOTAL_STEPS) ? size : TOTAL_STEPS % size;
LOG(INFO) << working_size << " processes will work now";
myself.size = working_size;
if (rank < working_size) {
LOG(INFO) << "doing step " << (curr_step_start + rank);
myself.init(mpi_start);
myself.create_windows();
myself.fine_val_in = initial_value;
myself.coarse_val_in = initial_value / FINE_MULTIPLIER;
LOG(INFO) << "inital values:\tcoarse=" << std::fixed << std::setprecision(3) << myself.coarse_val_in << "\tfine=" << myself.fine_val_in;
for(int iter = 0; myself.state.state > PState::FAILED; ++iter) {
update_state(myself, PState::ITERATING, iter);
doing_pre_coarse(myself);
doing_coarse(myself, iter);
doing_post_coarse(myself);
doing_pre_fine(myself);
doing_fine(myself, iter);
doing_post_fine(myself);
update_state(myself, PState::ITERATING);
check_finished(myself, iter);
log_fmt % iter % myself.state.residual % myself.coarse_val_out % myself.fine_val_out;
LOG(INFO) << log_fmt;
}
myself.free_windows();
} else {
// this rank hasn't to do anything anymore
LOG(WARNING) << "hasn't work anymore";
}
VLOG(4) << "broadcasting final value to all";
mpi_err = MPI_Bcast(&(myself.fine_val_out), 1, MPI_DOUBLE, working_size - 1, MPI_COMM_WORLD); assert(mpi_err == MPI_SUCCESS);
initial_value = myself.fine_val_out;
curr_step_start += size;
} while (curr_step_start < TOTAL_STEPS);
MPI_Type_free(&process_state_type);
VLOG(6) << "finalizing";
MPI_Finalize();
}
<|endoftext|> |
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Gus Grubba <mavlink@grubba.com>
#include "ScreenTools.h"
#include "MainWindow.h"
#include <QFont>
#include <QFontMetrics>
const double ScreenTools::_defaultFontPointSize = 13;
const double ScreenTools::_mediumFontPointSize = 16;
const double ScreenTools::_largeFontPointSize = 20;
ScreenTools::ScreenTools()
{
connect(MainWindow::instance(), &MainWindow::repaintCanvas, this, &ScreenTools::_updateCanvas);
connect(MainWindow::instance(), &MainWindow::pixelSizeChanged, this, &ScreenTools::_updatePixelSize);
connect(MainWindow::instance(), &MainWindow::fontSizeChanged, this, &ScreenTools::_updateFontSize);
}
qreal ScreenTools::adjustFontPointSize(qreal pointSize)
{
return adjustFontPointSize_s(pointSize);
}
qreal ScreenTools::adjustFontPointSize_s(qreal pointSize)
{
return pointSize * MainWindow::fontPointFactor();
}
qreal ScreenTools::adjustPixelSize(qreal pixelSize)
{
return adjustPixelSize_s(pixelSize);
}
qreal ScreenTools::adjustPixelSize_s(qreal pixelSize)
{
return pixelSize * MainWindow::pixelSizeFactor();
}
void ScreenTools::increasePixelSize()
{
MainWindow::instance()->setPixelSizeFactor(MainWindow::pixelSizeFactor() + 0.025);
}
void ScreenTools::decreasePixelSize()
{
MainWindow::instance()->setPixelSizeFactor(MainWindow::pixelSizeFactor() - 0.025);
}
void ScreenTools::increaseFontSize()
{
MainWindow::instance()->setFontSizeFactor(MainWindow::fontPointFactor() + 0.025);
}
void ScreenTools::decreaseFontSize()
{
MainWindow::instance()->setFontSizeFactor(MainWindow::fontPointFactor() - 0.025);
}
void ScreenTools::_updateCanvas()
{
emit repaintRequestedChanged();
}
void ScreenTools::_updatePixelSize()
{
emit pixelSizeFactorChanged();
}
void ScreenTools::_updateFontSize()
{
emit fontPointFactorChanged();
emit fontSizesChanged();
}
double ScreenTools::fontPointFactor()
{
return MainWindow::fontPointFactor();
}
double ScreenTools::pixelSizeFactor()
{
return MainWindow::pixelSizeFactor();
}
double ScreenTools::defaultFontPointSize(void)
{
return _defaultFontPointSize * MainWindow::fontPointFactor();
}
double ScreenTools::mediumFontPointSize(void)
{
return _mediumFontPointSize * MainWindow::fontPointFactor();
}
double ScreenTools::largeFontPointSize(void)
{
return _largeFontPointSize * MainWindow::fontPointFactor();
}
<commit_msg>No MainWindow possible when unit testing<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009, 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL 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.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/// @file
/// @author Gus Grubba <mavlink@grubba.com>
#include "ScreenTools.h"
#include "MainWindow.h"
#include <QFont>
#include <QFontMetrics>
const double ScreenTools::_defaultFontPointSize = 13;
const double ScreenTools::_mediumFontPointSize = 16;
const double ScreenTools::_largeFontPointSize = 20;
ScreenTools::ScreenTools()
{
MainWindow* mainWindow = MainWindow::instance();
// Unit tests can run Qml without MainWindow
if (mainWindow) {
connect(mainWindow, &MainWindow::repaintCanvas, this, &ScreenTools::_updateCanvas);
connect(mainWindow, &MainWindow::pixelSizeChanged, this, &ScreenTools::_updatePixelSize);
connect(mainWindow, &MainWindow::fontSizeChanged, this, &ScreenTools::_updateFontSize);
}
}
qreal ScreenTools::adjustFontPointSize(qreal pointSize)
{
return adjustFontPointSize_s(pointSize);
}
qreal ScreenTools::adjustFontPointSize_s(qreal pointSize)
{
return pointSize * MainWindow::fontPointFactor();
}
qreal ScreenTools::adjustPixelSize(qreal pixelSize)
{
return adjustPixelSize_s(pixelSize);
}
qreal ScreenTools::adjustPixelSize_s(qreal pixelSize)
{
return pixelSize * MainWindow::pixelSizeFactor();
}
void ScreenTools::increasePixelSize()
{
MainWindow::instance()->setPixelSizeFactor(MainWindow::pixelSizeFactor() + 0.025);
}
void ScreenTools::decreasePixelSize()
{
MainWindow::instance()->setPixelSizeFactor(MainWindow::pixelSizeFactor() - 0.025);
}
void ScreenTools::increaseFontSize()
{
MainWindow::instance()->setFontSizeFactor(MainWindow::fontPointFactor() + 0.025);
}
void ScreenTools::decreaseFontSize()
{
MainWindow::instance()->setFontSizeFactor(MainWindow::fontPointFactor() - 0.025);
}
void ScreenTools::_updateCanvas()
{
emit repaintRequestedChanged();
}
void ScreenTools::_updatePixelSize()
{
emit pixelSizeFactorChanged();
}
void ScreenTools::_updateFontSize()
{
emit fontPointFactorChanged();
emit fontSizesChanged();
}
double ScreenTools::fontPointFactor()
{
return MainWindow::fontPointFactor();
}
double ScreenTools::pixelSizeFactor()
{
return MainWindow::pixelSizeFactor();
}
double ScreenTools::defaultFontPointSize(void)
{
return _defaultFontPointSize * MainWindow::fontPointFactor();
}
double ScreenTools::mediumFontPointSize(void)
{
return _mediumFontPointSize * MainWindow::fontPointFactor();
}
double ScreenTools::largeFontPointSize(void)
{
return _largeFontPointSize * MainWindow::fontPointFactor();
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* 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.
*
* \file allocator.hxx
*
* Class for maintaining a bounded list of structures that can be allocated.
*
* @author Balazs Racz
* @date 19 October 2013
*/
#ifndef _EXECUTOR_ALLOCATOR_HXX_
#define _EXECUTOR_ALLOCATOR_HXX_
#include "executor/executor.hxx"
#include "executor/notifiable.hxx"
class AllocationResult : public Executable {
public:
// Callback from the allocator when an item was successfully allocated.
virtual void AllocationCallback(QueueMember* entry) = 0;
};
class AllocatorBase : public Lockable {
public:
AllocatorBase();
//! Returns an entry to the pool of free entries. no type checking is
//! performed by this function.
//
//! @param entry is the entry to release. It should be compatible with the
//! entries expected from this Allocator.
void Release(QueueMember* entry);
//! Returns an entry to the end (back) of the pool of free entries. no type
//! checking is performed by this function.
//
//! @param entry is the entry to release. It should be compatible with the
//! entries expected from this Allocator.
void ReleaseBack(QueueMember* entry);
//! Allocates an object, possibly by putting the caller into a waiting list
//! for allocated objects.
//
//! @param caller is a callback. When the next object to allocate is
//! available, the allocation callback will be called.
//
//! The callback may be called inline, but it may also be called from a
//! different thread. No locking is performed while calling the callback.
void AllocateEntry(AllocationResult* caller);
//! @returns true if there is an entry waiting to be allocated.
//
//! NOTE: using this method is likely result in race conditions.
bool Peek();
//! Synchronously tries to allocate an entry.
//
//! @returns the first allocatable entry, if there is any free. Otherwise
//! returns NULL.
QueueMember* AllocateOrNull();
private:
// List of users waiting for entries OR list of entries available to be
// allocated.
Queue waiting_list_;
// This is true if there are free entries on the waiting_list or the list is
// empty.
bool has_free_entries_;
};
//! An allocator class that can be used for type-safe operations.
template <class T>
class TypedAllocator : public AllocatorBase {
public:
//! Returns an entry to the allocator.
//
//! @param entry is the object to return.
void TypedRelease(T* entry) { Release(entry); }
//! Returns an entry to the allocator at the back of the freelist..
//
//! @param entry is the object to return.
void TypedReleaseBack(T* entry) { ReleaseBack(entry); }
T* TypedAllocateOrNull() { return cast_result(AllocateOrNull()); }
static T* cast_result(QueueMember* entry) { return static_cast<T*>(entry); }
};
//! Helper class that encapsulates a call to an allocator, which blocks the
//! current thread until a free entry shows up.
//
//! Usage:
//
//! SyncAllocation a(allocator); // may block the thread
//! DoSomething(a.untyped_result())
class SyncAllocation : private AllocationResult {
public:
//! Synchronously allocates an entry from an allocator. Blocks the current
//! thread until an entry is available.
//
//! @param allocator is the allocator to allocate an entry from.
SyncAllocation(AllocatorBase* allocator) : result_(nullptr) {
allocator->AllocateEntry(this);
notify_.WaitForNotification();
}
//! @returns the entry allocated.
QueueMember* untyped_result() { return result_; }
private:
//! Callback from the allocator.
//
//! @param entry is the entry allocated to this request.
virtual void AllocationCallback(QueueMember* entry) {
result_ = entry;
notify_.Notify();
}
//! A callback that should never be called, since *this is never used as an
//! Executable.
virtual void Run() {
extern int unexpected_call_to_syncallocation_run();
HASSERT(false && unexpected_call_to_syncallocation_run());
}
protected:
//! Stores the result of the allocation callback.
QueueMember* result_;
//! Helper for blocking the current thread until the allocation is
//! successful.
SyncNotifiable notify_;
};
//! Helper class for type-safe synchronous allocation from an Allocator.
template <class T>
class TypedSyncAllocation : public SyncAllocation {
public:
//! Allocates an entry from a (typed) allocator.
//
//! @param allocator is the allocator to allocate from.
TypedSyncAllocation(TypedAllocator<T>* allocator)
: SyncAllocation(allocator) {}
//! @returns the result of the allocation.
T* result() { return static_cast<T*>(untyped_result()); }
};
//! Helper class that simulates a (non-reentrant) mutex using the Allocator
//! queue and a single QueueMember token.
//
//! The mutex is defined as unlocked if there is an entry on the allocator
//! queue. Locking the mutex will take the entry off of the allocator
//! queue. Any other acquisition attempts will block so long as the allocator's
//! queue is empty.
//
//! Unlocking the mutex will release the token back to the allocator, waking up
//! the first caller in the queue.
//
//! To lock the mutex, use any allocation mechanism (e.g. control
//! flow::Allocate, or SyncAllocator). To Unlock the mutex, call the Unlock
//! method.
class AllocatorMutex : public AllocatorBase {
public:
//! Creates an allocator mutex.
AllocatorMutex() { Unlock(); }
//! Crashes if the the particular value is not the token associated with this
//! mutex.
//
//! @param token is the value to check.
void CheckToken(QueueMember* token) { HASSERT(token == &token_); }
//! Crashes if the mutex is not locked.
void AssertLocked() { HASSERT(!Peek()); }
//! Crashes if the mutex is locked.
void AssertUnlocked() { HASSERT(Peek()); }
//! Unlocks the mutex. Crashes if the mutex is unlocked.
void Unlock() { Release(&token_); }
//! Synchronously locks the mutex. Might block the current thread.
void Lock() { SyncAllocation a(this); }
private:
QueueMember token_;
};
#endif // _EXECUTOR_ALLOCATOR_HXX_
<commit_msg>Adds "InitializedAllocator" to create and own a configurable number of entries for the allocator.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* 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.
*
* \file allocator.hxx
*
* Class for maintaining a bounded list of structures that can be allocated.
*
* @author Balazs Racz
* @date 19 October 2013
*/
#ifndef _EXECUTOR_ALLOCATOR_HXX_
#define _EXECUTOR_ALLOCATOR_HXX_
#include <memory>
#include "executor/executor.hxx"
#include "executor/notifiable.hxx"
class AllocationResult : public Executable {
public:
// Callback from the allocator when an item was successfully allocated.
virtual void AllocationCallback(QueueMember* entry) = 0;
};
class AllocatorBase : public Lockable {
public:
AllocatorBase();
//! Returns an entry to the pool of free entries. no type checking is
//! performed by this function.
//
//! @param entry is the entry to release. It should be compatible with the
//! entries expected from this Allocator.
void Release(QueueMember* entry);
//! Returns an entry to the end (back) of the pool of free entries. no type
//! checking is performed by this function.
//
//! @param entry is the entry to release. It should be compatible with the
//! entries expected from this Allocator.
void ReleaseBack(QueueMember* entry);
//! Allocates an object, possibly by putting the caller into a waiting list
//! for allocated objects.
//
//! @param caller is a callback. When the next object to allocate is
//! available, the allocation callback will be called.
//
//! The callback may be called inline, but it may also be called from a
//! different thread. No locking is performed while calling the callback.
void AllocateEntry(AllocationResult* caller);
//! @returns true if there is an entry waiting to be allocated.
//
//! NOTE: using this method is likely result in race conditions.
bool Peek();
//! Synchronously tries to allocate an entry.
//
//! @returns the first allocatable entry, if there is any free. Otherwise
//! returns NULL.
QueueMember* AllocateOrNull();
private:
// List of users waiting for entries OR list of entries available to be
// allocated.
Queue waiting_list_;
// This is true if there are free entries on the waiting_list or the list is
// empty.
bool has_free_entries_;
};
//! An allocator class that can be used for type-safe operations.
template <class T>
class TypedAllocator : public AllocatorBase {
public:
//! Returns an entry to the allocator.
//
//! @param entry is the object to return.
void TypedRelease(T* entry) { Release(entry); }
//! Returns an entry to the allocator at the back of the freelist..
//
//! @param entry is the object to return.
void TypedReleaseBack(T* entry) { ReleaseBack(entry); }
T* TypedAllocateOrNull() { return cast_result(AllocateOrNull()); }
static T* cast_result(QueueMember* entry) { return static_cast<T*>(entry); }
};
template<class T>
class InitializedAllocator : public TypedAllocator<T> {
public:
//! Creates the allocator and fills it with @param count entries.
InitializedAllocator(size_t count)
: members_(new T[count]) {
for (size_t i = 0; i < count; ++i) {
TypedRelease(&members_[i]);
}
}
private:
std::unique_ptr<T[]> members_;
};
//! Helper class that encapsulates a call to an allocator, which blocks the
//! current thread until a free entry shows up.
//
//! Usage:
//
//! SyncAllocation a(allocator); // may block the thread
//! DoSomething(a.untyped_result())
class SyncAllocation : private AllocationResult {
public:
//! Synchronously allocates an entry from an allocator. Blocks the current
//! thread until an entry is available.
//
//! @param allocator is the allocator to allocate an entry from.
SyncAllocation(AllocatorBase* allocator) : result_(nullptr) {
allocator->AllocateEntry(this);
notify_.WaitForNotification();
}
//! @returns the entry allocated.
QueueMember* untyped_result() { return result_; }
private:
//! Callback from the allocator.
//
//! @param entry is the entry allocated to this request.
virtual void AllocationCallback(QueueMember* entry) {
result_ = entry;
notify_.Notify();
}
//! A callback that should never be called, since *this is never used as an
//! Executable.
virtual void Run() {
extern int unexpected_call_to_syncallocation_run();
HASSERT(false && unexpected_call_to_syncallocation_run());
}
protected:
//! Stores the result of the allocation callback.
QueueMember* result_;
//! Helper for blocking the current thread until the allocation is
//! successful.
SyncNotifiable notify_;
};
//! Helper class for type-safe synchronous allocation from an Allocator.
template <class T>
class TypedSyncAllocation : public SyncAllocation {
public:
//! Allocates an entry from a (typed) allocator.
//
//! @param allocator is the allocator to allocate from.
TypedSyncAllocation(TypedAllocator<T>* allocator)
: SyncAllocation(allocator) {}
//! @returns the result of the allocation.
T* result() { return static_cast<T*>(untyped_result()); }
};
//! Helper class that simulates a (non-reentrant) mutex using the Allocator
//! queue and a single QueueMember token.
//
//! The mutex is defined as unlocked if there is an entry on the allocator
//! queue. Locking the mutex will take the entry off of the allocator
//! queue. Any other acquisition attempts will block so long as the allocator's
//! queue is empty.
//
//! Unlocking the mutex will release the token back to the allocator, waking up
//! the first caller in the queue.
//
//! To lock the mutex, use any allocation mechanism (e.g. control
//! flow::Allocate, or SyncAllocator). To Unlock the mutex, call the Unlock
//! method.
class AllocatorMutex : public AllocatorBase {
public:
//! Creates an allocator mutex.
AllocatorMutex() { Unlock(); }
//! Crashes if the the particular value is not the token associated with this
//! mutex.
//
//! @param token is the value to check.
void CheckToken(QueueMember* token) { HASSERT(token == &token_); }
//! Crashes if the mutex is not locked.
void AssertLocked() { HASSERT(!Peek()); }
//! Crashes if the mutex is locked.
void AssertUnlocked() { HASSERT(Peek()); }
//! Unlocks the mutex. Crashes if the mutex is unlocked.
void Unlock() { Release(&token_); }
//! Synchronously locks the mutex. Might block the current thread.
void Lock() { SyncAllocation a(this); }
private:
QueueMember token_;
};
#endif // _EXECUTOR_ALLOCATOR_HXX_
<|endoftext|> |
<commit_before>//===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
//
// This library implements the functionality defined in llvm/Assembly/Writer.h
//
// This library uses the Analysis library to figure out offsets for
// variables in the method tables...
//
// TODO: print out the type name instead of the full type if a particular type
// is in the symbol table...
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/SlotCalculator.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/iOther.h"
#include "llvm/iMemory.h"
void DebugValue(const Value *V) {
cerr << V << endl;
}
// WriteAsOperand - Write the name of the specified value out to the specified
// ostream. This can be useful when you just want to print int %reg126, not the
// whole instruction that generated it.
//
ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
bool PrintName, SlotCalculator *Table) {
if (PrintType)
Out << " " << V->getType();
if (V->hasName() && PrintName) {
Out << " %" << V->getName();
} else {
if (const ConstPoolVal *CPV = V->castConstant()) {
Out << " " << CPV->getStrValue();
} else {
int Slot;
if (Table) {
Slot = Table->getValSlot(V);
} else {
if (const Type *Ty = V->castType()) {
return Out << " " << Ty;
} else if (const MethodArgument *MA = V->castMethodArgument()) {
Table = new SlotCalculator(MA->getParent(), true);
} else if (const Instruction *I = V->castInstruction()) {
Table = new SlotCalculator(I->getParent()->getParent(), true);
} else if (const BasicBlock *BB = V->castBasicBlock()) {
Table = new SlotCalculator(BB->getParent(), true);
} else if (const Method *Meth = V->castMethod()) {
Table = new SlotCalculator(Meth, true);
} else if (const Module *Mod = V->castModule()) {
Table = new SlotCalculator(Mod, true);
} else {
return Out << "BAD VALUE TYPE!";
}
Slot = Table->getValSlot(V);
delete Table;
}
if (Slot >= 0) Out << " %" << Slot;
else if (PrintName)
Out << "<badref>"; // Not embeded into a location?
}
}
return Out;
}
class AssemblyWriter : public ModuleAnalyzer {
ostream &Out;
SlotCalculator &Table;
public:
inline AssemblyWriter(ostream &o, SlotCalculator &Tab) : Out(o), Table(Tab) {
}
inline void write(const Module *M) { processModule(M); }
inline void write(const Method *M) { processMethod(M); }
inline void write(const BasicBlock *BB) { processBasicBlock(BB); }
inline void write(const Instruction *I) { processInstruction(I); }
inline void write(const ConstPoolVal *CPV) { processConstant(CPV); }
protected:
virtual bool visitMethod(const Method *M);
virtual bool processConstPool(const ConstantPool &CP, bool isMethod);
virtual bool processConstant(const ConstPoolVal *CPV);
virtual bool processMethod(const Method *M);
virtual bool processMethodArgument(const MethodArgument *MA);
virtual bool processBasicBlock(const BasicBlock *BB);
virtual bool processInstruction(const Instruction *I);
private :
void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
};
// visitMethod - This member is called after the above two steps, visting each
// method, because they are effectively values that go into the constant pool.
//
bool AssemblyWriter::visitMethod(const Method *M) {
return false;
}
bool AssemblyWriter::processConstPool(const ConstantPool &CP, bool isMethod) {
// Done printing arguments...
if (isMethod) {
if (CP.getParentV()->castMethodAsserting()->getType()->
isMethodType()->isVarArg())
Out << ", ..."; // Output varargs portion of signature!
Out << ")\n";
}
ModuleAnalyzer::processConstPool(CP, isMethod);
if (isMethod) {
if (!CP.getParentV()->castMethodAsserting()->isExternal())
Out << "begin";
} else {
Out << "implementation\n";
}
return false;
}
// processConstant - Print out a constant pool entry...
//
bool AssemblyWriter::processConstant(const ConstPoolVal *CPV) {
Out << "\t";
// Print out name if it exists...
if (CPV->hasName())
Out << "%" << CPV->getName() << " = ";
// Print out the opcode...
Out << CPV->getType();
// Write the value out now...
writeOperand(CPV, false, false);
if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
Out << "\t\t; <" << CPV->getType() << ">:";
if (Slot >= 0) Out << Slot;
else Out << "<badref>";
}
Out << endl;
return false;
}
// processMethod - Process all aspects of a method.
//
bool AssemblyWriter::processMethod(const Method *M) {
// Print out the return type and name...
Out << "\n" << (M->isExternal() ? "declare " : "")
<< M->getReturnType() << " \"" << M->getName() << "\"(";
Table.incorporateMethod(M);
ModuleAnalyzer::processMethod(M);
Table.purgeMethod();
if (!M->isExternal())
Out << "end\n";
return false;
}
// processMethodArgument - This member is called for every argument that
// is passed into the method. Simply print it out
//
bool AssemblyWriter::processMethodArgument(const MethodArgument *Arg) {
// Insert commas as we go... the first arg doesn't get a comma
if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
// Output type...
Out << Arg->getType();
// Output name, if available...
if (Arg->hasName())
Out << " %" << Arg->getName();
else if (Table.getValSlot(Arg) < 0)
Out << "<badref>";
return false;
}
// processBasicBlock - This member is called for each basic block in a methd.
//
bool AssemblyWriter::processBasicBlock(const BasicBlock *BB) {
if (BB->hasName()) { // Print out the label if it exists...
Out << "\n" << BB->getName() << ":";
} else {
int Slot = Table.getValSlot(BB);
Out << "\n; <label>:";
if (Slot >= 0)
Out << Slot; // Extra newline seperates out label's
else
Out << "<badref>";
}
Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
ModuleAnalyzer::processBasicBlock(BB);
return false;
}
// processInstruction - This member is called for each Instruction in a methd.
//
bool AssemblyWriter::processInstruction(const Instruction *I) {
Out << "\t";
// Print out name if it exists...
if (I && I->hasName())
Out << "%" << I->getName() << " = ";
// Print out the opcode...
Out << I->getOpcodeName();
// Print out the type of the operands...
const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
// Special case conditional branches to swizzle the condition out to the front
if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
writeOperand(I->getOperand(2), true);
Out << ",";
writeOperand(Operand, true);
Out << ",";
writeOperand(I->getOperand(1), true);
} else if (I->getOpcode() == Instruction::Switch) {
// Special case switch statement to get formatting nice and correct...
writeOperand(Operand , true); Out << ",";
writeOperand(I->getOperand(1), true); Out << " [";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << "\n\t\t";
writeOperand(I->getOperand(op ), true); Out << ",";
writeOperand(I->getOperand(op+1), true);
}
Out << "\n\t]";
} else if (I->isPHINode()) {
Out << " " << Operand->getType();
Out << " ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(1), false); Out << " ]";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << ", [";
writeOperand(I->getOperand(op ), false); Out << ",";
writeOperand(I->getOperand(op+1), false); Out << " ]";
}
} else if (I->getOpcode() == Instruction::Ret && !Operand) {
Out << " void";
} else if (I->getOpcode() == Instruction::Call) {
writeOperand(Operand, true);
Out << "(";
if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
Out << ",";
writeOperand(I->getOperand(op), true);
}
Out << " )";
} else if (I->getOpcode() == Instruction::Malloc ||
I->getOpcode() == Instruction::Alloca) {
Out << " " << ((const PointerType*)I->getType())->getValueType();
if (I->getNumOperands()) {
Out << ",";
writeOperand(I->getOperand(0), true);
}
} else if (I->getOpcode() == Instruction::Cast) {
writeOperand(Operand, true);
Out << " to " << I->getType();
} else if (Operand) { // Print the normal way...
// PrintAllTypes - Instructions who have operands of all the same type
// omit the type from all but the first operand. If the instruction has
// different type operands (for example br), then they are all printed.
bool PrintAllTypes = false;
const Type *TheType = Operand->getType();
for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
Operand = I->getOperand(i);
if (Operand->getType() != TheType) {
PrintAllTypes = true; // We have differing types! Print them all!
break;
}
}
if (!PrintAllTypes)
Out << " " << I->getOperand(0)->getType();
for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
if (i) Out << ",";
writeOperand(I->getOperand(i), PrintAllTypes);
}
}
// Print a little comment after the instruction indicating which slot it
// occupies.
//
if (I->getType() != Type::VoidTy) {
Out << "\t\t; <" << I->getType() << ">";
if (!I->hasName()) {
int Slot = Table.getValSlot(I); // Print out the def slot taken...
if (Slot >= 0) Out << ":" << Slot;
else Out << ":<badref>";
}
Out << "\t[#uses=" << I->use_size() << "]"; // Output # uses
}
Out << endl;
return false;
}
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
bool PrintName) {
WriteAsOperand(Out, Operand, PrintType, PrintName, &Table);
}
//===----------------------------------------------------------------------===//
// External Interface declarations
//===----------------------------------------------------------------------===//
void WriteToAssembly(const Module *M, ostream &o) {
if (M == 0) { o << "<null> module\n"; return; }
SlotCalculator SlotTable(M, true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const Method *M, ostream &o) {
if (M == 0) { o << "<null> method\n"; return; }
SlotCalculator SlotTable(M->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const BasicBlock *BB, ostream &o) {
if (BB == 0) { o << "<null> basic block\n"; return; }
SlotCalculator SlotTable(BB->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(BB);
}
void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
if (CPV == 0) { o << "<null> constant pool value\n"; return; }
SlotCalculator *SlotTable;
// A Constant pool value may have a parent that is either a method or a
// module. Untangle this now...
//
if (const Method *Meth = CPV->getParentV()->castMethod()) {
SlotTable = new SlotCalculator(Meth, true);
} else {
SlotTable =
new SlotCalculator(CPV->getParentV()->castModuleAsserting(), true);
}
AssemblyWriter W(o, *SlotTable);
W.write(CPV);
delete SlotTable;
}
void WriteToAssembly(const Instruction *I, ostream &o) {
if (I == 0) { o << "<null> instruction\n"; return; }
SlotCalculator SlotTable(I->getParent() ? I->getParent()->getParent() : 0,
true);
AssemblyWriter W(o, SlotTable);
W.write(I);
}
<commit_msg>Don't write out constants that do not have a name, they will be inlined.<commit_after>//===-- Writer.cpp - Library for Printing VM assembly files ------*- C++ -*--=//
//
// This library implements the functionality defined in llvm/Assembly/Writer.h
//
// This library uses the Analysis library to figure out offsets for
// variables in the method tables...
//
// TODO: print out the type name instead of the full type if a particular type
// is in the symbol table...
//
//===----------------------------------------------------------------------===//
#include "llvm/Assembly/Writer.h"
#include "llvm/Analysis/SlotCalculator.h"
#include "llvm/Module.h"
#include "llvm/Method.h"
#include "llvm/BasicBlock.h"
#include "llvm/ConstPoolVals.h"
#include "llvm/iOther.h"
#include "llvm/iMemory.h"
void DebugValue(const Value *V) {
cerr << V << endl;
}
// WriteAsOperand - Write the name of the specified value out to the specified
// ostream. This can be useful when you just want to print int %reg126, not the
// whole instruction that generated it.
//
ostream &WriteAsOperand(ostream &Out, const Value *V, bool PrintType,
bool PrintName, SlotCalculator *Table) {
if (PrintType)
Out << " " << V->getType();
if (V->hasName() && PrintName) {
Out << " %" << V->getName();
} else {
if (const ConstPoolVal *CPV = V->castConstant()) {
Out << " " << CPV->getStrValue();
} else {
int Slot;
if (Table) {
Slot = Table->getValSlot(V);
} else {
if (const Type *Ty = V->castType()) {
return Out << " " << Ty;
} else if (const MethodArgument *MA = V->castMethodArgument()) {
Table = new SlotCalculator(MA->getParent(), true);
} else if (const Instruction *I = V->castInstruction()) {
Table = new SlotCalculator(I->getParent()->getParent(), true);
} else if (const BasicBlock *BB = V->castBasicBlock()) {
Table = new SlotCalculator(BB->getParent(), true);
} else if (const Method *Meth = V->castMethod()) {
Table = new SlotCalculator(Meth, true);
} else if (const Module *Mod = V->castModule()) {
Table = new SlotCalculator(Mod, true);
} else {
return Out << "BAD VALUE TYPE!";
}
Slot = Table->getValSlot(V);
delete Table;
}
if (Slot >= 0) Out << " %" << Slot;
else if (PrintName)
Out << "<badref>"; // Not embeded into a location?
}
}
return Out;
}
class AssemblyWriter : public ModuleAnalyzer {
ostream &Out;
SlotCalculator &Table;
public:
inline AssemblyWriter(ostream &o, SlotCalculator &Tab) : Out(o), Table(Tab) {
}
inline void write(const Module *M) { processModule(M); }
inline void write(const Method *M) { processMethod(M); }
inline void write(const BasicBlock *BB) { processBasicBlock(BB); }
inline void write(const Instruction *I) { processInstruction(I); }
inline void write(const ConstPoolVal *CPV) { processConstant(CPV); }
protected:
virtual bool visitMethod(const Method *M);
virtual bool processConstPool(const ConstantPool &CP, bool isMethod);
virtual bool processConstant(const ConstPoolVal *CPV);
virtual bool processMethod(const Method *M);
virtual bool processMethodArgument(const MethodArgument *MA);
virtual bool processBasicBlock(const BasicBlock *BB);
virtual bool processInstruction(const Instruction *I);
private :
void writeOperand(const Value *Op, bool PrintType, bool PrintName = true);
};
// visitMethod - This member is called after the above two steps, visting each
// method, because they are effectively values that go into the constant pool.
//
bool AssemblyWriter::visitMethod(const Method *M) {
return false;
}
bool AssemblyWriter::processConstPool(const ConstantPool &CP, bool isMethod) {
// Done printing arguments...
if (isMethod) {
if (CP.getParentV()->castMethodAsserting()->getType()->
isMethodType()->isVarArg())
Out << ", ..."; // Output varargs portion of signature!
Out << ")\n";
}
ModuleAnalyzer::processConstPool(CP, isMethod);
if (isMethod) {
if (!CP.getParentV()->castMethodAsserting()->isExternal())
Out << "begin";
} else {
Out << "implementation\n";
}
return false;
}
// processConstant - Print out a constant pool entry...
//
bool AssemblyWriter::processConstant(const ConstPoolVal *CPV) {
if (!CPV->hasName())
return false; // Don't print out unnamed constants, they will be inlined
// Print out name...
Out << "\t%" << CPV->getName() << " = ";
// Print out the constant type...
Out << CPV->getType();
// Write the value out now...
writeOperand(CPV, false, false);
if (!CPV->hasName() && CPV->getType() != Type::VoidTy) {
int Slot = Table.getValSlot(CPV); // Print out the def slot taken...
Out << "\t\t; <" << CPV->getType() << ">:";
if (Slot >= 0) Out << Slot;
else Out << "<badref>";
}
Out << endl;
return false;
}
// processMethod - Process all aspects of a method.
//
bool AssemblyWriter::processMethod(const Method *M) {
// Print out the return type and name...
Out << "\n" << (M->isExternal() ? "declare " : "")
<< M->getReturnType() << " \"" << M->getName() << "\"(";
Table.incorporateMethod(M);
ModuleAnalyzer::processMethod(M);
Table.purgeMethod();
if (!M->isExternal())
Out << "end\n";
return false;
}
// processMethodArgument - This member is called for every argument that
// is passed into the method. Simply print it out
//
bool AssemblyWriter::processMethodArgument(const MethodArgument *Arg) {
// Insert commas as we go... the first arg doesn't get a comma
if (Arg != Arg->getParent()->getArgumentList().front()) Out << ", ";
// Output type...
Out << Arg->getType();
// Output name, if available...
if (Arg->hasName())
Out << " %" << Arg->getName();
else if (Table.getValSlot(Arg) < 0)
Out << "<badref>";
return false;
}
// processBasicBlock - This member is called for each basic block in a methd.
//
bool AssemblyWriter::processBasicBlock(const BasicBlock *BB) {
if (BB->hasName()) { // Print out the label if it exists...
Out << "\n" << BB->getName() << ":";
} else {
int Slot = Table.getValSlot(BB);
Out << "\n; <label>:";
if (Slot >= 0)
Out << Slot; // Extra newline seperates out label's
else
Out << "<badref>";
}
Out << "\t\t\t\t\t;[#uses=" << BB->use_size() << "]\n"; // Output # uses
ModuleAnalyzer::processBasicBlock(BB);
return false;
}
// processInstruction - This member is called for each Instruction in a methd.
//
bool AssemblyWriter::processInstruction(const Instruction *I) {
Out << "\t";
// Print out name if it exists...
if (I && I->hasName())
Out << "%" << I->getName() << " = ";
// Print out the opcode...
Out << I->getOpcodeName();
// Print out the type of the operands...
const Value *Operand = I->getNumOperands() ? I->getOperand(0) : 0;
// Special case conditional branches to swizzle the condition out to the front
if (I->getOpcode() == Instruction::Br && I->getNumOperands() > 1) {
writeOperand(I->getOperand(2), true);
Out << ",";
writeOperand(Operand, true);
Out << ",";
writeOperand(I->getOperand(1), true);
} else if (I->getOpcode() == Instruction::Switch) {
// Special case switch statement to get formatting nice and correct...
writeOperand(Operand , true); Out << ",";
writeOperand(I->getOperand(1), true); Out << " [";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << "\n\t\t";
writeOperand(I->getOperand(op ), true); Out << ",";
writeOperand(I->getOperand(op+1), true);
}
Out << "\n\t]";
} else if (I->isPHINode()) {
Out << " " << Operand->getType();
Out << " ["; writeOperand(Operand, false); Out << ",";
writeOperand(I->getOperand(1), false); Out << " ]";
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; op += 2) {
Out << ", [";
writeOperand(I->getOperand(op ), false); Out << ",";
writeOperand(I->getOperand(op+1), false); Out << " ]";
}
} else if (I->getOpcode() == Instruction::Ret && !Operand) {
Out << " void";
} else if (I->getOpcode() == Instruction::Call) {
writeOperand(Operand, true);
Out << "(";
if (I->getNumOperands() > 1) writeOperand(I->getOperand(1), true);
for (unsigned op = 2, Eop = I->getNumOperands(); op < Eop; ++op) {
Out << ",";
writeOperand(I->getOperand(op), true);
}
Out << " )";
} else if (I->getOpcode() == Instruction::Malloc ||
I->getOpcode() == Instruction::Alloca) {
Out << " " << ((const PointerType*)I->getType())->getValueType();
if (I->getNumOperands()) {
Out << ",";
writeOperand(I->getOperand(0), true);
}
} else if (I->getOpcode() == Instruction::Cast) {
writeOperand(Operand, true);
Out << " to " << I->getType();
} else if (Operand) { // Print the normal way...
// PrintAllTypes - Instructions who have operands of all the same type
// omit the type from all but the first operand. If the instruction has
// different type operands (for example br), then they are all printed.
bool PrintAllTypes = false;
const Type *TheType = Operand->getType();
for (unsigned i = 1, E = I->getNumOperands(); i != E; ++i) {
Operand = I->getOperand(i);
if (Operand->getType() != TheType) {
PrintAllTypes = true; // We have differing types! Print them all!
break;
}
}
if (!PrintAllTypes)
Out << " " << I->getOperand(0)->getType();
for (unsigned i = 0, E = I->getNumOperands(); i != E; ++i) {
if (i) Out << ",";
writeOperand(I->getOperand(i), PrintAllTypes);
}
}
// Print a little comment after the instruction indicating which slot it
// occupies.
//
if (I->getType() != Type::VoidTy) {
Out << "\t\t; <" << I->getType() << ">";
if (!I->hasName()) {
int Slot = Table.getValSlot(I); // Print out the def slot taken...
if (Slot >= 0) Out << ":" << Slot;
else Out << ":<badref>";
}
Out << "\t[#uses=" << I->use_size() << "]"; // Output # uses
}
Out << endl;
return false;
}
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType,
bool PrintName) {
WriteAsOperand(Out, Operand, PrintType, PrintName, &Table);
}
//===----------------------------------------------------------------------===//
// External Interface declarations
//===----------------------------------------------------------------------===//
void WriteToAssembly(const Module *M, ostream &o) {
if (M == 0) { o << "<null> module\n"; return; }
SlotCalculator SlotTable(M, true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const Method *M, ostream &o) {
if (M == 0) { o << "<null> method\n"; return; }
SlotCalculator SlotTable(M->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(M);
}
void WriteToAssembly(const BasicBlock *BB, ostream &o) {
if (BB == 0) { o << "<null> basic block\n"; return; }
SlotCalculator SlotTable(BB->getParent(), true);
AssemblyWriter W(o, SlotTable);
W.write(BB);
}
void WriteToAssembly(const ConstPoolVal *CPV, ostream &o) {
if (CPV == 0) { o << "<null> constant pool value\n"; return; }
SlotCalculator *SlotTable;
// A Constant pool value may have a parent that is either a method or a
// module. Untangle this now...
//
if (const Method *Meth = CPV->getParentV()->castMethod()) {
SlotTable = new SlotCalculator(Meth, true);
} else {
SlotTable =
new SlotCalculator(CPV->getParentV()->castModuleAsserting(), true);
}
AssemblyWriter W(o, *SlotTable);
W.write(CPV);
delete SlotTable;
}
void WriteToAssembly(const Instruction *I, ostream &o) {
if (I == 0) { o << "<null> instruction\n"; return; }
SlotCalculator SlotTable(I->getParent() ? I->getParent()->getParent() : 0,
true);
AssemblyWriter W(o, SlotTable);
W.write(I);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.