text
stringlengths 54
60.6k
|
---|
<commit_before>/* uefifind_main.cpp
Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include <QCoreApplication>
#include <iostream>
#include "uefifind.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setOrganizationName("CodeRush");
a.setOrganizationDomain("coderush.me");
a.setApplicationName("UEFIFind");
UEFIFind w;
UINT8 result;
if (a.arguments().length() == 5) {
// Get search mode
UINT8 mode;
if (a.arguments().at(1) == QString("header"))
mode = SEARCH_MODE_HEADER;
else if (a.arguments().at(1) == QString("body"))
mode = SEARCH_MODE_BODY;
else if (a.arguments().at(1) == QString("all"))
mode = SEARCH_MODE_ALL;
else
return ERR_INVALID_PARAMETER;
// Get result type
bool count;
if (a.arguments().at(2) == QString("list"))
count = false;
else if (a.arguments().at(2) == QString("count"))
count = true;
else
return ERR_INVALID_PARAMETER;
// Parse input file
result = w.init(a.arguments().at(4));
if (result)
return result;
// Go find the supplied pattern
QString found;
result = w.find(mode, count, a.arguments().at(3), found);
if (result)
return result;
// Nothing is found
if (found.isEmpty())
return ERR_ITEM_NOT_FOUND;
// Print result
std::cout << found.toStdString();
return ERR_SUCCESS;
}
else if (a.arguments().length() == 4) {
// Get search mode
if (a.arguments().at(1) != QString("file"))
return ERR_INVALID_PARAMETER;
// Open patterns file
QFileInfo fileInfo(a.arguments().at(2));
if (!fileInfo.exists())
return ERR_FILE_OPEN;
QFile patternsFile;
patternsFile.setFileName(a.arguments().at(2));
if (!patternsFile.open(QFile::ReadOnly))
return ERR_FILE_OPEN;
// Parse input file
result = w.init(a.arguments().at(3));
if (result)
return result;
// Perform searches
bool somethingFound = false;
while (!patternsFile.atEnd()) {
QByteArray line = patternsFile.readLine();
// Use sharp symbol as commentary
if (line.count() == 0 || line[0] == '#')
continue;
// Split the read line
QList<QByteArray> list = line.split(' ');
if (list.count() < 3) {
std::cout << line.toStdString() << "skipped, too few arguments" << std::endl;
continue;
}
// Get search mode
UINT8 mode;
if (list.at(0) == QString("header"))
mode = SEARCH_MODE_HEADER;
else if (list.at(0) == QString("body"))
mode = SEARCH_MODE_BODY;
else if (list.at(0) == QString("all"))
mode = SEARCH_MODE_ALL;
else {
std::cout << line.toStdString() << "skipped, invalid search mode" << std::endl;
continue;
}
// Get result type
bool count;
if (list.at(1) == QString("list"))
count = false;
else if (list.at(1) == QString("count"))
count = true;
else {
std::cout << line.toStdString() << "skipped, invalid result type" << std::endl;
continue;
}
// Go find the supplied pattern
QString found;
result = w.find(mode, count, list.at(2), found);
if (result) {
std::cout << line.toStdString() << "skipped, find failed with error " << result << std::endl;
continue;
}
if (found.isEmpty()) {
// Nothing is found
std::cout << line.toStdString() << "nothing found" << std::endl;
}
else {
// Print result
std::cout << line.toStdString() << found.toStdString() << std::endl;
somethingFound = true;
}
}
// Nothing is found
if (!somethingFound)
return ERR_ITEM_NOT_FOUND;
return ERR_SUCCESS;
}
else {
std::cout << "UEFIFind 0.10.0" << std::endl << std::endl <<
"Usage: uefifind {header | body | all} {list | count} pattern imagefile" << std::endl <<
" or uefitool file patternsfile imagefile" << std::endl;
return ERR_INVALID_PARAMETER;
}
}
<commit_msg>UF 0.10.1<commit_after>/* uefifind_main.cpp
Copyright (c) 2015, Nikolaj Schlej. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include <QCoreApplication>
#include <iostream>
#include "uefifind.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
a.setOrganizationName("CodeRush");
a.setOrganizationDomain("coderush.me");
a.setApplicationName("UEFIFind");
UEFIFind w;
UINT8 result;
if (a.arguments().length() == 5) {
// Get search mode
UINT8 mode;
if (a.arguments().at(1) == QString("header"))
mode = SEARCH_MODE_HEADER;
else if (a.arguments().at(1) == QString("body"))
mode = SEARCH_MODE_BODY;
else if (a.arguments().at(1) == QString("all"))
mode = SEARCH_MODE_ALL;
else
return ERR_INVALID_PARAMETER;
// Get result type
bool count;
if (a.arguments().at(2) == QString("list"))
count = false;
else if (a.arguments().at(2) == QString("count"))
count = true;
else
return ERR_INVALID_PARAMETER;
// Parse input file
result = w.init(a.arguments().at(4));
if (result)
return result;
// Go find the supplied pattern
QString found;
result = w.find(mode, count, a.arguments().at(3), found);
if (result)
return result;
// Nothing is found
if (found.isEmpty())
return ERR_ITEM_NOT_FOUND;
// Print result
std::cout << found.toStdString();
return ERR_SUCCESS;
}
else if (a.arguments().length() == 4) {
// Get search mode
if (a.arguments().at(1) != QString("file"))
return ERR_INVALID_PARAMETER;
// Open patterns file
QFileInfo fileInfo(a.arguments().at(2));
if (!fileInfo.exists())
return ERR_FILE_OPEN;
QFile patternsFile;
patternsFile.setFileName(a.arguments().at(2));
if (!patternsFile.open(QFile::ReadOnly))
return ERR_FILE_OPEN;
// Parse input file
result = w.init(a.arguments().at(3));
if (result)
return result;
// Perform searches
bool somethingFound = false;
while (!patternsFile.atEnd()) {
QByteArray line = patternsFile.readLine();
// Use sharp symbol as commentary
if (line.count() == 0 || line[0] == '#')
continue;
// Split the read line
QList<QByteArray> list = line.split(' ');
if (list.count() < 3) {
std::cout << line.toStdString() << "skipped, too few arguments" << std::endl << std::endl;
continue;
}
// Get search mode
UINT8 mode;
if (list.at(0) == QString("header"))
mode = SEARCH_MODE_HEADER;
else if (list.at(0) == QString("body"))
mode = SEARCH_MODE_BODY;
else if (list.at(0) == QString("all"))
mode = SEARCH_MODE_ALL;
else {
std::cout << line.toStdString() << "skipped, invalid search mode" << std::endl << std::endl;
continue;
}
// Get result type
bool count;
if (list.at(1) == QString("list"))
count = false;
else if (list.at(1) == QString("count"))
count = true;
else {
std::cout << line.toStdString() << "skipped, invalid result type" << std::endl << std::endl;
continue;
}
// Go find the supplied pattern
QString found;
result = w.find(mode, count, list.at(2), found);
if (result) {
std::cout << line.toStdString() << "skipped, find failed with error " << result << std::endl << std::endl;
continue;
}
if (found.isEmpty()) {
// Nothing is found
std::cout << line.toStdString() << "nothing found" << std::endl << std::endl;
}
else {
// Print result
std::cout << line.toStdString() << found.toStdString() << std::endl;
somethingFound = true;
}
}
// Nothing is found
if (!somethingFound)
return ERR_ITEM_NOT_FOUND;
return ERR_SUCCESS;
}
else {
std::cout << "UEFIFind 0.10.1" << std::endl << std::endl <<
"Usage: uefifind {header | body | all} {list | count} pattern imagefile" << std::endl <<
" or uefifind file patternsfile imagefile" << std::endl;
return ERR_INVALID_PARAMETER;
}
}
<|endoftext|> |
<commit_before>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
*
*
* @Version: 1.0.0
* @Author: Achim Grolimund ([email protected])
* @Date: 01.1.2017
*
* @Description:
*
* Beispiel:
*
* Anmerkung:
*
*
*==============================================[ EOF RDM ]=============================================================================*/
#define DEBUG
#include <bits/stdc++.h>
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"
using namespace std;
int main()
{
return 0;
}
<commit_msg>Update nach Unterrichtvorgabe<commit_after>/*===================================[ Algorithmen und Datenstrukturen]================================================================*
*
*
* @Version: 1.0.0
* @Author: Achim Grolimund ([email protected])
* @Date: 01.1.2017
*
* @Description:
*
* Beispiel:
*
* Anmerkung:
*
*
*==============================================[ EOF RDM ]=============================================================================*/
#define DEBUG
#include <bits/stdc++.h>
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/myfunks.h"
#include "C:/Users/achim/Documents/Programming/C++/HF-ICT-AAD/myFunks/myFunks/debug.h"
using namespace std;
int search(vector<int> & data, int element, int left, int right, int & counter) {
counter++;
if (left > right) {
return -1;
}
int mid = (left + right) / 2;
if (data[mid] == element) {
return mid;
}
if (element < data[mid]) {
return search(data, element, left, mid-1, counter);
} else {
return search(data, element, mid+1, right, counter);
}
}
int search(vector<int> & data, int element) {
int counter = 0;
int result = search(data, element, 0, data.size()-1, counter);
cout << "Counter: " << counter << endl;
return result;
}
int main(int argc, char **argv) {
const int N = 100;
vector<int> v;
for (int i=0; i<N; i++) {
v.push_back(rand()%10000);
}
sort(v.begin(), v.end());
vector<int>::iterator it;
for (it=v.begin(); it!=v.end(); it++) {
cout << *it << ", ";
}
cout << endl;
cout << search(v, 5368) << endl;
cout << search(v, 6000) << endl;
cout << search(v, 12) << endl;
cout << search(v, 9956) << endl;
return 0;
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef __MINIZINC_OPTIONS_HH__
#define __MINIZINC_OPTIONS_HH__
#include <minizinc/hash.hh>
namespace MiniZinc {
class Options {
protected:
UNORDERED_NAMESPACE::unordered_map<std::string, KeepAlive> _options;
inline Expression* getParam(const std::string& name) const;
public:
void setIntParam(const std::string& name, KeepAlive e);
void setFloatParam(const std::string& name, KeepAlive e);
void setBoolParam(const std::string& name, KeepAlive e);
void setStringParam(const std::string& name, KeepAlive e);
void setIntParam(const std::string& name, long long int e);
void setFloatParam(const std::string& name, double e);
void setBoolParam(const std::string& name, bool e);
void setStringParam(const std::string& name, std::string e);
long long int getIntParam(const std::string& name) const;
long long int getIntParam(const std::string& name, long long int def) const;
double getFloatParam(const std::string& name) const;
double getFloatParam(const std::string& name, double def) const;
bool getBoolParam(const std::string& name) const;
bool getBoolParam(const std::string& name, bool def) const;
std::string getStringParam(const std::string& name) const;
std::string getStringParam(const std::string& name, std::string def) const;
bool hasParam(const std::string& name) const;
std::ostream& dump(std::ostream& os);
};
}
#endif
<commit_msg>Remove incorrect inline<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <[email protected]>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef __MINIZINC_OPTIONS_HH__
#define __MINIZINC_OPTIONS_HH__
#include <minizinc/hash.hh>
namespace MiniZinc {
class Options {
protected:
UNORDERED_NAMESPACE::unordered_map<std::string, KeepAlive> _options;
Expression* getParam(const std::string& name) const;
public:
void setIntParam(const std::string& name, KeepAlive e);
void setFloatParam(const std::string& name, KeepAlive e);
void setBoolParam(const std::string& name, KeepAlive e);
void setStringParam(const std::string& name, KeepAlive e);
void setIntParam(const std::string& name, long long int e);
void setFloatParam(const std::string& name, double e);
void setBoolParam(const std::string& name, bool e);
void setStringParam(const std::string& name, std::string e);
long long int getIntParam(const std::string& name) const;
long long int getIntParam(const std::string& name, long long int def) const;
double getFloatParam(const std::string& name) const;
double getFloatParam(const std::string& name, double def) const;
bool getBoolParam(const std::string& name) const;
bool getBoolParam(const std::string& name, bool def) const;
std::string getStringParam(const std::string& name) const;
std::string getStringParam(const std::string& name, std::string def) const;
bool hasParam(const std::string& name) const;
std::ostream& dump(std::ostream& os);
};
}
#endif
<|endoftext|> |
<commit_before>#pragma once
#include "LogLevel.hpp"
#include <string>
#include <vector>
#include <stdint.h>
typedef struct tagAMX AMX;
typedef int32_t cell;
namespace samplog
{
struct AmxFuncCallInfo
{
int line;
const char *file;
const char *function;
};
class ILogger
{
public:
virtual bool IsLogLevel(LogLevel log_level) const = 0;
virtual bool LogNativeCall(AMX * const amx, cell * const params,
std::string name, std::string params_format) = 0;
virtual bool Log(LogLevel level, std::string msg,
std::vector<AmxFuncCallInfo> const &call_info) = 0;
virtual bool Log(LogLevel level, std::string msg) = 0;
virtual void Destroy() = 0;
virtual ~ILogger() = default;
};
}
<commit_msg>fix include name<commit_after>#pragma once
#include "LogLevel.hpp"
#include <cstdint>
#include <string>
#include <vector>
typedef struct tagAMX AMX;
typedef int32_t cell;
namespace samplog
{
struct AmxFuncCallInfo
{
int line;
const char *file;
const char *function;
};
class ILogger
{
public:
virtual bool IsLogLevel(LogLevel log_level) const = 0;
virtual bool LogNativeCall(AMX * const amx, cell * const params,
std::string name, std::string params_format) = 0;
virtual bool Log(LogLevel level, std::string msg,
std::vector<AmxFuncCallInfo> const &call_info) = 0;
virtual bool Log(LogLevel level, std::string msg) = 0;
virtual void Destroy() = 0;
virtual ~ILogger() = default;
};
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_XMLOFF_NUMEHELP_HXX
#define INCLUDED_XMLOFF_NUMEHELP_HXX
#include <sal/config.h>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/dllapi.h>
#include <sal/types.h>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#include <set>
class SvXMLExport;
struct XMLNumberFormat
{
OUString sCurrency;
sal_Int32 nNumberFormat;
sal_Int16 nType;
bool bIsStandard : 1;
XMLNumberFormat() : nNumberFormat(0), nType(0) {}
XMLNumberFormat(const OUString& sTempCurrency, sal_Int32 nTempFormat,
sal_Int16 nTempType) : sCurrency(sTempCurrency), nNumberFormat(nTempFormat),
nType(nTempType) {}
};
struct LessNumberFormat
{
bool operator() (const XMLNumberFormat& rValue1, const XMLNumberFormat& rValue2) const
{
return rValue1.nNumberFormat < rValue2.nNumberFormat;
}
};
typedef std::set<XMLNumberFormat, LessNumberFormat> XMLNumberFormatSet;
class XMLOFF_DLLPUBLIC XMLNumberFormatAttributesExportHelper
{
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats > xNumberFormats;
SvXMLExport* pExport;
const OUString sEmpty;
const OUString sStandardFormat;
const OUString sType;
const OUString sAttrValue;
const OUString sAttrDateValue;
const OUString sAttrTimeValue;
const OUString sAttrBooleanValue;
const OUString sAttrStringValue;
const OUString sAttrCurrency;
const OUString msCurrencySymbol;
const OUString msCurrencyAbbreviation;
XMLNumberFormatSet aNumberFormats;
public :
XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier);
XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier,
SvXMLExport& rExport );
~XMLNumberFormatAttributesExportHelper();
void SetExport(SvXMLExport* pExp) { this->pExport = pExp; }
sal_Int16 GetCellType(const sal_Int32 nNumberFormat, OUString& sCurrency, bool& bIsStandard);
static void WriteAttributes(SvXMLExport& rXMLExport,
const sal_Int16 nTypeKey,
const double& rValue,
const OUString& rCurrencySymbol,
bool bExportValue = true);
static bool GetCurrencySymbol(const sal_Int32 nNumberFormat, OUString& rCurrencySymbol,
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier);
static sal_Int16 GetCellType(const sal_Int32 nNumberFormat, bool& bIsStandard,
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier);
static void SetNumberFormatAttributes(SvXMLExport& rXMLExport,
const sal_Int32 nNumberFormat,
const double& rValue,
bool bExportValue = true);
static void SetNumberFormatAttributes(SvXMLExport& rXMLExport,
const OUString& rValue,
const OUString& rCharacters,
bool bExportValue = true,
bool bExportTypeAttribute = true);
bool GetCurrencySymbol(const sal_Int32 nNumberFormat, OUString& rCurrencySymbol);
sal_Int16 GetCellType(const sal_Int32 nNumberFormat, bool& bIsStandard);
void WriteAttributes(const sal_Int16 nTypeKey,
const double& rValue,
const OUString& rCurrencySymbol,
bool bExportValue = true, sal_uInt16 nNamespace = XML_NAMESPACE_OFFICE);
void SetNumberFormatAttributes(const sal_Int32 nNumberFormat,
const double& rValue,
bool bExportValue = true,
sal_uInt16 nNamespace = XML_NAMESPACE_OFFICE, bool bExportCurrencySymbol = true);
void SetNumberFormatAttributes(const OUString& rValue,
const OUString& rCharacters,
bool bExportValue = true,
bool bExportTypeAttribute = true,
sal_uInt16 nNamespace = XML_NAMESPACE_OFFICE);
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708217 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_XMLOFF_NUMEHELP_HXX
#define INCLUDED_XMLOFF_NUMEHELP_HXX
#include <sal/config.h>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/dllapi.h>
#include <sal/types.h>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#include <set>
class SvXMLExport;
struct XMLNumberFormat
{
OUString sCurrency;
sal_Int32 nNumberFormat;
sal_Int16 nType;
bool bIsStandard : 1;
XMLNumberFormat()
: nNumberFormat(0)
, nType(0)
, bIsStandard(false)
{
}
XMLNumberFormat(const OUString& sTempCurrency, sal_Int32 nTempFormat, sal_Int16 nTempType)
: sCurrency(sTempCurrency)
, nNumberFormat(nTempFormat)
, nType(nTempType)
, bIsStandard(false)
{
}
};
struct LessNumberFormat
{
bool operator() (const XMLNumberFormat& rValue1, const XMLNumberFormat& rValue2) const
{
return rValue1.nNumberFormat < rValue2.nNumberFormat;
}
};
typedef std::set<XMLNumberFormat, LessNumberFormat> XMLNumberFormatSet;
class XMLOFF_DLLPUBLIC XMLNumberFormatAttributesExportHelper
{
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats > xNumberFormats;
SvXMLExport* pExport;
const OUString sEmpty;
const OUString sStandardFormat;
const OUString sType;
const OUString sAttrValue;
const OUString sAttrDateValue;
const OUString sAttrTimeValue;
const OUString sAttrBooleanValue;
const OUString sAttrStringValue;
const OUString sAttrCurrency;
const OUString msCurrencySymbol;
const OUString msCurrencyAbbreviation;
XMLNumberFormatSet aNumberFormats;
public :
XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier);
XMLNumberFormatAttributesExportHelper(::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier,
SvXMLExport& rExport );
~XMLNumberFormatAttributesExportHelper();
void SetExport(SvXMLExport* pExp) { this->pExport = pExp; }
sal_Int16 GetCellType(const sal_Int32 nNumberFormat, OUString& sCurrency, bool& bIsStandard);
static void WriteAttributes(SvXMLExport& rXMLExport,
const sal_Int16 nTypeKey,
const double& rValue,
const OUString& rCurrencySymbol,
bool bExportValue = true);
static bool GetCurrencySymbol(const sal_Int32 nNumberFormat, OUString& rCurrencySymbol,
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier);
static sal_Int16 GetCellType(const sal_Int32 nNumberFormat, bool& bIsStandard,
::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier);
static void SetNumberFormatAttributes(SvXMLExport& rXMLExport,
const sal_Int32 nNumberFormat,
const double& rValue,
bool bExportValue = true);
static void SetNumberFormatAttributes(SvXMLExport& rXMLExport,
const OUString& rValue,
const OUString& rCharacters,
bool bExportValue = true,
bool bExportTypeAttribute = true);
bool GetCurrencySymbol(const sal_Int32 nNumberFormat, OUString& rCurrencySymbol);
sal_Int16 GetCellType(const sal_Int32 nNumberFormat, bool& bIsStandard);
void WriteAttributes(const sal_Int16 nTypeKey,
const double& rValue,
const OUString& rCurrencySymbol,
bool bExportValue = true, sal_uInt16 nNamespace = XML_NAMESPACE_OFFICE);
void SetNumberFormatAttributes(const sal_Int32 nNumberFormat,
const double& rValue,
bool bExportValue = true,
sal_uInt16 nNamespace = XML_NAMESPACE_OFFICE, bool bExportCurrencySymbol = true);
void SetNumberFormatAttributes(const OUString& rValue,
const OUString& rCharacters,
bool bExportValue = true,
bool bExportTypeAttribute = true,
sal_uInt16 nNamespace = XML_NAMESPACE_OFFICE);
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#pragma once
#include <cmath>
#include <array>
#include <vector>
#include "zmsg_cmm.hpp"
namespace zmsg {
/**
* \brief typedefs
*/
typedef signed char CHAR;
typedef unsigned char UCHAR;
typedef signed short SHORT;
typedef unsigned short USHORT;
typedef int8_t INT8;
typedef uint8_t UINT8;
typedef int16_t INT16;
typedef uint16_t UINT16;
typedef int32_t INT32;
typedef uint32_t UINT32;
typedef signed long LONG;
typedef unsigned long ULONG;
typedef float FLOAT;
typedef double DOUBLE;
typedef bool BOOL;
typedef void VOID;
} /* namespace zmsg */
/**
* \brief bool image
*/
struct bool_img {
bool_img()
: width(0)
, height(0)
, data()
{
}
void init(void)
{
this->width = 0;
this->height = 0;
this->data.clear();
}
uint16_t width;
uint16_t height;
std::vector<bool> data;
public:
ZMSG_PU(width, height, data)
};
/**
* \brief img fiber defect description
*/
typedef uint32_t ifd_t;
static constexpr ifd_t ifd_end_crude = 0x1;
static constexpr ifd_t ifd_horizontal_angle = 0x2;
static constexpr ifd_t ifd_vertical_angle = 0x4;
static constexpr ifd_t ifd_cant_identify = 0x80000000;
typedef struct ifd_line final {
ifd_t dbmp;
/// \note all angles' unit are degree
double h_angle;
double v_angle;
int32_t wrap_diameter; /// unit: pixel
ifd_line()
: dbmp(0)
, h_angle(0)
, v_angle(0)
, wrap_diameter(0)
{
}
void init(void)
{
this->dbmp = 0;
this->h_angle = 0;
this->v_angle = 0;
this->wrap_diameter = 0;
}
operator bool() const
{
return dbmp;
}
bool check(ifd_t msk) const
{
return (dbmp & msk);
}
public:
ZMSG_PU(dbmp, h_angle, v_angle, wrap_diameter)
} ifd_line_t;
typedef struct img_defects final {
ifd_line_t yzl;
ifd_line_t yzr;
ifd_line_t xzl;
ifd_line_t xzr;
/// the image contain missed corner info
bool_img yz_img;
bool_img xz_img;
img_defects()
: yzl(), yzr(), xzl(), xzr()
, yz_img(), xz_img()
{
}
void init(void)
{
this->yzl.init();
this->yzr.init();
this->xzl.init();
this->xzr.init();
this->yz_img.init();
this->xz_img.init();
}
operator bool() const
{
return (yzl || yzr || xzl || xzr);
}
bool check(ifd_t msk) const
{
return (yzl.check(msk)
|| yzr.check(msk)
|| xzl.check(msk)
|| xzr.check(msk));
}
double left_cut_angle(void) const
{
return std::max(yzl.v_angle, xzl.v_angle);
}
double right_cut_angle(void) const
{
return std::max(yzr.v_angle, xzr.v_angle);
}
public:
ZMSG_PU(yzl, yzr, xzl, xzr, yz_img, xz_img)
} img_defects_t;
/**
* \biref fiber recognition infomation
*/
typedef struct final {
uint32_t wrap_diameter; /// unit: nm
uint32_t core_diameter; /// unit: nm
public:
ZMSG_PU(wrap_diameter, core_diameter)
} fiber_rec_info_t;
/**
* \brief service fs state
* \note all states mean enter this state.
*/
enum class svc_fs_state_t : uint16_t {
fs_reseting,
fs_idle,
fs_ready,
fs_entering,
fs_push1,
fs_calibrating,
fs_waiting,
fs_clring,
fs_defect_detecting,
fs_push2,
fs_pause1,
fs_precise_calibrating,
fs_pause2,
fs_pre_splice,
fs_discharge1,
fs_discharge2,
fs_discharge_manual,
fs_loss_estimating,
fs_tension_testing,
fs_finished,
fs_wait_reset,
};
/**
* \brief service heat state
*/
enum class svc_heat_state_t : uint16_t {
heat_idle,
heat_ready,
heat_ascending,
heat_stabling,
heat_descending,
};
/**
* \brief motor id
*/
enum motorId_t : uint8_t {
LZ = 0, // left z
RZ, // right z
X, // x
Y, // y
NUM, // total number
};
/**
* \brief fusion splice display mode
*/
enum class fs_display_mode_t : uint8_t {
X = 0x0, /// only x
Y, /// only y
TB, /// top <-> bottom
LR, /// left <-> right
NO, /// no
max, /// number
};
/**
* \brief fusion splicer related error code
*/
enum class fs_err_t : uint8_t {
success,
cover_openned,
no_fiber,
fiber_defect,
fiber_cross_over,
fiber_off_center,
img_brightness,
abnormal_arc,
tense_test_fail,
fiber_broken,
quit_midway,
push_timeout,
calibrate_timeout,
reset_timeout,
arc_time_zero,
ignore,
revise1_mag,
revise2_mag,
};
/**
* \brief led id
*/
enum ledId_t : uint8_t {
CMOS_X = 0x0,
CMOS_Y,
LED_NUM,
};
/**
* \brief discharge_data_t, used for discharge revising
*/
typedef struct {
struct {
double x; /// unit: volt
double y; /// unit: um
public:
ZMSG_PU(x, y)
} p[2];
double temp; /// unit: degree centigrade
bool empty() const
{
return (p[0].x == p[1].x);
}
public:
ZMSG_PU(p, temp)
} discharge_data_t;
/**
* \brief fusion splice pattern
*/
enum class fs_pattern_t : uint8_t {
automatic = 0x0,
calibrate,
normal,
special,
};
/**
* \brief loss estimate mode
*/
enum class loss_estimate_mode_t : uint8_t {
off = 0x0,
accurate,
core,
cladding,
};
<commit_msg>zmsg: add focus error code for fs_err_t<commit_after>#pragma once
#include <cmath>
#include <array>
#include <vector>
#include "zmsg_cmm.hpp"
namespace zmsg {
/**
* \brief typedefs
*/
typedef signed char CHAR;
typedef unsigned char UCHAR;
typedef signed short SHORT;
typedef unsigned short USHORT;
typedef int8_t INT8;
typedef uint8_t UINT8;
typedef int16_t INT16;
typedef uint16_t UINT16;
typedef int32_t INT32;
typedef uint32_t UINT32;
typedef signed long LONG;
typedef unsigned long ULONG;
typedef float FLOAT;
typedef double DOUBLE;
typedef bool BOOL;
typedef void VOID;
} /* namespace zmsg */
/**
* \brief bool image
*/
struct bool_img {
bool_img()
: width(0)
, height(0)
, data()
{
}
void init(void)
{
this->width = 0;
this->height = 0;
this->data.clear();
}
uint16_t width;
uint16_t height;
std::vector<bool> data;
public:
ZMSG_PU(width, height, data)
};
/**
* \brief img fiber defect description
*/
typedef uint32_t ifd_t;
static constexpr ifd_t ifd_end_crude = 0x1;
static constexpr ifd_t ifd_horizontal_angle = 0x2;
static constexpr ifd_t ifd_vertical_angle = 0x4;
static constexpr ifd_t ifd_cant_identify = 0x80000000;
typedef struct ifd_line final {
ifd_t dbmp;
/// \note all angles' unit are degree
double h_angle;
double v_angle;
int32_t wrap_diameter; /// unit: pixel
ifd_line()
: dbmp(0)
, h_angle(0)
, v_angle(0)
, wrap_diameter(0)
{
}
void init(void)
{
this->dbmp = 0;
this->h_angle = 0;
this->v_angle = 0;
this->wrap_diameter = 0;
}
operator bool() const
{
return dbmp;
}
bool check(ifd_t msk) const
{
return (dbmp & msk);
}
public:
ZMSG_PU(dbmp, h_angle, v_angle, wrap_diameter)
} ifd_line_t;
typedef struct img_defects final {
ifd_line_t yzl;
ifd_line_t yzr;
ifd_line_t xzl;
ifd_line_t xzr;
/// the image contain missed corner info
bool_img yz_img;
bool_img xz_img;
img_defects()
: yzl(), yzr(), xzl(), xzr()
, yz_img(), xz_img()
{
}
void init(void)
{
this->yzl.init();
this->yzr.init();
this->xzl.init();
this->xzr.init();
this->yz_img.init();
this->xz_img.init();
}
operator bool() const
{
return (yzl || yzr || xzl || xzr);
}
bool check(ifd_t msk) const
{
return (yzl.check(msk)
|| yzr.check(msk)
|| xzl.check(msk)
|| xzr.check(msk));
}
double left_cut_angle(void) const
{
return std::max(yzl.v_angle, xzl.v_angle);
}
double right_cut_angle(void) const
{
return std::max(yzr.v_angle, xzr.v_angle);
}
public:
ZMSG_PU(yzl, yzr, xzl, xzr, yz_img, xz_img)
} img_defects_t;
/**
* \biref fiber recognition infomation
*/
typedef struct final {
uint32_t wrap_diameter; /// unit: nm
uint32_t core_diameter; /// unit: nm
public:
ZMSG_PU(wrap_diameter, core_diameter)
} fiber_rec_info_t;
/**
* \brief service fs state
* \note all states mean enter this state.
*/
enum class svc_fs_state_t : uint16_t {
fs_reseting,
fs_idle,
fs_ready,
fs_entering,
fs_push1,
fs_calibrating,
fs_waiting,
fs_clring,
fs_defect_detecting,
fs_push2,
fs_pause1,
fs_precise_calibrating,
fs_pause2,
fs_pre_splice,
fs_discharge1,
fs_discharge2,
fs_discharge_manual,
fs_loss_estimating,
fs_tension_testing,
fs_finished,
fs_wait_reset,
};
/**
* \brief service heat state
*/
enum class svc_heat_state_t : uint16_t {
heat_idle,
heat_ready,
heat_ascending,
heat_stabling,
heat_descending,
};
/**
* \brief motor id
*/
enum motorId_t : uint8_t {
LZ = 0, // left z
RZ, // right z
X, // x
Y, // y
NUM, // total number
};
/**
* \brief fusion splice display mode
*/
enum class fs_display_mode_t : uint8_t {
X = 0x0, /// only x
Y, /// only y
TB, /// top <-> bottom
LR, /// left <-> right
NO, /// no
max, /// number
};
/**
* \brief fusion splicer related error code
*/
enum class fs_err_t : uint8_t {
success,
cover_openned,
no_fiber,
fiber_defect,
fiber_cross_over,
fiber_off_center,
img_brightness,
abnormal_arc,
tense_test_fail,
fiber_broken,
quit_midway,
push_timeout,
calibrate_timeout,
reset_timeout,
arc_time_zero,
ignore,
revise1_mag,
revise2_mag,
focus_x,
focus_y,
};
/**
* \brief led id
*/
enum ledId_t : uint8_t {
CMOS_X = 0x0,
CMOS_Y,
LED_NUM,
};
/**
* \brief discharge_data_t, used for discharge revising
*/
typedef struct {
struct {
double x; /// unit: volt
double y; /// unit: um
public:
ZMSG_PU(x, y)
} p[2];
double temp; /// unit: degree centigrade
bool empty() const
{
return (p[0].x == p[1].x);
}
public:
ZMSG_PU(p, temp)
} discharge_data_t;
/**
* \brief fusion splice pattern
*/
enum class fs_pattern_t : uint8_t {
automatic = 0x0,
calibrate,
normal,
special,
};
/**
* \brief loss estimate mode
*/
enum class loss_estimate_mode_t : uint8_t {
off = 0x0,
accurate,
core,
cladding,
};
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_OgreCompositor.h"
#include "Renderer.h"
#include "FrameAPI.h"
#include "OgreRenderingModule.h"
#include "CompositionHandler.h"
#include "LoggingFunctions.h"
#include "MemoryLeakCheck.h"
EC_OgreCompositor::EC_OgreCompositor(Scene* scene) :
IComponent(scene),
enabled(this, "Enabled", true),
compositorref(this, "Compositor ref", ""),
priority(this, "Priority", -1),
parameters(this, "Parameters"),
previous_priority_(-1),
owner_(0),
handler_(0)
{
owner_ = framework->GetModule<OgreRenderer::OgreRenderingModule>();
assert(owner_ && "No OgrerenderingModule.");
handler_ = owner_->GetRenderer()->GetCompositionHandler();
assert (handler_ && "No CompositionHandler.");
connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(OnAttributeUpdated(IAttribute*)));
// Ogre sucks. Enable a timed one-time refresh to overcome issue with black screen.
framework->Frame()->DelayedExecute(0.01f, this, SLOT(OneTimeRefresh()));
}
EC_OgreCompositor::~EC_OgreCompositor()
{
if ((handler_) && (!previous_ref_.isEmpty()))
handler_->RemoveCompositorFromViewport(previous_ref_.toStdString());
}
void EC_OgreCompositor::OnAttributeUpdated(IAttribute* attribute)
{
if (attribute == &enabled)
{
UpdateCompositor(compositorref.Get());
UpdateCompositorParams(compositorref.Get());
handler_->SetCompositorEnabled(compositorref.Get().toStdString(), enabled.Get());
}
if (attribute == &compositorref)
{
UpdateCompositor(compositorref.Get());
}
if (attribute == &priority)
{
UpdateCompositor(compositorref.Get());
}
if (attribute == ¶meters)
{
UpdateCompositorParams(compositorref.Get());
}
}
void EC_OgreCompositor::UpdateCompositor(const QString &compositor)
{
if (ViewEnabled() && enabled.Get())
{
if ((previous_ref_ != compositorref.Get()) || (previous_priority_ != priority.Get()))
{
if (!previous_ref_.isEmpty())
handler_->RemoveCompositorFromViewport(previous_ref_.toStdString());
if (!compositorref.Get().isEmpty())
{
if (priority.Get() == -1)
handler_->AddCompositorForViewport(compositor.toStdString());
else
handler_->AddCompositorForViewportPriority(compositor.toStdString(), priority.Get());
}
previous_ref_ = compositor;
previous_priority_ = priority.Get();
}
}
}
void EC_OgreCompositor::UpdateCompositorParams(const QString &compositor)
{
if (ViewEnabled() && enabled.Get())
{
QList< std::pair<std::string, Ogre::Vector4> > programParams;
foreach(QVariant keyvalue, parameters.Get())
{
QString params = keyvalue.toString();
QStringList sepParams = params.split('=');
if (sepParams.size() > 1)
{
try
{
Ogre::Vector4 value;
QStringList valueList = sepParams[1].split(" ", QString::SkipEmptyParts);
if (valueList.size() > 0) value.x = boost::lexical_cast<Ogre::Real>(valueList[0].toStdString());
if (valueList.size() > 1) value.y = boost::lexical_cast<Ogre::Real>(valueList[1].toStdString());
if (valueList.size() > 2) value.z = boost::lexical_cast<Ogre::Real>(valueList[2].toStdString());
if (valueList.size() > 3) value.w = boost::lexical_cast<Ogre::Real>(valueList[3].toStdString());
std::string name = sepParams[0].toStdString();
programParams.push_back(std::make_pair(name, value));
}
catch(boost::bad_lexical_cast &) {}
}
}
handler_->SetCompositorParameter(compositorref.Get().toStdString(), programParams);
handler_->SetCompositorEnabled(compositorref.Get().toStdString(), false);
handler_->SetCompositorEnabled(compositorref.Get().toStdString(), true);
}
}
void EC_OgreCompositor::OneTimeRefresh()
{
if (!compositorref.Get().isEmpty())
OnAttributeUpdated(&enabled);
}
<commit_msg>fix unitialized use warning<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_OgreCompositor.h"
#include "Renderer.h"
#include "FrameAPI.h"
#include "OgreRenderingModule.h"
#include "CompositionHandler.h"
#include "LoggingFunctions.h"
#include "MemoryLeakCheck.h"
EC_OgreCompositor::EC_OgreCompositor(Scene* scene) :
IComponent(scene),
enabled(this, "Enabled", true),
compositorref(this, "Compositor ref", ""),
priority(this, "Priority", -1),
parameters(this, "Parameters"),
previous_priority_(-1),
owner_(0),
handler_(0)
{
owner_ = framework->GetModule<OgreRenderer::OgreRenderingModule>();
assert(owner_ && "No OgrerenderingModule.");
handler_ = owner_->GetRenderer()->GetCompositionHandler();
assert (handler_ && "No CompositionHandler.");
connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(OnAttributeUpdated(IAttribute*)));
// Ogre sucks. Enable a timed one-time refresh to overcome issue with black screen.
framework->Frame()->DelayedExecute(0.01f, this, SLOT(OneTimeRefresh()));
}
EC_OgreCompositor::~EC_OgreCompositor()
{
if ((handler_) && (!previous_ref_.isEmpty()))
handler_->RemoveCompositorFromViewport(previous_ref_.toStdString());
}
void EC_OgreCompositor::OnAttributeUpdated(IAttribute* attribute)
{
if (attribute == &enabled)
{
UpdateCompositor(compositorref.Get());
UpdateCompositorParams(compositorref.Get());
handler_->SetCompositorEnabled(compositorref.Get().toStdString(), enabled.Get());
}
if (attribute == &compositorref)
{
UpdateCompositor(compositorref.Get());
}
if (attribute == &priority)
{
UpdateCompositor(compositorref.Get());
}
if (attribute == ¶meters)
{
UpdateCompositorParams(compositorref.Get());
}
}
void EC_OgreCompositor::UpdateCompositor(const QString &compositor)
{
if (ViewEnabled() && enabled.Get())
{
if ((previous_ref_ != compositorref.Get()) || (previous_priority_ != priority.Get()))
{
if (!previous_ref_.isEmpty())
handler_->RemoveCompositorFromViewport(previous_ref_.toStdString());
if (!compositorref.Get().isEmpty())
{
if (priority.Get() == -1)
handler_->AddCompositorForViewport(compositor.toStdString());
else
handler_->AddCompositorForViewportPriority(compositor.toStdString(), priority.Get());
}
previous_ref_ = compositor;
previous_priority_ = priority.Get();
}
}
}
void EC_OgreCompositor::UpdateCompositorParams(const QString &compositor)
{
if (ViewEnabled() && enabled.Get())
{
QList< std::pair<std::string, Ogre::Vector4> > programParams;
foreach(QVariant keyvalue, parameters.Get())
{
QString params = keyvalue.toString();
QStringList sepParams = params.split('=');
if (sepParams.size() > 1)
{
try
{
Ogre::Vector4 value(0, 0, 0, 0);
QStringList valueList = sepParams[1].split(" ", QString::SkipEmptyParts);
if (valueList.size() > 0) value.x = boost::lexical_cast<Ogre::Real>(valueList[0].toStdString());
if (valueList.size() > 1) value.y = boost::lexical_cast<Ogre::Real>(valueList[1].toStdString());
if (valueList.size() > 2) value.z = boost::lexical_cast<Ogre::Real>(valueList[2].toStdString());
if (valueList.size() > 3) value.w = boost::lexical_cast<Ogre::Real>(valueList[3].toStdString());
std::string name = sepParams[0].toStdString();
programParams.push_back(std::make_pair(name, value));
}
catch(boost::bad_lexical_cast &) {}
}
}
handler_->SetCompositorParameter(compositorref.Get().toStdString(), programParams);
handler_->SetCompositorEnabled(compositorref.Get().toStdString(), false);
handler_->SetCompositorEnabled(compositorref.Get().toStdString(), true);
}
}
void EC_OgreCompositor::OneTimeRefresh()
{
if (!compositorref.Get().isEmpty())
OnAttributeUpdated(&enabled);
}
<|endoftext|> |
<commit_before>/* Copyright 2012-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "watchman.h"
#include <folly/Synchronized.h>
using namespace watchman;
namespace watchman {
namespace {
constexpr flag_map kFlags[] = {
{W_PENDING_CRAWL_ONLY, "CRAWL_ONLY"},
{W_PENDING_RECURSIVE, "RECURSIVE"},
{W_PENDING_VIA_NOTIFY, "VIA_NOTIFY"},
{W_PENDING_IS_DESYNCED, "IS_DESYNCED"},
{0, NULL},
};
}
bool is_path_prefix(
const char* path,
size_t path_len,
const char* other,
size_t common_prefix) {
if (common_prefix > path_len) {
return false;
}
w_assert(
memcmp(path, other, common_prefix) == 0,
"is_path_prefix: %.*s vs %.*s should have %d common_prefix chars\n",
(int)path_len,
path,
(int)common_prefix,
other,
(int)common_prefix);
(void)other;
if (common_prefix == path_len) {
return true;
}
return is_slash(path[common_prefix]);
}
} // namespace watchman
void PendingChanges::clear() {
pending_.reset();
tree_.clear();
}
void PendingChanges::add(
const w_string& path,
std::chrono::system_clock::time_point now,
int flags) {
char flags_label[128];
auto existing = tree_.search(path);
if (existing) {
/* Entry already exists: consolidate */
consolidateItem(existing->get(), flags);
/* all done */
return;
}
if (isObsoletedByContainingDir(path)) {
return;
}
// Try to allocate the new node before we prune any children.
auto p = std::make_shared<watchman_pending_fs>(path, now, flags);
maybePruneObsoletedChildren(path, flags);
w_expand_flags(kFlags, flags, flags_label, sizeof(flags_label));
logf(DBG, "add_pending: {} {}\n", path, flags_label);
tree_.insert(path, p);
linkHead(std::move(p));
}
void PendingChanges::add(
struct watchman_dir* dir,
const char* name,
std::chrono::system_clock::time_point now,
int flags) {
return add(dir->getFullPathToChild(name), now, flags);
}
void PendingChanges::append(std::shared_ptr<watchman_pending_fs> chain) {
auto p = std::move(chain);
while (p) {
auto target_p =
tree_.search((const uint8_t*)p->path.data(), p->path.size());
if (target_p) {
/* Entry already exists: consolidate */
consolidateItem(target_p->get(), p->flags);
p = std::move(p->next);
continue;
}
if (isObsoletedByContainingDir(p->path)) {
p = std::move(p->next);
continue;
}
maybePruneObsoletedChildren(p->path, p->flags);
auto next = std::move(p->next);
tree_.insert(p->path, p);
linkHead(std::move(p));
p = std::move(next);
}
}
std::shared_ptr<watchman_pending_fs> PendingChanges::stealItems() {
tree_.clear();
return std::move(pending_);
}
/* Returns the number of unique pending items in the collection */
uint32_t PendingChanges::size() const {
return tree_.size();
}
// if there are any entries that are obsoleted by a recursive insert,
// walk over them now and mark them as ignored.
void PendingChanges::maybePruneObsoletedChildren(w_string path, int flags) {
if ((flags & (W_PENDING_RECURSIVE | W_PENDING_CRAWL_ONLY)) ==
W_PENDING_RECURSIVE) {
uint32_t pruned = 0;
// Since deletion invalidates the iterator, we need to repeatedly
// call this to prune out the nodes. It will return 0 once no
// matching prefixes are found and deleted.
// Deletion is a bit awkward in this radix tree implementation.
// We can't recursively delete a given prefix as a built-in operation
// and it is non-trivial to add that functionality right now.
// When we lop-off a portion of a tree that we're going to analyze
// recursively, we have to iterate each leaf and explicitly delete
// that leaf.
// Since deletion invalidates the iteration state we have to signal
// to stop iteration after each deletion and then retry the prefix
// deletion.
//
// We need to compare the prefix to make sure that we don't delete
// a sibling node by mistake (see commentary on the is_path_prefix
// function for more on that).
auto callback = [&](const w_string& key,
std::shared_ptr<watchman_pending_fs>& p) -> int {
if (!p) {
// It was removed; update the tree to reflect this
tree_.erase(key);
// Stop iteration: we deleted something and invalidated the
// iterators.
return 1;
}
if ((p->flags & W_PENDING_CRAWL_ONLY) == 0 && key.size() > path.size() &&
is_path_prefix(
(const char*)key.data(), key.size(), path.data(), path.size()) &&
!watchman::CookieSync::isPossiblyACookie(p->path)) {
logf(
DBG,
"delete_kids: removing ({}) {} from pending because it is "
"obsoleted by ({}) {}\n",
p->path.size(),
p->path,
path.size(),
path);
// Unlink the child from the pending index.
unlinkItem(p);
// Remove it from the art tree.
tree_.erase(key);
// Stop iteration because we just invalidated the iterator state
// by modifying the tree mid-iteration.
return 1;
}
return 0;
};
while (tree_.iterPrefix(
reinterpret_cast<const uint8_t*>(path.data()), path.size(), callback)) {
// OK; try again
++pruned;
}
if (pruned) {
logf(
DBG,
"maybePruneObsoletedChildren: pruned {} nodes under ({}) {}\n",
pruned,
path.size(),
path);
}
}
}
void PendingChanges::consolidateItem(watchman_pending_fs* p, int flags) {
// Increase the strength of the pending item if either of these
// flags are set.
// We upgrade crawl-only as well as recursive; it indicates that
// we've recently just performed the stat and we want to avoid
// infinitely trying to stat-and-crawl
p->flags |= flags &
(W_PENDING_CRAWL_ONLY | W_PENDING_RECURSIVE | W_PENDING_IS_DESYNCED);
maybePruneObsoletedChildren(p->path, p->flags);
}
// Check the tree to see if there is a path that is earlier/higher in the
// filesystem than the input path; if there is, and it is recursive,
// return true to indicate that there is no need to track this new path
// due to the already scheduled higher level path.
bool PendingChanges::isObsoletedByContainingDir(const w_string& path) {
auto leaf = tree_.longestMatch((const uint8_t*)path.data(), path.size());
if (!leaf) {
return false;
}
auto p = leaf->value;
if ((p->flags & W_PENDING_RECURSIVE) &&
is_path_prefix(
path.data(),
path.size(),
(const char*)leaf->key.data(),
leaf->key.size())) {
if (watchman::CookieSync::isPossiblyACookie(path)) {
return false;
}
// Yes: the pre-existing entry higher up in the tree obsoletes this
// one that we would add now.
logf(DBG, "is_obsoleted: SKIP {} is obsoleted by {}\n", path, p->path);
return true;
}
return false;
}
// Helper to doubly-link a pending item to the head of a collection.
void PendingChanges::linkHead(std::shared_ptr<watchman_pending_fs>&& p) {
p->prev.reset();
p->next = pending_;
if (p->next) {
p->next->prev = p;
}
pending_ = std::move(p);
}
// Helper to un-doubly-link a pending item.
void PendingChanges::unlinkItem(std::shared_ptr<watchman_pending_fs>& p) {
if (pending_ == p) {
pending_ = p->next;
}
auto prev = p->prev.lock();
if (prev) {
prev->next = p->next;
}
if (p->next) {
p->next->prev = prev;
}
p->next.reset();
p->prev.reset();
}
PendingCollectionBase::PendingCollectionBase(std::condition_variable& cond)
: cond_(cond) {}
void PendingCollectionBase::ping() {
pinged_ = true;
cond_.notify_all();
}
bool PendingCollectionBase::checkAndResetPinged() {
if (pending_ || pinged_) {
pinged_ = false;
return true;
}
return false;
}
PendingCollection::PendingCollection()
: folly::Synchronized<PendingCollectionBase, std::mutex>{
folly::in_place,
cond_} {}
PendingCollection::LockedPtr PendingCollection::lockAndWait(
std::chrono::milliseconds timeoutms,
bool& pinged) {
auto lock = this->lock();
if (lock->checkAndResetPinged()) {
pinged = true;
return lock;
}
if (timeoutms.count() == -1) {
cond_.wait(lock.getUniqueLock());
} else {
cond_.wait_for(lock.getUniqueLock(), timeoutms);
}
pinged = lock->checkAndResetPinged();
return lock;
}
/* vim:ts=2:sw=2:et:
*/
<commit_msg>Bad pending changes condition<commit_after>/* Copyright 2012-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include "watchman.h"
#include <folly/Synchronized.h>
using namespace watchman;
namespace watchman {
namespace {
constexpr flag_map kFlags[] = {
{W_PENDING_CRAWL_ONLY, "CRAWL_ONLY"},
{W_PENDING_RECURSIVE, "RECURSIVE"},
{W_PENDING_VIA_NOTIFY, "VIA_NOTIFY"},
{W_PENDING_IS_DESYNCED, "IS_DESYNCED"},
{0, NULL},
};
}
bool is_path_prefix(
const char* path,
size_t path_len,
const char* other,
size_t common_prefix) {
if (common_prefix > path_len) {
return false;
}
w_assert(
memcmp(path, other, common_prefix) == 0,
"is_path_prefix: %.*s vs %.*s should have %d common_prefix chars\n",
(int)path_len,
path,
(int)common_prefix,
other,
(int)common_prefix);
(void)other;
if (common_prefix == path_len) {
return true;
}
return is_slash(path[common_prefix]);
}
} // namespace watchman
void PendingChanges::clear() {
pending_.reset();
tree_.clear();
}
void PendingChanges::add(
const w_string& path,
std::chrono::system_clock::time_point now,
int flags) {
char flags_label[128];
auto existing = tree_.search(path);
if (existing) {
/* Entry already exists: consolidate */
consolidateItem(existing->get(), flags);
/* all done */
return;
}
if (isObsoletedByContainingDir(path)) {
return;
}
// Try to allocate the new node before we prune any children.
auto p = std::make_shared<watchman_pending_fs>(path, now, flags);
maybePruneObsoletedChildren(path, flags);
w_expand_flags(kFlags, flags, flags_label, sizeof(flags_label));
logf(DBG, "add_pending: {} {}\n", path, flags_label);
tree_.insert(path, p);
linkHead(std::move(p));
}
void PendingChanges::add(
struct watchman_dir* dir,
const char* name,
std::chrono::system_clock::time_point now,
int flags) {
return add(dir->getFullPathToChild(name), now, flags);
}
void PendingChanges::append(std::shared_ptr<watchman_pending_fs> chain) {
auto p = std::move(chain);
while (p) {
auto target_p =
tree_.search((const uint8_t*)p->path.data(), p->path.size());
if (target_p) {
/* Entry already exists: consolidate */
consolidateItem(target_p->get(), p->flags);
p = std::move(p->next);
continue;
}
if (isObsoletedByContainingDir(p->path)) {
p = std::move(p->next);
continue;
}
maybePruneObsoletedChildren(p->path, p->flags);
auto next = std::move(p->next);
tree_.insert(p->path, p);
linkHead(std::move(p));
p = std::move(next);
}
}
std::shared_ptr<watchman_pending_fs> PendingChanges::stealItems() {
tree_.clear();
return std::move(pending_);
}
/* Returns the number of unique pending items in the collection */
uint32_t PendingChanges::size() const {
return tree_.size();
}
// if there are any entries that are obsoleted by a recursive insert,
// walk over them now and mark them as ignored.
void PendingChanges::maybePruneObsoletedChildren(w_string path, int flags) {
if ((flags & (W_PENDING_RECURSIVE | W_PENDING_CRAWL_ONLY)) ==
W_PENDING_RECURSIVE) {
uint32_t pruned = 0;
// Since deletion invalidates the iterator, we need to repeatedly
// call this to prune out the nodes. It will return 0 once no
// matching prefixes are found and deleted.
// Deletion is a bit awkward in this radix tree implementation.
// We can't recursively delete a given prefix as a built-in operation
// and it is non-trivial to add that functionality right now.
// When we lop-off a portion of a tree that we're going to analyze
// recursively, we have to iterate each leaf and explicitly delete
// that leaf.
// Since deletion invalidates the iteration state we have to signal
// to stop iteration after each deletion and then retry the prefix
// deletion.
//
// We need to compare the prefix to make sure that we don't delete
// a sibling node by mistake (see commentary on the is_path_prefix
// function for more on that).
auto callback = [&](const w_string& key,
std::shared_ptr<watchman_pending_fs>& p) -> int {
w_check(
p,
"Pending changes should be removed from both the list and the tree.");
if ((p->flags & W_PENDING_CRAWL_ONLY) == 0 && key.size() > path.size() &&
is_path_prefix(
(const char*)key.data(), key.size(), path.data(), path.size()) &&
!watchman::CookieSync::isPossiblyACookie(p->path)) {
logf(
DBG,
"delete_kids: removing ({}) {} from pending because it is "
"obsoleted by ({}) {}\n",
p->path.size(),
p->path,
path.size(),
path);
// Unlink the child from the pending index.
unlinkItem(p);
// Remove it from the art tree.
tree_.erase(key);
// Stop iteration because we just invalidated the iterator state
// by modifying the tree mid-iteration.
return 1;
}
return 0;
};
while (tree_.iterPrefix(
reinterpret_cast<const uint8_t*>(path.data()), path.size(), callback)) {
// OK; try again
++pruned;
}
if (pruned) {
logf(
DBG,
"maybePruneObsoletedChildren: pruned {} nodes under ({}) {}\n",
pruned,
path.size(),
path);
}
}
}
void PendingChanges::consolidateItem(watchman_pending_fs* p, int flags) {
// Increase the strength of the pending item if either of these
// flags are set.
// We upgrade crawl-only as well as recursive; it indicates that
// we've recently just performed the stat and we want to avoid
// infinitely trying to stat-and-crawl
p->flags |= flags &
(W_PENDING_CRAWL_ONLY | W_PENDING_RECURSIVE | W_PENDING_IS_DESYNCED);
maybePruneObsoletedChildren(p->path, p->flags);
}
// Check the tree to see if there is a path that is earlier/higher in the
// filesystem than the input path; if there is, and it is recursive,
// return true to indicate that there is no need to track this new path
// due to the already scheduled higher level path.
bool PendingChanges::isObsoletedByContainingDir(const w_string& path) {
auto leaf = tree_.longestMatch((const uint8_t*)path.data(), path.size());
if (!leaf) {
return false;
}
auto p = leaf->value;
if ((p->flags & W_PENDING_RECURSIVE) &&
is_path_prefix(
path.data(),
path.size(),
(const char*)leaf->key.data(),
leaf->key.size())) {
if (watchman::CookieSync::isPossiblyACookie(path)) {
return false;
}
// Yes: the pre-existing entry higher up in the tree obsoletes this
// one that we would add now.
logf(DBG, "is_obsoleted: SKIP {} is obsoleted by {}\n", path, p->path);
return true;
}
return false;
}
// Helper to doubly-link a pending item to the head of a collection.
void PendingChanges::linkHead(std::shared_ptr<watchman_pending_fs>&& p) {
p->prev.reset();
p->next = pending_;
if (p->next) {
p->next->prev = p;
}
pending_ = std::move(p);
}
// Helper to un-doubly-link a pending item.
void PendingChanges::unlinkItem(std::shared_ptr<watchman_pending_fs>& p) {
if (pending_ == p) {
pending_ = p->next;
}
auto prev = p->prev.lock();
if (prev) {
prev->next = p->next;
}
if (p->next) {
p->next->prev = prev;
}
p->next.reset();
p->prev.reset();
}
PendingCollectionBase::PendingCollectionBase(std::condition_variable& cond)
: cond_(cond) {}
void PendingCollectionBase::ping() {
pinged_ = true;
cond_.notify_all();
}
bool PendingCollectionBase::checkAndResetPinged() {
if (pending_ || pinged_) {
pinged_ = false;
return true;
}
return false;
}
PendingCollection::PendingCollection()
: folly::Synchronized<PendingCollectionBase, std::mutex>{
folly::in_place,
cond_} {}
PendingCollection::LockedPtr PendingCollection::lockAndWait(
std::chrono::milliseconds timeoutms,
bool& pinged) {
auto lock = this->lock();
if (lock->checkAndResetPinged()) {
pinged = true;
return lock;
}
if (timeoutms.count() == -1) {
cond_.wait(lock.getUniqueLock());
} else {
cond_.wait_for(lock.getUniqueLock(), timeoutms);
}
pinged = lock->checkAndResetPinged();
return lock;
}
/* vim:ts=2:sw=2:et:
*/
<|endoftext|> |
<commit_before>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <[email protected]>
#include "ArduCopterFirmwarePlugin.h"
#include "QGCApplication.h"
#include "MissionManager.h"
#include "ParameterManager.h"
bool ArduCopterFirmwarePlugin::_remapParamNameIntialized = false;
FirmwarePlugin::remapParamNameMajorVersionMap_t ArduCopterFirmwarePlugin::_remapParamName;
APMCopterMode::APMCopterMode(uint32_t mode, bool settable) :
APMCustomMode(mode, settable)
{
setEnumToStringMapping({
{ STABILIZE, "Stabilize"},
{ ACRO, "Acro"},
{ ALT_HOLD, "Altitude Hold"},
{ AUTO, "Auto"},
{ GUIDED, "Guided"},
{ LOITER, "Loiter"},
{ RTL, "RTL"},
{ CIRCLE, "Circle"},
{ LAND, "Land"},
{ DRIFT, "Drift"},
{ SPORT, "Sport"},
{ FLIP, "Flip"},
{ AUTOTUNE, "Autotune"},
{ POS_HOLD, "Position Hold"},
{ BRAKE, "Brake"},
{ THROW, "Throw"},
{ AVOID_ADSB, "Avoid ADSB"},
{ GUIDED_NOGPS, "Guided No GPS"},
{ SMART_RTL, "Smart RTL"},
{ FLOWHOLD, "Flow Hold" },
{ FOLLOW, "Follow" },
{ ZIGZAG, "ZigZag" },
});
}
ArduCopterFirmwarePlugin::ArduCopterFirmwarePlugin(void)
{
setSupportedModes({
APMCopterMode(APMCopterMode::STABILIZE, true),
APMCopterMode(APMCopterMode::ACRO, true),
APMCopterMode(APMCopterMode::ALT_HOLD, true),
APMCopterMode(APMCopterMode::AUTO, true),
APMCopterMode(APMCopterMode::GUIDED, true),
APMCopterMode(APMCopterMode::LOITER, true),
APMCopterMode(APMCopterMode::RTL, true),
APMCopterMode(APMCopterMode::CIRCLE, true),
APMCopterMode(APMCopterMode::LAND, true),
APMCopterMode(APMCopterMode::DRIFT, true),
APMCopterMode(APMCopterMode::SPORT, true),
APMCopterMode(APMCopterMode::FLIP, true),
APMCopterMode(APMCopterMode::AUTOTUNE, true),
APMCopterMode(APMCopterMode::POS_HOLD, true),
APMCopterMode(APMCopterMode::BRAKE, true),
APMCopterMode(APMCopterMode::THROW, true),
APMCopterMode(APMCopterMode::AVOID_ADSB, true),
APMCopterMode(APMCopterMode::GUIDED_NOGPS, true),
APMCopterMode(APMCopterMode::SMART_RTL, true),
APMCopterMode(APMCopterMode::FLOWHOLD, true),
APMCopterMode(APMCopterMode::FOLLOW, true),
APMCopterMode(APMCopterMode::ZIGZAG, true),
});
if (!_remapParamNameIntialized) {
FirmwarePlugin::remapParamNameMap_t& remapV3_6 = _remapParamName[3][6];
remapV3_6["BATT_AMP_PERVLT"] = QStringLiteral("BATT_AMP_PERVOL");
remapV3_6["BATT2_AMP_PERVLT"] = QStringLiteral("BATT2_AMP_PERVOL");
remapV3_6["BATT_LOW_MAH"] = QStringLiteral("FS_BATT_MAH");
remapV3_6["BATT_LOW_VOLT"] = QStringLiteral("FS_BATT_VOLTAGE");
remapV3_6["BATT_FS_LOW_ACT"] = QStringLiteral("FS_BATT_ENABLE");
remapV3_6["PSC_ACCZ_P"] = QStringLiteral("ACCEL_Z_P");
remapV3_6["PSC_ACCZ_I"] = QStringLiteral("ACCEL_Z_I");
FirmwarePlugin::remapParamNameMap_t& remapV3_7 = _remapParamName[3][7];
remapV3_7["BATT_ARM_VOLT"] = QStringLiteral("ARMING_VOLT_MIN");
remapV3_7["BATT2_ARM_VOLT"] = QStringLiteral("ARMING_VOLT2_MIN");
remapV3_7["RC7_OPTION"] = QStringLiteral("CH7_OPT");
remapV3_7["RC8_OPTION"] = QStringLiteral("CH8_OPT");
remapV3_7["RC9_OPTION"] = QStringLiteral("CH9_OPT");
remapV3_7["RC10_OPTION"] = QStringLiteral("CH10_OPT");
remapV3_7["RC11_OPTION"] = QStringLiteral("CH11_OPT");
remapV3_7["RC12_OPTION"] = QStringLiteral("CH12_OPT");
_remapParamNameIntialized = true;
}
}
int ArduCopterFirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const
{
// Remapping supports up to 3.7
return majorVersionNumber == 3 ? 7 : Vehicle::versionNotSetValue;
}
void ArduCopterFirmwarePlugin::guidedModeLand(Vehicle* vehicle)
{
_setFlightModeAndValidate(vehicle, "Land");
}
bool ArduCopterFirmwarePlugin::multiRotorCoaxialMotors(Vehicle* vehicle)
{
Q_UNUSED(vehicle);
return _coaxialMotors;
}
bool ArduCopterFirmwarePlugin::multiRotorXConfig(Vehicle* vehicle)
{
return vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, "FRAME")->rawValue().toInt() != 0;
}
bool ArduCopterFirmwarePlugin::vehicleYawsToNextWaypointInMission(const Vehicle* vehicle) const
{
if (vehicle->isOfflineEditingVehicle()) {
return FirmwarePlugin::vehicleYawsToNextWaypointInMission(vehicle);
} else {
if (vehicle->multiRotor() && vehicle->parameterManager()->parameterExists(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"))) {
Fact* yawMode = vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"));
return yawMode && yawMode->rawValue().toInt() != 0;
}
}
return true;
}
<commit_msg><commit_after>/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
/// @file
/// @author Don Gagne <[email protected]>
#include "ArduCopterFirmwarePlugin.h"
#include "QGCApplication.h"
#include "MissionManager.h"
#include "ParameterManager.h"
bool ArduCopterFirmwarePlugin::_remapParamNameIntialized = false;
FirmwarePlugin::remapParamNameMajorVersionMap_t ArduCopterFirmwarePlugin::_remapParamName;
APMCopterMode::APMCopterMode(uint32_t mode, bool settable) :
APMCustomMode(mode, settable)
{
setEnumToStringMapping({
{ STABILIZE, "Stabilize"},
{ ACRO, "Acro"},
{ ALT_HOLD, "Altitude Hold"},
{ AUTO, "Auto"},
{ GUIDED, "Guided"},
{ LOITER, "Loiter"},
{ RTL, "RTL"},
{ CIRCLE, "Circle"},
{ LAND, "Land"},
{ DRIFT, "Drift"},
{ SPORT, "Sport"},
{ FLIP, "Flip"},
{ AUTOTUNE, "Autotune"},
{ POS_HOLD, "Position Hold"},
{ BRAKE, "Brake"},
{ THROW, "Throw"},
{ AVOID_ADSB, "Avoid ADSB"},
{ GUIDED_NOGPS, "Guided No GPS"},
{ SMART_RTL, "Smart RTL"},
{ FLOWHOLD, "Flow Hold" },
{ FOLLOW, "Follow Vehicle" },
{ ZIGZAG, "ZigZag" },
});
}
ArduCopterFirmwarePlugin::ArduCopterFirmwarePlugin(void)
{
setSupportedModes({
APMCopterMode(APMCopterMode::STABILIZE, true),
APMCopterMode(APMCopterMode::ACRO, true),
APMCopterMode(APMCopterMode::ALT_HOLD, true),
APMCopterMode(APMCopterMode::AUTO, true),
APMCopterMode(APMCopterMode::GUIDED, true),
APMCopterMode(APMCopterMode::LOITER, true),
APMCopterMode(APMCopterMode::RTL, true),
APMCopterMode(APMCopterMode::CIRCLE, true),
APMCopterMode(APMCopterMode::LAND, true),
APMCopterMode(APMCopterMode::DRIFT, true),
APMCopterMode(APMCopterMode::SPORT, true),
APMCopterMode(APMCopterMode::FLIP, true),
APMCopterMode(APMCopterMode::AUTOTUNE, true),
APMCopterMode(APMCopterMode::POS_HOLD, true),
APMCopterMode(APMCopterMode::BRAKE, true),
APMCopterMode(APMCopterMode::THROW, true),
APMCopterMode(APMCopterMode::AVOID_ADSB, true),
APMCopterMode(APMCopterMode::GUIDED_NOGPS, true),
APMCopterMode(APMCopterMode::SMART_RTL, true),
APMCopterMode(APMCopterMode::FLOWHOLD, true),
APMCopterMode(APMCopterMode::FOLLOW, true),
APMCopterMode(APMCopterMode::ZIGZAG, true),
});
if (!_remapParamNameIntialized) {
FirmwarePlugin::remapParamNameMap_t& remapV3_6 = _remapParamName[3][6];
remapV3_6["BATT_AMP_PERVLT"] = QStringLiteral("BATT_AMP_PERVOL");
remapV3_6["BATT2_AMP_PERVLT"] = QStringLiteral("BATT2_AMP_PERVOL");
remapV3_6["BATT_LOW_MAH"] = QStringLiteral("FS_BATT_MAH");
remapV3_6["BATT_LOW_VOLT"] = QStringLiteral("FS_BATT_VOLTAGE");
remapV3_6["BATT_FS_LOW_ACT"] = QStringLiteral("FS_BATT_ENABLE");
remapV3_6["PSC_ACCZ_P"] = QStringLiteral("ACCEL_Z_P");
remapV3_6["PSC_ACCZ_I"] = QStringLiteral("ACCEL_Z_I");
FirmwarePlugin::remapParamNameMap_t& remapV3_7 = _remapParamName[3][7];
remapV3_7["BATT_ARM_VOLT"] = QStringLiteral("ARMING_VOLT_MIN");
remapV3_7["BATT2_ARM_VOLT"] = QStringLiteral("ARMING_VOLT2_MIN");
remapV3_7["RC7_OPTION"] = QStringLiteral("CH7_OPT");
remapV3_7["RC8_OPTION"] = QStringLiteral("CH8_OPT");
remapV3_7["RC9_OPTION"] = QStringLiteral("CH9_OPT");
remapV3_7["RC10_OPTION"] = QStringLiteral("CH10_OPT");
remapV3_7["RC11_OPTION"] = QStringLiteral("CH11_OPT");
remapV3_7["RC12_OPTION"] = QStringLiteral("CH12_OPT");
_remapParamNameIntialized = true;
}
}
int ArduCopterFirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const
{
// Remapping supports up to 3.7
return majorVersionNumber == 3 ? 7 : Vehicle::versionNotSetValue;
}
void ArduCopterFirmwarePlugin::guidedModeLand(Vehicle* vehicle)
{
_setFlightModeAndValidate(vehicle, "Land");
}
bool ArduCopterFirmwarePlugin::multiRotorCoaxialMotors(Vehicle* vehicle)
{
Q_UNUSED(vehicle);
return _coaxialMotors;
}
bool ArduCopterFirmwarePlugin::multiRotorXConfig(Vehicle* vehicle)
{
return vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, "FRAME")->rawValue().toInt() != 0;
}
bool ArduCopterFirmwarePlugin::vehicleYawsToNextWaypointInMission(const Vehicle* vehicle) const
{
if (vehicle->isOfflineEditingVehicle()) {
return FirmwarePlugin::vehicleYawsToNextWaypointInMission(vehicle);
} else {
if (vehicle->multiRotor() && vehicle->parameterManager()->parameterExists(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"))) {
Fact* yawMode = vehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, QStringLiteral("WP_YAW_BEHAVIOR"));
return yawMode && yawMode->rawValue().toInt() != 0;
}
}
return true;
}
<|endoftext|> |
<commit_before>#include "Graphics.h"
#include <SDL2_gfxPrimitives.h>
#include <SDL_ttf.h>
Graphics::Graphics(const int WIDTH, const int HEIGHT) : SCREEN_WIDTH(WIDTH), SCREEN_HEIGHT(HEIGHT)
{
window = createWindow("pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_RESIZABLE);
renderer = createRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED);
}
std::unique_ptr<SDL_Window, SDL2Graphics::SDL2Graphics_Deleter>
Graphics::createWindow(char const *title, int x, int y, int w, int h, Uint32 flags)
{
return std::unique_ptr<SDL_Window, SDL2Graphics::SDL2Graphics_Deleter>(SDL_CreateWindow(title, x, y, w, h, flags), SDL2Graphics::SDL2Graphics_Deleter());
}
std::unique_ptr<SDL_Renderer, SDL2Graphics::SDL2Graphics_Deleter>
Graphics::createRenderer(SDL_Window *window, int index, Uint32 flags)
{
return std::unique_ptr<SDL_Renderer, SDL2Graphics::SDL2Graphics_Deleter>(SDL_CreateRenderer(window, index, flags), SDL2Graphics::SDL2Graphics_Deleter());
}
std::unique_ptr<SDL_Texture, SDL2Graphics::SDL2Graphics_Deleter>
Graphics::createTextTexture(SDL_Surface *textSurface)
{
return std::unique_ptr<SDL_Texture, SDL2Graphics::SDL2Graphics_Deleter>
(SDL_CreateTextureFromSurface(renderer.get(), textSurface), SDL2Graphics::SDL2Graphics_Deleter());
}
SDL_Window *Graphics::getWindowScreen()
{
return window.get();
}
void Graphics::drawToScreen(SDL_Rect *playerRect, SDL_Rect *AIRect, Sint16 ballCenterX, Sint16 ballCenterY,
Sint16 ballRadius, std::string playerScoreText, std::string AIScoreText)
{
SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255);
SDL_RenderClear(renderer.get());
SDL_SetRenderDrawColor(renderer.get(), 255, 255, 255, 255);
drawHorizontalBoxes();
drawVerticalLine();
drawScore(playerScoreText.c_str(), AIScoreText.c_str());
Sint16 playPaddleXPos1 = (Sint16)playerPaddle->PADDLE_X_POSITION;
Sint16 playPaddleXPos2 = playPaddleXPos1 + playerPaddle->PADDLE_WIDTH;
Sint16 playPaddleYPos1 = (Sint16)playerPaddle->getYPosition();
Sint16 playPaddleYPos2 = playPaddleYPos1 + playerPaddle->PADDLE_HEIGHT;
boxRGBA(renderer.get(), playPaddleXPos1, playPaddleYPos1, playPaddleXPos2, playPaddleYPos2, 255, 255, 255, 255);
Sint16 AIPaddleXPos1 = (Sint16)AIPaddle->PADDLE_X_POSITION;
Sint16 AIPaddleXPos2 = AIPaddleXPos1 + AIPaddle->PADDLE_WIDTH;
Sint16 AIPaddleYPos1 = (Sint16)AIPaddle->getYPosition();
Sint16 AIPaddleYPos2 = AIPaddleYPos1 + AIPaddle->PADDLE_HEIGHT;
boxRGBA(renderer.get(), AIPaddleXPos1, AIPaddleYPos1, AIPaddleXPos2, AIPaddleYPos2, 255, 255, 255, 255);
filledCircleRGBA(renderer.get(), (Sint16)ball->getCenterX(), (Sint16)ball->getCenterY(), (Sint16)ball->RADIUS, 255, 255, 255, 255);
SDL_RenderPresent(renderer.get());
}
void Graphics::drawScore(const char *playerScoreText, const char *AIScoreText)
{
TTF_Font *pixelFont = TTF_OpenFont("slkscr.ttf", 60);
SDL_Color textColor = {255, 255, 255, 255};
SDL_Surface *playerTextSurface = TTF_RenderText_Solid(pixelFont, playerScoreText, textColor);
SDL_Surface *AiTextSurface = TTF_RenderText_Solid(pixelFont, AIScoreText, textColor);
playerScoreTexture = createTextTexture(playerTextSurface);
AIScoreTexture = createTextTexture(AiTextSurface);
SDL_FreeSurface(playerTextSurface);
SDL_FreeSurface(AiTextSurface);
playerTextSurface = nullptr;
AiTextSurface = nullptr;
SDL_Rect playerTextRect;
playerTextRect.x = (SCREEN_WIDTH / 2) - 52, playerTextRect.y = 20;
SDL_QueryTexture(playerScoreTexture.get(), NULL, NULL, &playerTextRect.w, &playerTextRect.h);
SDL_Rect AiTextRect;
AiTextRect.x = (SCREEN_WIDTH / 2) + 10, AiTextRect.y = 20;
SDL_QueryTexture(AIScoreTexture.get(), NULL, NULL, &AiTextRect.w, &AiTextRect.h);
SDL_RenderCopy(renderer.get(), playerScoreTexture.get(), NULL, &playerTextRect);
SDL_RenderCopy(renderer.get(), AIScoreTexture.get(), NULL, &AiTextRect);
TTF_CloseFont(pixelFont);
}
void Graphics:: drawVerticalLine()
{
int x = SCREEN_WIDTH / 2;
int verticalMaxHeight = SCREEN_HEIGHT - 20;
for (int y = 20; y < verticalMaxHeight; y += 6)
{
SDL_RenderDrawPoint(renderer.get(), x, y);
}
}
void Graphics::drawHorizontalBoxes()
{
SDL_Rect topHorizontalBox = {0, 0, SCREEN_WIDTH, 10};
SDL_RenderFillRect(renderer.get(), &topHorizontalBox);
SDL_Rect bottomHorizontalBox = { 0, SCREEN_HEIGHT - 10, SCREEN_WIDTH, 10};
SDL_RenderFillRect(renderer.get(), &bottomHorizontalBox);
}
<commit_msg>Update Graphics.cpp<commit_after>#include "Graphics.h"
#include "Paddle.h"
#include "Ball.h"
#include <SDL2_gfxPrimitives.h>
#include <SDL_ttf.h>
#include <string>
Graphics::Graphics(const int WIDTH, const int HEIGHT) : SCREEN_WIDTH(WIDTH), SCREEN_HEIGHT(HEIGHT)
{
window = createWindow("pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_RESIZABLE);
renderer = createRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED);
}
std::unique_ptr<SDL_Window, SDL2Graphics::SDL2Graphics_Deleter>
Graphics::createWindow(char const *title, int x, int y, int w, int h, Uint32 flags)
{
return std::unique_ptr<SDL_Window, SDL2Graphics::SDL2Graphics_Deleter>(SDL_CreateWindow(title, x, y, w, h, flags), SDL2Graphics::SDL2Graphics_Deleter());
}
std::unique_ptr<SDL_Renderer, SDL2Graphics::SDL2Graphics_Deleter>
Graphics::createRenderer(SDL_Window *window, int index, Uint32 flags)
{
return std::unique_ptr<SDL_Renderer, SDL2Graphics::SDL2Graphics_Deleter>(SDL_CreateRenderer(window, index, flags), SDL2Graphics::SDL2Graphics_Deleter());
}
std::unique_ptr<SDL_Texture, SDL2Graphics::SDL2Graphics_Deleter>
Graphics::createTextTexture(SDL_Surface *textSurface)
{
return std::unique_ptr<SDL_Texture, SDL2Graphics::SDL2Graphics_Deleter>
(SDL_CreateTextureFromSurface(renderer.get(), textSurface), SDL2Graphics::SDL2Graphics_Deleter());
}
SDL_Window *Graphics::getWindowScreen()
{
return window.get();
}
void Graphics::drawToScreen(Paddle *playerPaddle, Paddle *AIPaddle, Ball *ball, unsigned int playerScore, unsigned int AIScore)
{
SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255);
SDL_RenderClear(renderer.get());
SDL_SetRenderDrawColor(renderer.get(), 255, 255, 255, 255);
drawHorizontalBoxes();
drawVerticalLine();
std::string playerScoreText = std::to_string(playerScore);
std::string AIScoreText = std::to_string(AIScore);
drawScore(playerScoreText.c_str(), AIScoreText.c_str());
Sint16 playPaddleXPos1 = (Sint16)playerPaddle->PADDLE_X_POSITION;
Sint16 playPaddleXPos2 = playPaddleXPos1 + playerPaddle->PADDLE_WIDTH;
Sint16 playPaddleYPos1 = (Sint16)playerPaddle->getYPosition();
Sint16 playPaddleYPos2 = playPaddleYPos1 + playerPaddle->PADDLE_HEIGHT;
boxRGBA(renderer.get(), playPaddleXPos1, playPaddleYPos1, playPaddleXPos2, playPaddleYPos2, 255, 255, 255, 255);
Sint16 AIPaddleXPos1 = (Sint16)AIPaddle->PADDLE_X_POSITION;
Sint16 AIPaddleXPos2 = AIPaddleXPos1 + AIPaddle->PADDLE_WIDTH;
Sint16 AIPaddleYPos1 = (Sint16)AIPaddle->getYPosition();
Sint16 AIPaddleYPos2 = AIPaddleYPos1 + AIPaddle->PADDLE_HEIGHT;
boxRGBA(renderer.get(), AIPaddleXPos1, AIPaddleYPos1, AIPaddleXPos2, AIPaddleYPos2, 255, 255, 255, 255);
filledCircleRGBA(renderer.get(), (Sint16)ball->getCenterX(), (Sint16)ball->getCenterY(), (Sint16)ball->RADIUS, 255, 255, 255, 255);
SDL_RenderPresent(renderer.get());
}
void Graphics::drawScore(const char *playerScoreText, const char *AIScoreText)
{
TTF_Font *pixelFont = TTF_OpenFont("slkscr.ttf", 60);
SDL_Color textColor = {255, 255, 255, 255};
SDL_Surface *playerTextSurface = TTF_RenderText_Solid(pixelFont, playerScoreText, textColor);
SDL_Surface *AiTextSurface = TTF_RenderText_Solid(pixelFont, AIScoreText, textColor);
playerScoreTexture = createTextTexture(playerTextSurface);
AIScoreTexture = createTextTexture(AiTextSurface);
SDL_FreeSurface(playerTextSurface);
SDL_FreeSurface(AiTextSurface);
playerTextSurface = nullptr;
AiTextSurface = nullptr;
int playerTextWidth;
TTF_SizeText(pixelFont, playerScoreText, &playerTextWidth, NULL);
SDL_Rect playerTextRect;
playerTextRect.x = (SCREEN_WIDTH / 2) - playerTextWidth - 5, playerTextRect.y = 20;
SDL_QueryTexture(playerScoreTexture.get(), NULL, NULL, &playerTextRect.w, &playerTextRect.h);
SDL_Rect AiTextRect;
AiTextRect.x = (SCREEN_WIDTH / 2) + 10, AiTextRect.y = 20;
SDL_QueryTexture(AIScoreTexture.get(), NULL, NULL, &AiTextRect.w, &AiTextRect.h);
SDL_RenderCopy(renderer.get(), playerScoreTexture.get(), NULL, &playerTextRect);
SDL_RenderCopy(renderer.get(), AIScoreTexture.get(), NULL, &AiTextRect);
TTF_CloseFont(pixelFont);
}
void Graphics:: drawVerticalLine()
{
int x = SCREEN_WIDTH / 2;
int verticalMaxHeight = SCREEN_HEIGHT - 20;
for (int y = 20; y < verticalMaxHeight; y += 6)
{
SDL_RenderDrawPoint(renderer.get(), x, y);
}
}
void Graphics::drawHorizontalBoxes()
{
SDL_Rect topHorizontalBox = {0, 0, SCREEN_WIDTH, 10};
SDL_RenderFillRect(renderer.get(), &topHorizontalBox);
SDL_Rect bottomHorizontalBox = { 0, SCREEN_HEIGHT - 10, SCREEN_WIDTH, 10};
SDL_RenderFillRect(renderer.get(), &bottomHorizontalBox);
}
<|endoftext|> |
<commit_before>/*
* RGBTools
* Version 1 November, 2012
* Copyright 2012 Johannes Mittendorfer
*
* Use this code with RGB-LEDs.
*/
#include "RGBTools.h"
// pins for colors
int r_pin;
int g_pin;
int b_pin;
// saves current state (color)
int curr_r = 0;
int curr_g = 0;
int curr_b = 0;
// constructor; saves the pins
RGBTools::RGBTools(int r, int g, int b){
r_pin = r;
g_pin = g;
b_pin = b;
}
// Set LED-color to custom color instantely
void RGBTools::setColor(int r, int g, int b){
// set color of LED
analogWrite(r_pin,255-r);
analogWrite(g_pin,255-g);
analogWrite(b_pin,255-b);
// save state
curr_r = r;
curr_g = g;
curr_b = b;
}
// Fade to custom color in specific time in specific steps
void RGBTools::fadeTo(int r,int g,int b,int steps,int duration){
// calculate differance to target
float diff_r = r-curr_r;
float diff_g = g-curr_g;
float diff_b = b-curr_b;
// calculate the width of each step
float steps_r = diff_r / steps;
float steps_g = diff_g / steps;
float steps_b = diff_b / steps;
// loop through the steps
for(int i = 0; i < steps; i++){
// set color of current step
this->setColor(
r + i*steps_r, // red part plus i times the value of one step
g + i*steps_g, // green part plus i times the value of one step
b + i*steps_b // blue part plus i times the value of one step
);
// delay until next step
delay(duration/steps);
}
// save state
curr_r = r;
curr_g = g;
curr_b = b;
}
<commit_msg>fixed version code<commit_after>/*
* RGBTools
* Version 1.0 November, 2012
* Copyright 2012 Johannes Mittendorfer
*
* Use this code with RGB-LEDs.
*/
#include "RGBTools.h"
// pins for colors
int r_pin;
int g_pin;
int b_pin;
// saves current state (color)
int curr_r = 0;
int curr_g = 0;
int curr_b = 0;
// constructor; saves the pins
RGBTools::RGBTools(int r, int g, int b){
r_pin = r;
g_pin = g;
b_pin = b;
}
// Set LED-color to custom color instantely
void RGBTools::setColor(int r, int g, int b){
// set color of LED
analogWrite(r_pin,255-r);
analogWrite(g_pin,255-g);
analogWrite(b_pin,255-b);
// save state
curr_r = r;
curr_g = g;
curr_b = b;
}
// Fade to custom color in specific time in specific steps
void RGBTools::fadeTo(int r,int g,int b,int steps,int duration){
// calculate differance to target
float diff_r = r-curr_r;
float diff_g = g-curr_g;
float diff_b = b-curr_b;
// calculate the width of each step
float steps_r = diff_r / steps;
float steps_g = diff_g / steps;
float steps_b = diff_b / steps;
// loop through the steps
for(int i = 0; i < steps; i++){
// set color of current step
this->setColor(
r + i*steps_r, // red part plus i times the value of one step
g + i*steps_g, // green part plus i times the value of one step
b + i*steps_b // blue part plus i times the value of one step
);
// delay until next step
delay(duration/steps);
}
// save state
curr_r = r;
curr_g = g;
curr_b = b;
}
<|endoftext|> |
<commit_before>#include <config.h>
#include <assert.h>
#include <boost/concept/usage.hpp>
#include <boost/format.hpp>
#include <dune/common/exceptions.hh>
#include <dune/fem/io/file/dataoutput.hh>
#include <dune/fem/io/parameter.hh>
#include <dune/istl/scalarproducts.hh>
#include <dune/istl/solvers.hh>
#include <dune/multiscale/msfem/localproblems/localoperator.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
#include <dune/stuff/functions/norm.hh>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "dune/multiscale/msfem/localproblems/subgrid-list.hh"
#include "dune/multiscale/tools/misc/outputparameter.hh"
#include "localproblemsolver.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
/** \brief define output parameters for local problems
* appends "local_problems" for path
**/
struct LocalProblemDataOutputParameters : public OutputParameters {
public:
explicit LocalProblemDataOutputParameters();
};
LocalProblemDataOutputParameters::LocalProblemDataOutputParameters()
: OutputParameters(DSC_CONFIG_GET("global.datadir", "data") + "/local_problems/") {}
LocalProblemSolver::LocalProblemSolver(const CommonTraits::DiscreteFunctionSpaceType& coarse_space,
LocalGridList& subgrid_list,
const CommonTraits::DiffusionType& diffusion_operator)
: diffusion_(diffusion_operator)
, subgrid_list_(subgrid_list)
, coarse_space_(coarse_space) {}
void LocalProblemSolver::solve_all_on_single_cell(const MsFEMTraits::CoarseEntityType& coarseCell,
MsFEMTraits::LocalSolutionVectorType& allLocalSolutions) const {
assert(allLocalSolutions.size() > 0);
const bool hasBoundary = coarseCell.hasBoundaryIntersections();
const auto numBoundaryCorrectors = DSG::is_simplex_grid(coarse_space_) ? 1u : 2u;
const auto numInnerCorrectors = allLocalSolutions.size() - numBoundaryCorrectors;
// clear return argument
for (auto& localSol : allLocalSolutions)
localSol->clear();
const auto& subDiscreteFunctionSpace = allLocalSolutions[0]->space();
//! define the discrete (elliptic) local MsFEM problem operator
// ( effect of the discretized differential operator on a certain discrete function )
LocalProblemOperator localProblemOperator(coarse_space_, subDiscreteFunctionSpace, diffusion_);
// right hand side vector of the algebraic local MsFEM problem
MsFEMTraits::LocalSolutionVectorType allLocalRHS(allLocalSolutions.size());
for (auto& it : allLocalRHS)
it = DSC::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>("rhs of local MsFEM problem",
subDiscreteFunctionSpace);
localProblemOperator.assemble_all_local_rhs(coarseCell, allLocalRHS);
for (auto i : DSC::valueRange(allLocalSolutions.size())) {
auto& current_rhs = *allLocalRHS[i];
auto& current_solution = *allLocalSolutions[i];
// is the right hand side of the local MsFEM problem equal to zero or almost identical to zero?
// if yes, the solution of the local MsFEM problem is also identical to zero. The solver is getting a problem with
// this situation, which is why we do not solve local msfem problems for zero-right-hand-side, since we already know
// the result.
if (DS::l2norm(current_rhs) < 1e-12) {
current_solution.clear();
DSC_LOG_DEBUG << "Local MsFEM problem with solution zero." << std::endl;
continue;
}
// don't solve local problems for boundary correctors if coarse cell has no boundary intersections
if (i >= numInnerCorrectors && !hasBoundary) {
current_solution.clear();
DSC_LOG_DEBUG << "Zero-Boundary corrector." << std::endl;
continue;
}
localProblemOperator.apply_inverse(current_rhs, current_solution);
}
}
void LocalProblemSolver::solve_for_all_cells() {
static const int dimension = CommonTraits::GridType::dimension;
JacobianRangeType unitVectors[dimension];
for (int i = 0; i < dimension; ++i)
for (int j = 0; j < dimension; ++j) {
if (i == j) {
unitVectors[i][0][j] = 1.0;
} else {
unitVectors[i][0][j] = 0.0;
}
}
// number of coarse grid entities (of codim 0).
const auto coarseGridSize = coarse_space_.grid().size(0);
if (Dune::Fem::MPIManager::size() > 0)
DSC_LOG_DEBUG << "Rank " << Dune::Fem::MPIManager::rank() << " will solve local problems for " << coarseGridSize
<< " coarse entities!" << std::endl;
else {
DSC_LOG_DEBUG << "Will solve local problems for " << coarseGridSize << " coarse entities!" << std::endl;
}
DSC_PROFILER.startTiming("msfem.localProblemSolver.solveAndSaveAll");
// we want to determine minimum, average and maxiumum time for solving a local msfem problem in the current method
DSC::MinMaxAvg<double> solveTime;
const auto& coarseGridLeafIndexSet = coarse_space_.gridPart().grid().leafIndexSet();
for (const auto& coarseEntity : coarse_space_) {
const int coarse_index = coarseGridLeafIndexSet.index(coarseEntity);
DSC_LOG_DEBUG << "-------------------------" << std::endl << "Coarse index " << coarse_index << std::endl;
// take time
DSC_PROFILER.startTiming("msfem.localProblemSolver.solve");
LocalSolutionManager localSolutionManager(coarse_space_, coarseEntity, subgrid_list_);
// solve the problems
solve_all_on_single_cell(coarseEntity, localSolutionManager.getLocalSolutions());
solveTime(DSC_PROFILER.stopTiming("msfem.localProblemSolver.solve") / 1000.f);
// save the local solutions to disk/mem
localSolutionManager.save();
DSC_PROFILER.resetTiming("msfem.localProblemSolver.solve");
} // for
//! @todo The following debug-output is wrong (number of local problems may be different)
const auto totalTime = DSC_PROFILER.stopTiming("msfem.localProblemSolver.solveAndSaveAll") / 1000.f;
DSC_LOG_DEBUG << "Local problems solved for " << coarseGridSize << " coarse grid entities.\n";
DSC_LOG_DEBUG << "Minimum time for solving a local problem = " << solveTime.min() << "s.\n";
DSC_LOG_DEBUG << "Maximum time for solving a local problem = " << solveTime.max() << "s.\n";
DSC_LOG_DEBUG << "Average time for solving a local problem = " << solveTime.average() << "s.\n";
DSC_LOG_DEBUG << "Total time for computing and saving the localproblems = "
<< totalTime << "s on rank" << Dune::Fem::MPIManager::rank() << std::endl;
} // assemble_all
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>[localProblemSolver] Output correct number of local problems<commit_after>#include <config.h>
#include <assert.h>
#include <boost/concept/usage.hpp>
#include <boost/format.hpp>
#include <dune/common/exceptions.hh>
#include <dune/fem/io/file/dataoutput.hh>
#include <dune/fem/io/parameter.hh>
#include <dune/istl/scalarproducts.hh>
#include <dune/istl/solvers.hh>
#include <dune/multiscale/msfem/localproblems/localoperator.hh>
#include <dune/multiscale/problems/selector.hh>
#include <dune/multiscale/tools/discretefunctionwriter.hh>
#include <dune/multiscale/msfem/localproblems/localsolutionmanager.hh>
#include <dune/multiscale/tools/misc.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/parameter/configcontainer.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/fem/localmatrix_proxy.hh>
#include <dune/stuff/functions/norm.hh>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include "dune/multiscale/msfem/localproblems/subgrid-list.hh"
#include "dune/multiscale/tools/misc/outputparameter.hh"
#include "localproblemsolver.hh"
namespace Dune {
namespace Multiscale {
namespace MsFEM {
/** \brief define output parameters for local problems
* appends "local_problems" for path
**/
struct LocalProblemDataOutputParameters : public OutputParameters {
public:
explicit LocalProblemDataOutputParameters();
};
LocalProblemDataOutputParameters::LocalProblemDataOutputParameters()
: OutputParameters(DSC_CONFIG_GET("global.datadir", "data") + "/local_problems/") {}
LocalProblemSolver::LocalProblemSolver(const CommonTraits::DiscreteFunctionSpaceType& coarse_space,
LocalGridList& subgrid_list,
const CommonTraits::DiffusionType& diffusion_operator)
: diffusion_(diffusion_operator)
, subgrid_list_(subgrid_list)
, coarse_space_(coarse_space) {}
void LocalProblemSolver::solve_all_on_single_cell(const MsFEMTraits::CoarseEntityType& coarseCell,
MsFEMTraits::LocalSolutionVectorType& allLocalSolutions) const {
assert(allLocalSolutions.size() > 0);
const bool hasBoundary = coarseCell.hasBoundaryIntersections();
const auto numBoundaryCorrectors = DSG::is_simplex_grid(coarse_space_) ? 1u : 2u;
const auto numInnerCorrectors = allLocalSolutions.size() - numBoundaryCorrectors;
// clear return argument
for (auto& localSol : allLocalSolutions)
localSol->clear();
const auto& subDiscreteFunctionSpace = allLocalSolutions[0]->space();
//! define the discrete (elliptic) local MsFEM problem operator
// ( effect of the discretized differential operator on a certain discrete function )
LocalProblemOperator localProblemOperator(coarse_space_, subDiscreteFunctionSpace, diffusion_);
// right hand side vector of the algebraic local MsFEM problem
MsFEMTraits::LocalSolutionVectorType allLocalRHS(allLocalSolutions.size());
for (auto& it : allLocalRHS)
it = DSC::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>("rhs of local MsFEM problem",
subDiscreteFunctionSpace);
localProblemOperator.assemble_all_local_rhs(coarseCell, allLocalRHS);
for (auto i : DSC::valueRange(allLocalSolutions.size())) {
auto& current_rhs = *allLocalRHS[i];
auto& current_solution = *allLocalSolutions[i];
// is the right hand side of the local MsFEM problem equal to zero or almost identical to zero?
// if yes, the solution of the local MsFEM problem is also identical to zero. The solver is getting a problem with
// this situation, which is why we do not solve local msfem problems for zero-right-hand-side, since we already know
// the result.
if (DS::l2norm(current_rhs) < 1e-12) {
current_solution.clear();
DSC_LOG_DEBUG << "Local MsFEM problem with solution zero." << std::endl;
continue;
}
// don't solve local problems for boundary correctors if coarse cell has no boundary intersections
if (i >= numInnerCorrectors && !hasBoundary) {
current_solution.clear();
DSC_LOG_DEBUG << "Zero-Boundary corrector." << std::endl;
continue;
}
localProblemOperator.apply_inverse(current_rhs, current_solution);
}
}
void LocalProblemSolver::solve_for_all_cells() {
static const int dimension = CommonTraits::GridType::dimension;
JacobianRangeType unitVectors[dimension];
for (int i = 0; i < dimension; ++i)
for (int j = 0; j < dimension; ++j) {
if (i == j) {
unitVectors[i][0][j] = 1.0;
} else {
unitVectors[i][0][j] = 0.0;
}
}
// number of coarse grid entities (of codim 0).
const auto coarseGridSize = coarse_space_.grid().size(0) - coarse_space_.grid().overlapSize(0);
if (Dune::Fem::MPIManager::size() > 0)
DSC_LOG_DEBUG << "Rank " << Dune::Fem::MPIManager::rank() << " will solve local problems for " << coarseGridSize
<< " coarse entities!" << std::endl;
else {
DSC_LOG_DEBUG << "Will solve local problems for " << coarseGridSize << " coarse entities!" << std::endl;
}
DSC_PROFILER.startTiming("msfem.localProblemSolver.solveAndSaveAll");
// we want to determine minimum, average and maxiumum time for solving a local msfem problem in the current method
DSC::MinMaxAvg<double> solveTime;
const auto& coarseGridLeafIndexSet = coarse_space_.gridPart().grid().leafIndexSet();
for (const auto& coarseEntity : coarse_space_) {
const int coarse_index = coarseGridLeafIndexSet.index(coarseEntity);
DSC_LOG_DEBUG << "-------------------------" << std::endl << "Coarse index " << coarse_index << std::endl;
// take time
DSC_PROFILER.startTiming("msfem.localProblemSolver.solve");
LocalSolutionManager localSolutionManager(coarse_space_, coarseEntity, subgrid_list_);
// solve the problems
solve_all_on_single_cell(coarseEntity, localSolutionManager.getLocalSolutions());
solveTime(DSC_PROFILER.stopTiming("msfem.localProblemSolver.solve") / 1000.f);
// save the local solutions to disk/mem
localSolutionManager.save();
DSC_PROFILER.resetTiming("msfem.localProblemSolver.solve");
} // for
//! @todo The following debug-output is wrong (number of local problems may be different)
const auto totalTime = DSC_PROFILER.stopTiming("msfem.localProblemSolver.solveAndSaveAll") / 1000.f;
DSC_LOG_DEBUG << "Local problems solved for " << coarseGridSize << " coarse grid entities.\n";
DSC_LOG_DEBUG << "Minimum time for solving a local problem = " << solveTime.min() << "s.\n";
DSC_LOG_DEBUG << "Maximum time for solving a local problem = " << solveTime.max() << "s.\n";
DSC_LOG_DEBUG << "Average time for solving a local problem = " << solveTime.average() << "s.\n";
DSC_LOG_DEBUG << "Total time for computing and saving the localproblems = "
<< totalTime << "s on rank" << Dune::Fem::MPIManager::rank() << std::endl;
} // assemble_all
} // namespace MsFEM {
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|> |
<commit_before><commit_msg>Padding.<commit_after><|endoftext|> |
<commit_before>/* Copyright 2021 Sergei Bastrakov
*
* This file exemplifies usage of alpaka.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED “AS IS” AND ISC DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <alpaka/alpaka.hpp>
#include <alpaka/example/ExampleDefaultAcc.hpp>
#include <iostream>
//#############################################################################
//! Kernel to illustrate specialization for a particular accelerator
//!
//! It has a general operator() implementation and a specialized one for the CUDA accelerator.
//! When running the kernel on a CUDA device, the specialized version of operator() is called.
//! Otherwise the general version is called.
//! The same technique can be applied for any function called from inside the kernel,
//! thus allowing specialization of only relevant part of the code.
//! It can be useful for optimization or accessing specific functionality not abstracted by alpaka.
struct Kernel
{
//-----------------------------------------------------------------------------
//! Implementation for the general case
//!
//! It will be called when no specialization is a better fit.
template<typename TAcc>
ALPAKA_FN_ACC auto operator()(TAcc const& acc) const
{
// For simplicity assume 1d thread indexing
auto const globalThreadIdx = alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0];
if(globalThreadIdx == 0u)
printf("Running the general kernel implementation\n");
}
//! Simple partial specialization for the CUDA accelerator
//!
//! We have to guard it with #ifdef as the types of alpaka accelerators are only conditionally available.
//! Specialization for other accelerators is similar, with another template name instead of AccGpuCudaRt.
#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED
template<typename TDim, typename TIdx>
ALPAKA_FN_ACC auto operator()(alpaka::AccGpuCudaRt<TDim, TIdx> const& acc) const
{
// This specialization is used when the kernel is run on the CUDA accelerator.
// So inside we can use both alpaka and native CUDA directly.
// For simplicity assume 1d thread indexing
auto const globalThreadIdx = blockIdx.x * gridDim.x + threadIdx.x;
if(globalThreadIdx == 0)
printf("Running the specialization for the CUDA accelerator\n");
}
#endif
};
auto main() -> int
{
// Fallback for the CI with disabled sequential backend
#if defined(ALPAKA_CI) && !defined(ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED)
return EXIT_SUCCESS;
#else
// Define the accelerator
//
// It is possible to choose from a set of accelerators:
// - AccGpuCudaRt
// - AccGpuHipRt
// - AccCpuThreads
// - AccCpuFibers
// - AccCpuOmp2Threads
// - AccCpuOmp2Blocks
// - AccOmp5
// - AccCpuTbbBlocks
// - AccCpuSerial
//
// For simplicity this examples always uses 1 dimensional indexing, and index type size_t
using Acc = alpaka::ExampleDefaultAcc<alpaka::DimInt<1>, std::size_t>;
std::cout << "Using alpaka accelerator: " << alpaka::getAccName<Acc>() << std::endl;
// Defines the synchronization behavior of a queue
using QueueProperty = alpaka::Blocking;
using Queue = alpaka::Queue<Acc, QueueProperty>;
// Select a device
auto const devAcc = alpaka::getDevByIdx<Acc>(0u);
// Create a queue on the device
Queue queue(devAcc);
// Define the work division
std::size_t const threadsPerGrid = 16u;
std::size_t const elementsPerThread = 1u;
auto const workDiv = alpaka::getValidWorkDiv<Acc>(
devAcc,
threadsPerGrid,
elementsPerThread,
false,
alpaka::GridBlockExtentSubDivRestrictions::Unrestricted);
// Run the kernel
alpaka::exec<Acc>(queue, workDiv, Kernel{});
alpaka::wait(queue);
return EXIT_SUCCESS;
#endif
}
<commit_msg>Address reviewers' comments<commit_after>/* Copyright 2021 Sergei Bastrakov
*
* This file exemplifies usage of alpaka.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED “AS IS” AND ISC DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <alpaka/alpaka.hpp>
#include <alpaka/example/ExampleDefaultAcc.hpp>
#include <iostream>
//#############################################################################
//! Kernel to illustrate specialization for a particular accelerator
//!
//! It has a generic operator() implementation and an overload for the CUDA accelerator.
//! When running the kernel on a CUDA device, the corresponding overload of operator() is called.
//! Otherwise the generic version is called.
//! The same technique can be applied for any function called from inside the kernel,
//! thus allowing specialization of only relevant part of the code.
//! It can be useful for optimization or accessing specific functionality not abstracted by alpaka.
//!
//! This kernel demonstrates the simplest way to achieve the effect by function overloading.
//! Note that it does not perform specialization (in C++ template meaning) of function templates.
//! We use the word "specialization" as it represents a case of having a special version for a particular accelerator.
//! One could apply a similar technique by having an additional class template parametrized by the accelerator type.
//! For such a case, both template specialization and function overloading of the methods can be employed.
struct Kernel
{
//-----------------------------------------------------------------------------
//! Implementation for the general case
//!
//! It will be called when no overload is a better match.
template<typename TAcc>
ALPAKA_FN_ACC auto operator()(TAcc const& acc) const
{
// For simplicity assume 1d thread indexing
auto const globalThreadIdx = alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0];
if(globalThreadIdx == 0u)
printf("Running the general kernel implementation\n");
}
//! Simple overload to have a special version for the CUDA accelerator
//!
//! We have to guard it with #ifdef as the types of alpaka accelerators are only conditionally available.
//! Overloading for other accelerators is similar, with another template name instead of AccGpuCudaRt.
#ifdef ALPAKA_ACC_GPU_CUDA_ENABLED
template<typename TDim, typename TIdx>
ALPAKA_FN_ACC auto operator()(alpaka::AccGpuCudaRt<TDim, TIdx> const& acc) const
{
// This overload is used when the kernel is run on the CUDA accelerator.
// So inside we can use both alpaka and native CUDA directly.
// For simplicity assume 1d thread indexing
auto const globalThreadIdx = blockIdx.x * gridDim.x + threadIdx.x;
if(globalThreadIdx == 0)
printf("Running the specialization for the CUDA accelerator\n");
}
#endif
};
auto main() -> int
{
// Fallback for the CI with disabled sequential backend
#if defined(ALPAKA_CI) && !defined(ALPAKA_ACC_CPU_B_SEQ_T_SEQ_ENABLED)
return EXIT_SUCCESS;
#else
// Define the accelerator
//
// It is possible to choose from a set of accelerators:
// - AccGpuCudaRt
// - AccGpuHipRt
// - AccCpuThreads
// - AccCpuFibers
// - AccCpuOmp2Threads
// - AccCpuOmp2Blocks
// - AccOmp5
// - AccCpuTbbBlocks
// - AccCpuSerial
//
// For simplicity this examples always uses 1 dimensional indexing, and index type size_t
using Acc = alpaka::ExampleDefaultAcc<alpaka::DimInt<1>, std::size_t>;
std::cout << "Using alpaka accelerator: " << alpaka::getAccName<Acc>() << std::endl;
// Defines the synchronization behavior of a queue
using QueueProperty = alpaka::Blocking;
using Queue = alpaka::Queue<Acc, QueueProperty>;
// Select a device
auto const devAcc = alpaka::getDevByIdx<Acc>(0u);
// Create a queue on the device
Queue queue(devAcc);
// Define the work division
std::size_t const threadsPerGrid = 16u;
std::size_t const elementsPerThread = 1u;
auto const workDiv = alpaka::getValidWorkDiv<Acc>(
devAcc,
threadsPerGrid,
elementsPerThread,
false,
alpaka::GridBlockExtentSubDivRestrictions::Unrestricted);
// Run the kernel
alpaka::exec<Acc>(queue, workDiv, Kernel{});
alpaka::wait(queue);
return EXIT_SUCCESS;
#endif
}
<|endoftext|> |
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "summarymanager.h"
#include "documentstoreadapter.h"
#include "summarycompacttarget.h"
#include "summaryflushtarget.h"
#include <vespa/config/print/ostreamconfigwriter.h>
#include <vespa/document/repo/documenttyperepo.h>
#include <vespa/juniper/rpinterface.h>
#include <vespa/searchcore/proton/flushengine/shrink_lid_space_flush_target.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/searchsummary/docsummary/docsumconfig.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/fastlib/text/normwordfolder.h>
#include <sstream>
#include <vespa/log/log.h>
LOG_SETUP(".proton.docsummary.summarymanager");
using namespace config;
using namespace document;
using namespace search::docsummary;
using namespace vespa::config::search::summary;
using namespace vespa::config::search;
using vespalib::make_string;
using vespalib::IllegalArgumentException;
using vespalib::compression::CompressionConfig;
using search::DocumentStore;
using search::IDocumentStore;
using search::LogDocumentStore;
using search::WriteableFileChunk;
using vespalib::makeLambdaTask;
using search::TuneFileSummary;
using search::common::FileHeaderContext;
using searchcorespi::IFlushTarget;
namespace proton {
namespace {
class ShrinkSummaryLidSpaceFlushTarget : public ShrinkLidSpaceFlushTarget
{
using ICompactableLidSpace = search::common::ICompactableLidSpace;
vespalib::Executor & _summaryService;
public:
ShrinkSummaryLidSpaceFlushTarget(const vespalib::string &name, Type type, Component component,
SerialNum flushedSerialNum, vespalib::system_time lastFlushTime,
vespalib::Executor & summaryService,
std::shared_ptr<ICompactableLidSpace> target);
~ShrinkSummaryLidSpaceFlushTarget() override;
Task::UP initFlush(SerialNum currentSerial, std::shared_ptr<search::IFlushToken> flush_token) override;
};
ShrinkSummaryLidSpaceFlushTarget::
ShrinkSummaryLidSpaceFlushTarget(const vespalib::string &name, Type type, Component component,
SerialNum flushedSerialNum, vespalib::system_time lastFlushTime,
vespalib::Executor & summaryService,
std::shared_ptr<ICompactableLidSpace> target)
: ShrinkLidSpaceFlushTarget(name, type, component, flushedSerialNum, lastFlushTime, std::move(target)),
_summaryService(summaryService)
{
}
ShrinkSummaryLidSpaceFlushTarget::~ShrinkSummaryLidSpaceFlushTarget() = default;
IFlushTarget::Task::UP
ShrinkSummaryLidSpaceFlushTarget::initFlush(SerialNum currentSerial, std::shared_ptr<search::IFlushToken> flush_token)
{
std::promise<Task::UP> promise;
std::future<Task::UP> future = promise.get_future();
_summaryService.execute(makeLambdaTask([&]() { promise.set_value(ShrinkLidSpaceFlushTarget::initFlush(currentSerial, flush_token)); }));
return future.get();
}
}
SummaryManager::SummarySetup::
SummarySetup(const vespalib::string & baseDir, const DocTypeName & docTypeName, const SummaryConfig & summaryCfg,
const SummarymapConfig & summarymapCfg, const JuniperrcConfig & juniperCfg,
search::IAttributeManager::SP attributeMgr, search::IDocumentStore::SP docStore,
std::shared_ptr<const DocumentTypeRepo> repo)
: _docsumWriter(),
_wordFolder(std::make_unique<Fast_NormalizeWordFolder>()),
_juniperProps(juniperCfg),
_juniperConfig(),
_attributeMgr(std::move(attributeMgr)),
_docStore(std::move(docStore)),
_fieldCacheRepo(),
_repo(repo),
_markupFields()
{
DocsumBlobEntryFilter docsum_blob_entry_filter;
docsum_blob_entry_filter.add_skip(RES_INT);
docsum_blob_entry_filter.add_skip(RES_SHORT);
docsum_blob_entry_filter.add_skip(RES_BOOL);
docsum_blob_entry_filter.add_skip(RES_BYTE);
docsum_blob_entry_filter.add_skip(RES_FLOAT);
docsum_blob_entry_filter.add_skip(RES_DOUBLE);
docsum_blob_entry_filter.add_skip(RES_INT64);
docsum_blob_entry_filter.add_skip(RES_JSONSTRING);
docsum_blob_entry_filter.add_skip(RES_TENSOR);
docsum_blob_entry_filter.add_skip(RES_FEATUREDATA);
auto resultConfig = std::make_unique<ResultConfig>(docsum_blob_entry_filter);
if (!resultConfig->ReadConfig(summaryCfg, make_string("SummaryManager(%s)", baseDir.c_str()).c_str())) {
std::ostringstream oss;
::config::OstreamConfigWriter writer(oss);
writer.write(summaryCfg);
throw IllegalArgumentException
(make_string("Could not initialize summary result config for directory '%s' based on summary config '%s'",
baseDir.c_str(), oss.str().c_str()));
}
_juniperConfig = std::make_unique<juniper::Juniper>(&_juniperProps, _wordFolder.get());
_docsumWriter = std::make_unique<DynamicDocsumWriter>(resultConfig.release(), nullptr);
DynamicDocsumConfig dynCfg(this, _docsumWriter.get());
dynCfg.configure(summarymapCfg);
for (const auto & o : summarymapCfg.override) {
if (o.command == "dynamicteaser" || o.command == "textextractor") {
vespalib::string markupField = o.arguments;
if (markupField.empty())
continue;
// Assume just one argument: source field that must contain markup
_markupFields.insert(markupField);
}
}
const DocumentType *docType = repo->getDocumentType(docTypeName.getName());
if (docType != nullptr) {
_fieldCacheRepo = std::make_unique<FieldCacheRepo>(getResultConfig(), *docType);
} else if (getResultConfig().GetNumResultClasses() == 0) {
LOG(debug, "Create empty field cache repo for document type '%s'", docTypeName.toString().c_str());
_fieldCacheRepo = std::make_unique<FieldCacheRepo>();
} else {
throw IllegalArgumentException(make_string("Did not find document type '%s' in current document type repo."
" Cannot setup field cache repo for the summary setup",
docTypeName.toString().c_str()));
}
}
IDocsumStore::UP
SummaryManager::SummarySetup::createDocsumStore(const vespalib::string &resultClassName) {
return std::make_unique<DocumentStoreAdapter>(*_docStore, *_repo, getResultConfig(), resultClassName,
_fieldCacheRepo->getFieldCache(resultClassName), _markupFields);
}
ISummaryManager::ISummarySetup::SP
SummaryManager::createSummarySetup(const SummaryConfig & summaryCfg, const SummarymapConfig & summarymapCfg,
const JuniperrcConfig & juniperCfg, const std::shared_ptr<const DocumentTypeRepo> &repo,
const search::IAttributeManager::SP &attributeMgr)
{
return std::make_shared<SummarySetup>(_baseDir, _docTypeName, summaryCfg, summarymapCfg,
juniperCfg, attributeMgr, _docStore, repo);
}
SummaryManager::SummaryManager(vespalib::Executor &shared_executor, const LogDocumentStore::Config & storeConfig,
const search::GrowStrategy & growStrategy, const vespalib::string &baseDir,
const DocTypeName &docTypeName, const TuneFileSummary &tuneFileSummary,
const FileHeaderContext &fileHeaderContext, search::transactionlog::SyncProxy &tlSyncer,
search::IBucketizer::SP bucketizer)
: _baseDir(baseDir),
_docTypeName(docTypeName),
_docStore()
{
_docStore = std::make_shared<LogDocumentStore>(shared_executor, baseDir, storeConfig, growStrategy, tuneFileSummary,
fileHeaderContext, tlSyncer, std::move(bucketizer));
}
SummaryManager::~SummaryManager() = default;
void
SummaryManager::putDocument(uint64_t syncToken, search::DocumentIdT lid, const Document & doc)
{
_docStore->write(syncToken, lid, doc);
}
void
SummaryManager::putDocument(uint64_t syncToken, search::DocumentIdT lid, const vespalib::nbostream & doc)
{
_docStore->write(syncToken, lid, doc);
}
void
SummaryManager::removeDocument(uint64_t syncToken, search::DocumentIdT lid)
{
_docStore->remove(syncToken, lid);
}
namespace {
IFlushTarget::SP
createShrinkLidSpaceFlushTarget(vespalib::Executor & summaryService, IDocumentStore::SP docStore)
{
return std::make_shared<ShrinkSummaryLidSpaceFlushTarget>("summary.shrink",
IFlushTarget::Type::GC,
IFlushTarget::Component::DOCUMENT_STORE,
docStore->lastSyncToken(),
docStore->getLastFlushTime(),
summaryService,
std::move(docStore));
}
}
IFlushTarget::List
SummaryManager::getFlushTargets(vespalib::Executor & summaryService)
{
IFlushTarget::List ret;
ret.push_back(std::make_shared<SummaryFlushTarget>(getBackingStore(), summaryService));
if (dynamic_cast<LogDocumentStore *>(_docStore.get()) != nullptr) {
ret.push_back(std::make_shared<SummaryCompactBloatTarget>(summaryService, getBackingStore()));
ret.push_back(std::make_shared<SummaryCompactSpreadTarget>(summaryService, getBackingStore()));
}
ret.push_back(createShrinkLidSpaceFlushTarget(summaryService, _docStore));
return ret;
}
void
SummaryManager::reconfigure(const LogDocumentStore::Config & config) {
auto & docStore = dynamic_cast<LogDocumentStore &> (*_docStore);
docStore.reconfigure(config);
}
} // namespace proton
<commit_msg>Stop storing data and longdata in docsum blobs for indexed search.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "summarymanager.h"
#include "documentstoreadapter.h"
#include "summarycompacttarget.h"
#include "summaryflushtarget.h"
#include <vespa/config/print/ostreamconfigwriter.h>
#include <vespa/document/repo/documenttyperepo.h>
#include <vespa/juniper/rpinterface.h>
#include <vespa/searchcore/proton/flushengine/shrink_lid_space_flush_target.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/searchsummary/docsummary/docsumconfig.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/fastlib/text/normwordfolder.h>
#include <sstream>
#include <vespa/log/log.h>
LOG_SETUP(".proton.docsummary.summarymanager");
using namespace config;
using namespace document;
using namespace search::docsummary;
using namespace vespa::config::search::summary;
using namespace vespa::config::search;
using vespalib::make_string;
using vespalib::IllegalArgumentException;
using vespalib::compression::CompressionConfig;
using search::DocumentStore;
using search::IDocumentStore;
using search::LogDocumentStore;
using search::WriteableFileChunk;
using vespalib::makeLambdaTask;
using search::TuneFileSummary;
using search::common::FileHeaderContext;
using searchcorespi::IFlushTarget;
namespace proton {
namespace {
class ShrinkSummaryLidSpaceFlushTarget : public ShrinkLidSpaceFlushTarget
{
using ICompactableLidSpace = search::common::ICompactableLidSpace;
vespalib::Executor & _summaryService;
public:
ShrinkSummaryLidSpaceFlushTarget(const vespalib::string &name, Type type, Component component,
SerialNum flushedSerialNum, vespalib::system_time lastFlushTime,
vespalib::Executor & summaryService,
std::shared_ptr<ICompactableLidSpace> target);
~ShrinkSummaryLidSpaceFlushTarget() override;
Task::UP initFlush(SerialNum currentSerial, std::shared_ptr<search::IFlushToken> flush_token) override;
};
ShrinkSummaryLidSpaceFlushTarget::
ShrinkSummaryLidSpaceFlushTarget(const vespalib::string &name, Type type, Component component,
SerialNum flushedSerialNum, vespalib::system_time lastFlushTime,
vespalib::Executor & summaryService,
std::shared_ptr<ICompactableLidSpace> target)
: ShrinkLidSpaceFlushTarget(name, type, component, flushedSerialNum, lastFlushTime, std::move(target)),
_summaryService(summaryService)
{
}
ShrinkSummaryLidSpaceFlushTarget::~ShrinkSummaryLidSpaceFlushTarget() = default;
IFlushTarget::Task::UP
ShrinkSummaryLidSpaceFlushTarget::initFlush(SerialNum currentSerial, std::shared_ptr<search::IFlushToken> flush_token)
{
std::promise<Task::UP> promise;
std::future<Task::UP> future = promise.get_future();
_summaryService.execute(makeLambdaTask([&]() { promise.set_value(ShrinkLidSpaceFlushTarget::initFlush(currentSerial, flush_token)); }));
return future.get();
}
}
SummaryManager::SummarySetup::
SummarySetup(const vespalib::string & baseDir, const DocTypeName & docTypeName, const SummaryConfig & summaryCfg,
const SummarymapConfig & summarymapCfg, const JuniperrcConfig & juniperCfg,
search::IAttributeManager::SP attributeMgr, search::IDocumentStore::SP docStore,
std::shared_ptr<const DocumentTypeRepo> repo)
: _docsumWriter(),
_wordFolder(std::make_unique<Fast_NormalizeWordFolder>()),
_juniperProps(juniperCfg),
_juniperConfig(),
_attributeMgr(std::move(attributeMgr)),
_docStore(std::move(docStore)),
_fieldCacheRepo(),
_repo(repo),
_markupFields()
{
DocsumBlobEntryFilter docsum_blob_entry_filter;
docsum_blob_entry_filter.add_skip(RES_INT);
docsum_blob_entry_filter.add_skip(RES_SHORT);
docsum_blob_entry_filter.add_skip(RES_BOOL);
docsum_blob_entry_filter.add_skip(RES_BYTE);
docsum_blob_entry_filter.add_skip(RES_FLOAT);
docsum_blob_entry_filter.add_skip(RES_DOUBLE);
docsum_blob_entry_filter.add_skip(RES_INT64);
docsum_blob_entry_filter.add_skip(RES_DATA);
docsum_blob_entry_filter.add_skip(RES_LONG_DATA);
docsum_blob_entry_filter.add_skip(RES_JSONSTRING);
docsum_blob_entry_filter.add_skip(RES_TENSOR);
docsum_blob_entry_filter.add_skip(RES_FEATUREDATA);
auto resultConfig = std::make_unique<ResultConfig>(docsum_blob_entry_filter);
if (!resultConfig->ReadConfig(summaryCfg, make_string("SummaryManager(%s)", baseDir.c_str()).c_str())) {
std::ostringstream oss;
::config::OstreamConfigWriter writer(oss);
writer.write(summaryCfg);
throw IllegalArgumentException
(make_string("Could not initialize summary result config for directory '%s' based on summary config '%s'",
baseDir.c_str(), oss.str().c_str()));
}
_juniperConfig = std::make_unique<juniper::Juniper>(&_juniperProps, _wordFolder.get());
_docsumWriter = std::make_unique<DynamicDocsumWriter>(resultConfig.release(), nullptr);
DynamicDocsumConfig dynCfg(this, _docsumWriter.get());
dynCfg.configure(summarymapCfg);
for (const auto & o : summarymapCfg.override) {
if (o.command == "dynamicteaser" || o.command == "textextractor") {
vespalib::string markupField = o.arguments;
if (markupField.empty())
continue;
// Assume just one argument: source field that must contain markup
_markupFields.insert(markupField);
}
}
const DocumentType *docType = repo->getDocumentType(docTypeName.getName());
if (docType != nullptr) {
_fieldCacheRepo = std::make_unique<FieldCacheRepo>(getResultConfig(), *docType);
} else if (getResultConfig().GetNumResultClasses() == 0) {
LOG(debug, "Create empty field cache repo for document type '%s'", docTypeName.toString().c_str());
_fieldCacheRepo = std::make_unique<FieldCacheRepo>();
} else {
throw IllegalArgumentException(make_string("Did not find document type '%s' in current document type repo."
" Cannot setup field cache repo for the summary setup",
docTypeName.toString().c_str()));
}
}
IDocsumStore::UP
SummaryManager::SummarySetup::createDocsumStore(const vespalib::string &resultClassName) {
return std::make_unique<DocumentStoreAdapter>(*_docStore, *_repo, getResultConfig(), resultClassName,
_fieldCacheRepo->getFieldCache(resultClassName), _markupFields);
}
ISummaryManager::ISummarySetup::SP
SummaryManager::createSummarySetup(const SummaryConfig & summaryCfg, const SummarymapConfig & summarymapCfg,
const JuniperrcConfig & juniperCfg, const std::shared_ptr<const DocumentTypeRepo> &repo,
const search::IAttributeManager::SP &attributeMgr)
{
return std::make_shared<SummarySetup>(_baseDir, _docTypeName, summaryCfg, summarymapCfg,
juniperCfg, attributeMgr, _docStore, repo);
}
SummaryManager::SummaryManager(vespalib::Executor &shared_executor, const LogDocumentStore::Config & storeConfig,
const search::GrowStrategy & growStrategy, const vespalib::string &baseDir,
const DocTypeName &docTypeName, const TuneFileSummary &tuneFileSummary,
const FileHeaderContext &fileHeaderContext, search::transactionlog::SyncProxy &tlSyncer,
search::IBucketizer::SP bucketizer)
: _baseDir(baseDir),
_docTypeName(docTypeName),
_docStore()
{
_docStore = std::make_shared<LogDocumentStore>(shared_executor, baseDir, storeConfig, growStrategy, tuneFileSummary,
fileHeaderContext, tlSyncer, std::move(bucketizer));
}
SummaryManager::~SummaryManager() = default;
void
SummaryManager::putDocument(uint64_t syncToken, search::DocumentIdT lid, const Document & doc)
{
_docStore->write(syncToken, lid, doc);
}
void
SummaryManager::putDocument(uint64_t syncToken, search::DocumentIdT lid, const vespalib::nbostream & doc)
{
_docStore->write(syncToken, lid, doc);
}
void
SummaryManager::removeDocument(uint64_t syncToken, search::DocumentIdT lid)
{
_docStore->remove(syncToken, lid);
}
namespace {
IFlushTarget::SP
createShrinkLidSpaceFlushTarget(vespalib::Executor & summaryService, IDocumentStore::SP docStore)
{
return std::make_shared<ShrinkSummaryLidSpaceFlushTarget>("summary.shrink",
IFlushTarget::Type::GC,
IFlushTarget::Component::DOCUMENT_STORE,
docStore->lastSyncToken(),
docStore->getLastFlushTime(),
summaryService,
std::move(docStore));
}
}
IFlushTarget::List
SummaryManager::getFlushTargets(vespalib::Executor & summaryService)
{
IFlushTarget::List ret;
ret.push_back(std::make_shared<SummaryFlushTarget>(getBackingStore(), summaryService));
if (dynamic_cast<LogDocumentStore *>(_docStore.get()) != nullptr) {
ret.push_back(std::make_shared<SummaryCompactBloatTarget>(summaryService, getBackingStore()));
ret.push_back(std::make_shared<SummaryCompactSpreadTarget>(summaryService, getBackingStore()));
}
ret.push_back(createShrinkLidSpaceFlushTarget(summaryService, _docStore));
return ret;
}
void
SummaryManager::reconfigure(const LogDocumentStore::Config & config) {
auto & docStore = dynamic_cast<LogDocumentStore &> (*_docStore);
docStore.reconfigure(config);
}
} // namespace proton
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: dispatchinformationprovider.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-11-16 14:53:00 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_DISPATCH_DISPATCHINFORMATIONPROVIDER_HXX_
#include <dispatch/dispatchinformationprovider.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
#include <dispatch/closedispatcher.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_FRAME_COMMANDGROUP_HPP_
#include <com/sun/star/frame/CommandGroup.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_SEQUENCEASVECTOR_HXX_
#include <comphelper/sequenceasvector.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
namespace css = ::com::sun::star;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
DEFINE_XINTERFACE_1(DispatchInformationProvider ,
OWeakObject ,
DIRECT_INTERFACE(css::frame::XDispatchInformationProvider))
//_________________________________________________________________________________________________________________
DispatchInformationProvider::DispatchInformationProvider(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xFrame)
: ThreadHelpBase(&Application::GetSolarMutex())
, m_xSMGR (xSMGR )
, m_xFrame (xFrame )
{
}
//_________________________________________________________________________________________________________________
DispatchInformationProvider::~DispatchInformationProvider()
{
}
//_________________________________________________________________________________________________________________
css::uno::Sequence< sal_Int16 > SAL_CALL DispatchInformationProvider::getSupportedCommandGroups()
throw (css::uno::RuntimeException)
{
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
sal_Int32 c1 = lProvider.getLength();
sal_Int32 i1 = 0;
::comphelper::SequenceAsVector< sal_Int16 > lGroups;
for (i1=0; i1<c1; ++i1)
{
// ignore controller, which doesnt implement the right interface
css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
if (!xProvider.is())
continue;
const css::uno::Sequence< sal_Int16 > lProviderGroups = xProvider->getSupportedCommandGroups();
sal_Int32 c2 = lProviderGroups.getLength();
sal_Int32 i2 = 0;
for (i2=0; i2<c2; ++i2)
{
const sal_Int16& rGroup = lProviderGroups[i2];
::comphelper::SequenceAsVector< sal_Int16 >::const_iterator pGroup = ::std::find(lGroups.begin(), lGroups.end(), rGroup);
if (pGroup == lGroups.end())
lGroups.push_back(rGroup);
}
}
return lGroups.getAsConstList();
}
//_________________________________________________________________________________________________________________
css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL DispatchInformationProvider::getConfigurableDispatchInformation(sal_Int16 nCommandGroup)
throw (css::uno::RuntimeException)
{
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
sal_Int32 c1 = lProvider.getLength();
sal_Int32 i1 = 0;
BaseHash< css::frame::DispatchInformation > lInfos;
for (i1=0; i1<c1; ++i1)
{
try
{
// ignore controller, which doesnt implement the right interface
css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
if (!xProvider.is())
continue;
const css::uno::Sequence< css::frame::DispatchInformation > lProviderInfos = xProvider->getConfigurableDispatchInformation(nCommandGroup);
sal_Int32 c2 = lProviderInfos.getLength();
sal_Int32 i2 = 0;
for (i2=0; i2<c2; ++i2)
{
const css::frame::DispatchInformation& rInfo = lProviderInfos[i2];
BaseHash< css::frame::DispatchInformation >::const_iterator pInfo = lInfos.find(rInfo.Command);
if (pInfo == lInfos.end())
lInfos[rInfo.Command] = rInfo;
}
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{ continue; }
}
c1 = (sal_Int32)lInfos.size();
i1 = 0;
css::uno::Sequence< css::frame::DispatchInformation > lReturn(c1);
BaseHash< css::frame::DispatchInformation >::const_iterator pStepp ;
for ( pStepp = lInfos.begin() ;
pStepp != lInfos.end () && i1<c1 ;
++pStepp, ++i1 )
{
lReturn[i1] = pStepp->second;
}
return lReturn;
}
//_________________________________________________________________________________________________________________
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > DispatchInformationProvider::implts_getAllSubProvider()
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
css::uno::Reference< css::frame::XFrame > xFrame(m_xFrame.get(), css::uno::UNO_QUERY);
aReadLock.unlock();
// <- SAFE ----------------------------------
if (!xFrame.is())
return css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > >();
CloseDispatcher* pCloser = new CloseDispatcher(xSMGR, xFrame);
css::uno::Reference< css::uno::XInterface > xCloser(static_cast< css::frame::XDispatch* >(pCloser), css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchInformationProvider > xCloseDispatch(xCloser , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchInformationProvider > xController (xFrame->getController() , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchInformationProvider > xAppDispatcher(xSMGR->createInstance(IMPLEMENTATIONNAME_APPDISPATCHPROVIDER), css::uno::UNO_QUERY);
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider(3);
lProvider[0] = xController ;
lProvider[1] = xCloseDispatch;
lProvider[2] = xAppDispatcher;
return lProvider;
}
} // namespace framework
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.190); FILE MERGED 2005/09/05 13:06:16 rt 1.2.190.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dispatchinformationprovider.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 01:19:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_DISPATCH_DISPATCHINFORMATIONPROVIDER_HXX_
#include <dispatch/dispatchinformationprovider.hxx>
#endif
#ifndef __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
#include <dispatch/closedispatcher.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_FRAME_COMMANDGROUP_HPP_
#include <com/sun/star/frame/CommandGroup.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _COMPHELPER_SEQUENCEASVECTOR_HXX_
#include <comphelper/sequenceasvector.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
namespace css = ::com::sun::star;
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
DEFINE_XINTERFACE_1(DispatchInformationProvider ,
OWeakObject ,
DIRECT_INTERFACE(css::frame::XDispatchInformationProvider))
//_________________________________________________________________________________________________________________
DispatchInformationProvider::DispatchInformationProvider(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xFrame)
: ThreadHelpBase(&Application::GetSolarMutex())
, m_xSMGR (xSMGR )
, m_xFrame (xFrame )
{
}
//_________________________________________________________________________________________________________________
DispatchInformationProvider::~DispatchInformationProvider()
{
}
//_________________________________________________________________________________________________________________
css::uno::Sequence< sal_Int16 > SAL_CALL DispatchInformationProvider::getSupportedCommandGroups()
throw (css::uno::RuntimeException)
{
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
sal_Int32 c1 = lProvider.getLength();
sal_Int32 i1 = 0;
::comphelper::SequenceAsVector< sal_Int16 > lGroups;
for (i1=0; i1<c1; ++i1)
{
// ignore controller, which doesnt implement the right interface
css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
if (!xProvider.is())
continue;
const css::uno::Sequence< sal_Int16 > lProviderGroups = xProvider->getSupportedCommandGroups();
sal_Int32 c2 = lProviderGroups.getLength();
sal_Int32 i2 = 0;
for (i2=0; i2<c2; ++i2)
{
const sal_Int16& rGroup = lProviderGroups[i2];
::comphelper::SequenceAsVector< sal_Int16 >::const_iterator pGroup = ::std::find(lGroups.begin(), lGroups.end(), rGroup);
if (pGroup == lGroups.end())
lGroups.push_back(rGroup);
}
}
return lGroups.getAsConstList();
}
//_________________________________________________________________________________________________________________
css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL DispatchInformationProvider::getConfigurableDispatchInformation(sal_Int16 nCommandGroup)
throw (css::uno::RuntimeException)
{
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
sal_Int32 c1 = lProvider.getLength();
sal_Int32 i1 = 0;
BaseHash< css::frame::DispatchInformation > lInfos;
for (i1=0; i1<c1; ++i1)
{
try
{
// ignore controller, which doesnt implement the right interface
css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
if (!xProvider.is())
continue;
const css::uno::Sequence< css::frame::DispatchInformation > lProviderInfos = xProvider->getConfigurableDispatchInformation(nCommandGroup);
sal_Int32 c2 = lProviderInfos.getLength();
sal_Int32 i2 = 0;
for (i2=0; i2<c2; ++i2)
{
const css::frame::DispatchInformation& rInfo = lProviderInfos[i2];
BaseHash< css::frame::DispatchInformation >::const_iterator pInfo = lInfos.find(rInfo.Command);
if (pInfo == lInfos.end())
lInfos[rInfo.Command] = rInfo;
}
}
catch(const css::uno::RuntimeException& exRun)
{ throw exRun; }
catch(const css::uno::Exception&)
{ continue; }
}
c1 = (sal_Int32)lInfos.size();
i1 = 0;
css::uno::Sequence< css::frame::DispatchInformation > lReturn(c1);
BaseHash< css::frame::DispatchInformation >::const_iterator pStepp ;
for ( pStepp = lInfos.begin() ;
pStepp != lInfos.end () && i1<c1 ;
++pStepp, ++i1 )
{
lReturn[i1] = pStepp->second;
}
return lReturn;
}
//_________________________________________________________________________________________________________________
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > DispatchInformationProvider::implts_getAllSubProvider()
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
css::uno::Reference< css::frame::XFrame > xFrame(m_xFrame.get(), css::uno::UNO_QUERY);
aReadLock.unlock();
// <- SAFE ----------------------------------
if (!xFrame.is())
return css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > >();
CloseDispatcher* pCloser = new CloseDispatcher(xSMGR, xFrame);
css::uno::Reference< css::uno::XInterface > xCloser(static_cast< css::frame::XDispatch* >(pCloser), css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchInformationProvider > xCloseDispatch(xCloser , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchInformationProvider > xController (xFrame->getController() , css::uno::UNO_QUERY);
css::uno::Reference< css::frame::XDispatchInformationProvider > xAppDispatcher(xSMGR->createInstance(IMPLEMENTATIONNAME_APPDISPATCHPROVIDER), css::uno::UNO_QUERY);
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider(3);
lProvider[0] = xController ;
lProvider[1] = xCloseDispatch;
lProvider[2] = xAppDispatcher;
return lProvider;
}
} // namespace framework
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>
#include "base/logging.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_device_linux.h"
namespace {
// -----------------------------------------------------------------------------
// Callback functions to proxy to RenderWidgetHostViewGtk...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
RenderWidgetHostViewGtk* host) {
const gfx::Rect damage_rect(expose->area);
host->Paint(damage_rect);
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
RenderWidgetHostViewGtk* host) {
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
} // anonymous namespace
// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
RenderWidgetHost* widget) {
return new RenderWidgetHostViewGtk(widget);
}
RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget)
: widget_(widget) {
widget_->set_view(this);
view_ = gtk_drawing_area_new();
gtk_widget_add_events(view_, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(view_, GTK_CAN_FOCUS);
g_signal_connect(view_, "configure-event", G_CALLBACK(ConfigureEvent), this);
g_signal_connect(view_, "expose-event", G_CALLBACK(ExposeEvent), this);
g_signal_connect(view_, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
this);
g_signal_connect(view_, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), this);
g_signal_connect(view_, "focus-in-event", G_CALLBACK(FocusIn), this);
g_signal_connect(view_, "focus-out-event", G_CALLBACK(FocusOut), this);
g_signal_connect(view_, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), this);
g_signal_connect(view_, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), this);
g_signal_connect(view_, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
this);
g_signal_connect(view_, "scroll-event", G_CALLBACK(MouseScrollEvent),
this);
}
RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
gtk_widget_destroy(view_);
}
void RenderWidgetHostViewGtk::DidBecomeSelected() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::WasHidden() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
NOTIMPLEMENTED();
}
gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
NOTIMPLEMENTED();
return NULL;
}
void RenderWidgetHostViewGtk::MovePluginWindows(
const std::vector<WebPluginGeometry>& plugin_window_moves) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Focus() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Blur() {
NOTIMPLEMENTED();
}
bool RenderWidgetHostViewGtk::HasFocus() {
NOTIMPLEMENTED();
return false;
}
void RenderWidgetHostViewGtk::Show() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Hide() {
NOTIMPLEMENTED();
}
gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
return gfx::Rect(view_->allocation.x, view_->allocation.y,
view_->allocation.width, view_->allocation.height);
}
void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::UpdateCursorIfOverSelf() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
const gfx::Rect& caret_rect) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
int dy) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::RendererGone() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Destroy() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
BackingStore* backing_store = widget_->GetBackingStore();
if (backing_store) {
GdkRectangle grect = {
damage_rect.x(),
damage_rect.y(),
damage_rect.width(),
damage_rect.height()
};
GdkWindow* window = view_->window;
gdk_window_begin_paint_rect(window, &grect);
skia::PlatformDeviceLinux &platdev =
backing_store->canvas()->getTopPlatformDevice();
skia::BitmapPlatformDeviceLinux* const bitdev =
static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(window);
} else {
NOTIMPLEMENTED();
}
}
<commit_msg>Linux: fix crash in OnGetScreenInfo<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/render_widget_host_view_gtk.h"
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <cairo/cairo.h>
#include "base/logging.h"
#include "chrome/browser/renderer_host/backing_store.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "skia/ext/bitmap_platform_device_linux.h"
#include "skia/ext/platform_device_linux.h"
namespace {
// -----------------------------------------------------------------------------
// Callback functions to proxy to RenderWidgetHostViewGtk...
gboolean ConfigureEvent(GtkWidget* widget, GdkEventConfigure* config,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean ExposeEvent(GtkWidget* widget, GdkEventExpose* expose,
RenderWidgetHostViewGtk* host) {
const gfx::Rect damage_rect(expose->area);
host->Paint(damage_rect);
return FALSE;
}
gboolean KeyPressReleaseEvent(GtkWidget* widget, GdkEventKey* event,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean FocusIn(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean FocusOut(GtkWidget* widget, GdkEventFocus* focus,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean ButtonPressReleaseEvent(GtkWidget* widget, GdkEventButton* event,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
gboolean MouseMoveEvent(GtkWidget* widget, GdkEventMotion* event,
RenderWidgetHostViewGtk* host) {
return FALSE;
}
gboolean MouseScrollEvent(GtkWidget* widget, GdkEventScroll* event,
RenderWidgetHostViewGtk* host) {
NOTIMPLEMENTED();
return FALSE;
}
} // anonymous namespace
// static
RenderWidgetHostView* RenderWidgetHostView::CreateViewForWidget(
RenderWidgetHost* widget) {
return new RenderWidgetHostViewGtk(widget);
}
RenderWidgetHostViewGtk::RenderWidgetHostViewGtk(RenderWidgetHost* widget)
: widget_(widget) {
widget_->set_view(this);
view_ = gtk_drawing_area_new();
gtk_widget_add_events(view_, GDK_EXPOSURE_MASK |
GDK_POINTER_MOTION_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_BUTTON_RELEASE_MASK |
GDK_KEY_PRESS_MASK |
GDK_KEY_RELEASE_MASK);
GTK_WIDGET_SET_FLAGS(view_, GTK_CAN_FOCUS);
g_signal_connect(view_, "configure-event", G_CALLBACK(ConfigureEvent), this);
g_signal_connect(view_, "expose-event", G_CALLBACK(ExposeEvent), this);
g_signal_connect(view_, "key-press-event", G_CALLBACK(KeyPressReleaseEvent),
this);
g_signal_connect(view_, "key-release-event",
G_CALLBACK(KeyPressReleaseEvent), this);
g_signal_connect(view_, "focus-in-event", G_CALLBACK(FocusIn), this);
g_signal_connect(view_, "focus-out-event", G_CALLBACK(FocusOut), this);
g_signal_connect(view_, "button-press-event",
G_CALLBACK(ButtonPressReleaseEvent), this);
g_signal_connect(view_, "button-release-event",
G_CALLBACK(ButtonPressReleaseEvent), this);
g_signal_connect(view_, "motion-notify-event", G_CALLBACK(MouseMoveEvent),
this);
g_signal_connect(view_, "scroll-event", G_CALLBACK(MouseScrollEvent),
this);
}
RenderWidgetHostViewGtk::~RenderWidgetHostViewGtk() {
gtk_widget_destroy(view_);
}
void RenderWidgetHostViewGtk::DidBecomeSelected() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::WasHidden() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetSize(const gfx::Size& size) {
NOTIMPLEMENTED();
}
gfx::NativeView RenderWidgetHostViewGtk::GetPluginNativeView() {
NOTIMPLEMENTED();
// TODO(port): We need to pass some widget pointer out here because the
// renderer echos it back to us when it asks for GetScreenInfo. However, we
// should probably be passing the top-level window or some such instead.
return view_;
}
void RenderWidgetHostViewGtk::MovePluginWindows(
const std::vector<WebPluginGeometry>& plugin_window_moves) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Focus() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Blur() {
NOTIMPLEMENTED();
}
bool RenderWidgetHostViewGtk::HasFocus() {
NOTIMPLEMENTED();
return false;
}
void RenderWidgetHostViewGtk::Show() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Hide() {
NOTIMPLEMENTED();
}
gfx::Rect RenderWidgetHostViewGtk::GetViewBounds() const {
return gfx::Rect(view_->allocation.x, view_->allocation.y,
view_->allocation.width, view_->allocation.height);
}
void RenderWidgetHostViewGtk::UpdateCursor(const WebCursor& cursor) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::UpdateCursorIfOverSelf() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetIsLoading(bool is_loading) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::IMEUpdateStatus(int control,
const gfx::Rect& caret_rect) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::DidPaintRect(const gfx::Rect& rect) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::DidScrollRect(const gfx::Rect& rect, int dx,
int dy) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::RendererGone() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Destroy() {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::SetTooltipText(const std::wstring& tooltip_text) {
NOTIMPLEMENTED();
}
void RenderWidgetHostViewGtk::Paint(const gfx::Rect& damage_rect) {
BackingStore* backing_store = widget_->GetBackingStore();
if (backing_store) {
GdkRectangle grect = {
damage_rect.x(),
damage_rect.y(),
damage_rect.width(),
damage_rect.height()
};
GdkWindow* window = view_->window;
gdk_window_begin_paint_rect(window, &grect);
skia::PlatformDeviceLinux &platdev =
backing_store->canvas()->getTopPlatformDevice();
skia::BitmapPlatformDeviceLinux* const bitdev =
static_cast<skia::BitmapPlatformDeviceLinux* >(&platdev);
cairo_t* cairo_drawable = gdk_cairo_create(window);
cairo_set_source_surface(cairo_drawable, bitdev->surface(), 0, 0);
cairo_paint(cairo_drawable);
cairo_destroy(cairo_drawable);
gdk_window_end_paint(window);
} else {
NOTIMPLEMENTED();
}
}
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "sizegroup.hh"
namespace Rapicorn {
// == WidgetGroup ==
WidgetGroup*
WidgetGroup::create (const String &name, WidgetGroupType type)
{
assert_return (name.empty() == false, NULL);
if (type == WIDGET_GROUP_HSIZE || type == WIDGET_GROUP_VSIZE)
return new SizeGroup (name, type);
else
return new WidgetGroup (name, type);
}
WidgetGroup::WidgetGroup (const String &name, WidgetGroupType type) :
name_ (name), type_ (type)
{}
WidgetGroup::~WidgetGroup()
{
assert (widgets_.size() == 0);
}
static DataKey<WidgetGroup::GroupVector> widget_group_key;
vector<WidgetGroup*>
WidgetGroup::list_groups (WidgetImpl &widget)
{
return widget.get_data (&widget_group_key);
}
void
WidgetGroup::add_widget (WidgetImpl &widget)
{
ref (this); // ref_pair_1
// add widget to group's list
widgets_.push_back (&widget);
// add group to widget's list
GroupVector wgv = widget.get_data (&widget_group_key);
wgv.push_back (this);
widget.set_data (&widget_group_key, wgv);
widget_transit (widget);
}
void
WidgetGroup::remove_widget (WidgetImpl &widget)
{
ref (this); // ref_pair_2
widget_transit (widget);
// remove widget from group's list
bool found_one = false;
for (uint i = 0; i < widgets_.size(); i++)
if (widgets_[i] == &widget)
{
widgets_.erase (widgets_.begin() + i);
found_one = true;
unref (this); // ref_pair_1
break;
}
if (!found_one)
{
critical ("attempt to remove unknown widget (%s) from group: %p", widget.name().c_str(), this);
unref (this); // ref_pair_2
return;
}
// remove group from widget's list */
found_one = false;
GroupVector wgv = widget.get_data (&widget_group_key);
for (uint i = 0; i < wgv.size(); i++)
if (wgv[i] == this)
{
wgv.erase (wgv.begin() + i);
found_one = true;
break;
}
if (!found_one)
fatal ("failed to remove size group (%p) from widget: %s", this, widget.name().c_str());
if (wgv.size() == 0)
widget.delete_data (&widget_group_key);
else
widget.set_data (&widget_group_key, wgv);
unref (this); // ref_pair_2
}
void
WidgetGroup::delete_widget (WidgetImpl &widget)
{
// remove from all groups
GroupVector wgl = list_groups (widget);
for (size_t i = 0; i < wgl.size(); i++)
wgl[i]->remove_widget (widget);
}
void
WidgetGroup::invalidate_widget (WidgetImpl &widget)
{
// invalidate all active groups
GroupVector wgl = list_groups (widget);
for (size_t i = 0; i < wgl.size(); i++)
wgl[i]->widget_invalidated (widget);
}
// == SizeGroup ==
SizeGroup::SizeGroup (const String &name, WidgetGroupType type) :
WidgetGroup (name, type),
active_ (true), all_dirty_ (false)
{}
void
SizeGroup::widget_invalidated (WidgetImpl &widget)
{
invalidate_sizes();
}
void
SizeGroup::widget_transit (WidgetImpl &widget)
{
invalidate_sizes();
if (active())
widget.invalidate_size();
}
void
SizeGroup::invalidate_sizes()
{
if (active())
{
if (all_dirty_)
return;
all_dirty_ = true;
for (size_t i = 0; i < widgets_.size(); i++)
widgets_[i]->invalidate_size();
}
}
const Requisition&
SizeGroup::group_requisition ()
{
while (all_dirty_)
{
all_dirty_ = false;
req_ = Requisition();
// beware, widgets_ vector _could_ change during loop
for (size_t i = 0; i < widgets_.size(); i++)
{
WidgetImpl &widget = *widgets_[i];
const Requisition ireq = widget.inner_size_request();
req_.width = MAX (req_.width, ireq.width);
req_.height = MAX (req_.height, ireq.height);
}
}
return req_;
}
Requisition
SizeGroup::widget_requisition (WidgetImpl &widget)
{
// size request all active groups
Requisition zreq; // 0,0
if (widget.visible())
{
GroupVector wgl = list_groups (widget);
for (size_t i = 0; i < wgl.size(); i++)
if (wgl[i]->type() == WIDGET_GROUP_HSIZE || wgl[i]->type() == WIDGET_GROUP_VSIZE)
{
SizeGroup *sg = dynamic_cast<SizeGroup*> (wgl[i]);
if (!sg->active())
continue;
Requisition gr = sg->group_requisition();
if (sg->type() == WIDGET_GROUP_HSIZE)
zreq.width = MAX (zreq.width, gr.width);
if (sg->type() == WIDGET_GROUP_VSIZE)
zreq.height = MAX (zreq.height, gr.height);
}
}
// size request ungrouped/invisible widgets
Requisition ireq = widget.inner_size_request();
// determine final requisition
ireq.width = MAX (zreq.width, ireq.width);
ireq.height = MAX (zreq.height, ireq.height);
return ireq;
}
} // Rapicorn
<commit_msg>UI: consider only visible widgets in size groups<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include "sizegroup.hh"
namespace Rapicorn {
// == WidgetGroup ==
WidgetGroup*
WidgetGroup::create (const String &name, WidgetGroupType type)
{
assert_return (name.empty() == false, NULL);
if (type == WIDGET_GROUP_HSIZE || type == WIDGET_GROUP_VSIZE)
return new SizeGroup (name, type);
else
return new WidgetGroup (name, type);
}
WidgetGroup::WidgetGroup (const String &name, WidgetGroupType type) :
name_ (name), type_ (type)
{}
WidgetGroup::~WidgetGroup()
{
assert (widgets_.size() == 0);
}
static DataKey<WidgetGroup::GroupVector> widget_group_key;
vector<WidgetGroup*>
WidgetGroup::list_groups (WidgetImpl &widget)
{
return widget.get_data (&widget_group_key);
}
void
WidgetGroup::add_widget (WidgetImpl &widget)
{
ref (this); // ref_pair_1
// add widget to group's list
widgets_.push_back (&widget);
// add group to widget's list
GroupVector wgv = widget.get_data (&widget_group_key);
wgv.push_back (this);
widget.set_data (&widget_group_key, wgv);
widget_transit (widget);
}
void
WidgetGroup::remove_widget (WidgetImpl &widget)
{
ref (this); // ref_pair_2
widget_transit (widget);
// remove widget from group's list
bool found_one = false;
for (uint i = 0; i < widgets_.size(); i++)
if (widgets_[i] == &widget)
{
widgets_.erase (widgets_.begin() + i);
found_one = true;
unref (this); // ref_pair_1
break;
}
if (!found_one)
{
critical ("attempt to remove unknown widget (%s) from group: %p", widget.name().c_str(), this);
unref (this); // ref_pair_2
return;
}
// remove group from widget's list */
found_one = false;
GroupVector wgv = widget.get_data (&widget_group_key);
for (uint i = 0; i < wgv.size(); i++)
if (wgv[i] == this)
{
wgv.erase (wgv.begin() + i);
found_one = true;
break;
}
if (!found_one)
fatal ("failed to remove size group (%p) from widget: %s", this, widget.name().c_str());
if (wgv.size() == 0)
widget.delete_data (&widget_group_key);
else
widget.set_data (&widget_group_key, wgv);
unref (this); // ref_pair_2
}
void
WidgetGroup::delete_widget (WidgetImpl &widget)
{
// remove from all groups
GroupVector wgl = list_groups (widget);
for (size_t i = 0; i < wgl.size(); i++)
wgl[i]->remove_widget (widget);
}
void
WidgetGroup::invalidate_widget (WidgetImpl &widget)
{
// invalidate all active groups
GroupVector wgl = list_groups (widget);
for (size_t i = 0; i < wgl.size(); i++)
wgl[i]->widget_invalidated (widget);
}
// == SizeGroup ==
SizeGroup::SizeGroup (const String &name, WidgetGroupType type) :
WidgetGroup (name, type),
active_ (true), all_dirty_ (false)
{}
void
SizeGroup::widget_invalidated (WidgetImpl &widget)
{
invalidate_sizes();
}
void
SizeGroup::widget_transit (WidgetImpl &widget)
{
invalidate_sizes();
if (active())
widget.invalidate_size();
}
void
SizeGroup::invalidate_sizes()
{
if (active())
{
if (all_dirty_)
return;
all_dirty_ = true;
for (size_t i = 0; i < widgets_.size(); i++)
widgets_[i]->invalidate_size();
}
}
const Requisition&
SizeGroup::group_requisition ()
{
while (all_dirty_)
{
all_dirty_ = false;
req_ = Requisition();
// beware, widgets_ vector _could_ change during loop
for (size_t i = 0; i < widgets_.size(); i++)
{
WidgetImpl &widget = *widgets_[i];
if (widget.visible())
{
const Requisition ireq = widget.inner_size_request();
req_.width = MAX (req_.width, ireq.width);
req_.height = MAX (req_.height, ireq.height);
}
}
}
return req_;
}
Requisition
SizeGroup::widget_requisition (WidgetImpl &widget)
{
// size request all active groups
Requisition zreq; // 0,0
if (widget.visible())
{
GroupVector wgl = list_groups (widget);
for (size_t i = 0; i < wgl.size(); i++)
if (wgl[i]->type() == WIDGET_GROUP_HSIZE || wgl[i]->type() == WIDGET_GROUP_VSIZE)
{
SizeGroup *sg = dynamic_cast<SizeGroup*> (wgl[i]);
if (!sg->active())
continue;
Requisition gr = sg->group_requisition();
if (sg->type() == WIDGET_GROUP_HSIZE)
zreq.width = MAX (zreq.width, gr.width);
if (sg->type() == WIDGET_GROUP_VSIZE)
zreq.height = MAX (zreq.height, gr.height);
}
}
// size request ungrouped/invisible widgets
Requisition ireq = widget.inner_size_request();
// determine final requisition
ireq.width = MAX (zreq.width, ireq.width);
ireq.height = MAX (zreq.height, ireq.height);
return ireq;
}
} // Rapicorn
<|endoftext|> |
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "utilities.hh"
#include <cstring>
#include <errno.h>
#include <malloc.h>
namespace Rapicorn {
/* --- exceptions --- */
Exception::Exception (const String &s1, const String &s2, const String &s3, const String &s4,
const String &s5, const String &s6, const String &s7, const String &s8) :
reason (NULL)
{
String s (s1);
if (s2.size())
s += s2;
if (s3.size())
s += s3;
if (s4.size())
s += s4;
if (s5.size())
s += s5;
if (s6.size())
s += s6;
if (s7.size())
s += s7;
if (s8.size())
s += s8;
set (s);
}
Exception::Exception (const Exception &e) :
reason (e.reason ? strdup (e.reason) : NULL)
{}
void
Exception::set (const String &s)
{
if (reason)
free (reason);
reason = strdup (s.c_str());
}
Exception::~Exception() throw()
{
if (reason)
free (reason);
}
} // Rapicorn
<commit_msg>UI: use noexcept instead of dynamic exception specifications<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "utilities.hh"
#include <cstring>
#include <errno.h>
#include <malloc.h>
namespace Rapicorn {
/* --- exceptions --- */
Exception::Exception (const String &s1, const String &s2, const String &s3, const String &s4,
const String &s5, const String &s6, const String &s7, const String &s8) :
reason (NULL)
{
String s (s1);
if (s2.size())
s += s2;
if (s3.size())
s += s3;
if (s4.size())
s += s4;
if (s5.size())
s += s5;
if (s6.size())
s += s6;
if (s7.size())
s += s7;
if (s8.size())
s += s8;
set (s);
}
Exception::Exception (const Exception &e) :
reason (e.reason ? strdup (e.reason) : NULL)
{}
void
Exception::set (const String &s)
{
if (reason)
free (reason);
reason = strdup (s.c_str());
}
Exception::~Exception() noexcept
{
if (reason)
free (reason);
}
} // Rapicorn
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestDijkstraImageGeodesicPath.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 "vtkContourWidget.h"
#include "vtkDijkstraImageContourLineInterpolator.h"
#include "vtkDijkstraImageGeodesicPath.h"
#include "vtkImageActor.h"
#include "vtkImageActorPointPlacer.h"
#include "vtkImageAnisotropicDiffusion2D.h"
#include "vtkImageData.h"
#include "vtkImageGradientMagnitude.h"
#include "vtkImageMapToWindowLevelColors.h"
#include "vtkImageShiftScale.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkInteractorStyleImage.h"
#include "vtkOrientedGlyphContourRepresentation.h"
#include "vtkPNGReader.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTestUtilities.h"
char TestDijkstraImageGeodesicPathLog[] =
"# StreamVersion 1 i\n"
"RenderEvent 0 0 0 0 0 0 0 i\n"
"EnterEvent 399 96 0 0 0 0 0 i\n"
"MouseMoveEvent 321 96 0 0 0 0 0 i\n"
"RightButtonPressEvent 321 96 0 0 0 0 0 i\n"
"StartInteractionEvent 321 96 0 0 0 0 0 i\n"
"MouseMoveEvent 321 97 0 0 0 0 0 i\n"
"RenderEvent 321 97 0 0 0 0 0 i\n"
"MouseMoveEvent 316 169 0 0 0 0 0 i\n"
"RenderEvent 316 169 0 0 0 0 0 i\n"
"RightButtonReleaseEvent 316 169 0 0 0 0 0 i\n"
"EndInteractionEvent 316 169 0 0 0 0 0 i\n"
"RenderEvent 316 169 0 0 0 0 0 i\n"
"MouseMoveEvent 190 356 0 0 0 0 0 i\n"
"LeftButtonPressEvent 190 356 0 0 0 0 0 i\n"
"RenderEvent 190 356 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 190 356 0 0 0 0 0 i\n"
"MouseMoveEvent 61 226 0 0 0 0 0 i\n"
"LeftButtonPressEvent 61 226 0 0 0 0 0 i\n"
"RenderEvent 61 226 0 0 0 0 0 i\n"
"MouseMoveEvent 62 226 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 62 226 0 0 0 0 0 i\n"
"MouseMoveEvent 131 49 0 0 0 0 0 i\n"
"LeftButtonPressEvent 131 49 0 0 0 0 0 i\n"
"RenderEvent 131 49 0 0 0 0 0 i\n"
"MouseMoveEvent 131 50 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 131 50 0 0 0 0 0 i\n"
"MouseMoveEvent 292 69 0 0 0 0 0 i\n"
"LeftButtonPressEvent 292 69 0 0 0 0 0 i\n"
"RenderEvent 292 69 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 292 69 0 0 0 0 0 i\n"
"MouseMoveEvent 347 189 0 0 0 0 0 i\n"
"LeftButtonPressEvent 347 189 0 0 0 0 0 i\n"
"RenderEvent 347 189 0 0 0 0 0 i\n"
"MouseMoveEvent 347 190 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 347 190 0 0 0 0 0 i\n"
"MouseMoveEvent 300 302 0 0 0 0 0 i\n"
"LeftButtonPressEvent 300 302 0 0 0 0 0 i\n"
"RenderEvent 300 302 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 300 302 0 0 0 0 0 i\n"
"MouseMoveEvent 191 354 0 0 0 0 0 i\n"
"RightButtonPressEvent 191 354 0 0 0 0 0 i\n"
"RenderEvent 191 354 0 0 0 0 0 i\n"
"RightButtonReleaseEvent 191 354 0 0 0 0 0 i\n"
"MouseMoveEvent 63 225 0 0 0 0 0 i\n"
"LeftButtonPressEvent 63 225 0 0 0 0 0 i\n"
"MouseMoveEvent 63 226 0 0 0 0 0 i\n"
"RenderEvent 63 226 0 0 0 0 0 i\n"
"MouseMoveEvent 63 238 0 0 0 0 0 i\n"
"RenderEvent 63 238 0 0 0 0 0 i\n"
"MouseMoveEvent 63 239 0 0 0 0 0 i\n"
"RenderEvent 63 239 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 63 239 0 0 0 0 0 i\n"
"MouseMoveEvent 127 47 0 0 0 0 0 i\n"
"KeyPressEvent 127 47 0 0 0 1 Delete i\n"
"RenderEvent 127 47 0 0 0 1 Delete i\n"
"KeyReleaseEvent 127 47 0 0 0 1 Delete i\n"
"MouseMoveEvent 286 71 0 0 0 0 Delete i\n"
"RenderEvent 286 71 0 0 0 0 Delete i\n"
"MouseMoveEvent 287 68 0 0 0 0 Delete i\n"
"KeyPressEvent 287 68 0 0 0 1 Delete i\n"
"RenderEvent 287 68 0 0 0 1 Delete i\n"
"KeyReleaseEvent 287 68 0 0 0 1 Delete i\n"
"MouseMoveEvent 179 218 0 0 0 0 Delete i\n"
"LeftButtonPressEvent 179 218 0 0 0 0 Delete i\n"
"MouseMoveEvent 78 122 0 0 0 0 Delete i\n"
"RenderEvent 78 122 0 0 0 0 Delete i\n"
"LeftButtonReleaseEvent 78 122 0 0 0 0 Delete i\n"
"MouseMoveEvent 154 106 0 0 0 0 Delete i\n"
"KeyPressEvent 154 106 0 0 113 1 q i\n"
"CharEvent 154 106 0 0 113 1 q i\n"
"ExitEvent 154 106 0 0 113 1 q i\n"
;
int TestDijkstraImageGeodesicPath(int argc, char*argv[])
{
char* fname =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/fullhead15.png");
vtkPNGReader *reader = vtkPNGReader::New();
reader->SetFileName( fname );
delete [] fname;
// Smooth the image
vtkImageAnisotropicDiffusion2D *diffusion = vtkImageAnisotropicDiffusion2D::New();
diffusion->SetInputConnection( reader->GetOutputPort() );
diffusion->SetDiffusionFactor( 1.0 );
diffusion->SetDiffusionThreshold( 200.0 );
diffusion->SetNumberOfIterations( 5 );
// Gradient magnitude for edges
vtkImageGradientMagnitude *grad = vtkImageGradientMagnitude::New();
grad->SetDimensionality( 2 );
grad->HandleBoundariesOn();
grad->SetInputConnection( diffusion->GetOutputPort() );
grad->Update();
double* range = grad->GetOutput()->GetScalarRange();
// Invert the gradient magnitude so that low costs are
// associated with strong edges and scale from 0 to 1
vtkImageShiftScale *gradInvert = vtkImageShiftScale::New();
gradInvert->SetShift( -1.0*range[ 1 ] );
gradInvert->SetScale( 1.0 /( range[ 0 ] - range[ 1 ] ) );
gradInvert->SetOutputScalarTypeToFloat();
gradInvert->SetInputConnection( grad->GetOutputPort() );
gradInvert->Update();
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer( renderer );
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow( renWin );
vtkInteractorStyleImage* style = vtkInteractorStyleImage::New();
iren->SetInteractorStyle( style );
style->Delete();
// The color map will accept any scalar image type and convert to
// unsigned char for the image actor
vtkImageMapToWindowLevelColors *colorMap = vtkImageMapToWindowLevelColors::New();
colorMap->SetInputConnection( gradInvert->GetOutputPort() );
range = gradInvert->GetOutput()->GetScalarRange();
colorMap->SetWindow(1.0);
colorMap->SetLevel(0.5);
vtkImageActor *actor = vtkImageActor::New();
actor->SetInput( colorMap->GetOutput() );
actor->SetDisplayExtent( 0, 255, 0, 255, 0, 0 );
renderer->AddActor( actor );
renderer->SetBackground(0.2,0.2,1);
renWin->SetSize(400,400);
// Contour widget for interactive path definition
vtkContourWidget *contourWidget = vtkContourWidget::New();
contourWidget->SetInteractor( iren );
vtkOrientedGlyphContourRepresentation *rep = vtkOrientedGlyphContourRepresentation::New();
contourWidget->SetRepresentation( rep );
rep->GetLinesProperty()->SetColor(1, 0.2, 0);
rep->GetProperty()->SetColor(0, 0.2, 1);
rep->GetLinesProperty()->SetLineWidth( 3 );
// The contour rep requires a suitable point placer
vtkImageActorPointPlacer *placer = vtkImageActorPointPlacer::New();
placer->SetImageActor( actor );
rep->SetPointPlacer( placer );
// The line interpolator defines how intermediate points are
// generated between the representations nodes. This
// interpolator uses Dijkstra's shortest path algorithm.
vtkDijkstraImageContourLineInterpolator *interpolator =
vtkDijkstraImageContourLineInterpolator::New();
interpolator->SetCostImage( gradInvert->GetOutput() );
vtkDijkstraImageGeodesicPath* path =
interpolator->GetDijkstraImageGeodesicPath();
path->StopWhenEndReachedOn();
// prevent contour segments from overlapping
path->RepelPathFromVerticesOn();
// weights are scaled from 0 to 1 as are associated cost
// components
path->SetCurvatureWeight( 0.15 );
path->SetEdgeLengthWeight( 0.8 );
path->SetImageWeight( 1.0 );
rep->SetLineInterpolator( interpolator );
contourWidget->EnabledOn();
renWin->Render();
renderer->ResetCamera();
iren->Initialize();
vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
recorder->SetInteractor( iren );
recorder->ReadFromInputStringOn();
recorder->SetInputString( TestDijkstraImageGeodesicPathLog );
recorder->EnabledOn();
recorder->Play();
int retVal = vtkRegressionTestImage( renWin );
if ( retVal == vtkRegressionTester::DO_INTERACTOR )
{
iren->Start();
}
recorder->Stop();
// Cleanups
recorder->Delete();
contourWidget->Delete();
placer->Delete();
reader->Delete();
actor->Delete();
iren->Delete();
renWin->Delete();
renderer->Delete();
grad->Delete();
gradInvert->Delete();
interpolator->Delete();
rep->Delete();
diffusion->Delete();
colorMap->Delete();
return !retVal;
}
<commit_msg>ENH: Use threshold of 11 instead of default threshold of 10 for this test. Resulting image on dashmacmini1 continuous dashboard is considered close enough and should pass with a threshold of 11.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestDijkstraImageGeodesicPath.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 "vtkContourWidget.h"
#include "vtkDijkstraImageContourLineInterpolator.h"
#include "vtkDijkstraImageGeodesicPath.h"
#include "vtkImageActor.h"
#include "vtkImageActorPointPlacer.h"
#include "vtkImageAnisotropicDiffusion2D.h"
#include "vtkImageData.h"
#include "vtkImageGradientMagnitude.h"
#include "vtkImageMapToWindowLevelColors.h"
#include "vtkImageShiftScale.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkInteractorStyleImage.h"
#include "vtkOrientedGlyphContourRepresentation.h"
#include "vtkPNGReader.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkTestUtilities.h"
char TestDijkstraImageGeodesicPathLog[] =
"# StreamVersion 1 i\n"
"RenderEvent 0 0 0 0 0 0 0 i\n"
"EnterEvent 399 96 0 0 0 0 0 i\n"
"MouseMoveEvent 321 96 0 0 0 0 0 i\n"
"RightButtonPressEvent 321 96 0 0 0 0 0 i\n"
"StartInteractionEvent 321 96 0 0 0 0 0 i\n"
"MouseMoveEvent 321 97 0 0 0 0 0 i\n"
"RenderEvent 321 97 0 0 0 0 0 i\n"
"MouseMoveEvent 316 169 0 0 0 0 0 i\n"
"RenderEvent 316 169 0 0 0 0 0 i\n"
"RightButtonReleaseEvent 316 169 0 0 0 0 0 i\n"
"EndInteractionEvent 316 169 0 0 0 0 0 i\n"
"RenderEvent 316 169 0 0 0 0 0 i\n"
"MouseMoveEvent 190 356 0 0 0 0 0 i\n"
"LeftButtonPressEvent 190 356 0 0 0 0 0 i\n"
"RenderEvent 190 356 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 190 356 0 0 0 0 0 i\n"
"MouseMoveEvent 61 226 0 0 0 0 0 i\n"
"LeftButtonPressEvent 61 226 0 0 0 0 0 i\n"
"RenderEvent 61 226 0 0 0 0 0 i\n"
"MouseMoveEvent 62 226 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 62 226 0 0 0 0 0 i\n"
"MouseMoveEvent 131 49 0 0 0 0 0 i\n"
"LeftButtonPressEvent 131 49 0 0 0 0 0 i\n"
"RenderEvent 131 49 0 0 0 0 0 i\n"
"MouseMoveEvent 131 50 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 131 50 0 0 0 0 0 i\n"
"MouseMoveEvent 292 69 0 0 0 0 0 i\n"
"LeftButtonPressEvent 292 69 0 0 0 0 0 i\n"
"RenderEvent 292 69 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 292 69 0 0 0 0 0 i\n"
"MouseMoveEvent 347 189 0 0 0 0 0 i\n"
"LeftButtonPressEvent 347 189 0 0 0 0 0 i\n"
"RenderEvent 347 189 0 0 0 0 0 i\n"
"MouseMoveEvent 347 190 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 347 190 0 0 0 0 0 i\n"
"MouseMoveEvent 300 302 0 0 0 0 0 i\n"
"LeftButtonPressEvent 300 302 0 0 0 0 0 i\n"
"RenderEvent 300 302 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 300 302 0 0 0 0 0 i\n"
"MouseMoveEvent 191 354 0 0 0 0 0 i\n"
"RightButtonPressEvent 191 354 0 0 0 0 0 i\n"
"RenderEvent 191 354 0 0 0 0 0 i\n"
"RightButtonReleaseEvent 191 354 0 0 0 0 0 i\n"
"MouseMoveEvent 63 225 0 0 0 0 0 i\n"
"LeftButtonPressEvent 63 225 0 0 0 0 0 i\n"
"MouseMoveEvent 63 226 0 0 0 0 0 i\n"
"RenderEvent 63 226 0 0 0 0 0 i\n"
"MouseMoveEvent 63 238 0 0 0 0 0 i\n"
"RenderEvent 63 238 0 0 0 0 0 i\n"
"MouseMoveEvent 63 239 0 0 0 0 0 i\n"
"RenderEvent 63 239 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 63 239 0 0 0 0 0 i\n"
"MouseMoveEvent 127 47 0 0 0 0 0 i\n"
"KeyPressEvent 127 47 0 0 0 1 Delete i\n"
"RenderEvent 127 47 0 0 0 1 Delete i\n"
"KeyReleaseEvent 127 47 0 0 0 1 Delete i\n"
"MouseMoveEvent 286 71 0 0 0 0 Delete i\n"
"RenderEvent 286 71 0 0 0 0 Delete i\n"
"MouseMoveEvent 287 68 0 0 0 0 Delete i\n"
"KeyPressEvent 287 68 0 0 0 1 Delete i\n"
"RenderEvent 287 68 0 0 0 1 Delete i\n"
"KeyReleaseEvent 287 68 0 0 0 1 Delete i\n"
"MouseMoveEvent 179 218 0 0 0 0 Delete i\n"
"LeftButtonPressEvent 179 218 0 0 0 0 Delete i\n"
"MouseMoveEvent 78 122 0 0 0 0 Delete i\n"
"RenderEvent 78 122 0 0 0 0 Delete i\n"
"LeftButtonReleaseEvent 78 122 0 0 0 0 Delete i\n"
"MouseMoveEvent 154 106 0 0 0 0 Delete i\n"
"KeyPressEvent 154 106 0 0 113 1 q i\n"
"CharEvent 154 106 0 0 113 1 q i\n"
"ExitEvent 154 106 0 0 113 1 q i\n"
;
int TestDijkstraImageGeodesicPath(int argc, char*argv[])
{
char* fname =
vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/fullhead15.png");
vtkPNGReader *reader = vtkPNGReader::New();
reader->SetFileName( fname );
delete [] fname;
// Smooth the image
vtkImageAnisotropicDiffusion2D *diffusion = vtkImageAnisotropicDiffusion2D::New();
diffusion->SetInputConnection( reader->GetOutputPort() );
diffusion->SetDiffusionFactor( 1.0 );
diffusion->SetDiffusionThreshold( 200.0 );
diffusion->SetNumberOfIterations( 5 );
// Gradient magnitude for edges
vtkImageGradientMagnitude *grad = vtkImageGradientMagnitude::New();
grad->SetDimensionality( 2 );
grad->HandleBoundariesOn();
grad->SetInputConnection( diffusion->GetOutputPort() );
grad->Update();
double* range = grad->GetOutput()->GetScalarRange();
// Invert the gradient magnitude so that low costs are
// associated with strong edges and scale from 0 to 1
vtkImageShiftScale *gradInvert = vtkImageShiftScale::New();
gradInvert->SetShift( -1.0*range[ 1 ] );
gradInvert->SetScale( 1.0 /( range[ 0 ] - range[ 1 ] ) );
gradInvert->SetOutputScalarTypeToFloat();
gradInvert->SetInputConnection( grad->GetOutputPort() );
gradInvert->Update();
vtkRenderer *renderer = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
renWin->AddRenderer( renderer );
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
iren->SetRenderWindow( renWin );
vtkInteractorStyleImage* style = vtkInteractorStyleImage::New();
iren->SetInteractorStyle( style );
style->Delete();
// The color map will accept any scalar image type and convert to
// unsigned char for the image actor
vtkImageMapToWindowLevelColors *colorMap = vtkImageMapToWindowLevelColors::New();
colorMap->SetInputConnection( gradInvert->GetOutputPort() );
range = gradInvert->GetOutput()->GetScalarRange();
colorMap->SetWindow(1.0);
colorMap->SetLevel(0.5);
vtkImageActor *actor = vtkImageActor::New();
actor->SetInput( colorMap->GetOutput() );
actor->SetDisplayExtent( 0, 255, 0, 255, 0, 0 );
renderer->AddActor( actor );
renderer->SetBackground(0.2,0.2,1);
renWin->SetSize(400,400);
// Contour widget for interactive path definition
vtkContourWidget *contourWidget = vtkContourWidget::New();
contourWidget->SetInteractor( iren );
vtkOrientedGlyphContourRepresentation *rep = vtkOrientedGlyphContourRepresentation::New();
contourWidget->SetRepresentation( rep );
rep->GetLinesProperty()->SetColor(1, 0.2, 0);
rep->GetProperty()->SetColor(0, 0.2, 1);
rep->GetLinesProperty()->SetLineWidth( 3 );
// The contour rep requires a suitable point placer
vtkImageActorPointPlacer *placer = vtkImageActorPointPlacer::New();
placer->SetImageActor( actor );
rep->SetPointPlacer( placer );
// The line interpolator defines how intermediate points are
// generated between the representations nodes. This
// interpolator uses Dijkstra's shortest path algorithm.
vtkDijkstraImageContourLineInterpolator *interpolator =
vtkDijkstraImageContourLineInterpolator::New();
interpolator->SetCostImage( gradInvert->GetOutput() );
vtkDijkstraImageGeodesicPath* path =
interpolator->GetDijkstraImageGeodesicPath();
path->StopWhenEndReachedOn();
// prevent contour segments from overlapping
path->RepelPathFromVerticesOn();
// weights are scaled from 0 to 1 as are associated cost
// components
path->SetCurvatureWeight( 0.15 );
path->SetEdgeLengthWeight( 0.8 );
path->SetImageWeight( 1.0 );
rep->SetLineInterpolator( interpolator );
contourWidget->EnabledOn();
renWin->Render();
renderer->ResetCamera();
iren->Initialize();
vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
recorder->SetInteractor( iren );
recorder->ReadFromInputStringOn();
recorder->SetInputString( TestDijkstraImageGeodesicPathLog );
recorder->EnabledOn();
recorder->Play();
int retVal = vtkRegressionTestImageThreshold( renWin, 11 );
if ( retVal == vtkRegressionTester::DO_INTERACTOR )
{
iren->Start();
}
recorder->Stop();
// Cleanups
recorder->Delete();
contourWidget->Delete();
placer->Delete();
reader->Delete();
actor->Delete();
iren->Delete();
renWin->Delete();
renderer->Delete();
grad->Delete();
gradInvert->Delete();
interpolator->Delete();
rep->Delete();
diffusion->Delete();
colorMap->Delete();
return !retVal;
}
<|endoftext|> |
<commit_before>//Mike Zrimsek
//Computer Graphics
//Homework 3
#include <stdlib.h>
#include <GL/glut.h>
GLfloat mat_specular[] = { 1.0, 1.0, 0.0, 1.0 };
GLfloat mat_shininess[] = { 100.0 };
GLfloat mat_emission[] = { 1.0, 1.0, 0.1, 1.0 };
GLfloat default_emission[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
GLfloat red[] = { 1.0, 0.0, 0.0, 1.0 };
GLfloat light[] = { 1.0, 1.0, 1.0 };
void init(void)
{
GLfloat lmodel_ambient[] = { 1.0, 1.0, 1.0, 1.0 };
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light);
glLightfv(GL_LIGHT0, GL_SPECULAR, light);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, red);
glEnable(GL_LIGHT0);
glTranslatef(0.0, 0.0, 0.0);
glutSolidSphere(0.4, 20, 16);
glPopMatrix();
glDisable(GL_LIGHT0);
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-1.5, 1.5, -1.5*(GLfloat)h / (GLfloat)w,
1.5*(GLfloat)h / (GLfloat)w, -10.0, 10.0);
else
glOrtho(-1.5*(GLfloat)w / (GLfloat)h,
1.5*(GLfloat)w / (GLfloat)h, -1.5, 1.5, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
<commit_msg>rendering 3 balls with separate light sources<commit_after>//Mike Zrimsek
//Computer Graphics
//Homework 3
#include <stdlib.h>
#include <GL/glut.h>
GLfloat mat_specular[] = { 1.0, 1.0, 0.0, 1.0 };
GLfloat mat_shininess[] = { 100.0 };
GLfloat mat_emission[] = { 1.0, 1.0, 0.1, 1.0 };
GLfloat default_emission[] = { 0.0, 0.0, 0.0, 1.0 };
//red ball
GLfloat red[] = { 1.0, 0.0, 0.0, 1.0 };
GLfloat red_light[] = { 1.0, 1.0, 1.0 };
GLfloat red_light_position[] = { 1.0, 1.0, 1.0, 0.0 };
//blue ball
GLfloat blue[] = { 0.0, 0.0, 1.0, 1.0 };
GLfloat blue_light[] = { 1.0, 1.0, 1.0 };
GLfloat blue_light_position[] = { 1.0, 1.0, 1.0, 0.0 };
//green ball
GLfloat green[] = { 0.0, 1.0, 0.0, 1.0 };
GLfloat green_light[] = { 1.0, 1.0, 1.0 };
GLfloat green_light_position[] = { 1.0, 1.0, 1.0, 0.0 };
void init(void)
{
GLfloat lmodel_ambient[] = { 1.0, 1.0, 1.0, 1.0 };
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
//red light
glLightfv(GL_LIGHT0, GL_DIFFUSE, red_light);
glLightfv(GL_LIGHT0, GL_SPECULAR, red_light);
glLightfv(GL_LIGHT0, GL_POSITION, red_light_position);
//blue light
glLightfv(GL_LIGHT1, GL_DIFFUSE, blue_light);
glLightfv(GL_LIGHT1, GL_SPECULAR, blue_light);
glLightfv(GL_LIGHT1, GL_POSITION, blue_light_position);
//green light
glLightfv(GL_LIGHT2, GL_DIFFUSE, green_light);
glLightfv(GL_LIGHT2, GL_SPECULAR, green_light);
glLightfv(GL_LIGHT2, GL_POSITION, green_light_position);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glEnable(GL_LIGHTING);
glEnable(GL_DEPTH_TEST);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
//red ball
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, red);
glEnable(GL_LIGHT0);
glTranslatef(0.75, -0.5, 0.0);
glutSolidSphere(0.4, 20, 16);
glPopMatrix();
glDisable(GL_LIGHT0);
//blue ball
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, blue);
glEnable(GL_LIGHT1);
glTranslatef(0.0, 0.5, 0.0);
glutSolidSphere(0.4, 20, 16);
glPopMatrix();
glDisable(GL_LIGHT1);
//green ball
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, green);
glEnable(GL_LIGHT2);
glTranslatef(-0.75, -1.0, 0.0);
glutSolidSphere(0.4, 20, 16);
glPopMatrix();
glDisable(GL_LIGHT2);
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-1.5, 1.5, -1.5*(GLfloat)h / (GLfloat)w,
1.5*(GLfloat)h / (GLfloat)w, -10.0, 10.0);
else
glOrtho(-1.5*(GLfloat)w / (GLfloat)h,
1.5*(GLfloat)w / (GLfloat)h, -1.5, 1.5, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLLineNumberingSeparatorImportContext.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:09:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_XMLLINENUMBERINGSEPARATORIMPORTCONTEXT_HXX_
#include "XMLLineNumberingSeparatorImportContext.hxx"
#endif
#ifndef _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_
#include "XMLLineNumberingImportContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
using namespace ::com::sun::star::uno;
using ::com::sun::star::xml::sax::XAttributeList;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_INCREMENT;
TYPEINIT1( XMLLineNumberingSeparatorImportContext, SvXMLImportContext );
XMLLineNumberingSeparatorImportContext::XMLLineNumberingSeparatorImportContext(
SvXMLImport& rImport,
sal_uInt16 nPrfx,
const OUString& rLocalName,
XMLLineNumberingImportContext& rLineNumbering) :
SvXMLImportContext(rImport, nPrfx, rLocalName),
rLineNumberingContext(rLineNumbering)
{
}
XMLLineNumberingSeparatorImportContext::~XMLLineNumberingSeparatorImportContext()
{
}
void XMLLineNumberingSeparatorImportContext::StartElement(
const Reference<XAttributeList> & xAttrList)
{
sal_Int16 nLength = xAttrList->getLength();
for(sal_Int16 i=0; i<nLength; i++)
{
OUString sLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
GetKeyByAttrName( xAttrList->getNameByIndex(i), &sLocalName );
if ( (nPrefix == XML_NAMESPACE_TEXT) &&
IsXMLToken(sLocalName, XML_INCREMENT) )
{
sal_Int32 nTmp;
if (SvXMLUnitConverter::convertNumber(
nTmp, xAttrList->getValueByIndex(i), 0))
{
rLineNumberingContext.SetSeparatorIncrement((sal_Int16)nTmp);
}
// else: invalid number -> ignore
}
// else: unknown attribute -> ignore
}
}
void XMLLineNumberingSeparatorImportContext::Characters(
const OUString& rChars )
{
sSeparatorBuf.append(rChars);
}
void XMLLineNumberingSeparatorImportContext::EndElement()
{
rLineNumberingContext.SetSeparatorText(sSeparatorBuf.makeStringAndClear());
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.124); FILE MERGED 2007/06/04 13:23:38 vg 1.4.124.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLLineNumberingSeparatorImportContext.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:03:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#ifndef _XMLOFF_XMLLINENUMBERINGSEPARATORIMPORTCONTEXT_HXX_
#include "XMLLineNumberingSeparatorImportContext.hxx"
#endif
#ifndef _XMLOFF_XMLLINENUMBERINGIMPORTCONTEXT_HXX_
#include "XMLLineNumberingImportContext.hxx"
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
using namespace ::com::sun::star::uno;
using ::com::sun::star::xml::sax::XAttributeList;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_INCREMENT;
TYPEINIT1( XMLLineNumberingSeparatorImportContext, SvXMLImportContext );
XMLLineNumberingSeparatorImportContext::XMLLineNumberingSeparatorImportContext(
SvXMLImport& rImport,
sal_uInt16 nPrfx,
const OUString& rLocalName,
XMLLineNumberingImportContext& rLineNumbering) :
SvXMLImportContext(rImport, nPrfx, rLocalName),
rLineNumberingContext(rLineNumbering)
{
}
XMLLineNumberingSeparatorImportContext::~XMLLineNumberingSeparatorImportContext()
{
}
void XMLLineNumberingSeparatorImportContext::StartElement(
const Reference<XAttributeList> & xAttrList)
{
sal_Int16 nLength = xAttrList->getLength();
for(sal_Int16 i=0; i<nLength; i++)
{
OUString sLocalName;
sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
GetKeyByAttrName( xAttrList->getNameByIndex(i), &sLocalName );
if ( (nPrefix == XML_NAMESPACE_TEXT) &&
IsXMLToken(sLocalName, XML_INCREMENT) )
{
sal_Int32 nTmp;
if (SvXMLUnitConverter::convertNumber(
nTmp, xAttrList->getValueByIndex(i), 0))
{
rLineNumberingContext.SetSeparatorIncrement((sal_Int16)nTmp);
}
// else: invalid number -> ignore
}
// else: unknown attribute -> ignore
}
}
void XMLLineNumberingSeparatorImportContext::Characters(
const OUString& rChars )
{
sSeparatorBuf.append(rChars);
}
void XMLLineNumberingSeparatorImportContext::EndElement()
{
rLineNumberingContext.SetSeparatorText(sSeparatorBuf.makeStringAndClear());
}
<|endoftext|> |
<commit_before>#include "rapid_pbd/motion_planning.h"
#include <map>
#include <string>
#include "geometry_msgs/Pose.h"
#include "moveit_goal_builder/builder.h"
#include "moveit_msgs/MoveGroupAction.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "ros/ros.h"
#include "tf/transform_listener.h"
#include "transform_graph/graph.h"
#include "rapid_pbd/errors.h"
#include "rapid_pbd/world.h"
using std::string;
namespace msgs = rapid_pbd_msgs;
namespace tg = transform_graph;
namespace rapid {
namespace pbd {
MotionPlanning::MotionPlanning(const RobotConfig& robot_config, World* world,
const tf::TransformListener& tf_listener)
: robot_config_(robot_config),
world_(world),
tf_listener_(tf_listener),
builder_(robot_config.planning_frame(), robot_config.planning_group()),
num_goals_(0) {}
string MotionPlanning::AddPoseGoal(const string& actuator_group,
const geometry_msgs::Pose& pose,
const rapid_pbd_msgs::Landmark& landmark) {
string ee_link = robot_config_.ee_frame_for_group(actuator_group);
if (ee_link == "") {
ROS_ERROR("Unable to look up EE link for actuator group \"%s\"",
actuator_group.c_str());
return "Invalid actuator in the program.";
}
tg::Graph graph;
graph.Add("ee", tg::RefFrame("landmark"), pose);
if (landmark.type == msgs::Landmark::TF_FRAME) {
tf::StampedTransform st;
try {
tf_listener_.lookupTransform(robot_config_.base_link(), landmark.name,
ros::Time(0), st);
} catch (const tf::TransformException& ex) {
ROS_ERROR(
"Unable to get TF transform from \"%s\" to landmark frame \"%s\"",
robot_config_.base_link().c_str(), landmark.name.c_str());
return "Unable to get TF transform";
}
graph.Add("landmark", tg::RefFrame(robot_config_.base_link()), st);
} else if (landmark.type == msgs::Landmark::SURFACE_BOX) {
// TODO: Register the landmark
msgs::Landmark match;
bool success = MatchLandmark(*world_, landmark, &match);
if (!success) {
return errors::kNoLandmarksMatch;
}
if (landmark.pose_stamped.header.frame_id != robot_config_.base_link()) {
ROS_ERROR("Landmark not in base frame: \"%s\"",
landmark.pose_stamped.header.frame_id.c_str());
return "Landmark not in base frame.";
}
graph.Add("landmark", tg::RefFrame(landmark.pose_stamped.header.frame_id),
landmark.pose_stamped.pose);
} else {
ROS_ERROR("Unsupported landmark type \"%s\"", landmark.type.c_str());
return "Unsupported landmark type.";
}
// Transform pose into base frame
tg::Transform landmark_transform;
graph.ComputeDescription(tg::LocalFrame("ee"),
tg::RefFrame(robot_config_.base_link()),
&landmark_transform);
geometry_msgs::Pose pose_in_base;
landmark_transform.ToPose(&pose_in_base);
builder_.AddPoseGoal(ee_link, pose_in_base);
++num_goals_;
return "";
}
void MotionPlanning::AddJointGoal(const string& actuator_group,
const geometry_msgs::Pose& pose) {
// TODO: use moveit instead of joint controllers
ROS_ERROR("MotionPlanning::AddJointGoal not implemented");
}
void MotionPlanning::ClearGoals() {
std::map<string, geometry_msgs::Pose> goals;
// Overrides joint goals if any and deletes pose goals.
builder_.SetPoseGoals(goals);
num_goals_ = 0;
}
void MotionPlanning::BuildGoal(moveit_msgs::MoveGroupGoal* goal) const {
builder_.Build(goal);
}
int MotionPlanning::num_goals() const { return num_goals_; }
} // namespace pbd
} // namespace rapid
<commit_msg>Use matched landmark when executing.<commit_after>#include "rapid_pbd/motion_planning.h"
#include <map>
#include <string>
#include "geometry_msgs/Pose.h"
#include "moveit_goal_builder/builder.h"
#include "moveit_msgs/MoveGroupAction.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "ros/ros.h"
#include "tf/transform_listener.h"
#include "transform_graph/graph.h"
#include "rapid_pbd/errors.h"
#include "rapid_pbd/world.h"
using std::string;
namespace msgs = rapid_pbd_msgs;
namespace tg = transform_graph;
namespace rapid {
namespace pbd {
MotionPlanning::MotionPlanning(const RobotConfig& robot_config, World* world,
const tf::TransformListener& tf_listener)
: robot_config_(robot_config),
world_(world),
tf_listener_(tf_listener),
builder_(robot_config.planning_frame(), robot_config.planning_group()),
num_goals_(0) {}
string MotionPlanning::AddPoseGoal(const string& actuator_group,
const geometry_msgs::Pose& pose,
const rapid_pbd_msgs::Landmark& landmark) {
string ee_link = robot_config_.ee_frame_for_group(actuator_group);
if (ee_link == "") {
ROS_ERROR("Unable to look up EE link for actuator group \"%s\"",
actuator_group.c_str());
return "Invalid actuator in the program.";
}
tg::Graph graph;
graph.Add("ee", tg::RefFrame("landmark"), pose);
if (landmark.type == msgs::Landmark::TF_FRAME) {
tf::StampedTransform st;
try {
tf_listener_.lookupTransform(robot_config_.base_link(), landmark.name,
ros::Time(0), st);
} catch (const tf::TransformException& ex) {
ROS_ERROR(
"Unable to get TF transform from \"%s\" to landmark frame \"%s\"",
robot_config_.base_link().c_str(), landmark.name.c_str());
return "Unable to get TF transform";
}
graph.Add("landmark", tg::RefFrame(robot_config_.base_link()), st);
} else if (landmark.type == msgs::Landmark::SURFACE_BOX) {
msgs::Landmark match;
bool success = MatchLandmark(*world_, landmark, &match);
if (!success) {
return errors::kNoLandmarksMatch;
}
if (match.pose_stamped.header.frame_id != robot_config_.base_link()) {
ROS_ERROR("Landmark not in base frame: \"%s\"",
match.pose_stamped.header.frame_id.c_str());
return "Landmark not in base frame.";
}
graph.Add("landmark", tg::RefFrame(match.pose_stamped.header.frame_id),
match.pose_stamped.pose);
} else {
ROS_ERROR("Unsupported landmark type \"%s\"", landmark.type.c_str());
return "Unsupported landmark type.";
}
// Transform pose into base frame
tg::Transform landmark_transform;
graph.ComputeDescription(tg::LocalFrame("ee"),
tg::RefFrame(robot_config_.base_link()),
&landmark_transform);
geometry_msgs::Pose pose_in_base;
landmark_transform.ToPose(&pose_in_base);
builder_.AddPoseGoal(ee_link, pose_in_base);
++num_goals_;
return "";
}
void MotionPlanning::AddJointGoal(const string& actuator_group,
const geometry_msgs::Pose& pose) {
// TODO: use moveit instead of joint controllers
ROS_ERROR("MotionPlanning::AddJointGoal not implemented");
}
void MotionPlanning::ClearGoals() {
std::map<string, geometry_msgs::Pose> goals;
// Overrides joint goals if any and deletes pose goals.
builder_.SetPoseGoals(goals);
num_goals_ = 0;
}
void MotionPlanning::BuildGoal(moveit_msgs::MoveGroupGoal* goal) const {
builder_.Build(goal);
}
int MotionPlanning::num_goals() const { return num_goals_; }
} // namespace pbd
} // namespace rapid
<|endoftext|> |
<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <memory>
#include "core/CompileConfig.h"
#if OUZEL_SUPPORTS_OPENGL
#define GL_GLEXT_PROTOTYPES 1
#include <GL/glx.h>
#endif
#include "WindowLinux.h"
#include "core/Application.h"
#include "core/Engine.h"
#include "utils/Log.h"
static const long _NET_WM_STATE_TOGGLE = 2;
namespace ouzel
{
WindowLinux::WindowLinux()
{
}
WindowLinux::~WindowLinux()
{
if (visualInfo)
{
XFree(visualInfo);
}
if (display)
{
if (window)
{
XDestroyWindow(display, window);
}
XCloseDisplay(display);
}
}
bool WindowLinux::init(const Size2& newSize,
bool newResizable,
bool newFullscreen,
const std::string& newTitle,
bool newHighDpi,
bool depth)
{
if (!Window::init(newSize, newResizable, newFullscreen, newTitle, newHighDpi, depth))
{
return false;
}
#if OUZEL_SUPPORTS_OPENGL
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
// open a connection to the X server
display = XOpenDisplay(nullptr);
if (!display)
{
Log(Log::Level::ERR) << "Failed to open display";
return false;
}
// find an OpenGL-capable RGB visual
static int doubleBuffer[] = {
GLX_RGBA,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_DEPTH_SIZE, depth ? 24 : 0,
GLX_DOUBLEBUFFER,
None
};
Screen* screen = XDefaultScreenOfDisplay(display);
int screenIndex = XScreenNumberOfScreen(screen);
visualInfo = glXChooseVisual(display, screenIndex, doubleBuffer);
if (!visualInfo)
{
Log(Log::Level::ERR) << "Failed to choose visual";
return false;
}
if (visualInfo->c_class != TrueColor)
{
Log(Log::Level::ERR) << "TrueColor visual required for this program";
return false;
}
// create an X colormap since probably not using default visual
Colormap cmap = XCreateColormap(display, RootWindow(display, visualInfo->screen), visualInfo->visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap = cmap;
swa.border_pixel = 0;
swa.event_mask = FocusChangeMask | KeyPressMask | KeyRelease | ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
if (size.v[0] <= 0.0f) size.v[0] = static_cast<float>(XWidthOfScreen(screen)) * 0.8f;
if (size.v[1] <= 0.0f) size.v[1] = static_cast<float>(XHeightOfScreen(screen)) * 0.8f;
window = XCreateWindow(display, RootWindow(display, visualInfo->screen), 0, 0,
static_cast<unsigned int>(size.v[0]), static_cast<unsigned int>(size.v[1]),
0, visualInfo->depth, InputOutput, visualInfo->visual,
CWBorderPixel | CWColormap | CWEventMask, &swa);
XSetStandardProperties(display, window, title.c_str(), title.c_str(), None, sharedApplication->getArgv(), sharedApplication->getArgc(), nullptr);
// request the X window to be displayed on the screen
XMapWindow(display, window);
deleteMessage = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, window, &deleteMessage, 1);
protocols = XInternAtom(display, "WM_PROTOCOLS", False);
state = XInternAtom(display, "_NET_WM_STATE", False);
stateFullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False);
if (fullscreen)
{
toggleFullscreen();
}
}
#endif
return true;
}
void WindowLinux::close()
{
Window::close();
ouzel::sharedApplication->execute([this] {
XEvent event;
event.type = ClientMessage;
event.xclient.window = window;
event.xclient.message_type = protocols;
event.xclient.format = 32; // data is set as 32-bit integers
event.xclient.data.l[0] = deleteMessage;
event.xclient.data.l[1] = CurrentTime;
event.xclient.data.l[2] = 0; // unused
event.xclient.data.l[3] = 0; // unused
event.xclient.data.l[4] = 0; // unused
if (!XSendEvent(display, window, False, NoEventMask, &event))
{
Log(Log::Level::ERR) << "Failed to send X11 delete message";
}
});
}
void WindowLinux::setSize(const Size2& newSize)
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
sharedApplication->execute([this, newSize] {
XWindowChanges changes;
changes.width = static_cast<int>(newSize.v[0]);
changes.height = static_cast<int>(newSize.v[1]);
XConfigureWindow(display, window, CWWidth | CWHeight, &changes);
});
}
Window::setSize(newSize);
}
void WindowLinux::setFullscreen(bool newFullscreen)
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
if (fullscreen != newFullscreen)
{
toggleFullscreen();
}
}
Window::setFullscreen(newFullscreen);
}
void WindowLinux::setTitle(const std::string& newTitle)
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
if (title != newTitle)
{
sharedApplication->execute([this, newTitle] {
XStoreName(display, window, newTitle.c_str());
});
}
}
Window::setTitle(newTitle);
}
bool WindowLinux::toggleFullscreen()
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
if(!state || !stateFullscreen)
{
return false;
}
sharedApplication->execute([this] {
XEvent event;
event.type = ClientMessage;
event.xclient.window = window;
event.xclient.message_type = state;
event.xclient.format = 32;
event.xclient.data.l[0] = _NET_WM_STATE_TOGGLE;
event.xclient.data.l[1] = stateFullscreen;
event.xclient.data.l[2] = 0; // no second property to toggle
event.xclient.data.l[3] = 1; // source indication: application
event.xclient.data.l[4] = 0; // unused
if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureRedirectMask | SubstructureNotifyMask, &event))
{
Log(Log::Level::ERR) << "Failed to send X11 fullscreen message";
}
});
}
return true;
}
void WindowLinux::handleResize(const Size2& newSize)
{
Event event;
event.type = Event::Type::WINDOW_SIZE_CHANGE;
event.windowEvent.window = this;
event.windowEvent.size = newSize;
sharedEngine->getEventDispatcher()->postEvent(event);
}
}
<commit_msg>Create empty window on Linux if empty renderer is selected<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.
#include <memory>
#include "core/CompileConfig.h"
#if OUZEL_SUPPORTS_OPENGL
#define GL_GLEXT_PROTOTYPES 1
#include <GL/glx.h>
#endif
#include "WindowLinux.h"
#include "core/Application.h"
#include "core/Engine.h"
#include "utils/Log.h"
static const long _NET_WM_STATE_TOGGLE = 2;
namespace ouzel
{
WindowLinux::WindowLinux()
{
}
WindowLinux::~WindowLinux()
{
if (visualInfo)
{
XFree(visualInfo);
}
if (display)
{
if (window)
{
XDestroyWindow(display, window);
}
XCloseDisplay(display);
}
}
bool WindowLinux::init(const Size2& newSize,
bool newResizable,
bool newFullscreen,
const std::string& newTitle,
bool newHighDpi,
bool depth)
{
if (!Window::init(newSize, newResizable, newFullscreen, newTitle, newHighDpi, depth))
{
return false;
}
// open a connection to the X server
display = XOpenDisplay(nullptr);
if (!display)
{
Log(Log::Level::ERR) << "Failed to open display";
return false;
}
Screen* screen = XDefaultScreenOfDisplay(display);
if (size.v[0] <= 0.0f) size.v[0] = static_cast<float>(XWidthOfScreen(screen)) * 0.8f;
if (size.v[1] <= 0.0f) size.v[1] = static_cast<float>(XHeightOfScreen(screen)) * 0.8f;
switch(sharedEngine->getRenderer()->getDriver())
{
case graphics::Renderer::Driver::EMPTY:
{
XSetWindowAttributes swa;
swa.background_pixel = XWhitePixel(display, screen);
swa.event_mask = FocusChangeMask | KeyPressMask | KeyRelease | ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
window = XCreateWindow(display, RootWindow(display, screen), 0, 0,
static_cast<unsigned int>(size.v[0]), static_cast<unsigned int>(size.v[1]),
0, DefaultDepth(display, screen), InputOutput, DefaultVisual(display, screen),
CWBackPixel | CWEventMask, &swa);
break;
}
#if OUZEL_SUPPORTS_OPENGL
case graphics::Renderer::Driver::OPENGL:
{
// find an OpenGL-capable RGB visual
static int doubleBuffer[] = {
GLX_RGBA,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_DEPTH_SIZE, depth ? 24 : 0,
GLX_DOUBLEBUFFER,
None
};
int screenIndex = XScreenNumberOfScreen(screen);
visualInfo = glXChooseVisual(display, screenIndex, doubleBuffer);
if (!visualInfo)
{
Log(Log::Level::ERR) << "Failed to choose visual";
return false;
}
if (visualInfo->c_class != TrueColor)
{
Log(Log::Level::ERR) << "TrueColor visual required for this program";
return false;
}
// create an X colormap since probably not using default visual
Colormap cmap = XCreateColormap(display, RootWindow(display, visualInfo->screen), visualInfo->visual, AllocNone);
XSetWindowAttributes swa;
swa.colormap = cmap;
swa.border_pixel = 0;
swa.event_mask = FocusChangeMask | KeyPressMask | KeyRelease | ExposureMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | StructureNotifyMask;
window = XCreateWindow(display, RootWindow(display, visualInfo->screen), 0, 0,
static_cast<unsigned int>(size.v[0]), static_cast<unsigned int>(size.v[1]),
0, visualInfo->depth, InputOutput, visualInfo->visual,
CWBorderPixel | CWColormap | CWEventMask, &swa);
break;
}
#endif
default:
Log(Log::Level::ERR) << "Unsupported render driver";
return false;
}
XSetStandardProperties(display, window, title.c_str(), title.c_str(), None, sharedApplication->getArgv(), sharedApplication->getArgc(), nullptr);
// request the X window to be displayed on the screen
XMapWindow(display, window);
deleteMessage = XInternAtom(display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(display, window, &deleteMessage, 1);
protocols = XInternAtom(display, "WM_PROTOCOLS", False);
state = XInternAtom(display, "_NET_WM_STATE", False);
stateFullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False);
if (fullscreen)
{
toggleFullscreen();
}
return true;
}
void WindowLinux::close()
{
Window::close();
ouzel::sharedApplication->execute([this] {
XEvent event;
event.type = ClientMessage;
event.xclient.window = window;
event.xclient.message_type = protocols;
event.xclient.format = 32; // data is set as 32-bit integers
event.xclient.data.l[0] = deleteMessage;
event.xclient.data.l[1] = CurrentTime;
event.xclient.data.l[2] = 0; // unused
event.xclient.data.l[3] = 0; // unused
event.xclient.data.l[4] = 0; // unused
if (!XSendEvent(display, window, False, NoEventMask, &event))
{
Log(Log::Level::ERR) << "Failed to send X11 delete message";
}
});
}
void WindowLinux::setSize(const Size2& newSize)
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
sharedApplication->execute([this, newSize] {
XWindowChanges changes;
changes.width = static_cast<int>(newSize.v[0]);
changes.height = static_cast<int>(newSize.v[1]);
XConfigureWindow(display, window, CWWidth | CWHeight, &changes);
});
}
Window::setSize(newSize);
}
void WindowLinux::setFullscreen(bool newFullscreen)
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
if (fullscreen != newFullscreen)
{
toggleFullscreen();
}
}
Window::setFullscreen(newFullscreen);
}
void WindowLinux::setTitle(const std::string& newTitle)
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
if (title != newTitle)
{
sharedApplication->execute([this, newTitle] {
XStoreName(display, window, newTitle.c_str());
});
}
}
Window::setTitle(newTitle);
}
bool WindowLinux::toggleFullscreen()
{
if (sharedEngine->getRenderer()->getDriver() == graphics::Renderer::Driver::OPENGL)
{
if(!state || !stateFullscreen)
{
return false;
}
sharedApplication->execute([this] {
XEvent event;
event.type = ClientMessage;
event.xclient.window = window;
event.xclient.message_type = state;
event.xclient.format = 32;
event.xclient.data.l[0] = _NET_WM_STATE_TOGGLE;
event.xclient.data.l[1] = stateFullscreen;
event.xclient.data.l[2] = 0; // no second property to toggle
event.xclient.data.l[3] = 1; // source indication: application
event.xclient.data.l[4] = 0; // unused
if (!XSendEvent(display, DefaultRootWindow(display), 0, SubstructureRedirectMask | SubstructureNotifyMask, &event))
{
Log(Log::Level::ERR) << "Failed to send X11 fullscreen message";
}
});
}
return true;
}
void WindowLinux::handleResize(const Size2& newSize)
{
Event event;
event.type = Event::Type::WINDOW_SIZE_CHANGE;
event.windowEvent.window = this;
event.windowEvent.size = newSize;
sharedEngine->getEventDispatcher()->postEvent(event);
}
}
<|endoftext|> |
<commit_before>
// Copyright (c) 2012, 2013, 2014 Pierre MOULON.
// 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/.
#pragma once
#include "sfm_data_io.hpp"
#include "openMVG/geometry/pose3.hpp"
#include "openMVG/exif/exif_IO_EasyExif.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <fstream>
#include <vector>
namespace openMVG {
namespace sfm {
static bool read_openMVG_Camera(const std::string & camName, cameras::Pinhole_Intrinsic & cam, geometry::Pose3 & pose)
{
std::vector<double> val;
if (stlplus::extension_part(camName) == "bin")
{
std::ifstream in(camName.c_str(), std::ios::in|std::ios::binary);
if (!in.is_open())
{
std::cerr << "Error: failed to open file '" << camName << "' for reading" << std::endl;
return false;
}
val.resize(12);
in.read((char*)&val[0],(std::streamsize)12*sizeof(double));
if (in.fail())
{
val.clear();
return false;
}
}
else
{
std::ifstream ifs;
ifs.open( camName.c_str(), std::ifstream::in);
if (!ifs.is_open()) {
std::cerr << "Error: failed to open file '" << camName << "' for reading" << std::endl;
return false;
}
while (ifs.good())
{
double valT;
ifs >> valT;
if (!ifs.fail())
val.push_back(valT);
}
}
//Update the camera from file value
Mat34 P;
if (stlplus::extension_part(camName) == "bin")
{
P << val[0], val[3], val[6], val[9],
val[1], val[4], val[7], val[10],
val[2], val[5], val[8], val[11];
}
else
{
P << val[0], val[1], val[2], val[3],
val[4], val[5], val[6], val[7],
val[8], val[9], val[10], val[11];
}
Mat3 K, R;
Vec3 t;
KRt_From_P(P, &K, &R, &t);
cam = cameras::Pinhole_Intrinsic(0,0,K);
// K.transpose() is applied to give [R t] to the constructor instead of P = K [R t]
pose = geometry::Pose3(K.transpose() * P);
return true;
}
static bool read_Strecha_Camera(const std::string & camName, cameras::Pinhole_Intrinsic & cam, geometry::Pose3 & pose)
{
std::ifstream ifs;
ifs.open( camName.c_str(), std::ifstream::in);
if (!ifs.is_open()) {
std::cerr << "Error: failed to open file '" << camName << "' for reading" << std::endl;
return false;
}
std::vector<double> val;
while (ifs.good() && !ifs.eof())
{
double valT;
ifs >> valT;
if (!ifs.fail())
val.push_back(valT);
}
if (!(val.size() == 3*3 +3 +3*3 +3 + 3 || val.size() == 26)) //Strecha cam
{
std::cerr << "File " << camName << " is not in Stretcha format ! " << std::endl;
return false;
}
Mat3 K, R;
K << val[0], val[1], val[2],
val[3], val[4], val[5],
val[6], val[7], val[8];
R << val[12], val[13], val[14],
val[15], val[16], val[17],
val[18], val[19], val[20];
Vec3 C (val[21], val[22], val[23]);
// R need to be transposed
cam = cameras::Pinhole_Intrinsic(0,0,K);
cam.setWidth(val[24]);
cam.setHeight(val[25]);
pose = geometry::Pose3(R.transpose(), C);
return true;
}
/**
@brief Reads a set of Pinhole Cameras and its poses from a ground truth dataset.
@param[in] sRootPath, the directory containing an image folder "images" and a GT folder "gt_dense_cameras".
@param[out] sfm_data, the SfM_Data structure to put views/poses/intrinsics in.
@return Returns true if data has been read without errors
**/
bool readGt(const std::string sRootPath, SfM_Data & sfm_data)
{
// IF GT_Folder exists, perform evaluation of the quality of rotation estimates
const std::string sGTPath = stlplus::folder_down(sRootPath, "gt_dense_cameras");
if (!stlplus::is_folder(sGTPath))
{
std::cout << std::endl << "There is not valid GT data to read from " << sGTPath << std::endl;
return false;
}
// Switch between case to choose the file reader according to the file types in GT path
bool (*fcnReadCamPtr)(const std::string &, cameras::Pinhole_Intrinsic &, geometry::Pose3&);
std::string suffix;
if (!stlplus::folder_wildcard(sGTPath, "*.bin", true, true).empty())
{
std::cout << "\nusing openMVG Camera";
fcnReadCamPtr = &read_openMVG_Camera;
suffix = "bin";
}
else if (!stlplus::folder_wildcard(sGTPath, "*.camera", true, true).empty())
{
std::cout << "\nusing Strechas Camera";
fcnReadCamPtr = &read_Strecha_Camera;
suffix = "camera";
}
else
{
throw std::logic_error(std::string("No camera found in ") + sGTPath);
}
std::cout << std::endl << "Read rotation and translation estimates" << std::endl;
const std::string sImgPath = stlplus::folder_down(sRootPath, "images");
std::map< std::string, Mat3 > map_R_gt;
//Try to read .suffix camera (parse camera names)
std::vector<std::string> vec_camfilenames =
stlplus::folder_wildcard(sGTPath, "*."+suffix, true, true);
std::sort(vec_camfilenames.begin(), vec_camfilenames.end());
if (vec_camfilenames.empty())
{
std::cout << "No camera found in " << sGTPath << std::endl;
return false;
}
IndexT id = 0;
for (std::vector<std::string>::const_iterator iter = vec_camfilenames.begin();
iter != vec_camfilenames.end(); ++iter, ++id)
{
geometry::Pose3 pose;
std::shared_ptr<cameras::Pinhole_Intrinsic> pinholeIntrinsic = std::make_shared<cameras::Pinhole_Intrinsic>();
bool loaded = fcnReadCamPtr(stlplus::create_filespec(sGTPath, *iter), *pinholeIntrinsic.get(), pose);
if (!loaded)
{
std::cout << "Failed to load: " << *iter << std::endl;
return false;
}
const std::string sImgName = stlplus::basename_part(*iter);
const std::string sImgFile = stlplus::create_filespec(sImgPath, sImgName);
// Generate UID
if (!stlplus::file_exists(sImgFile))
{
throw std::logic_error("Impossible to generate UID from this file, because it does not exists: "+sImgFile);
}
exif::Exif_IO_EasyExif exifReader;
exifReader.open( sImgFile );
const size_t uid = computeUID(exifReader, sImgName);
// Update intrinsics with width and height of image
sfm_data.views.emplace((IndexT)uid, std::make_shared<View>(stlplus::basename_part(*iter), (IndexT)uid, id, id, pinholeIntrinsic->w(), pinholeIntrinsic->h()));
sfm_data.poses.emplace(id, pose);
sfm_data.intrinsics.emplace(id, pinholeIntrinsic);
}
return true;
}
} // namespace sfm
} // namespace openMVG<commit_msg>don't use UID when loading ground truth folder<commit_after>
// Copyright (c) 2012, 2013, 2014 Pierre MOULON.
// 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/.
#pragma once
#include "sfm_data_io.hpp"
#include "openMVG/geometry/pose3.hpp"
#include "openMVG/exif/exif_IO_EasyExif.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <fstream>
#include <vector>
namespace openMVG {
namespace sfm {
static bool read_openMVG_Camera(const std::string & camName, cameras::Pinhole_Intrinsic & cam, geometry::Pose3 & pose)
{
std::vector<double> val;
if (stlplus::extension_part(camName) == "bin")
{
std::ifstream in(camName.c_str(), std::ios::in|std::ios::binary);
if (!in.is_open())
{
std::cerr << "Error: failed to open file '" << camName << "' for reading" << std::endl;
return false;
}
val.resize(12);
in.read((char*)&val[0],(std::streamsize)12*sizeof(double));
if (in.fail())
{
val.clear();
return false;
}
}
else
{
std::ifstream ifs;
ifs.open( camName.c_str(), std::ifstream::in);
if (!ifs.is_open()) {
std::cerr << "Error: failed to open file '" << camName << "' for reading" << std::endl;
return false;
}
while (ifs.good())
{
double valT;
ifs >> valT;
if (!ifs.fail())
val.push_back(valT);
}
}
//Update the camera from file value
Mat34 P;
if (stlplus::extension_part(camName) == "bin")
{
P << val[0], val[3], val[6], val[9],
val[1], val[4], val[7], val[10],
val[2], val[5], val[8], val[11];
}
else
{
P << val[0], val[1], val[2], val[3],
val[4], val[5], val[6], val[7],
val[8], val[9], val[10], val[11];
}
Mat3 K, R;
Vec3 t;
KRt_From_P(P, &K, &R, &t);
cam = cameras::Pinhole_Intrinsic(0,0,K);
// K.transpose() is applied to give [R t] to the constructor instead of P = K [R t]
pose = geometry::Pose3(K.transpose() * P);
return true;
}
static bool read_Strecha_Camera(const std::string & camName, cameras::Pinhole_Intrinsic & cam, geometry::Pose3 & pose)
{
std::ifstream ifs;
ifs.open( camName.c_str(), std::ifstream::in);
if (!ifs.is_open()) {
std::cerr << "Error: failed to open file '" << camName << "' for reading" << std::endl;
return false;
}
std::vector<double> val;
while (ifs.good() && !ifs.eof())
{
double valT;
ifs >> valT;
if (!ifs.fail())
val.push_back(valT);
}
if (!(val.size() == 3*3 +3 +3*3 +3 + 3 || val.size() == 26)) //Strecha cam
{
std::cerr << "File " << camName << " is not in Stretcha format ! " << std::endl;
return false;
}
Mat3 K, R;
K << val[0], val[1], val[2],
val[3], val[4], val[5],
val[6], val[7], val[8];
R << val[12], val[13], val[14],
val[15], val[16], val[17],
val[18], val[19], val[20];
Vec3 C (val[21], val[22], val[23]);
// R need to be transposed
cam = cameras::Pinhole_Intrinsic(0,0,K);
cam.setWidth(val[24]);
cam.setHeight(val[25]);
pose = geometry::Pose3(R.transpose(), C);
return true;
}
/**
@brief Reads a set of Pinhole Cameras and its poses from a ground truth dataset.
@param[in] sRootPath, the directory containing an image folder "images" and a GT folder "gt_dense_cameras".
@param[out] sfm_data, the SfM_Data structure to put views/poses/intrinsics in.
@return Returns true if data has been read without errors
**/
bool readGt(const std::string sRootPath, SfM_Data & sfm_data)
{
// IF GT_Folder exists, perform evaluation of the quality of rotation estimates
const std::string sGTPath = stlplus::folder_down(sRootPath, "gt_dense_cameras");
if (!stlplus::is_folder(sGTPath))
{
std::cout << std::endl << "There is not valid GT data to read from " << sGTPath << std::endl;
return false;
}
// Switch between case to choose the file reader according to the file types in GT path
bool (*fcnReadCamPtr)(const std::string &, cameras::Pinhole_Intrinsic &, geometry::Pose3&);
std::string suffix;
if (!stlplus::folder_wildcard(sGTPath, "*.bin", true, true).empty())
{
std::cout << "\nusing openMVG Camera";
fcnReadCamPtr = &read_openMVG_Camera;
suffix = "bin";
}
else if (!stlplus::folder_wildcard(sGTPath, "*.camera", true, true).empty())
{
std::cout << "\nusing Strechas Camera";
fcnReadCamPtr = &read_Strecha_Camera;
suffix = "camera";
}
else
{
throw std::logic_error(std::string("No camera found in ") + sGTPath);
}
std::cout << std::endl << "Read rotation and translation estimates" << std::endl;
const std::string sImgPath = stlplus::folder_down(sRootPath, "images");
std::map< std::string, Mat3 > map_R_gt;
//Try to read .suffix camera (parse camera names)
std::vector<std::string> vec_camfilenames =
stlplus::folder_wildcard(sGTPath, "*."+suffix, true, true);
std::sort(vec_camfilenames.begin(), vec_camfilenames.end());
if (vec_camfilenames.empty())
{
std::cout << "No camera found in " << sGTPath << std::endl;
return false;
}
IndexT id = 0;
for (std::vector<std::string>::const_iterator iter = vec_camfilenames.begin();
iter != vec_camfilenames.end(); ++iter, ++id)
{
geometry::Pose3 pose;
std::shared_ptr<cameras::Pinhole_Intrinsic> pinholeIntrinsic = std::make_shared<cameras::Pinhole_Intrinsic>();
bool loaded = fcnReadCamPtr(stlplus::create_filespec(sGTPath, *iter), *pinholeIntrinsic.get(), pose);
if (!loaded)
{
std::cout << "Failed to load: " << *iter << std::endl;
return false;
}
const std::string sImgName = stlplus::basename_part(*iter);
const std::string sImgFile = stlplus::create_filespec(sImgPath, sImgName);
// Generate UID
if (!stlplus::file_exists(sImgFile))
{
throw std::logic_error("Impossible to generate UID from this file, because it does not exists: "+sImgFile);
}
exif::Exif_IO_EasyExif exifReader;
exifReader.open( sImgFile );
const size_t uid = computeUID(exifReader, sImgName);
// Update intrinsics with width and height of image
sfm_data.views.emplace((IndexT)uid, std::make_shared<View>(stlplus::basename_part(*iter), id, id, id, pinholeIntrinsic->w(), pinholeIntrinsic->h()));
sfm_data.poses.emplace(id, pose);
sfm_data.intrinsics.emplace(id, pinholeIntrinsic);
}
return true;
}
} // namespace sfm
} // namespace openMVG<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "socket-utils.h"
#include "Logger/Logger.h"
////////////////////////////////////////////////////////////////////////////////
/// @brief closes a socket
////////////////////////////////////////////////////////////////////////////////
int TRI_closesocket(TRI_socket_t s) {
int res = TRI_ERROR_NO_ERROR;
#ifdef _WIN32
if (s.fileHandle != TRI_INVALID_SOCKET) {
res = shutdown(s.fileHandle, SD_SEND);
if (res != 0) {
// Windows complains about shutting down a socket that was not bound
// so we will not print out the error here
// LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "socket shutdown error: " << WSAGetLastError();
} else {
char buf[256];
int len;
do {
len = TRI_readsocket(s, buf, sizeof(buf), 0);
} while (len > 0);
}
res = closesocket(s.fileHandle);
if (res != 0) {
LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "socket close error: " << WSAGetLastError();
}
// We patch libev on Windows lightly to not really distinguish between
// socket handles and file descriptors, therefore, we do not have to do the
// following any more:
// if (s.fileDescriptor != -1) {
// res = _close(s.fileDescriptor);
// "To close a file opened with _open_osfhandle, call _close."
// The underlying handle is also closed by a call to _close,
// so it is not necessary to call the Win32 function CloseHandle
// on the original handle.
// However, we do want to do the special shutdown/recv magic above
// because only then we can reuse the port quickly, which we want
// to do directly after a port test.
// }
}
#else
if (s.fileDescriptor != TRI_INVALID_SOCKET) {
res = close(s.fileDescriptor);
if (res == -1) {
int myerrno = errno;
LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "socket close error: " << myerrno << ": " << strerror(myerrno);
}
}
#endif
return res;
}
int TRI_readsocket(TRI_socket_t s, void* buffer, size_t numBytesToRead,
int flags) {
int res;
#ifdef _WIN32
res = recv(s.fileHandle, (char*)(buffer), (int)(numBytesToRead), flags);
#else
res = read(s.fileDescriptor, buffer, numBytesToRead);
#endif
return res;
}
int TRI_writesocket(TRI_socket_t s, const void* buffer, size_t numBytesToWrite,
int flags) {
int res;
#ifdef _WIN32
res =
send(s.fileHandle, (char const*)(buffer), (int)(numBytesToWrite), flags);
#else
res = (int)write(s.fileDescriptor, buffer, numBytesToWrite);
#endif
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets close-on-exit for a socket
////////////////////////////////////////////////////////////////////////////////
#ifdef TRI_HAVE_WIN32_CLOSE_ON_EXEC
bool TRI_SetCloseOnExecSocket(TRI_socket_t s) { return true; }
#else
bool TRI_SetCloseOnExecSocket(TRI_socket_t s) {
long flags = fcntl(s.fileDescriptor, F_GETFD, 0);
if (flags < 0) {
return false;
}
flags = fcntl(s.fileDescriptor, F_SETFD, flags | FD_CLOEXEC);
if (flags < 0) {
return false;
}
return true;
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief sets non-blocking mode for a socket
////////////////////////////////////////////////////////////////////////////////
#ifdef TRI_HAVE_WIN32_NON_BLOCKING
bool TRI_SetNonBlockingSocket(TRI_socket_t s) {
DWORD ul = 1;
int res = ioctlsocket(s.fileHandle, FIONBIO, &ul);
return (res == 0);
}
#else
bool TRI_SetNonBlockingSocket(TRI_socket_t s) {
long flags = fcntl(s.fileDescriptor, F_GETFL, 0);
if (flags < 0) {
return false;
}
flags = fcntl(s.fileDescriptor, F_SETFL, flags | O_NONBLOCK);
if (flags < 0) {
return false;
}
return true;
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief translates for IPv4 address
///
/// This code is copyright Internet Systems Consortium, Inc. ("ISC")
////////////////////////////////////////////////////////////////////////////////
int TRI_InetPton4(char const* src, unsigned char* dst) {
static char const digits[] = "0123456789";
int saw_digit, octets, ch;
unsigned char tmp[sizeof(struct in_addr)], *tp;
if (nullptr == src) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
saw_digit = 0;
octets = 0;
*(tp = tmp) = 0;
while ((ch = *src++) != '\0') {
char const* pch;
if ((pch = strchr(digits, ch)) != nullptr) {
unsigned int nw = (unsigned int)(*tp * 10 + (pch - digits));
if (saw_digit && *tp == 0) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (nw > 255) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*tp = nw;
if (!saw_digit) {
if (++octets > 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
saw_digit = 1;
}
} else if (ch == '.' && saw_digit) {
if (octets == 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*++tp = 0;
saw_digit = 0;
} else {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
}
if (octets < 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (nullptr != dst) {
memcpy(dst, tmp, sizeof(struct in_addr));
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief translates for IPv6 address
///
/// This code is copyright Internet Systems Consortium, Inc. ("ISC")
////////////////////////////////////////////////////////////////////////////////
int TRI_InetPton6(char const* src, unsigned char* dst) {
static char const xdigits_l[] = "0123456789abcdef";
static char const xdigits_u[] = "0123456789ABCDEF";
unsigned char tmp[sizeof(struct in6_addr)], *tp, *endp, *colonp;
char const* curtok;
int ch, seen_xdigits;
unsigned int val;
if (nullptr == src) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
memset((tp = tmp), '\0', sizeof tmp);
endp = tp + sizeof tmp;
colonp = nullptr;
/* Leading :: requires some special handling. */
if (*src == ':') {
if (*++src != ':') {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
}
curtok = src;
seen_xdigits = 0;
val = 0;
while ((ch = *src++) != '\0') {
char const* pch;
char const* xdigits;
if ((pch = strchr((xdigits = xdigits_l), ch)) == nullptr) {
pch = strchr((xdigits = xdigits_u), ch);
}
if (pch != nullptr) {
val <<= 4;
val |= (pch - xdigits);
if (++seen_xdigits > 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
continue;
}
if (ch == ':') {
curtok = src;
if (!seen_xdigits) {
if (colonp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
colonp = tp;
continue;
} else if (*src == '\0') {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (tp + sizeof(uint16_t) > endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*tp++ = (unsigned char)(val >> 8) & 0xff;
*tp++ = (unsigned char)val & 0xff;
seen_xdigits = 0;
val = 0;
continue;
}
if (ch == '.' && ((tp + sizeof(struct in_addr)) <= endp)) {
int err = TRI_InetPton4(curtok, tp);
if (err == 0) {
tp += sizeof(struct in_addr);
seen_xdigits = 0;
break; /*%< '\\0' was seen by inet_pton4(). */
}
}
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (seen_xdigits) {
if (tp + sizeof(uint16_t) > endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*tp++ = (unsigned char)(val >> 8) & 0xff;
*tp++ = (unsigned char)val & 0xff;
}
if (colonp != nullptr) {
/*
* Since some memmove()'s erroneously fail to handle
* overlapping regions, we'll do the shift by hand.
*/
int const n = (int const)(tp - colonp);
int i;
if (tp == endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
for (i = 1; i <= n; i++) {
endp[-i] = colonp[n - i];
colonp[n - i] = 0;
}
tp = endp;
}
if (tp != endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (nullptr != dst) {
memcpy(dst, tmp, sizeof tmp);
}
return TRI_ERROR_NO_ERROR;
}
<commit_msg>remove obsolete comment<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "socket-utils.h"
#include "Logger/Logger.h"
////////////////////////////////////////////////////////////////////////////////
/// @brief closes a socket
////////////////////////////////////////////////////////////////////////////////
int TRI_closesocket(TRI_socket_t s) {
int res = TRI_ERROR_NO_ERROR;
#ifdef _WIN32
if (s.fileHandle != TRI_INVALID_SOCKET) {
res = shutdown(s.fileHandle, SD_SEND);
if (res != 0) {
// Windows complains about shutting down a socket that was not bound
// so we will not print out the error here
// LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "socket shutdown error: " << WSAGetLastError();
} else {
char buf[256];
int len;
do {
len = TRI_readsocket(s, buf, sizeof(buf), 0);
} while (len > 0);
}
res = closesocket(s.fileHandle);
if (res != 0) {
LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "socket close error: " << WSAGetLastError();
}
}
#else
if (s.fileDescriptor != TRI_INVALID_SOCKET) {
res = close(s.fileDescriptor);
if (res == -1) {
int myerrno = errno;
LOG_TOPIC(WARN, arangodb::Logger::FIXME) << "socket close error: " << myerrno << ": " << strerror(myerrno);
}
}
#endif
return res;
}
int TRI_readsocket(TRI_socket_t s, void* buffer, size_t numBytesToRead,
int flags) {
int res;
#ifdef _WIN32
res = recv(s.fileHandle, (char*)(buffer), (int)(numBytesToRead), flags);
#else
res = read(s.fileDescriptor, buffer, numBytesToRead);
#endif
return res;
}
int TRI_writesocket(TRI_socket_t s, const void* buffer, size_t numBytesToWrite,
int flags) {
int res;
#ifdef _WIN32
res =
send(s.fileHandle, (char const*)(buffer), (int)(numBytesToWrite), flags);
#else
res = (int)write(s.fileDescriptor, buffer, numBytesToWrite);
#endif
return res;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief sets close-on-exit for a socket
////////////////////////////////////////////////////////////////////////////////
#ifdef TRI_HAVE_WIN32_CLOSE_ON_EXEC
bool TRI_SetCloseOnExecSocket(TRI_socket_t s) { return true; }
#else
bool TRI_SetCloseOnExecSocket(TRI_socket_t s) {
long flags = fcntl(s.fileDescriptor, F_GETFD, 0);
if (flags < 0) {
return false;
}
flags = fcntl(s.fileDescriptor, F_SETFD, flags | FD_CLOEXEC);
if (flags < 0) {
return false;
}
return true;
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief sets non-blocking mode for a socket
////////////////////////////////////////////////////////////////////////////////
#ifdef TRI_HAVE_WIN32_NON_BLOCKING
bool TRI_SetNonBlockingSocket(TRI_socket_t s) {
DWORD ul = 1;
int res = ioctlsocket(s.fileHandle, FIONBIO, &ul);
return (res == 0);
}
#else
bool TRI_SetNonBlockingSocket(TRI_socket_t s) {
long flags = fcntl(s.fileDescriptor, F_GETFL, 0);
if (flags < 0) {
return false;
}
flags = fcntl(s.fileDescriptor, F_SETFL, flags | O_NONBLOCK);
if (flags < 0) {
return false;
}
return true;
}
#endif
////////////////////////////////////////////////////////////////////////////////
/// @brief translates for IPv4 address
///
/// This code is copyright Internet Systems Consortium, Inc. ("ISC")
////////////////////////////////////////////////////////////////////////////////
int TRI_InetPton4(char const* src, unsigned char* dst) {
static char const digits[] = "0123456789";
int saw_digit, octets, ch;
unsigned char tmp[sizeof(struct in_addr)], *tp;
if (nullptr == src) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
saw_digit = 0;
octets = 0;
*(tp = tmp) = 0;
while ((ch = *src++) != '\0') {
char const* pch;
if ((pch = strchr(digits, ch)) != nullptr) {
unsigned int nw = (unsigned int)(*tp * 10 + (pch - digits));
if (saw_digit && *tp == 0) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (nw > 255) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*tp = nw;
if (!saw_digit) {
if (++octets > 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
saw_digit = 1;
}
} else if (ch == '.' && saw_digit) {
if (octets == 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*++tp = 0;
saw_digit = 0;
} else {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
}
if (octets < 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (nullptr != dst) {
memcpy(dst, tmp, sizeof(struct in_addr));
}
return TRI_ERROR_NO_ERROR;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief translates for IPv6 address
///
/// This code is copyright Internet Systems Consortium, Inc. ("ISC")
////////////////////////////////////////////////////////////////////////////////
int TRI_InetPton6(char const* src, unsigned char* dst) {
static char const xdigits_l[] = "0123456789abcdef";
static char const xdigits_u[] = "0123456789ABCDEF";
unsigned char tmp[sizeof(struct in6_addr)], *tp, *endp, *colonp;
char const* curtok;
int ch, seen_xdigits;
unsigned int val;
if (nullptr == src) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
memset((tp = tmp), '\0', sizeof tmp);
endp = tp + sizeof tmp;
colonp = nullptr;
/* Leading :: requires some special handling. */
if (*src == ':') {
if (*++src != ':') {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
}
curtok = src;
seen_xdigits = 0;
val = 0;
while ((ch = *src++) != '\0') {
char const* pch;
char const* xdigits;
if ((pch = strchr((xdigits = xdigits_l), ch)) == nullptr) {
pch = strchr((xdigits = xdigits_u), ch);
}
if (pch != nullptr) {
val <<= 4;
val |= (pch - xdigits);
if (++seen_xdigits > 4) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
continue;
}
if (ch == ':') {
curtok = src;
if (!seen_xdigits) {
if (colonp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
colonp = tp;
continue;
} else if (*src == '\0') {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (tp + sizeof(uint16_t) > endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*tp++ = (unsigned char)(val >> 8) & 0xff;
*tp++ = (unsigned char)val & 0xff;
seen_xdigits = 0;
val = 0;
continue;
}
if (ch == '.' && ((tp + sizeof(struct in_addr)) <= endp)) {
int err = TRI_InetPton4(curtok, tp);
if (err == 0) {
tp += sizeof(struct in_addr);
seen_xdigits = 0;
break; /*%< '\\0' was seen by inet_pton4(). */
}
}
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (seen_xdigits) {
if (tp + sizeof(uint16_t) > endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
*tp++ = (unsigned char)(val >> 8) & 0xff;
*tp++ = (unsigned char)val & 0xff;
}
if (colonp != nullptr) {
/*
* Since some memmove()'s erroneously fail to handle
* overlapping regions, we'll do the shift by hand.
*/
int const n = (int const)(tp - colonp);
int i;
if (tp == endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
for (i = 1; i <= n; i++) {
endp[-i] = colonp[n - i];
colonp[n - i] = 0;
}
tp = endp;
}
if (tp != endp) {
return TRI_ERROR_IP_ADDRESS_INVALID;
}
if (nullptr != dst) {
memcpy(dst, tmp, sizeof tmp);
}
return TRI_ERROR_NO_ERROR;
}
<|endoftext|> |
<commit_before>#include <stdexcept>
#include <aikido/constraint/uniform/RealVectorBoxConstraint.hpp>
namespace aikido {
namespace statespace {
using constraint::ConstraintType;
//=============================================================================
class RealVectorBoxConstraintSampleGenerator
: public constraint::SampleGenerator
{
public:
statespace::StateSpacePtr getStateSpace() const override;
bool sample(statespace::StateSpace::State* _state) override;
int getNumSamples() const override;
bool canSample() const override;
private:
RealVectorBoxConstraintSampleGenerator(
std::shared_ptr<statespace::RealVectorStateSpace> _space,
std::unique_ptr<util::RNG> _rng,
const Eigen::VectorXd& _lowerLimits,
const Eigen::VectorXd& _upperLimits);
std::shared_ptr<statespace::RealVectorStateSpace> mSpace;
std::unique_ptr<util::RNG> mRng;
std::vector<std::uniform_real_distribution<double>> mDistributions;
friend class RealVectorBoxConstraint;
};
//=============================================================================
RealVectorBoxConstraintSampleGenerator::RealVectorBoxConstraintSampleGenerator(
std::shared_ptr<statespace::RealVectorStateSpace> _space,
std::unique_ptr<util::RNG> _rng,
const Eigen::VectorXd& _lowerLimits,
const Eigen::VectorXd& _upperLimits)
: mSpace(std::move(_space))
, mRng(std::move(_rng))
{
const auto dimension = mSpace->getDimension();
mDistributions.reserve(dimension);
for (size_t i = 0; i < dimension; ++i)
mDistributions.emplace_back(_lowerLimits[i], _upperLimits[i]);
}
//=============================================================================
statespace::StateSpacePtr
RealVectorBoxConstraintSampleGenerator::getStateSpace() const
{
return mSpace;
}
//=============================================================================
bool RealVectorBoxConstraintSampleGenerator::sample(
statespace::StateSpace::State* _state)
{
Eigen::VectorXd value(mDistributions.size());
for (size_t i = 0; i < value.size(); ++i)
value[i] = mDistributions[i](*mRng);
mSpace->setValue(static_cast<RealVectorStateSpace::State*>(_state), value);
return true;
}
//=============================================================================
int RealVectorBoxConstraintSampleGenerator::getNumSamples() const
{
return NO_LIMIT;
}
//=============================================================================
bool RealVectorBoxConstraintSampleGenerator::canSample() const
{
return true;
}
//=============================================================================
RealVectorBoxConstraint
::RealVectorBoxConstraint(
std::shared_ptr<statespace::RealVectorStateSpace> _space,
std::unique_ptr<util::RNG> _rng,
const Eigen::VectorXd& _lowerLimits,
const Eigen::VectorXd& _upperLimits)
: mSpace(std::move(_space))
, mRng(std::move(_rng))
, mLowerLimits(_lowerLimits)
, mUpperLimits(_upperLimits)
{
if (!mSpace)
throw std::invalid_argument("StateSpace is null.");
if (!mRng)
throw std::invalid_argument("mRng is null.");
const auto dimension = mSpace->getDimension();
if (mLowerLimits.size() != dimension)
{
std::stringstream msg;
msg << "Lower limits have incorrect dimension: expected "
<< mSpace->getDimension() << ", got " << mLowerLimits.size() << ".";
throw std::invalid_argument(msg.str());
}
if (mUpperLimits.size() != dimension)
{
std::stringstream msg;
msg << "Upper limits have incorrect dimension: expected "
<< mSpace->getDimension() << ", got " << mUpperLimits.size() << ".";
throw std::invalid_argument(msg.str());
}
for (size_t i = 0; i < dimension; ++i)
{
if (mLowerLimits[i] > mUpperLimits[i])
{
std::stringstream msg;
msg << "Unable to sample from StateSpace because lower limit exeeds"
" upper limit on dimension " << i << ": "
<< mLowerLimits[i] << " > " << mUpperLimits[i] << ".";
throw std::invalid_argument(msg.str());
}
}
}
//=============================================================================
statespace::StateSpacePtr RealVectorBoxConstraint::getStateSpace() const
{
return mSpace;
}
//=============================================================================
size_t RealVectorBoxConstraint::getConstraintDimension() const
{
// TODO: Only create constraints for bounded dimensions.
return mSpace->getDimension();
}
//=============================================================================
std::vector<ConstraintType> RealVectorBoxConstraint::getConstraintTypes() const
{
return std::vector<ConstraintType>(
mSpace->getDimension(), ConstraintType::INEQUALITY);
}
//=============================================================================
bool RealVectorBoxConstraint::isSatisfied(const StateSpace::State* state) const
{
const auto value = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(state));
for (size_t i = 0; i < value.size(); ++i)
{
if (value[i] < mLowerLimits[i] || value[i] > mUpperLimits[i])
return false;
}
return true;
}
//=============================================================================
bool RealVectorBoxConstraint::project(
const statespace::StateSpace::State* _s,
statespace::StateSpace::State* _out) const
{
Eigen::VectorXd value = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(_s));
for (size_t i = 0; i < value.size(); ++i)
{
if (value[i] < mLowerLimits[i])
value[i] = mLowerLimits[i];
else if (value[i] > mUpperLimits[i])
value[i] = mUpperLimits[i];
}
mSpace->setValue(
static_cast<RealVectorStateSpace::State*>(_out), value);
return true;
}
//=============================================================================
Eigen::VectorXd RealVectorBoxConstraint::getValue(
const statespace::StateSpace::State* _s) const
{
auto stateValue = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(_s));
const size_t dimension = mSpace->getDimension();
Eigen::VectorXd constraintValue(dimension);
for (size_t i = 0; i < dimension; ++i)
{
if (stateValue[i] < mLowerLimits[i])
constraintValue[i] = stateValue[i] - mLowerLimits[i];
else if (stateValue[i] > mUpperLimits[i])
constraintValue[i] = mUpperLimits[i] - stateValue[i];
else
constraintValue[i] = 0.;
}
return constraintValue;
}
//=============================================================================
Eigen::MatrixXd RealVectorBoxConstraint::getJacobian(
const statespace::StateSpace::State* _s) const
{
auto stateValue = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(_s));
const size_t dimension = mSpace->getDimension();
Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(dimension, dimension);
for (size_t i = 0; i < jacobian.rows(); ++i)
{
if (stateValue[i] < mLowerLimits[i])
jacobian(i, i) = -1.;
else if (stateValue[i] > mUpperLimits[i])
jacobian(i, i) = 1.;
else
jacobian(i, i) = 0.;
}
return jacobian;
}
//=============================================================================
std::pair<Eigen::VectorXd, Eigen::MatrixXd> RealVectorBoxConstraint
::getValueAndJacobian(const statespace::StateSpace::State* _s) const
{
// TODO: Avoid calling getValue twice here.
return std::make_pair(getValue(_s), getJacobian(_s));
}
//=============================================================================
std::unique_ptr<constraint::SampleGenerator>
RealVectorBoxConstraint::createSampleGenerator() const
{
for (size_t i = 0; i < mSpace->getDimension(); ++i)
{
if (!std::isfinite(mLowerLimits[i]) || !std::isfinite(mUpperLimits[i]))
{
std::stringstream msg;
msg << "Unable to sample from StateSpace because dimension "
<< i << " is unbounded.";
throw std::runtime_error(msg.str());
}
}
return std::unique_ptr<RealVectorBoxConstraintSampleGenerator>(
new RealVectorBoxConstraintSampleGenerator(
mSpace, mRng->clone(), mLowerLimits, mUpperLimits));
}
//=============================================================================
Eigen::VectorXd RealVectorBoxConstraint::getLowerLimits()
{
return mLowerLimits;
}
//=============================================================================
Eigen::VectorXd RealVectorBoxConstraint::getUpperLimits()
{
return mUpperLimits;
}
} // namespace statespace
} // namespace aikido
<commit_msg>Fixed mRng test.<commit_after>#include <stdexcept>
#include <aikido/constraint/uniform/RealVectorBoxConstraint.hpp>
namespace aikido {
namespace statespace {
using constraint::ConstraintType;
//=============================================================================
class RealVectorBoxConstraintSampleGenerator
: public constraint::SampleGenerator
{
public:
statespace::StateSpacePtr getStateSpace() const override;
bool sample(statespace::StateSpace::State* _state) override;
int getNumSamples() const override;
bool canSample() const override;
private:
RealVectorBoxConstraintSampleGenerator(
std::shared_ptr<statespace::RealVectorStateSpace> _space,
std::unique_ptr<util::RNG> _rng,
const Eigen::VectorXd& _lowerLimits,
const Eigen::VectorXd& _upperLimits);
std::shared_ptr<statespace::RealVectorStateSpace> mSpace;
std::unique_ptr<util::RNG> mRng;
std::vector<std::uniform_real_distribution<double>> mDistributions;
friend class RealVectorBoxConstraint;
};
//=============================================================================
RealVectorBoxConstraintSampleGenerator::RealVectorBoxConstraintSampleGenerator(
std::shared_ptr<statespace::RealVectorStateSpace> _space,
std::unique_ptr<util::RNG> _rng,
const Eigen::VectorXd& _lowerLimits,
const Eigen::VectorXd& _upperLimits)
: mSpace(std::move(_space))
, mRng(std::move(_rng))
{
const auto dimension = mSpace->getDimension();
mDistributions.reserve(dimension);
for (size_t i = 0; i < dimension; ++i)
mDistributions.emplace_back(_lowerLimits[i], _upperLimits[i]);
}
//=============================================================================
statespace::StateSpacePtr
RealVectorBoxConstraintSampleGenerator::getStateSpace() const
{
return mSpace;
}
//=============================================================================
bool RealVectorBoxConstraintSampleGenerator::sample(
statespace::StateSpace::State* _state)
{
Eigen::VectorXd value(mDistributions.size());
for (size_t i = 0; i < value.size(); ++i)
value[i] = mDistributions[i](*mRng);
mSpace->setValue(static_cast<RealVectorStateSpace::State*>(_state), value);
return true;
}
//=============================================================================
int RealVectorBoxConstraintSampleGenerator::getNumSamples() const
{
return NO_LIMIT;
}
//=============================================================================
bool RealVectorBoxConstraintSampleGenerator::canSample() const
{
return true;
}
//=============================================================================
RealVectorBoxConstraint
::RealVectorBoxConstraint(
std::shared_ptr<statespace::RealVectorStateSpace> _space,
std::unique_ptr<util::RNG> _rng,
const Eigen::VectorXd& _lowerLimits,
const Eigen::VectorXd& _upperLimits)
: mSpace(std::move(_space))
, mRng(std::move(_rng))
, mLowerLimits(_lowerLimits)
, mUpperLimits(_upperLimits)
{
if (!mSpace)
throw std::invalid_argument("StateSpace is null.");
const auto dimension = mSpace->getDimension();
if (mLowerLimits.size() != dimension)
{
std::stringstream msg;
msg << "Lower limits have incorrect dimension: expected "
<< mSpace->getDimension() << ", got " << mLowerLimits.size() << ".";
throw std::invalid_argument(msg.str());
}
if (mUpperLimits.size() != dimension)
{
std::stringstream msg;
msg << "Upper limits have incorrect dimension: expected "
<< mSpace->getDimension() << ", got " << mUpperLimits.size() << ".";
throw std::invalid_argument(msg.str());
}
for (size_t i = 0; i < dimension; ++i)
{
if (mLowerLimits[i] > mUpperLimits[i])
{
std::stringstream msg;
msg << "Unable to sample from StateSpace because lower limit exeeds"
" upper limit on dimension " << i << ": "
<< mLowerLimits[i] << " > " << mUpperLimits[i] << ".";
throw std::invalid_argument(msg.str());
}
}
}
//=============================================================================
statespace::StateSpacePtr RealVectorBoxConstraint::getStateSpace() const
{
return mSpace;
}
//=============================================================================
size_t RealVectorBoxConstraint::getConstraintDimension() const
{
// TODO: Only create constraints for bounded dimensions.
return mSpace->getDimension();
}
//=============================================================================
std::vector<ConstraintType> RealVectorBoxConstraint::getConstraintTypes() const
{
return std::vector<ConstraintType>(
mSpace->getDimension(), ConstraintType::INEQUALITY);
}
//=============================================================================
bool RealVectorBoxConstraint::isSatisfied(const StateSpace::State* state) const
{
const auto value = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(state));
for (size_t i = 0; i < value.size(); ++i)
{
if (value[i] < mLowerLimits[i] || value[i] > mUpperLimits[i])
return false;
}
return true;
}
//=============================================================================
bool RealVectorBoxConstraint::project(
const statespace::StateSpace::State* _s,
statespace::StateSpace::State* _out) const
{
Eigen::VectorXd value = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(_s));
for (size_t i = 0; i < value.size(); ++i)
{
if (value[i] < mLowerLimits[i])
value[i] = mLowerLimits[i];
else if (value[i] > mUpperLimits[i])
value[i] = mUpperLimits[i];
}
mSpace->setValue(
static_cast<RealVectorStateSpace::State*>(_out), value);
return true;
}
//=============================================================================
Eigen::VectorXd RealVectorBoxConstraint::getValue(
const statespace::StateSpace::State* _s) const
{
auto stateValue = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(_s));
const size_t dimension = mSpace->getDimension();
Eigen::VectorXd constraintValue(dimension);
for (size_t i = 0; i < dimension; ++i)
{
if (stateValue[i] < mLowerLimits[i])
constraintValue[i] = stateValue[i] - mLowerLimits[i];
else if (stateValue[i] > mUpperLimits[i])
constraintValue[i] = mUpperLimits[i] - stateValue[i];
else
constraintValue[i] = 0.;
}
return constraintValue;
}
//=============================================================================
Eigen::MatrixXd RealVectorBoxConstraint::getJacobian(
const statespace::StateSpace::State* _s) const
{
auto stateValue = mSpace->getValue(
static_cast<const RealVectorStateSpace::State*>(_s));
const size_t dimension = mSpace->getDimension();
Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(dimension, dimension);
for (size_t i = 0; i < jacobian.rows(); ++i)
{
if (stateValue[i] < mLowerLimits[i])
jacobian(i, i) = -1.;
else if (stateValue[i] > mUpperLimits[i])
jacobian(i, i) = 1.;
else
jacobian(i, i) = 0.;
}
return jacobian;
}
//=============================================================================
std::pair<Eigen::VectorXd, Eigen::MatrixXd> RealVectorBoxConstraint
::getValueAndJacobian(const statespace::StateSpace::State* _s) const
{
// TODO: Avoid calling getValue twice here.
return std::make_pair(getValue(_s), getJacobian(_s));
}
//=============================================================================
std::unique_ptr<constraint::SampleGenerator>
RealVectorBoxConstraint::createSampleGenerator() const
{
if (!mRng)
throw std::invalid_argument("mRng is null.");
for (size_t i = 0; i < mSpace->getDimension(); ++i)
{
if (!std::isfinite(mLowerLimits[i]) || !std::isfinite(mUpperLimits[i]))
{
std::stringstream msg;
msg << "Unable to sample from StateSpace because dimension "
<< i << " is unbounded.";
throw std::runtime_error(msg.str());
}
}
return std::unique_ptr<RealVectorBoxConstraintSampleGenerator>(
new RealVectorBoxConstraintSampleGenerator(
mSpace, mRng->clone(), mLowerLimits, mUpperLimits));
}
//=============================================================================
Eigen::VectorXd RealVectorBoxConstraint::getLowerLimits()
{
return mLowerLimits;
}
//=============================================================================
Eigen::VectorXd RealVectorBoxConstraint::getUpperLimits()
{
return mUpperLimits;
}
} // namespace statespace
} // namespace aikido
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/keyboard_codes.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/find_bar_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/views/find_bar_host.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"
namespace {
// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const char kSimplePage[] = "files/find_in_page/simple.html";
class FindInPageTest : public InProcessBrowserTest {
public:
FindInPageTest() {
set_show_window(true);
FindBarHost::disable_animations_during_testing_ = true;
}
string16 GetFindBarText() {
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
return find_bar->GetFindText();
}
};
} // namespace
IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) {
ASSERT_TRUE(test_server()->Start());
// First we navigate to our test page (tab A).
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
browser()->Find();
// Open another tab (tab B).
browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Select tab A.
browser()->SelectTabContentsAt(0, true);
// Close tab B.
browser()->CloseTabContents(browser()->GetTabContentsAt(1));
// Click on the location bar so that Find box loses focus.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_LOCATION_BAR));
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
// Check the location bar is focused.
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
#endif
// This used to crash until bug 1303709 was fixed.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_ESCAPE, false, false, false, false));
}
IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL("title1.html");
ui_test_utils::NavigateToURL(browser(), url);
// Focus the location bar, open and close the find-in-page, focus should
// return to the location bar.
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Ensure the creation of the find bar controller.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Focus the location bar, find something on the page, close the find box,
// focus should go to the page.
browser()->FocusLocationBar();
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
ui_test_utils::FindInPage(browser()->GetSelectedTabContents(),
ASCIIToUTF16("a"), true, false, NULL);
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Focus the location bar, open and close the find box, focus should return to
// the location bar (same as before, just checking that http://crbug.com/23599
// is fixed).
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}
// This tests that whenever you clear values from the Find box and close it that
// it respects that and doesn't show you the last search, as reported in bug:
// http://crbug.com/40121.
// Disabled, http://crbug.com/62937.
IN_PROC_BROWSER_TEST_F(FindInPageTest, DISABLED_PrepopulateRespectBlank) {
#if defined(OS_MACOSX)
// FindInPage on Mac doesn't use prepopulated values. Search there is global.
return;
#endif
ASSERT_TRUE(test_server()->Start());
// First we navigate to any page.
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
// Show the Find bar.
browser()->GetFindBarController()->Show();
// Search for "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_A, false, false, false, false));
// We should find "a" here.
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());
// Delete "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_BACK, false, false, false, false));
// Validate we have cleared the text.
EXPECT_EQ(string16(), GetFindBarText());
// Close the Find box.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_ESCAPE, false, false, false, false));
// Show the Find bar.
browser()->GetFindBarController()->Show();
// After the Find box has been reopened, it should not have been prepopulated
// with "a" again.
EXPECT_EQ(string16(), GetFindBarText());
// Close the Find box.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_ESCAPE, false, false, false, false));
// Press F3 to trigger FindNext.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_F3, false, false, false, false));
// After the Find box has been reopened, it should still have no prepopulate
// value.
EXPECT_EQ(string16(), GetFindBarText());
}
<commit_msg>Add timing traces to PrepopulateRespectBlank to try to track down a timeout in the test. <commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/keyboard_codes.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/find_bar_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/views/find_bar_host.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/test/test_server.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"
namespace {
// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const char kSimplePage[] = "files/find_in_page/simple.html";
class FindInPageTest : public InProcessBrowserTest {
public:
FindInPageTest() {
set_show_window(true);
FindBarHost::disable_animations_during_testing_ = true;
}
string16 GetFindBarText() {
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
return find_bar->GetFindText();
}
};
void Checkpoint(const char* message, const base::TimeTicks& start_time) {
LOG(INFO) << message << " : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
}
} // namespace
IN_PROC_BROWSER_TEST_F(FindInPageTest, CrashEscHandlers) {
ASSERT_TRUE(test_server()->Start());
// First we navigate to our test page (tab A).
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
browser()->Find();
// Open another tab (tab B).
browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Select tab A.
browser()->SelectTabContentsAt(0, true);
// Close tab B.
browser()->CloseTabContents(browser()->GetTabContentsAt(1));
// Click on the location bar so that Find box loses focus.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_LOCATION_BAR));
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
// Check the location bar is focused.
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
#endif
// This used to crash until bug 1303709 was fixed.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_ESCAPE, false, false, false, false));
}
IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL("title1.html");
ui_test_utils::NavigateToURL(browser(), url);
// Focus the location bar, open and close the find-in-page, focus should
// return to the location bar.
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Ensure the creation of the find bar controller.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Focus the location bar, find something on the page, close the find box,
// focus should go to the page.
browser()->FocusLocationBar();
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
ui_test_utils::FindInPage(browser()->GetSelectedTabContents(),
ASCIIToUTF16("a"), true, false, NULL);
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Focus the location bar, open and close the find box, focus should return to
// the location bar (same as before, just checking that http://crbug.com/23599
// is fixed).
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}
// This tests that whenever you clear values from the Find box and close it that
// it respects that and doesn't show you the last search, as reported in bug:
// http://crbug.com/40121.
IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {
#if defined(OS_MACOSX)
// FindInPage on Mac doesn't use prepopulated values. Search there is global.
return;
#endif
base::TimeTicks start_time = base::TimeTicks::Now();
Checkpoint("Starting test server", start_time);
ASSERT_TRUE(test_server()->Start());
// First we navigate to any page.
Checkpoint("Navigating", start_time);
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
// Show the Find bar.
Checkpoint("Showing Find window", start_time);
browser()->GetFindBarController()->Show();
// Search for "a".
Checkpoint("Search for 'a'", start_time);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_A, false, false, false, false));
// We should find "a" here.
Checkpoint("GetFindBarText", start_time);
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());
// Delete "a".
Checkpoint("Delete 'a'", start_time);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_BACK, false, false, false, false));
// Validate we have cleared the text.
Checkpoint("Validate clear", start_time);
EXPECT_EQ(string16(), GetFindBarText());
// Close the Find box.
Checkpoint("Close find", start_time);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_ESCAPE, false, false, false, false));
// Show the Find bar.
Checkpoint("Showing Find window", start_time);
browser()->GetFindBarController()->Show();
// After the Find box has been reopened, it should not have been prepopulated
// with "a" again.
Checkpoint("GetFindBarText", start_time);
EXPECT_EQ(string16(), GetFindBarText());
// Close the Find box.
Checkpoint("Press Esc", start_time);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_ESCAPE, false, false, false, false));
// Press F3 to trigger FindNext.
Checkpoint("Press F3", start_time);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), app::VKEY_F3, false, false, false, false));
// After the Find box has been reopened, it should still have no prepopulate
// value.
Checkpoint("GetFindBarText", start_time);
EXPECT_EQ(string16(), GetFindBarText());
Checkpoint("Test completed", start_time);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/infobars/after_translate_infobar.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/translate/translate_infobar_delegate.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/controls/button/menu_button.h"
#include "views/controls/label.h"
#include "views/controls/menu/menu_2.h"
AfterTranslateInfoBar::AfterTranslateInfoBar(
TranslateInfoBarDelegate* delegate)
: TranslateInfoBarBase(delegate),
label_1_(NULL),
label_2_(NULL),
label_3_(NULL),
original_language_menu_button_(NULL),
target_language_menu_button_(NULL),
revert_button_(NULL),
options_menu_button_(NULL),
original_language_menu_model_(delegate, LanguagesMenuModel::ORIGINAL),
target_language_menu_model_(delegate, LanguagesMenuModel::TARGET),
options_menu_model_(delegate),
swapped_language_buttons_(false) {
}
AfterTranslateInfoBar::~AfterTranslateInfoBar() {
}
void AfterTranslateInfoBar::Layout() {
TranslateInfoBarBase::Layout();
int available_width = std::max(0, EndX() - StartX() - ContentMinimumWidth());
gfx::Size label_1_size = label_1_->GetPreferredSize();
label_1_->SetBounds(StartX(), OffsetY(this, label_1_size),
std::min(label_1_size.width(), available_width), label_1_size.height());
available_width = std::max(0, available_width - label_1_size.width());
views::MenuButton* first_button = original_language_menu_button_;
views::MenuButton* second_button = target_language_menu_button_;
if (swapped_language_buttons_)
std::swap(first_button, second_button);
gfx::Size first_button_size = first_button->GetPreferredSize();
first_button->SetBounds(label_1_->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, first_button_size), first_button_size.width(),
first_button_size.height());
gfx::Size label_2_size = label_2_->GetPreferredSize();
label_2_->SetBounds(first_button->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, label_2_size),
std::min(label_2_size.width(), available_width), label_2_size.height());
available_width = std::max(0, available_width - label_2_size.width());
gfx::Size second_button_size = second_button->GetPreferredSize();
second_button->SetBounds(label_2_->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, second_button_size), second_button_size.width(),
second_button_size.height());
gfx::Size label_3_size = label_3_->GetPreferredSize();
label_3_->SetBounds(second_button->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, label_3_size),
std::min(label_3_size.width(), available_width), label_3_size.height());
gfx::Size revert_button_size = revert_button_->GetPreferredSize();
revert_button_->SetBounds(label_3_->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, revert_button_size),
revert_button_size.width(), revert_button_size.height());
gfx::Size options_size = options_menu_button_->GetPreferredSize();
options_menu_button_->SetBounds(EndX() - options_size.width(),
OffsetY(this, options_size), options_size.width(), options_size.height());
}
void AfterTranslateInfoBar::ViewHierarchyChanged(bool is_add,
View* parent,
View* child) {
if (!is_add || (child != this) || (label_1_ != NULL)) {
TranslateInfoBarBase::ViewHierarchyChanged(is_add, parent, child);
return;
}
std::vector<string16> strings;
GetDelegate()->GetAfterTranslateStrings(&strings, &swapped_language_buttons_);
DCHECK_EQ(3U, strings.size());
label_1_ = CreateLabel(strings[0]);
AddChildView(label_1_);
original_language_menu_button_ = CreateMenuButton(string16(), true, this);
target_language_menu_button_ = CreateMenuButton(string16(), true, this);
AddChildView(swapped_language_buttons_ ?
target_language_menu_button_ : original_language_menu_button_);
label_2_ = CreateLabel(strings[1]);
AddChildView(label_2_);
AddChildView(swapped_language_buttons_ ?
original_language_menu_button_ : target_language_menu_button_);
label_3_ = CreateLabel(strings[2]);
AddChildView(label_3_);
revert_button_ = CreateTextButton(this,
l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_REVERT), false);
AddChildView(revert_button_);
options_menu_button_ = CreateMenuButton(
l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_OPTIONS), false, this);
AddChildView(options_menu_button_);
// This must happen after adding all other children so InfoBarView can ensure
// the close button is the last child.
TranslateInfoBarBase::ViewHierarchyChanged(is_add, parent, child);
// These must happen after adding all children because they trigger layout,
// which assumes that particular children (e.g. the close button) have already
// been added.
OriginalLanguageChanged();
TargetLanguageChanged();
}
void AfterTranslateInfoBar::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender == revert_button_)
GetDelegate()->RevertTranslation();
else
TranslateInfoBarBase::ButtonPressed(sender, event);
}
int AfterTranslateInfoBar::ContentMinimumWidth() const {
return
(kButtonInLabelSpacing +
original_language_menu_button_->GetPreferredSize().width() +
kButtonInLabelSpacing) +
(kButtonInLabelSpacing +
target_language_menu_button_->GetPreferredSize().width() +
kButtonInLabelSpacing) +
(kButtonInLabelSpacing + revert_button_->GetPreferredSize().width()) +
(kEndOfLabelSpacing + options_menu_button_->GetPreferredSize().width());
}
void AfterTranslateInfoBar::OriginalLanguageChanged() {
UpdateLanguageButtonText(original_language_menu_button_,
LanguagesMenuModel::ORIGINAL);
}
void AfterTranslateInfoBar::TargetLanguageChanged() {
UpdateLanguageButtonText(target_language_menu_button_,
LanguagesMenuModel::TARGET);
}
void AfterTranslateInfoBar::RunMenu(View* source, const gfx::Point& pt) {
if (source == original_language_menu_button_) {
original_language_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
} else if (source == target_language_menu_button_) {
target_language_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
} else {
DCHECK_EQ(options_menu_button_, source);
options_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
}
<commit_msg>Fix uninitialized variables.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/infobars/after_translate_infobar.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/translate/translate_infobar_delegate.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "views/controls/button/menu_button.h"
#include "views/controls/label.h"
#include "views/controls/menu/menu_2.h"
AfterTranslateInfoBar::AfterTranslateInfoBar(
TranslateInfoBarDelegate* delegate)
: TranslateInfoBarBase(delegate),
label_1_(NULL),
label_2_(NULL),
label_3_(NULL),
original_language_menu_button_(NULL),
target_language_menu_button_(NULL),
revert_button_(NULL),
options_menu_button_(NULL),
original_language_menu_model_(delegate, LanguagesMenuModel::ORIGINAL),
original_language_menu_(new views::Menu2(&original_language_menu_model_)),
target_language_menu_model_(delegate, LanguagesMenuModel::TARGET),
target_language_menu_(new views::Menu2(&target_language_menu_model_)),
options_menu_model_(delegate),
options_menu_(new views::Menu2(&options_menu_model_)),
swapped_language_buttons_(false) {
}
AfterTranslateInfoBar::~AfterTranslateInfoBar() {
}
void AfterTranslateInfoBar::Layout() {
TranslateInfoBarBase::Layout();
int available_width = std::max(0, EndX() - StartX() - ContentMinimumWidth());
gfx::Size label_1_size = label_1_->GetPreferredSize();
label_1_->SetBounds(StartX(), OffsetY(this, label_1_size),
std::min(label_1_size.width(), available_width), label_1_size.height());
available_width = std::max(0, available_width - label_1_size.width());
views::MenuButton* first_button = original_language_menu_button_;
views::MenuButton* second_button = target_language_menu_button_;
if (swapped_language_buttons_)
std::swap(first_button, second_button);
gfx::Size first_button_size = first_button->GetPreferredSize();
first_button->SetBounds(label_1_->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, first_button_size), first_button_size.width(),
first_button_size.height());
gfx::Size label_2_size = label_2_->GetPreferredSize();
label_2_->SetBounds(first_button->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, label_2_size),
std::min(label_2_size.width(), available_width), label_2_size.height());
available_width = std::max(0, available_width - label_2_size.width());
gfx::Size second_button_size = second_button->GetPreferredSize();
second_button->SetBounds(label_2_->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, second_button_size), second_button_size.width(),
second_button_size.height());
gfx::Size label_3_size = label_3_->GetPreferredSize();
label_3_->SetBounds(second_button->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, label_3_size),
std::min(label_3_size.width(), available_width), label_3_size.height());
gfx::Size revert_button_size = revert_button_->GetPreferredSize();
revert_button_->SetBounds(label_3_->bounds().right() + kButtonInLabelSpacing,
OffsetY(this, revert_button_size),
revert_button_size.width(), revert_button_size.height());
gfx::Size options_size = options_menu_button_->GetPreferredSize();
options_menu_button_->SetBounds(EndX() - options_size.width(),
OffsetY(this, options_size), options_size.width(), options_size.height());
}
void AfterTranslateInfoBar::ViewHierarchyChanged(bool is_add,
View* parent,
View* child) {
if (!is_add || (child != this) || (label_1_ != NULL)) {
TranslateInfoBarBase::ViewHierarchyChanged(is_add, parent, child);
return;
}
std::vector<string16> strings;
GetDelegate()->GetAfterTranslateStrings(&strings, &swapped_language_buttons_);
DCHECK_EQ(3U, strings.size());
label_1_ = CreateLabel(strings[0]);
AddChildView(label_1_);
original_language_menu_button_ = CreateMenuButton(string16(), true, this);
target_language_menu_button_ = CreateMenuButton(string16(), true, this);
AddChildView(swapped_language_buttons_ ?
target_language_menu_button_ : original_language_menu_button_);
label_2_ = CreateLabel(strings[1]);
AddChildView(label_2_);
AddChildView(swapped_language_buttons_ ?
original_language_menu_button_ : target_language_menu_button_);
label_3_ = CreateLabel(strings[2]);
AddChildView(label_3_);
revert_button_ = CreateTextButton(this,
l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_REVERT), false);
AddChildView(revert_button_);
options_menu_button_ = CreateMenuButton(
l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_OPTIONS), false, this);
AddChildView(options_menu_button_);
// This must happen after adding all other children so InfoBarView can ensure
// the close button is the last child.
TranslateInfoBarBase::ViewHierarchyChanged(is_add, parent, child);
// These must happen after adding all children because they trigger layout,
// which assumes that particular children (e.g. the close button) have already
// been added.
OriginalLanguageChanged();
TargetLanguageChanged();
}
void AfterTranslateInfoBar::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender == revert_button_)
GetDelegate()->RevertTranslation();
else
TranslateInfoBarBase::ButtonPressed(sender, event);
}
int AfterTranslateInfoBar::ContentMinimumWidth() const {
return
(kButtonInLabelSpacing +
original_language_menu_button_->GetPreferredSize().width() +
kButtonInLabelSpacing) +
(kButtonInLabelSpacing +
target_language_menu_button_->GetPreferredSize().width() +
kButtonInLabelSpacing) +
(kButtonInLabelSpacing + revert_button_->GetPreferredSize().width()) +
(kEndOfLabelSpacing + options_menu_button_->GetPreferredSize().width());
}
void AfterTranslateInfoBar::OriginalLanguageChanged() {
UpdateLanguageButtonText(original_language_menu_button_,
LanguagesMenuModel::ORIGINAL);
}
void AfterTranslateInfoBar::TargetLanguageChanged() {
UpdateLanguageButtonText(target_language_menu_button_,
LanguagesMenuModel::TARGET);
}
void AfterTranslateInfoBar::RunMenu(View* source, const gfx::Point& pt) {
if (source == original_language_menu_button_) {
original_language_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
} else if (source == target_language_menu_button_) {
target_language_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
} else {
DCHECK_EQ(options_menu_button_, source);
options_menu_->RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
}
<|endoftext|> |
<commit_before>// Name: clibgame.hpp
//
// Description:
// This file re-exports the rest of the library such that one need only use
// one include if they so choose.
#ifndef _CLIBGAME_HPP_
#define _CLIBGAME_HPP_
#include "clibgame/res/animation.hpp"
#include "clibgame/res/texsheet.hpp"
#include "clibgame/res/texable.hpp"
#include "clibgame/res/texture.hpp"
#include "clibgame/res/shader.hpp"
#include "clibgame/eventing.hpp"
#include "clibgame/engine.hpp"
#include "clibgame/delta.hpp"
#include "clibgame/timer.hpp"
#include "clibgame/ecp.hpp"
#include "clibgame/res.hpp"
#endif
<commit_msg>Added engineconfig & font to the clibgame.hpp include.<commit_after>// Name: clibgame.hpp
//
// Description:
// This file re-exports the rest of the library such that one need only use
// one include if they so choose.
#ifndef _CLIBGAME_HPP_
#define _CLIBGAME_HPP_
#include "clibgame/res/animation.hpp"
#include "clibgame/res/texsheet.hpp"
#include "clibgame/engineconfig.hpp"
#include "clibgame/res/texable.hpp"
#include "clibgame/res/texture.hpp"
#include "clibgame/res/shader.hpp"
#include "clibgame/res/font.hpp"
#include "clibgame/eventing.hpp"
#include "clibgame/engine.hpp"
#include "clibgame/delta.hpp"
#include "clibgame/timer.hpp"
#include "clibgame/ecp.hpp"
#include "clibgame/res.hpp"
#endif
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "ECEditorWindow.h"
#include "ECEditorModule.h"
#include "ModuleManager.h"
#include "UiModule.h"
#include "SceneManager.h"
#include "ComponentInterface.h"
#include "ComponentManager.h"
#include "Inworld/InworldSceneController.h"
#include "Inworld/View/UiProxyWidget.h"
#include "XmlUtilities.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include <QDomDocument>
#include <QVBoxLayout>
#include <QUiLoader>
#include <QFile>
#include <QPushButton>
#include <QTextEdit>
#include <QComboBox>
#include <QListWidget>
using namespace RexTypes;
namespace ECEditor
{
uint AddUniqueItem(QListWidget* list, const QString& name)
{
for (int i = 0; i < list->count(); ++i)
{
if (list->item(i)->text() == name)
return i;
}
list->addItem(name);
return list->count() - 1;
}
ECEditorWindow::ECEditorWindow(Foundation::Framework* framework) :
framework_(framework),
contents_(0),
save_button_(0),
revert_button_(0),
create_button_(0),
delete_button_(0),
entity_list_(0),
component_list_(0),
create_combo_(0),
data_edit_(0),
delete_shortcut_(0)
{
Initialize();
}
ECEditorWindow::~ECEditorWindow()
{
}
void ECEditorWindow::Initialize()
{
QUiLoader loader;
QFile file("./data/ui/eceditor.ui");
file.open(QFile::ReadOnly);
contents_ = loader.load(&file, this);
if (!contents_)
{
ECEditorModule::LogError("Could not load editor layout");
return;
}
file.close();
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(contents_);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
save_button_ = findChild<QPushButton*>("but_save");
revert_button_ = findChild<QPushButton*>("but_revert");
create_button_ = findChild<QPushButton*>("but_create");
delete_button_ = findChild<QPushButton*>("but_delete");
entity_list_ = findChild<QListWidget*>("list_entities");
component_list_ = findChild<QListWidget*>("list_components");
data_edit_ = findChild<QTextEdit*>("text_attredit");
create_combo_ = findChild<QComboBox*>("combo_create");
if (entity_list_)
{
entity_list_->setSelectionMode(QAbstractItemView::ExtendedSelection);
delete_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Delete), entity_list_);
QObject::connect(entity_list_, SIGNAL(itemSelectionChanged()), this, SLOT(RefreshEntityComponents()));
QObject::connect(delete_shortcut_, SIGNAL(activated()), this, SLOT(DeleteEntitiesFromList()));
}
if (component_list_)
{
component_list_->setSelectionMode(QAbstractItemView::ExtendedSelection);
QObject::connect(component_list_, SIGNAL(itemSelectionChanged()), this, SLOT(RefreshComponentData()));
}
if (delete_button_)
QObject::connect(delete_button_, SIGNAL(pressed()), this, SLOT(DeleteComponent()));
if (create_button_)
QObject::connect(create_button_, SIGNAL(pressed()), this, SLOT(CreateComponent()));
if (save_button_)
QObject::connect(save_button_, SIGNAL(pressed()), this, SLOT(SaveData()));
if (revert_button_)
QObject::connect(revert_button_, SIGNAL(pressed()), this, SLOT(RevertData()));
boost::shared_ptr<UiServices::UiModule> ui_module = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(
Foundation::Module::MT_UiServices).lock();
if (ui_module)
ui_module->GetInworldSceneController()->AddWidgetToScene(this, UiServices::UiWidgetProperties(contents_->windowTitle(), UiServices::ModuleWidget));
else
ECEditorModule::LogError("Could not add widget to scene");
RefreshAvailableComponents();
}
void ECEditorWindow::RefreshAvailableComponents()
{
// Fill the create component combo box with the types of EC's the ComponentManager can create
Foundation::ComponentManagerPtr comp_mgr = framework_->GetComponentManager();
const Foundation::ComponentManager::ComponentFactoryMap& factories = comp_mgr->GetComponentFactoryMap();
if (create_combo_)
{
create_combo_->clear();
Foundation::ComponentManager::ComponentFactoryMap::const_iterator i = factories.begin();
while (i != factories.end())
{
create_combo_->addItem(QString::fromStdString(i->first));
++i;
}
}
}
void ECEditorWindow::DeleteComponent()
{
if (!component_list_)
return;
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
StringVector components;
for (uint i = 0; i < component_list_->count(); ++i)
{
QListWidgetItem* item = component_list_->item(i);
if (item->isSelected())
components.push_back(item->text().toStdString());
}
for (uint i = 0; i < entities.size(); ++i)
{
for (uint j = 0; j < components.size(); ++j)
entities[i]->RemoveComponent(entities[i]->GetComponent(components[j]));
}
RefreshEntityComponents();
}
void ECEditorWindow::CreateComponent()
{
if (!create_combo_)
return;
std::string name = create_combo_->currentText().toStdString();
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
for (uint i = 0; i < entities.size(); ++i)
{
// We (mis)use the GetOrCreateComponent function to avoid adding the same EC multiple times, since identifying multiple EC's of similar type
// is problematic with current API
entities[i]->GetOrCreateComponent(name);
}
RefreshEntityComponents();
}
void ECEditorWindow::RevertData()
{
RefreshComponentData();
}
void ECEditorWindow::SaveData()
{
if (!data_edit_)
return;
QDomDocument edited_doc;
QString text = data_edit_->toPlainText();
if (!text.length())
{
ECEditorModule::LogWarning("Empty XML data");
return;
}
if (edited_doc.setContent(text))
{
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
bool entity_found = false;
// Check if multi-entity or single-entity
QDomElement entities_elem = edited_doc.firstChildElement("entities");
// Deserialize all entities/components contained in the data, provided we still find them from the scene
QDomElement entity_elem;
if (!entities_elem.isNull())
entity_elem = entities_elem.firstChildElement("entity");
else
entity_elem = edited_doc.firstChildElement("entity");
while (!entity_elem.isNull())
{
entity_found = true;
entity_id_t id = (entity_id_t)ParseInt(entity_elem.attribute("id").toStdString());
Scene::EntityPtr entity = scene->GetEntity(id);
if (entity)
{
QDomElement comp_elem = entity_elem.firstChildElement("component");
while (!comp_elem.isNull())
{
Foundation::ComponentInterfacePtr comp = entity->GetComponent(comp_elem.attribute("type").toStdString());
if (comp)
comp->DeserializeFrom(comp_elem);
comp_elem = comp_elem.nextSiblingElement("component");
}
Scene::Events::SceneEventData event_data(id);
Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
event_manager->SendEvent(event_manager->QueryEventCategory("Scene"), Scene::Events::EVENT_ENTITY_ECS_MODIFIED, &event_data);
}
else
{
ECEditorModule::LogWarning("Could not find entity " + ToString<int>(id) + " in scene!");
}
entity_elem = entity_elem.nextSiblingElement("entity");
}
// Refresh immediately after, so that any extra stuff is stripped out, and illegal parameters are (hopefully) straightened
if (entity_found)
RefreshComponentData();
else
ECEditorModule::LogWarning("No entity elements in XML data");
}
else
ECEditorModule::LogWarning("Could not parse XML data");
}
void ECEditorWindow::hideEvent(QHideEvent* hide_event)
{
ClearEntities();
QWidget::hideEvent(hide_event);
}
void ECEditorWindow::showEvent(QShowEvent* show_event)
{
RefreshAvailableComponents();
QWidget::showEvent(show_event);
}
void ECEditorWindow::DeleteEntitiesFromList()
{
if ((entity_list_) && (entity_list_->hasFocus()))
{
for (int i = entity_list_->count() - 1; i >= 0; --i)
{
if (entity_list_->item(i)->isSelected())
{
QListWidgetItem* item = entity_list_->takeItem(i);
delete item;
}
}
}
}
void ECEditorWindow::AddEntity(entity_id_t entity_id)
{
if ((isVisible()) && (entity_list_))
{
QString entity_id_str;
entity_id_str.setNum((int)entity_id);
entity_list_->setCurrentRow(AddUniqueItem(entity_list_, entity_id_str));
}
}
void ECEditorWindow::RefreshEntityComponents()
{
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
// If no entities selected, just clear the list and we're done
if (!entities.size())
{
component_list_->clear();
return;
}
std::vector<QString> added_components;
for (uint i = 0; i < entities.size(); ++i)
{
const Scene::Entity::ComponentVector& components = entities[i]->GetComponentVector();
for (uint j = 0; j < components.size(); ++j)
{
QString component_name = QString::fromStdString(components[j]->TypeName());
added_components.push_back(component_name);
// If multiple selected entities have the same component, add it only once to the EC selector list
AddUniqueItem(component_list_, QString::fromStdString(components[j]->TypeName()));
}
}
// Now delete components that should not be in the component list
// This code is kind of ugly...
// Note: the whole reason for going to this trouble (instead of just nuking and refilling the list)
// is to retain the user's selection, if several entities share a set of components, as often is the case
for (int i = component_list_->count() - 1; i >= 0; --i)
{
bool found = false;
QListWidgetItem* item = component_list_->item(i);
for (uint j = 0; j < added_components.size(); ++j)
{
if (item->text() == added_components[j])
{
found = true;
break;
}
}
if (!found)
{
QListWidgetItem* item = component_list_->takeItem(i);
delete item;
}
}
RefreshComponentData();
}
void ECEditorWindow::RefreshComponentData()
{
if (!data_edit_)
return;
data_edit_->clear();
std::vector<EntityComponentSelection> selection = GetSelectedComponents();
if (!selection.size())
return;
QDomDocument temp_doc;
if (selection.size() > 1)
{
// Multi-entity: create a root element to hold entities
QDomElement entities_elem = temp_doc.createElement("entities");
temp_doc.appendChild(entities_elem);
for (uint i = 0; i < selection.size(); ++i)
{
QDomElement entity_elem = temp_doc.createElement("entity");
QString id_str;
id_str.setNum(selection[i].entity_->GetId());
entity_elem.setAttribute("id", id_str);
for (uint j = 0; j < selection[i].components_.size(); ++j)
selection[i].components_[j]->SerializeTo(temp_doc, entity_elem);
entities_elem.appendChild(entity_elem);
}
}
else
{
// Single entity
QDomElement entity_elem = temp_doc.createElement("entity");
temp_doc.appendChild(entity_elem);
QString id_str;
id_str.setNum(selection[0].entity_->GetId());
entity_elem.setAttribute("id", id_str);
for (uint j = 0; j < selection[0].components_.size(); ++j)
selection[0].components_[j]->SerializeTo(temp_doc, entity_elem);
temp_doc.appendChild(entity_elem);
}
data_edit_->setText(temp_doc.toString());
}
std::vector<Scene::EntityPtr> ECEditorWindow::GetSelectedEntities()
{
std::vector<Scene::EntityPtr> ret;
if (!entity_list_)
return ret;
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
for (uint i = 0; i < entity_list_->count(); ++i)
{
QListWidgetItem* item = entity_list_->item(i);
if (item->isSelected())
{
entity_id_t id = (entity_id_t)item->text().toInt();
Scene::EntityPtr entity = scene->GetEntity(id);
if (entity)
ret.push_back(entity);
}
}
return ret;
}
std::vector<EntityComponentSelection> ECEditorWindow::GetSelectedComponents()
{
std::vector<EntityComponentSelection> ret;
if (!component_list_)
return ret;
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
StringVector components;
for (uint i = 0; i < component_list_->count(); ++i)
{
QListWidgetItem* item = component_list_->item(i);
if (item->isSelected())
components.push_back(item->text().toStdString());
}
for (uint i = 0; i < entities.size(); ++i)
{
EntityComponentSelection selection;
selection.entity_ = entities[i];
for (uint j = 0; j < components.size(); ++j)
{
Foundation::ComponentInterfacePtr comp = selection.entity_->GetComponent(components[j]);
if (comp)
selection.components_.push_back(comp);
}
ret.push_back(selection);
}
return ret;
}
void ECEditorWindow::ClearEntities()
{
if (entity_list_)
entity_list_->clear();
if (component_list_)
component_list_->clear();
}
}
<commit_msg>Yet another case sensitivity fix for XMLUtilities. Perhaps should have renamed the file instead :p<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "ECEditorWindow.h"
#include "ECEditorModule.h"
#include "ModuleManager.h"
#include "UiModule.h"
#include "SceneManager.h"
#include "ComponentInterface.h"
#include "ComponentManager.h"
#include "Inworld/InworldSceneController.h"
#include "Inworld/View/UiProxyWidget.h"
#include "XMLUtilities.h"
#include "SceneEvents.h"
#include "EventManager.h"
#include <QDomDocument>
#include <QVBoxLayout>
#include <QUiLoader>
#include <QFile>
#include <QPushButton>
#include <QTextEdit>
#include <QComboBox>
#include <QListWidget>
using namespace RexTypes;
namespace ECEditor
{
uint AddUniqueItem(QListWidget* list, const QString& name)
{
for (int i = 0; i < list->count(); ++i)
{
if (list->item(i)->text() == name)
return i;
}
list->addItem(name);
return list->count() - 1;
}
ECEditorWindow::ECEditorWindow(Foundation::Framework* framework) :
framework_(framework),
contents_(0),
save_button_(0),
revert_button_(0),
create_button_(0),
delete_button_(0),
entity_list_(0),
component_list_(0),
create_combo_(0),
data_edit_(0),
delete_shortcut_(0)
{
Initialize();
}
ECEditorWindow::~ECEditorWindow()
{
}
void ECEditorWindow::Initialize()
{
QUiLoader loader;
QFile file("./data/ui/eceditor.ui");
file.open(QFile::ReadOnly);
contents_ = loader.load(&file, this);
if (!contents_)
{
ECEditorModule::LogError("Could not load editor layout");
return;
}
file.close();
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(contents_);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
save_button_ = findChild<QPushButton*>("but_save");
revert_button_ = findChild<QPushButton*>("but_revert");
create_button_ = findChild<QPushButton*>("but_create");
delete_button_ = findChild<QPushButton*>("but_delete");
entity_list_ = findChild<QListWidget*>("list_entities");
component_list_ = findChild<QListWidget*>("list_components");
data_edit_ = findChild<QTextEdit*>("text_attredit");
create_combo_ = findChild<QComboBox*>("combo_create");
if (entity_list_)
{
entity_list_->setSelectionMode(QAbstractItemView::ExtendedSelection);
delete_shortcut_ = new QShortcut(QKeySequence(Qt::Key_Delete), entity_list_);
QObject::connect(entity_list_, SIGNAL(itemSelectionChanged()), this, SLOT(RefreshEntityComponents()));
QObject::connect(delete_shortcut_, SIGNAL(activated()), this, SLOT(DeleteEntitiesFromList()));
}
if (component_list_)
{
component_list_->setSelectionMode(QAbstractItemView::ExtendedSelection);
QObject::connect(component_list_, SIGNAL(itemSelectionChanged()), this, SLOT(RefreshComponentData()));
}
if (delete_button_)
QObject::connect(delete_button_, SIGNAL(pressed()), this, SLOT(DeleteComponent()));
if (create_button_)
QObject::connect(create_button_, SIGNAL(pressed()), this, SLOT(CreateComponent()));
if (save_button_)
QObject::connect(save_button_, SIGNAL(pressed()), this, SLOT(SaveData()));
if (revert_button_)
QObject::connect(revert_button_, SIGNAL(pressed()), this, SLOT(RevertData()));
boost::shared_ptr<UiServices::UiModule> ui_module = framework_->GetModuleManager()->GetModule<UiServices::UiModule>(
Foundation::Module::MT_UiServices).lock();
if (ui_module)
ui_module->GetInworldSceneController()->AddWidgetToScene(this, UiServices::UiWidgetProperties(contents_->windowTitle(), UiServices::ModuleWidget));
else
ECEditorModule::LogError("Could not add widget to scene");
RefreshAvailableComponents();
}
void ECEditorWindow::RefreshAvailableComponents()
{
// Fill the create component combo box with the types of EC's the ComponentManager can create
Foundation::ComponentManagerPtr comp_mgr = framework_->GetComponentManager();
const Foundation::ComponentManager::ComponentFactoryMap& factories = comp_mgr->GetComponentFactoryMap();
if (create_combo_)
{
create_combo_->clear();
Foundation::ComponentManager::ComponentFactoryMap::const_iterator i = factories.begin();
while (i != factories.end())
{
create_combo_->addItem(QString::fromStdString(i->first));
++i;
}
}
}
void ECEditorWindow::DeleteComponent()
{
if (!component_list_)
return;
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
StringVector components;
for (uint i = 0; i < component_list_->count(); ++i)
{
QListWidgetItem* item = component_list_->item(i);
if (item->isSelected())
components.push_back(item->text().toStdString());
}
for (uint i = 0; i < entities.size(); ++i)
{
for (uint j = 0; j < components.size(); ++j)
entities[i]->RemoveComponent(entities[i]->GetComponent(components[j]));
}
RefreshEntityComponents();
}
void ECEditorWindow::CreateComponent()
{
if (!create_combo_)
return;
std::string name = create_combo_->currentText().toStdString();
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
for (uint i = 0; i < entities.size(); ++i)
{
// We (mis)use the GetOrCreateComponent function to avoid adding the same EC multiple times, since identifying multiple EC's of similar type
// is problematic with current API
entities[i]->GetOrCreateComponent(name);
}
RefreshEntityComponents();
}
void ECEditorWindow::RevertData()
{
RefreshComponentData();
}
void ECEditorWindow::SaveData()
{
if (!data_edit_)
return;
QDomDocument edited_doc;
QString text = data_edit_->toPlainText();
if (!text.length())
{
ECEditorModule::LogWarning("Empty XML data");
return;
}
if (edited_doc.setContent(text))
{
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
bool entity_found = false;
// Check if multi-entity or single-entity
QDomElement entities_elem = edited_doc.firstChildElement("entities");
// Deserialize all entities/components contained in the data, provided we still find them from the scene
QDomElement entity_elem;
if (!entities_elem.isNull())
entity_elem = entities_elem.firstChildElement("entity");
else
entity_elem = edited_doc.firstChildElement("entity");
while (!entity_elem.isNull())
{
entity_found = true;
entity_id_t id = (entity_id_t)ParseInt(entity_elem.attribute("id").toStdString());
Scene::EntityPtr entity = scene->GetEntity(id);
if (entity)
{
QDomElement comp_elem = entity_elem.firstChildElement("component");
while (!comp_elem.isNull())
{
Foundation::ComponentInterfacePtr comp = entity->GetComponent(comp_elem.attribute("type").toStdString());
if (comp)
comp->DeserializeFrom(comp_elem);
comp_elem = comp_elem.nextSiblingElement("component");
}
Scene::Events::SceneEventData event_data(id);
Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
event_manager->SendEvent(event_manager->QueryEventCategory("Scene"), Scene::Events::EVENT_ENTITY_ECS_MODIFIED, &event_data);
}
else
{
ECEditorModule::LogWarning("Could not find entity " + ToString<int>(id) + " in scene!");
}
entity_elem = entity_elem.nextSiblingElement("entity");
}
// Refresh immediately after, so that any extra stuff is stripped out, and illegal parameters are (hopefully) straightened
if (entity_found)
RefreshComponentData();
else
ECEditorModule::LogWarning("No entity elements in XML data");
}
else
ECEditorModule::LogWarning("Could not parse XML data");
}
void ECEditorWindow::hideEvent(QHideEvent* hide_event)
{
ClearEntities();
QWidget::hideEvent(hide_event);
}
void ECEditorWindow::showEvent(QShowEvent* show_event)
{
RefreshAvailableComponents();
QWidget::showEvent(show_event);
}
void ECEditorWindow::DeleteEntitiesFromList()
{
if ((entity_list_) && (entity_list_->hasFocus()))
{
for (int i = entity_list_->count() - 1; i >= 0; --i)
{
if (entity_list_->item(i)->isSelected())
{
QListWidgetItem* item = entity_list_->takeItem(i);
delete item;
}
}
}
}
void ECEditorWindow::AddEntity(entity_id_t entity_id)
{
if ((isVisible()) && (entity_list_))
{
QString entity_id_str;
entity_id_str.setNum((int)entity_id);
entity_list_->setCurrentRow(AddUniqueItem(entity_list_, entity_id_str));
}
}
void ECEditorWindow::RefreshEntityComponents()
{
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
// If no entities selected, just clear the list and we're done
if (!entities.size())
{
component_list_->clear();
return;
}
std::vector<QString> added_components;
for (uint i = 0; i < entities.size(); ++i)
{
const Scene::Entity::ComponentVector& components = entities[i]->GetComponentVector();
for (uint j = 0; j < components.size(); ++j)
{
QString component_name = QString::fromStdString(components[j]->TypeName());
added_components.push_back(component_name);
// If multiple selected entities have the same component, add it only once to the EC selector list
AddUniqueItem(component_list_, QString::fromStdString(components[j]->TypeName()));
}
}
// Now delete components that should not be in the component list
// This code is kind of ugly...
// Note: the whole reason for going to this trouble (instead of just nuking and refilling the list)
// is to retain the user's selection, if several entities share a set of components, as often is the case
for (int i = component_list_->count() - 1; i >= 0; --i)
{
bool found = false;
QListWidgetItem* item = component_list_->item(i);
for (uint j = 0; j < added_components.size(); ++j)
{
if (item->text() == added_components[j])
{
found = true;
break;
}
}
if (!found)
{
QListWidgetItem* item = component_list_->takeItem(i);
delete item;
}
}
RefreshComponentData();
}
void ECEditorWindow::RefreshComponentData()
{
if (!data_edit_)
return;
data_edit_->clear();
std::vector<EntityComponentSelection> selection = GetSelectedComponents();
if (!selection.size())
return;
QDomDocument temp_doc;
if (selection.size() > 1)
{
// Multi-entity: create a root element to hold entities
QDomElement entities_elem = temp_doc.createElement("entities");
temp_doc.appendChild(entities_elem);
for (uint i = 0; i < selection.size(); ++i)
{
QDomElement entity_elem = temp_doc.createElement("entity");
QString id_str;
id_str.setNum(selection[i].entity_->GetId());
entity_elem.setAttribute("id", id_str);
for (uint j = 0; j < selection[i].components_.size(); ++j)
selection[i].components_[j]->SerializeTo(temp_doc, entity_elem);
entities_elem.appendChild(entity_elem);
}
}
else
{
// Single entity
QDomElement entity_elem = temp_doc.createElement("entity");
temp_doc.appendChild(entity_elem);
QString id_str;
id_str.setNum(selection[0].entity_->GetId());
entity_elem.setAttribute("id", id_str);
for (uint j = 0; j < selection[0].components_.size(); ++j)
selection[0].components_[j]->SerializeTo(temp_doc, entity_elem);
temp_doc.appendChild(entity_elem);
}
data_edit_->setText(temp_doc.toString());
}
std::vector<Scene::EntityPtr> ECEditorWindow::GetSelectedEntities()
{
std::vector<Scene::EntityPtr> ret;
if (!entity_list_)
return ret;
Scene::ScenePtr scene = framework_->GetDefaultWorldScene();
for (uint i = 0; i < entity_list_->count(); ++i)
{
QListWidgetItem* item = entity_list_->item(i);
if (item->isSelected())
{
entity_id_t id = (entity_id_t)item->text().toInt();
Scene::EntityPtr entity = scene->GetEntity(id);
if (entity)
ret.push_back(entity);
}
}
return ret;
}
std::vector<EntityComponentSelection> ECEditorWindow::GetSelectedComponents()
{
std::vector<EntityComponentSelection> ret;
if (!component_list_)
return ret;
std::vector<Scene::EntityPtr> entities = GetSelectedEntities();
StringVector components;
for (uint i = 0; i < component_list_->count(); ++i)
{
QListWidgetItem* item = component_list_->item(i);
if (item->isSelected())
components.push_back(item->text().toStdString());
}
for (uint i = 0; i < entities.size(); ++i)
{
EntityComponentSelection selection;
selection.entity_ = entities[i];
for (uint j = 0; j < components.size(); ++j)
{
Foundation::ComponentInterfacePtr comp = selection.entity_->GetComponent(components[j]);
if (comp)
selection.components_.push_back(comp);
}
ret.push_back(selection);
}
return ret;
}
void ECEditorWindow::ClearEntities()
{
if (entity_list_)
entity_list_->clear();
if (component_list_)
component_list_->clear();
}
}
<|endoftext|> |
<commit_before>#include "DDImage/Enumeration_KnobI.h"
#include "DDImage/Reader.h"
#include "DDImage/Row.h"
#include "OpenImageIO/imageio.h"
using namespace DD::Image;
/*
* TODO:
* - Look into using the planar Reader API in Nuke 8, which may map better to
* TIFF/OIIO.
* - It would be nice to have a way to read in a region, rather than the whole
* image, but this would require access to the Read's request region,
* which isn't currently possible. A feature request for this is logged
* with The Foundry as Bug 46237.
*/
namespace TxReaderNS
{
OIIO_NAMESPACE_USING
static const char* const EMPTY[] = {NULL};
class TxReaderFormat : public ReaderFormat {
int mipLevel_;
Knob* mipLevelKnob_;
public:
TxReaderFormat() : mipLevel_(0), mipLevelKnob_(NULL) { }
void knobs(Knob_Callback cb) {
mipLevelKnob_ = Enumeration_knob(cb, &mipLevel_, EMPTY,
"tx_mip_level", "mip level");
SetFlags(cb, Knob::EXPAND_TO_WIDTH);
Tooltip(cb, "The mip level to read from the file. Currently, this will "
"be resampled to fill the same resolution as the base image.");
}
void append(Hash& hash) { hash.append(mipLevel_); }
inline int mipLevel() { return mipLevel_; }
void setMipLabels(std::vector<std::string> items) {
mipLevelKnob_->enumerationKnob()->menu(items);
}
const char* help() { return "Tiled, mipmapped texture format"; }
};
class txReader : public Reader {
ImageInput* oiioInput_;
TxReaderFormat* txFmt_;
int chanCount_, lastMipLevel_;
bool haveImage_, flip_;
std::vector<float> imageBuf_;
std::map<Channel, int> chanMap_;
MetaData::Bundle meta_;
static const Description d;
void fillMetadata(const ImageSpec& spec, bool isEXR) {
switch (spec.format.basetype) {
case TypeDesc::UINT8:
case TypeDesc::INT8:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_8);
break;
case TypeDesc::UINT16:
case TypeDesc::INT16:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_16);
break;
case TypeDesc::UINT32:
case TypeDesc::INT32:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_32);
break;
case TypeDesc::FLOAT:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_FLOAT);
break;
case TypeDesc::DOUBLE:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_DOUBLE);
break;
default:
meta_.setData(MetaData::DEPTH, "Unknown");
break;
}
meta_.setData("tx/tile_width", spec.tile_width);
meta_.setData("tx/tile_height", spec.tile_height);
string_view val;
val = spec.get_string_attribute("ImageDescription");
if (!val.empty())
meta_.setData("tx/image_description", val);
val = spec.get_string_attribute("DateTime");
if (!val.empty())
meta_.setData(MetaData::CREATED_TIME, val);
val = spec.get_string_attribute("Software");
if (!val.empty())
meta_.setData(MetaData::CREATOR, val);
val = spec.get_string_attribute("textureformat");
if (!val.empty())
meta_.setData("tx/texture_format", val);
val = spec.get_string_attribute("wrapmodes");
if (!val.empty())
meta_.setData("tx/wrap_modes", val);
val = spec.get_string_attribute("fovcot");
if (!val.empty())
meta_.setData("tx/fovcot", val);
val = spec.get_string_attribute("compression");
if (!val.empty())
meta_.setData("tx/compression", val);
if (isEXR) {
val = spec.get_string_attribute("openexr:lineOrder");
if (!val.empty())
meta_.setData("exr/line_order", val);
float cl = spec.get_float_attribute("openexr:dwaCompressionLevel", 0.0f);
if (val > 0)
meta_.setData("exr/dwa_compression_level", cl);
}
else {
val = spec.get_string_attribute("tiff:planarconfig");
if (!val.empty())
meta_.setData("tiff/planar_config", val);
}
}
void setChannels(const ImageSpec& spec) {
ChannelSet mask;
Channel chan;
int chanIndex = 0;
for (std::vector<std::string>::const_iterator it = spec.channelnames.begin();
it != spec.channelnames.end(); it++) {
chan = Reader::channel(it->c_str());
mask += chan;
chanMap_[chan] = chanIndex++;
}
info_.channels(mask);
}
public:
txReader(Read* iop) : Reader(iop),
chanCount_(0),
lastMipLevel_(-1),
haveImage_(false),
flip_(false)
{
txFmt_ = dynamic_cast<TxReaderFormat*>(iop->handler());
OIIO::attribute("threads", (int)Thread::numThreads / 2);
oiioInput_ = ImageInput::open(filename());
if (!oiioInput_) {
iop->internalError("OIIO: Failed to open file %s: %s", filename(),
geterror().c_str());
return;
}
const ImageSpec& baseSpec = oiioInput_->spec();
if (!(baseSpec.width * baseSpec.height)) {
iop->internalError("tx file has one or more zero dimensions "
"(%d x %d)", baseSpec.width, baseSpec.height);
return;
}
chanCount_ = baseSpec.nchannels;
const bool isEXR = strcmp(oiioInput_->format_name(), "openexr") == 0;
if (isEXR) {
float pixAspect = baseSpec.get_float_attribute("PixelAspectRatio", 0);
set_info(baseSpec.width, baseSpec.height, 1, pixAspect);
meta_.setData(MetaData::PIXEL_ASPECT, pixAspect > 0 ? pixAspect : 1.0f);
setChannels(baseSpec); // Fills chanMap_
flip_ = true;
}
else {
set_info(baseSpec.width, baseSpec.height, chanCount_);
int orientation = baseSpec.get_int_attribute("Orientation", 1);
meta_.setData("tiff/orientation", orientation);
flip_ = !((orientation - 1) & 2);
int chanIndex = 0;
foreach(z, info_.channels())
chanMap_[z] = chanIndex++;
}
fillMetadata(baseSpec, isEXR);
// Populate mip level pulldown with labels in the form:
// "MIPLEVEL\tMIPLEVEL - WxH" (e.g. "0\t0 - 1920x1080")
// The knob will split these on tab characters, and only store the
// first part (i.e. the index) when the knob is serialized.
std::vector<std::string> mipLabels;
std::ostringstream buf;
ImageSpec mipSpec(baseSpec);
int mipLevel = 0;
while (true) {
buf << mipLevel << '\t' << mipLevel << " - " << mipSpec.width << 'x' << mipSpec.height;
mipLabels.push_back(buf.str());
if (oiioInput_->seek_subimage(0, mipLevel + 1, mipSpec)) {
buf.str(std::string());
buf.clear();
mipLevel++;
}
else
break;
}
meta_.setData("tx/mip_levels", mipLevel + 1);
txFmt_->setMipLabels(mipLabels);
}
virtual ~txReader() {
if (oiioInput_)
oiioInput_->close();
delete oiioInput_;
oiioInput_ = NULL;
}
void open() {
if (lastMipLevel_ != txFmt_->mipLevel()) {
ImageSpec mipSpec;
if (!oiioInput_->seek_subimage(0, txFmt_->mipLevel(), mipSpec)) {
iop->internalError("Failed to seek to mip level %d: %s",
txFmt_->mipLevel(), oiioInput_->geterror().c_str());
return;
}
if (txFmt_->mipLevel() && mipSpec.nchannels != chanCount_) {
iop->internalError("txReader does not support mip levels with "
"different channel counts");
return;
}
lastMipLevel_ = txFmt_->mipLevel();
haveImage_ = false;
}
if (!haveImage_) {
const int needSize = oiioInput_->spec().width
* oiioInput_->spec().height
* oiioInput_->spec().nchannels;
if (needSize > imageBuf_.size())
imageBuf_.resize(needSize);
oiioInput_->read_image(&imageBuf_[0]);
haveImage_ = true;
}
}
void engine(int y, int x, int r, ChannelMask channels, Row& row) {
if (!haveImage_)
iop->internalError("engine called, but haveImage_ is false");
if (aborted()) {
row.erase(channels);
return;
}
const bool doAlpha = channels.contains(Chan_Alpha);
if (flip_)
y = height() - y - 1;
if (lastMipLevel_) { // Mip level other than 0
const int mipW = oiioInput_->spec().width;
const int mipMult = width() / mipW;
y = y * oiioInput_->spec().height / height();
const int bufX = x ? x / mipMult : 0;
const int bufR = r / mipMult;
const int bufW = bufR - bufX;
std::vector<float> chanBuf(bufW);
float* chanStart = &chanBuf[0];
const int bufStart = y * mipW * chanCount_ + bufX * chanCount_;
const float* alpha = doAlpha ? &imageBuf_[bufStart + chanMap_[Chan_Alpha]] : NULL;
foreach (z, channels) {
from_float(z, &chanBuf[0], &imageBuf_[bufStart + chanMap_[z]],
alpha, bufW, chanCount_);
float* OUT = row.writable(z);
for (int stride = 0, c = 0; stride < bufW; stride++, c = 0)
for (; c < mipMult; c++)
*OUT++ = *(chanStart + stride);
}
}
else { // Mip level 0
const int pixStart = y * width() * chanCount_ + x * chanCount_;
const float* alpha = doAlpha ? &imageBuf_[pixStart + chanMap_[Chan_Alpha]] : NULL;
foreach (z, channels) {
from_float(z, row.writable(z) + x, &imageBuf_[pixStart + chanMap_[z]],
alpha, r - x, chanCount_);
}
}
}
const MetaData::Bundle& fetchMetaData(const char* key) { return meta_; }
};
} // ~TxReaderNS
static Reader* buildReader(Read* iop, int fd, const unsigned char* b, int n) {
close(fd);
return new TxReaderNS::txReader(iop);
}
static ReaderFormat* buildformat(Read* iop) {
return new TxReaderNS::TxReaderFormat();
}
static bool test(int fd, const unsigned char* block, int length) {
// Big-endian TIFF
if (block[0] == 'M' && block[1] == 'M' && block[2] == 0 && block[3] == 42)
return true;
// Little-endian TIFF
if (block[0] == 'I' && block[1] == 'I' && block[2] == 42 && block[3] == 0)
return true;
// EXR
return block[0] == 0x76 && block[1] == 0x2f &&
block[2] == 0x31 && block[3] == 0x01;
}
const Reader::Description TxReaderNS::txReader::d("tx\0TX\0", buildReader, test,
buildformat);
<commit_msg>Fix gcc compiler warnings<commit_after>#ifndef _WIN32
#include <unistd.h>
#endif
#include "DDImage/Enumeration_KnobI.h"
#include "DDImage/Reader.h"
#include "DDImage/Row.h"
#include "OpenImageIO/imageio.h"
using namespace DD::Image;
/*
* TODO:
* - Look into using the planar Reader API in Nuke 8, which may map better to
* TIFF/OIIO.
* - It would be nice to have a way to read in a region, rather than the whole
* image, but this would require access to the Read's request region,
* which isn't currently possible. A feature request for this is logged
* with The Foundry as Bug 46237.
*/
namespace TxReaderNS
{
OIIO_NAMESPACE_USING
static const char* const EMPTY[] = {NULL};
class TxReaderFormat : public ReaderFormat {
int mipLevel_;
Knob* mipLevelKnob_;
public:
TxReaderFormat() : mipLevel_(0), mipLevelKnob_(NULL) { }
void knobs(Knob_Callback cb) {
mipLevelKnob_ = Enumeration_knob(cb, &mipLevel_, EMPTY,
"tx_mip_level", "mip level");
SetFlags(cb, Knob::EXPAND_TO_WIDTH);
Tooltip(cb, "The mip level to read from the file. Currently, this will "
"be resampled to fill the same resolution as the base image.");
}
void append(Hash& hash) { hash.append(mipLevel_); }
inline int mipLevel() { return mipLevel_; }
void setMipLabels(std::vector<std::string> items) {
mipLevelKnob_->enumerationKnob()->menu(items);
}
const char* help() { return "Tiled, mipmapped texture format"; }
};
class txReader : public Reader {
ImageInput* oiioInput_;
TxReaderFormat* txFmt_;
int chanCount_, lastMipLevel_;
bool haveImage_, flip_;
std::vector<float> imageBuf_;
std::map<Channel, int> chanMap_;
MetaData::Bundle meta_;
static const Description d;
void fillMetadata(const ImageSpec& spec, bool isEXR) {
switch (spec.format.basetype) {
case TypeDesc::UINT8:
case TypeDesc::INT8:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_8);
break;
case TypeDesc::UINT16:
case TypeDesc::INT16:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_16);
break;
case TypeDesc::UINT32:
case TypeDesc::INT32:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_32);
break;
case TypeDesc::FLOAT:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_FLOAT);
break;
case TypeDesc::DOUBLE:
meta_.setData(MetaData::DEPTH, MetaData::DEPTH_DOUBLE);
break;
default:
meta_.setData(MetaData::DEPTH, "Unknown");
break;
}
meta_.setData("tx/tile_width", spec.tile_width);
meta_.setData("tx/tile_height", spec.tile_height);
string_view val;
val = spec.get_string_attribute("ImageDescription");
if (!val.empty())
meta_.setData("tx/image_description", val);
val = spec.get_string_attribute("DateTime");
if (!val.empty())
meta_.setData(MetaData::CREATED_TIME, val);
val = spec.get_string_attribute("Software");
if (!val.empty())
meta_.setData(MetaData::CREATOR, val);
val = spec.get_string_attribute("textureformat");
if (!val.empty())
meta_.setData("tx/texture_format", val);
val = spec.get_string_attribute("wrapmodes");
if (!val.empty())
meta_.setData("tx/wrap_modes", val);
val = spec.get_string_attribute("fovcot");
if (!val.empty())
meta_.setData("tx/fovcot", val);
val = spec.get_string_attribute("compression");
if (!val.empty())
meta_.setData("tx/compression", val);
if (isEXR) {
val = spec.get_string_attribute("openexr:lineOrder");
if (!val.empty())
meta_.setData("exr/line_order", val);
float cl = spec.get_float_attribute("openexr:dwaCompressionLevel", 0.0f);
if (val > 0)
meta_.setData("exr/dwa_compression_level", cl);
}
else {
val = spec.get_string_attribute("tiff:planarconfig");
if (!val.empty())
meta_.setData("tiff/planar_config", val);
}
}
void setChannels(const ImageSpec& spec) {
ChannelSet mask;
Channel chan;
int chanIndex = 0;
for (std::vector<std::string>::const_iterator it = spec.channelnames.begin();
it != spec.channelnames.end(); it++) {
chan = Reader::channel(it->c_str());
mask += chan;
chanMap_[chan] = chanIndex++;
}
info_.channels(mask);
}
public:
txReader(Read* iop) : Reader(iop),
chanCount_(0),
lastMipLevel_(-1),
haveImage_(false),
flip_(false)
{
txFmt_ = dynamic_cast<TxReaderFormat*>(iop->handler());
OIIO::attribute("threads", (int)Thread::numThreads / 2);
oiioInput_ = ImageInput::open(filename());
if (!oiioInput_) {
iop->internalError("OIIO: Failed to open file %s: %s", filename(),
geterror().c_str());
return;
}
const ImageSpec& baseSpec = oiioInput_->spec();
if (!(baseSpec.width * baseSpec.height)) {
iop->internalError("tx file has one or more zero dimensions "
"(%d x %d)", baseSpec.width, baseSpec.height);
return;
}
chanCount_ = baseSpec.nchannels;
const bool isEXR = strcmp(oiioInput_->format_name(), "openexr") == 0;
if (isEXR) {
float pixAspect = baseSpec.get_float_attribute("PixelAspectRatio", 0);
set_info(baseSpec.width, baseSpec.height, 1, pixAspect);
meta_.setData(MetaData::PIXEL_ASPECT, pixAspect > 0 ? pixAspect : 1.0f);
setChannels(baseSpec); // Fills chanMap_
flip_ = true;
}
else {
set_info(baseSpec.width, baseSpec.height, chanCount_);
int orientation = baseSpec.get_int_attribute("Orientation", 1);
meta_.setData("tiff/orientation", orientation);
flip_ = !((orientation - 1) & 2);
int chanIndex = 0;
foreach(z, info_.channels())
chanMap_[z] = chanIndex++;
}
fillMetadata(baseSpec, isEXR);
// Populate mip level pulldown with labels in the form:
// "MIPLEVEL\tMIPLEVEL - WxH" (e.g. "0\t0 - 1920x1080")
// The knob will split these on tab characters, and only store the
// first part (i.e. the index) when the knob is serialized.
std::vector<std::string> mipLabels;
std::ostringstream buf;
ImageSpec mipSpec(baseSpec);
int mipLevel = 0;
while (true) {
buf << mipLevel << '\t' << mipLevel << " - " << mipSpec.width << 'x' << mipSpec.height;
mipLabels.push_back(buf.str());
if (oiioInput_->seek_subimage(0, mipLevel + 1, mipSpec)) {
buf.str(std::string());
buf.clear();
mipLevel++;
}
else
break;
}
meta_.setData("tx/mip_levels", mipLevel + 1);
txFmt_->setMipLabels(mipLabels);
}
virtual ~txReader() {
if (oiioInput_)
oiioInput_->close();
delete oiioInput_;
oiioInput_ = NULL;
}
void open() {
if (lastMipLevel_ != txFmt_->mipLevel()) {
ImageSpec mipSpec;
if (!oiioInput_->seek_subimage(0, txFmt_->mipLevel(), mipSpec)) {
iop->internalError("Failed to seek to mip level %d: %s",
txFmt_->mipLevel(), oiioInput_->geterror().c_str());
return;
}
if (txFmt_->mipLevel() && mipSpec.nchannels != chanCount_) {
iop->internalError("txReader does not support mip levels with "
"different channel counts");
return;
}
lastMipLevel_ = txFmt_->mipLevel();
haveImage_ = false;
}
if (!haveImage_) {
const int needSize = oiioInput_->spec().width
* oiioInput_->spec().height
* oiioInput_->spec().nchannels;
if (size_t(needSize) > imageBuf_.size())
imageBuf_.resize(needSize);
oiioInput_->read_image(&imageBuf_[0]);
haveImage_ = true;
}
}
void engine(int y, int x, int r, ChannelMask channels, Row& row) {
if (!haveImage_)
iop->internalError("engine called, but haveImage_ is false");
if (aborted()) {
row.erase(channels);
return;
}
const bool doAlpha = channels.contains(Chan_Alpha);
if (flip_)
y = height() - y - 1;
if (lastMipLevel_) { // Mip level other than 0
const int mipW = oiioInput_->spec().width;
const int mipMult = width() / mipW;
y = y * oiioInput_->spec().height / height();
const int bufX = x ? x / mipMult : 0;
const int bufR = r / mipMult;
const int bufW = bufR - bufX;
std::vector<float> chanBuf(bufW);
float* chanStart = &chanBuf[0];
const int bufStart = y * mipW * chanCount_ + bufX * chanCount_;
const float* alpha = doAlpha ? &imageBuf_[bufStart + chanMap_[Chan_Alpha]] : NULL;
foreach (z, channels) {
from_float(z, &chanBuf[0], &imageBuf_[bufStart + chanMap_[z]],
alpha, bufW, chanCount_);
float* OUT = row.writable(z);
for (int stride = 0, c = 0; stride < bufW; stride++, c = 0)
for (; c < mipMult; c++)
*OUT++ = *(chanStart + stride);
}
}
else { // Mip level 0
const int pixStart = y * width() * chanCount_ + x * chanCount_;
const float* alpha = doAlpha ? &imageBuf_[pixStart + chanMap_[Chan_Alpha]] : NULL;
foreach (z, channels) {
from_float(z, row.writable(z) + x, &imageBuf_[pixStart + chanMap_[z]],
alpha, r - x, chanCount_);
}
}
}
const MetaData::Bundle& fetchMetaData(const char* key) { return meta_; }
};
} // ~TxReaderNS
static Reader* buildReader(Read* iop, int fd, const unsigned char* b, int n) {
// FIXME: I expect that this close() may be problematic on Windows.
// For Linux/gcc, we needed to #include <unistd.h> at the top of
// this file. If this is a problem for Windows, a different #include
// or a different close call here may be necessary.
close(fd);
return new TxReaderNS::txReader(iop);
}
static ReaderFormat* buildformat(Read* iop) {
return new TxReaderNS::TxReaderFormat();
}
static bool test(int fd, const unsigned char* block, int length) {
// Big-endian TIFF
if (block[0] == 'M' && block[1] == 'M' && block[2] == 0 && block[3] == 42)
return true;
// Little-endian TIFF
if (block[0] == 'I' && block[1] == 'I' && block[2] == 42 && block[3] == 0)
return true;
// EXR
return block[0] == 0x76 && block[1] == 0x2f &&
block[2] == 0x31 && block[3] == 0x01;
}
const Reader::Description TxReaderNS::txReader::d("tx\0TX\0", buildReader, test,
buildformat);
<|endoftext|> |
<commit_before><commit_msg>ATO-83 & ATO-46: Use AliDrawStyle to specify graph attibutes * kkeping back compatibility<commit_after><|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file ImageParser.cpp
\author Jens Krueger
SCI Institute
University of Utah
\version 1.2
\date September 2008
*/
#include "ImageParser.h"
#ifndef TUVOK_NO_QT
# include <QtGui/QImage>
# include <QtGui/QColor>
#endif
#include <Basics/SysTools.h>
#include <Controller/Controller.h>
using namespace boost;
using namespace std;
ImageFileInfo::ImageFileInfo() :
SimpleFileInfo(),
m_ivSize(0,0),
m_iAllocated(0),
m_iComponentCount(1)
{}
ImageFileInfo::ImageFileInfo(const std::string& strFileName) :
SimpleFileInfo(strFileName),
m_ivSize(0,0),
m_iAllocated(0),
m_iComponentCount(1)
{}
ImageFileInfo::ImageFileInfo(const std::wstring& wstrFileName) :
SimpleFileInfo(wstrFileName),
m_ivSize(0,0),
m_iAllocated(0),
m_iComponentCount(1)
{}
void ImageFileInfo::ComputeSize() {
m_iDataSize = m_iComponentCount*m_ivSize.area()*m_iAllocated/8;
}
SimpleFileInfo* ImageFileInfo::clone() {
SimpleFileInfo* sinfo = new ImageFileInfo(*this);
return sinfo;
}
uint32_t ImageFileInfo::GetComponentCount() const { return m_iComponentCount; }
#ifdef TUVOK_NO_QT
bool ImageFileInfo::GetData(std::vector<char>&, uint32_t, uint32_t)
#else
bool ImageFileInfo::GetData(std::vector<char>& vData, uint32_t iLength,
uint32_t iOffset)
#endif
{
#ifndef TUVOK_NO_QT
QImage qImage(m_strFileName.c_str());
if (qImage.isNull()) return false;
if(qImage.depth() == 32) {
m_iComponentCount = 4;
ComputeSize();
vData.resize(GetDataSize());
size_t w = static_cast<size_t>(qImage.width());
size_t h = static_cast<size_t>(qImage.height());
#if QT_VERSION >= 0x040600
assert(qImage.byteCount() == (w*h*m_iComponentCount));
#endif
// Qt says we can't use bits() directly as a uchar; the byte order differs
// per-platform. So pull out each component the slow way.
const QRgb* bits = reinterpret_cast<const QRgb*>(qImage.bits());
for(uint64_t i=0; i < uint64_t(w)*h; ++i) {
vData[i*4 + 0] = qRed(*bits);
vData[i*4 + 1] = qGreen(*bits);
vData[i*4 + 2] = qBlue(*bits);
vData[i*4 + 3] = qAlpha(*bits);
++bits;
}
} else {
int iCount = 0;
for (int y = 0;y<qImage.height();y++) {
for (int x = 0;x<qImage.width();x++) {
if (int(iOffset) > iCount) { continue; }
QColor pixel(qImage.pixel(x,y));
unsigned char cValue = (unsigned char)((pixel.red() + pixel.green() +
pixel.blue()) /
3);
unsigned char *pData = reinterpret_cast<unsigned char*>(&vData[0]);
pData[iCount-iOffset] = cValue;
if (int(iLength) == iCount-int(iOffset)) break;
iCount++;
}
}
}
return true;
#else
T_ERROR("Qt needed/used to load image data!");
return false;
#endif
}
/*************************************************************************************/
ImageStackInfo::ImageStackInfo() :
FileStackInfo()
{}
ImageStackInfo::ImageStackInfo(const ImageFileInfo* fileInfo) :
FileStackInfo(UINTVECTOR3(fileInfo->m_ivSize,1), FLOATVECTOR3(1,1,1),
fileInfo->m_iAllocated, fileInfo->m_iAllocated,
fileInfo->m_iComponentCount, false,
false, false, "image file", "IMAGE")
{
m_Elements.push_back(new ImageFileInfo(*fileInfo));
}
ImageStackInfo::ImageStackInfo(const ImageStackInfo* other)
{
m_ivSize = other->m_ivSize;
m_fvfAspect = other->m_fvfAspect;
m_iAllocated = other->m_iAllocated;
m_iStored = other->m_iStored;
m_iComponentCount = other->m_iComponentCount;
m_bSigned = other->m_bSigned;
m_bIsBigEndian = other->m_bIsBigEndian;
m_bIsJPEGEncoded = other->m_bIsJPEGEncoded;
m_strDesc = other->m_strDesc;
m_strFileType = other->m_strFileType;
for (size_t i=0;i<other->m_Elements.size();i++) {
ImageFileInfo* e = new ImageFileInfo(
*dynamic_cast<ImageFileInfo*>(other->m_Elements[i])
);
m_Elements.push_back(e);
}
}
bool ImageStackInfo::Match(const ImageFileInfo* info) {
if (m_ivSize.xy() == info->m_ivSize &&
m_iAllocated == info->m_iAllocated &&
m_iComponentCount == info->m_iComponentCount) {
std::vector<SimpleFileInfo*>::iterator iter;
for (iter = m_Elements.begin(); iter < m_Elements.end(); iter++) {
if ((*iter)->m_iImageIndex > info->m_iImageIndex) break;
}
m_Elements.insert(iter,new ImageFileInfo(*info));
return true;
} else return false;
}
/*************************************************************************************/
ImageParser::ImageParser(void)
{
}
ImageParser::~ImageParser(void)
{
}
void ImageParser::GetDirInfo(string strDirectory) {
vector<string> files = SysTools::GetDirContents(strDirectory);
vector<ImageFileInfo> fileInfos;
#ifndef TUVOK_NO_QT
// query directory for image files
for (size_t i = 0;i<files.size();i++) {
MESSAGE("Looking for image data in file %s", files[i].c_str());
QImage qImage(files[i].c_str());
if (!qImage.isNull()) {
ImageFileInfo info(files[i]);
info.m_ivSize = UINTVECTOR2(qImage.size().width(), qImage.size().height());
info.m_iAllocated = 8; // lets assume all images are 8 bit
info.m_iComponentCount = 1; // as qt converts any image to RGBA we also assume that the images were 1 component
info.ComputeSize();
fileInfos.push_back(info);
}
}
#else
T_ERROR("Images loaded/verified through Qt, which is disabled!");
#endif
// sort results into stacks
for (size_t i = 0; i<m_FileStacks.size(); i++) delete m_FileStacks[i];
m_FileStacks.clear();
for (size_t i = 0; i<fileInfos.size(); i++) {
bool bFoundMatch = false;
for (size_t j = 0; j<m_FileStacks.size(); j++) {
if (((ImageStackInfo*)m_FileStacks[j])->Match(&fileInfos[i])) {
bFoundMatch = true;
break;
}
}
if (!bFoundMatch) {
ImageStackInfo* newStack = new ImageStackInfo(&fileInfos[i]);
m_FileStacks.push_back(newStack);
}
}
}
void ImageParser::GetDirInfo(wstring wstrDirectory) {
string strDirectory(wstrDirectory.begin(), wstrDirectory.end());
GetDirInfo(strDirectory);
}
<commit_msg>Compare unsigned values with unsigned.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file ImageParser.cpp
\author Jens Krueger
SCI Institute
University of Utah
\version 1.2
\date September 2008
*/
#include "ImageParser.h"
#ifndef TUVOK_NO_QT
# include <QtGui/QImage>
# include <QtGui/QColor>
#endif
#include <Basics/SysTools.h>
#include <Controller/Controller.h>
using namespace boost;
using namespace std;
ImageFileInfo::ImageFileInfo() :
SimpleFileInfo(),
m_ivSize(0,0),
m_iAllocated(0),
m_iComponentCount(1)
{}
ImageFileInfo::ImageFileInfo(const std::string& strFileName) :
SimpleFileInfo(strFileName),
m_ivSize(0,0),
m_iAllocated(0),
m_iComponentCount(1)
{}
ImageFileInfo::ImageFileInfo(const std::wstring& wstrFileName) :
SimpleFileInfo(wstrFileName),
m_ivSize(0,0),
m_iAllocated(0),
m_iComponentCount(1)
{}
void ImageFileInfo::ComputeSize() {
m_iDataSize = m_iComponentCount*m_ivSize.area()*m_iAllocated/8;
}
SimpleFileInfo* ImageFileInfo::clone() {
SimpleFileInfo* sinfo = new ImageFileInfo(*this);
return sinfo;
}
uint32_t ImageFileInfo::GetComponentCount() const { return m_iComponentCount; }
#ifdef TUVOK_NO_QT
bool ImageFileInfo::GetData(std::vector<char>&, uint32_t, uint32_t)
#else
bool ImageFileInfo::GetData(std::vector<char>& vData, uint32_t iLength,
uint32_t iOffset)
#endif
{
#ifndef TUVOK_NO_QT
QImage qImage(m_strFileName.c_str());
if (qImage.isNull()) return false;
if(qImage.depth() == 32) {
m_iComponentCount = 4;
ComputeSize();
vData.resize(GetDataSize());
size_t w = static_cast<size_t>(qImage.width());
size_t h = static_cast<size_t>(qImage.height());
#if QT_VERSION >= 0x040600
assert(static_cast<uint64_t>(qImage.byteCount()) ==
(w*h*m_iComponentCount));
#endif
// Qt says we can't use bits() directly as a uchar; the byte order differs
// per-platform. So pull out each component the slow way.
const QRgb* bits = reinterpret_cast<const QRgb*>(qImage.bits());
for(uint64_t i=0; i < uint64_t(w)*h; ++i) {
vData[i*4 + 0] = qRed(*bits);
vData[i*4 + 1] = qGreen(*bits);
vData[i*4 + 2] = qBlue(*bits);
vData[i*4 + 3] = qAlpha(*bits);
++bits;
}
} else {
int iCount = 0;
for (int y = 0;y<qImage.height();y++) {
for (int x = 0;x<qImage.width();x++) {
if (int(iOffset) > iCount) { continue; }
QColor pixel(qImage.pixel(x,y));
unsigned char cValue = (unsigned char)((pixel.red() + pixel.green() +
pixel.blue()) /
3);
unsigned char *pData = reinterpret_cast<unsigned char*>(&vData[0]);
pData[iCount-iOffset] = cValue;
if (int(iLength) == iCount-int(iOffset)) break;
iCount++;
}
}
}
return true;
#else
T_ERROR("Qt needed/used to load image data!");
return false;
#endif
}
/*************************************************************************************/
ImageStackInfo::ImageStackInfo() :
FileStackInfo()
{}
ImageStackInfo::ImageStackInfo(const ImageFileInfo* fileInfo) :
FileStackInfo(UINTVECTOR3(fileInfo->m_ivSize,1), FLOATVECTOR3(1,1,1),
fileInfo->m_iAllocated, fileInfo->m_iAllocated,
fileInfo->m_iComponentCount, false,
false, false, "image file", "IMAGE")
{
m_Elements.push_back(new ImageFileInfo(*fileInfo));
}
ImageStackInfo::ImageStackInfo(const ImageStackInfo* other)
{
m_ivSize = other->m_ivSize;
m_fvfAspect = other->m_fvfAspect;
m_iAllocated = other->m_iAllocated;
m_iStored = other->m_iStored;
m_iComponentCount = other->m_iComponentCount;
m_bSigned = other->m_bSigned;
m_bIsBigEndian = other->m_bIsBigEndian;
m_bIsJPEGEncoded = other->m_bIsJPEGEncoded;
m_strDesc = other->m_strDesc;
m_strFileType = other->m_strFileType;
for (size_t i=0;i<other->m_Elements.size();i++) {
ImageFileInfo* e = new ImageFileInfo(
*dynamic_cast<ImageFileInfo*>(other->m_Elements[i])
);
m_Elements.push_back(e);
}
}
bool ImageStackInfo::Match(const ImageFileInfo* info) {
if (m_ivSize.xy() == info->m_ivSize &&
m_iAllocated == info->m_iAllocated &&
m_iComponentCount == info->m_iComponentCount) {
std::vector<SimpleFileInfo*>::iterator iter;
for (iter = m_Elements.begin(); iter < m_Elements.end(); iter++) {
if ((*iter)->m_iImageIndex > info->m_iImageIndex) break;
}
m_Elements.insert(iter,new ImageFileInfo(*info));
return true;
} else return false;
}
/*************************************************************************************/
ImageParser::ImageParser(void)
{
}
ImageParser::~ImageParser(void)
{
}
void ImageParser::GetDirInfo(string strDirectory) {
vector<string> files = SysTools::GetDirContents(strDirectory);
vector<ImageFileInfo> fileInfos;
#ifndef TUVOK_NO_QT
// query directory for image files
for (size_t i = 0;i<files.size();i++) {
MESSAGE("Looking for image data in file %s", files[i].c_str());
QImage qImage(files[i].c_str());
if (!qImage.isNull()) {
ImageFileInfo info(files[i]);
info.m_ivSize = UINTVECTOR2(qImage.size().width(), qImage.size().height());
info.m_iAllocated = 8; // lets assume all images are 8 bit
info.m_iComponentCount = 1; // as qt converts any image to RGBA we also assume that the images were 1 component
info.ComputeSize();
fileInfos.push_back(info);
}
}
#else
T_ERROR("Images loaded/verified through Qt, which is disabled!");
#endif
// sort results into stacks
for (size_t i = 0; i<m_FileStacks.size(); i++) delete m_FileStacks[i];
m_FileStacks.clear();
for (size_t i = 0; i<fileInfos.size(); i++) {
bool bFoundMatch = false;
for (size_t j = 0; j<m_FileStacks.size(); j++) {
if (((ImageStackInfo*)m_FileStacks[j])->Match(&fileInfos[i])) {
bFoundMatch = true;
break;
}
}
if (!bFoundMatch) {
ImageStackInfo* newStack = new ImageStackInfo(&fileInfos[i]);
m_FileStacks.push_back(newStack);
}
}
}
void ImageParser::GetDirInfo(wstring wstrDirectory) {
string strDirectory(wstrDirectory.begin(), wstrDirectory.end());
GetDirInfo(strDirectory);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/metrics/variations/uniformity_field_trials.h"
#include "base/metrics/field_trial.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chrome/common/metrics/variations/variations_util.h"
namespace chrome_variations {
namespace {
// Set up a uniformity field trial. |one_time_randomized| indicates if the
// field trial is one-time randomized or session-randomized. |trial_name_string|
// must contain a "%d" since the percentage of the group will be inserted in
// the trial name. |num_trial_groups| must be a divisor of 100 (e.g. 5, 20)
void SetupSingleUniformityFieldTrial(
base::FieldTrial::RandomizationType randomization_type,
const std::string& trial_name_string,
const VariationID trial_base_id,
int num_trial_groups) {
// Probability per group remains constant for all uniformity trials, what
// changes is the probability divisor.
static const base::FieldTrial::Probability kProbabilityPerGroup = 1;
const std::string kDefaultGroupName = "default";
const base::FieldTrial::Probability divisor = num_trial_groups;
DCHECK_EQ(100 % num_trial_groups, 0);
const int group_percent = 100 / num_trial_groups;
const std::string trial_name = base::StringPrintf(trial_name_string.c_str(),
group_percent);
DVLOG(1) << "Trial name = " << trial_name;
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
trial_name, divisor, kDefaultGroupName, 2015, 1, 1,
randomization_type, NULL));
AssociateGoogleVariationID(GOOGLE_UPDATE_SERVICE, trial_name,
kDefaultGroupName, trial_base_id);
// Loop starts with group 1 because the field trial automatically creates a
// default group, which would be group 0.
for (int group_number = 1; group_number < num_trial_groups; ++group_number) {
const std::string group_name =
base::StringPrintf("group_%02d", group_number);
DVLOG(1) << " Group name = " << group_name;
trial->AppendGroup(group_name, kProbabilityPerGroup);
AssociateGoogleVariationID(
GOOGLE_UPDATE_SERVICE, trial_name, group_name,
static_cast<VariationID>(trial_base_id + group_number));
}
// Now that all groups have been appended, call group() on the trial to
// ensure that our trial is registered. This resolves an off-by-one issue
// where the default group never gets chosen if we don't "use" the trial.
const int chosen_group = trial->group();
DVLOG(1) << "Chosen Group: " << chosen_group;
}
// Setup a 50% uniformity trial for new installs only. This is accomplished by
// disabling the trial on clients that were installed before a specified date.
void SetupNewInstallUniformityTrial(const base::Time install_date) {
const base::Time::Exploded kStartDate = {
2012, 11, 0, 6, // Nov 6, 2012
0, 0, 0, 0 // 00:00:00.000
};
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
"UMA-New-Install-Uniformity-Trial", 100, "Disabled",
2015, 1, 1, base::FieldTrial::ONE_TIME_RANDOMIZED, NULL));
trial->AppendGroup("Control", 50);
trial->AppendGroup("Experiment", 50);
const base::Time start_date = base::Time::FromLocalExploded(kStartDate);
if (install_date < start_date)
trial->Disable();
else
trial->group();
}
} // namespace
void SetupUniformityFieldTrials(const base::Time install_date) {
// One field trial will be created for each entry in this array. The i'th
// field trial will have |trial_sizes[i]| groups in it, including the default
// group. Each group will have a probability of 1/|trial_sizes[i]|.
const int num_trial_groups[] = { 100, 20, 10, 5, 2 };
// Declare our variation ID bases along side this array so we can loop over it
// and assign the IDs appropriately. So for example, the 1 percent experiments
// should have a size of 100 (100/100 = 1).
const VariationID trial_base_ids[] = {
UNIFORMITY_1_PERCENT_BASE,
UNIFORMITY_5_PERCENT_BASE,
UNIFORMITY_10_PERCENT_BASE,
UNIFORMITY_20_PERCENT_BASE,
UNIFORMITY_50_PERCENT_BASE
};
const std::string kOneTimeRandomizedTrialName =
"UMA-Uniformity-Trial-%d-Percent";
for (size_t i = 0; i < arraysize(num_trial_groups); ++i) {
SetupSingleUniformityFieldTrial(base::FieldTrial::ONE_TIME_RANDOMIZED,
kOneTimeRandomizedTrialName,
trial_base_ids[i], num_trial_groups[i]);
}
// Setup a 5% session-randomized uniformity trial.
const std::string kSessionRandomizedTrialName =
"UMA-Session-Randomized-Uniformity-Trial-%d-Percent";
SetupSingleUniformityFieldTrial(
base::FieldTrial::SESSION_RANDOMIZED, kSessionRandomizedTrialName,
UNIFORMITY_SESSION_RANDOMIZED_5_PERCENT_BASE, 20);
SetupNewInstallUniformityTrial(install_date);
}
} // namespace chrome_variations
<commit_msg>Add a 100 percent uniformity field trial.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/metrics/variations/uniformity_field_trials.h"
#include "base/metrics/field_trial.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chrome/common/metrics/variations/variations_util.h"
namespace chrome_variations {
namespace {
// Set up a uniformity field trial. |one_time_randomized| indicates if the
// field trial is one-time randomized or session-randomized. |trial_name_string|
// must contain a "%d" since the percentage of the group will be inserted in
// the trial name. |num_trial_groups| must be a divisor of 100 (e.g. 5, 20)
void SetupSingleUniformityFieldTrial(
base::FieldTrial::RandomizationType randomization_type,
const std::string& trial_name_string,
const VariationID trial_base_id,
int num_trial_groups) {
// Probability per group remains constant for all uniformity trials, what
// changes is the probability divisor.
static const base::FieldTrial::Probability kProbabilityPerGroup = 1;
const std::string kDefaultGroupName = "default";
const base::FieldTrial::Probability divisor = num_trial_groups;
DCHECK_EQ(100 % num_trial_groups, 0);
const int group_percent = 100 / num_trial_groups;
const std::string trial_name = base::StringPrintf(trial_name_string.c_str(),
group_percent);
DVLOG(1) << "Trial name = " << trial_name;
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
trial_name, divisor, kDefaultGroupName, 2015, 1, 1,
randomization_type, NULL));
AssociateGoogleVariationID(GOOGLE_UPDATE_SERVICE, trial_name,
kDefaultGroupName, trial_base_id);
// Loop starts with group 1 because the field trial automatically creates a
// default group, which would be group 0.
for (int group_number = 1; group_number < num_trial_groups; ++group_number) {
const std::string group_name =
base::StringPrintf("group_%02d", group_number);
DVLOG(1) << " Group name = " << group_name;
trial->AppendGroup(group_name, kProbabilityPerGroup);
AssociateGoogleVariationID(
GOOGLE_UPDATE_SERVICE, trial_name, group_name,
static_cast<VariationID>(trial_base_id + group_number));
}
// Now that all groups have been appended, call group() on the trial to
// ensure that our trial is registered. This resolves an off-by-one issue
// where the default group never gets chosen if we don't "use" the trial.
const int chosen_group = trial->group();
DVLOG(1) << "Chosen Group: " << chosen_group;
}
// Setup a 50% uniformity trial for new installs only. This is accomplished by
// disabling the trial on clients that were installed before a specified date.
void SetupNewInstallUniformityTrial(const base::Time install_date) {
const base::Time::Exploded kStartDate = {
2012, 11, 0, 6, // Nov 6, 2012
0, 0, 0, 0 // 00:00:00.000
};
scoped_refptr<base::FieldTrial> trial(
base::FieldTrialList::FactoryGetFieldTrial(
"UMA-New-Install-Uniformity-Trial", 100, "Disabled",
2015, 1, 1, base::FieldTrial::ONE_TIME_RANDOMIZED, NULL));
trial->AppendGroup("Control", 50);
trial->AppendGroup("Experiment", 50);
const base::Time start_date = base::Time::FromLocalExploded(kStartDate);
if (install_date < start_date)
trial->Disable();
else
trial->group();
}
} // namespace
void SetupUniformityFieldTrials(const base::Time install_date) {
// The 100 percent field trial in which everyone is a member is a special
// case. It is useful to create as it permits viewing all UMA data in UIs
// and tools that require a field trial.
base::FieldTrialList::CreateFieldTrial("UMA-Uniformity-Trial-100-Percent",
"group_01");
// One field trial will be created for each entry in this array. The i'th
// field trial will have |trial_sizes[i]| groups in it, including the default
// group. Each group will have a probability of 1/|trial_sizes[i]|.
const int num_trial_groups[] = { 100, 20, 10, 5, 2 };
// Declare our variation ID bases along side this array so we can loop over it
// and assign the IDs appropriately. So for example, the 1 percent experiments
// should have a size of 100 (100/100 = 1).
const VariationID trial_base_ids[] = {
UNIFORMITY_1_PERCENT_BASE,
UNIFORMITY_5_PERCENT_BASE,
UNIFORMITY_10_PERCENT_BASE,
UNIFORMITY_20_PERCENT_BASE,
UNIFORMITY_50_PERCENT_BASE
};
const std::string kOneTimeRandomizedTrialName =
"UMA-Uniformity-Trial-%d-Percent";
for (size_t i = 0; i < arraysize(num_trial_groups); ++i) {
SetupSingleUniformityFieldTrial(base::FieldTrial::ONE_TIME_RANDOMIZED,
kOneTimeRandomizedTrialName,
trial_base_ids[i], num_trial_groups[i]);
}
// Setup a 5% session-randomized uniformity trial.
const std::string kSessionRandomizedTrialName =
"UMA-Session-Randomized-Uniformity-Trial-%d-Percent";
SetupSingleUniformityFieldTrial(
base::FieldTrial::SESSION_RANDOMIZED, kSessionRandomizedTrialName,
UNIFORMITY_SESSION_RANDOMIZED_5_PERCENT_BASE, 20);
SetupNewInstallUniformityTrial(install_date);
}
} // namespace chrome_variations
<|endoftext|> |
<commit_before>/*
ESP8266WiFiScan.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "ESP8266WiFi.h"
#include "ESP8266WiFiGeneric.h"
#include "ESP8266WiFiScan.h"
extern "C" {
#include "c_types.h"
#include "ets_sys.h"
#include "os_type.h"
#include "osapi.h"
#include "mem.h"
#include "user_interface.h"
}
#include "debug.h"
extern "C" void esp_schedule();
extern "C" void esp_yield();
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------- scan function ---------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
bool ESP8266WiFiScanClass::_scanAsync = false;
bool ESP8266WiFiScanClass::_scanStarted = false;
bool ESP8266WiFiScanClass::_scanComplete = false;
size_t ESP8266WiFiScanClass::_scanCount = 0;
void* ESP8266WiFiScanClass::_scanResult = 0;
/**
* Start scan WiFi networks available
* @param async run in async mode
* @param show_hidden show hidden networks
* @return Number of discovered networks
*/
int8_t ESP8266WiFiScanClass::scanNetworks(bool async, bool show_hidden) {
if(ESP8266WiFiScanClass::_scanStarted) {
return WIFI_SCAN_RUNNING;
}
ESP8266WiFiScanClass::_scanAsync = async;
WiFi.enableSTA(true);
int status = wifi_station_get_connect_status();
if(status != STATION_GOT_IP && status != STATION_IDLE) {
WiFi.disconnect(false);
}
scanDelete();
struct scan_config config;
config.ssid = 0;
config.bssid = 0;
config.channel = 0;
config.show_hidden = show_hidden;
if(wifi_station_scan(&config, reinterpret_cast<scan_done_cb_t>(&ESP8266WiFiScanClass::_scanDone))) {
ESP8266WiFiScanClass::_scanComplete = false;
ESP8266WiFiScanClass::_scanStarted = true;
if(ESP8266WiFiScanClass::_scanAsync) {
delay(0); // time for the OS to trigger the scan
return WIFI_SCAN_RUNNING;
}
esp_yield();
return ESP8266WiFiScanClass::_scanCount;
} else {
return WIFI_SCAN_FAILED;
}
}
/**
* called to get the scan state in Async mode
* @return scan result or status
* -1 if scan not fin
* -2 if scan not triggered
*/
int8_t ESP8266WiFiScanClass::scanComplete() {
if(_scanStarted) {
return WIFI_SCAN_RUNNING;
}
if(_scanComplete) {
return ESP8266WiFiScanClass::_scanCount;
}
return WIFI_SCAN_FAILED;
}
/**
* delete last scan result from RAM
*/
void ESP8266WiFiScanClass::scanDelete() {
if(ESP8266WiFiScanClass::_scanResult) {
delete[] reinterpret_cast<bss_info*>(ESP8266WiFiScanClass::_scanResult);
ESP8266WiFiScanClass::_scanResult = 0;
ESP8266WiFiScanClass::_scanCount = 0;
}
_scanComplete = false;
}
/**
* loads all infos from a scanned wifi in to the ptr parameters
* @param networkItem uint8_t
* @param ssid const char**
* @param encryptionType uint8_t *
* @param RSSI int32_t *
* @param BSSID uint8_t **
* @param channel int32_t *
* @param isHidden bool *
* @return (true if ok)
*/
bool ESP8266WiFiScanClass::getNetworkInfo(uint8_t i, String &ssid, uint8_t &encType, int32_t &rssi, uint8_t* &bssid, int32_t &channel, bool &isHidden) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return false;
}
ssid = (const char*) it->ssid;
encType = encryptionType(i);
rssi = it->rssi;
bssid = it->bssid; // move ptr
channel = it->channel;
isHidden = (it->is_hidden != 0);
return true;
}
/**
* Return the SSID discovered during the network scan.
* @param i specify from which network item want to get the information
* @return ssid string of the specified item on the networks scanned list
*/
String ESP8266WiFiScanClass::SSID(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return "";
}
return String(reinterpret_cast<const char*>(it->ssid));
}
/**
* Return the encryption type of the networks discovered during the scanNetworks
* @param i specify from which network item want to get the information
* @return encryption type (enum wl_enc_type) of the specified item on the networks scanned list
*/
uint8_t ESP8266WiFiScanClass::encryptionType(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return -1;
}
switch(it->authmode) {
case AUTH_OPEN:
return ENC_TYPE_NONE;
case AUTH_WEP:
return ENC_TYPE_WEP;
case AUTH_WPA_PSK:
return ENC_TYPE_TKIP;
case AUTH_WPA2_PSK:
return ENC_TYPE_CCMP;
case AUTH_WPA_WPA2_PSK:
return ENC_TYPE_AUTO;
default:
return -1;
}
}
/**
* Return the RSSI of the networks discovered during the scanNetworks
* @param i specify from which network item want to get the information
* @return signed value of RSSI of the specified item on the networks scanned list
*/
int32_t ESP8266WiFiScanClass::RSSI(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->rssi;
}
/**
* return MAC / BSSID of scanned wifi
* @param i specify from which network item want to get the information
* @return uint8_t * MAC / BSSID of scanned wifi
*/
uint8_t * ESP8266WiFiScanClass::BSSID(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->bssid;
}
/**
* return MAC / BSSID of scanned wifi
* @param i specify from which network item want to get the information
* @return String MAC / BSSID of scanned wifi
*/
String ESP8266WiFiScanClass::BSSIDstr(uint8_t i) {
char mac[18] = { 0 };
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return String("");
}
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]);
return String(mac);
}
int32_t ESP8266WiFiScanClass::channel(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->channel;
}
/**
* return if the scanned wifi is Hidden (no SSID)
* @param networkItem specify from which network item want to get the information
* @return bool (true == hidden)
*/
bool ESP8266WiFiScanClass::isHidden(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return false;
}
return (it->is_hidden != 0);
}
/**
* private
* scan callback
* @param result void *arg
* @param status STATUS
*/
void ESP8266WiFiScanClass::_scanDone(void* result, int status) {
if(status != OK) {
ESP8266WiFiScanClass::_scanCount = 0;
ESP8266WiFiScanClass::_scanResult = 0;
} else {
int i = 0;
bss_info_head_t* head = reinterpret_cast<bss_info_head_t*>(result);
for(bss_info* it = STAILQ_FIRST(head); it; it = STAILQ_NEXT(it, next), ++i)
;
ESP8266WiFiScanClass::_scanCount = i;
if(i == 0) {
ESP8266WiFiScanClass::_scanResult = 0;
} else {
bss_info* copied_info = new bss_info[i];
i = 0;
for(bss_info* it = STAILQ_FIRST(head); it; it = STAILQ_NEXT(it, next), ++i) {
memcpy(copied_info + i, it, sizeof(bss_info));
}
ESP8266WiFiScanClass::_scanResult = copied_info;
}
}
ESP8266WiFiScanClass::_scanStarted = false;
ESP8266WiFiScanClass::_scanComplete = true;
if(!ESP8266WiFiScanClass::_scanAsync) {
esp_schedule();
}
}
/**
*
* @param i specify from which network item want to get the information
* @return bss_info *
*/
void * ESP8266WiFiScanClass::_getScanInfoByIndex(int i) {
if(!ESP8266WiFiScanClass::_scanResult || (size_t) i > ESP8266WiFiScanClass::_scanCount) {
return 0;
}
return reinterpret_cast<bss_info*>(ESP8266WiFiScanClass::_scanResult) + i;
}
<commit_msg>Fix WiFi scan issue (#1355)<commit_after>/*
ESP8266WiFiScan.cpp - WiFi library for esp8266
Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
This file is part of the esp8266 core for Arduino environment.
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
Reworked on 28 Dec 2015 by Markus Sattler
*/
#include "ESP8266WiFi.h"
#include "ESP8266WiFiGeneric.h"
#include "ESP8266WiFiScan.h"
extern "C" {
#include "c_types.h"
#include "ets_sys.h"
#include "os_type.h"
#include "osapi.h"
#include "mem.h"
#include "user_interface.h"
}
#include "debug.h"
extern "C" void esp_schedule();
extern "C" void esp_yield();
// -----------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------- Private functions ------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------- scan function ---------------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------
bool ESP8266WiFiScanClass::_scanAsync = false;
bool ESP8266WiFiScanClass::_scanStarted = false;
bool ESP8266WiFiScanClass::_scanComplete = false;
size_t ESP8266WiFiScanClass::_scanCount = 0;
void* ESP8266WiFiScanClass::_scanResult = 0;
/**
* Start scan WiFi networks available
* @param async run in async mode
* @param show_hidden show hidden networks
* @return Number of discovered networks
*/
int8_t ESP8266WiFiScanClass::scanNetworks(bool async, bool show_hidden) {
if(ESP8266WiFiScanClass::_scanStarted) {
return WIFI_SCAN_RUNNING;
}
ESP8266WiFiScanClass::_scanAsync = async;
WiFi.enableSTA(true);
int status = wifi_station_get_connect_status();
if(status != STATION_GOT_IP && status != STATION_IDLE) {
WiFi.disconnect(false);
}
scanDelete();
struct scan_config config;
config.ssid = 0;
config.bssid = 0;
config.channel = 0;
config.show_hidden = show_hidden;
if(wifi_station_scan(&config, reinterpret_cast<scan_done_cb_t>(&ESP8266WiFiScanClass::_scanDone))) {
ESP8266WiFiScanClass::_scanComplete = false;
ESP8266WiFiScanClass::_scanStarted = true;
if(ESP8266WiFiScanClass::_scanAsync) {
delay(0); // time for the OS to trigger the scan
return WIFI_SCAN_RUNNING;
}
esp_yield();
return ESP8266WiFiScanClass::_scanCount;
} else {
return WIFI_SCAN_FAILED;
}
}
/**
* called to get the scan state in Async mode
* @return scan result or status
* -1 if scan not fin
* -2 if scan not triggered
*/
int8_t ESP8266WiFiScanClass::scanComplete() {
if(_scanStarted) {
return WIFI_SCAN_RUNNING;
}
if(_scanComplete) {
return ESP8266WiFiScanClass::_scanCount;
}
return WIFI_SCAN_FAILED;
}
/**
* delete last scan result from RAM
*/
void ESP8266WiFiScanClass::scanDelete() {
if(ESP8266WiFiScanClass::_scanResult) {
delete[] reinterpret_cast<bss_info*>(ESP8266WiFiScanClass::_scanResult);
ESP8266WiFiScanClass::_scanResult = 0;
ESP8266WiFiScanClass::_scanCount = 0;
}
_scanComplete = false;
}
/**
* loads all infos from a scanned wifi in to the ptr parameters
* @param networkItem uint8_t
* @param ssid const char**
* @param encryptionType uint8_t *
* @param RSSI int32_t *
* @param BSSID uint8_t **
* @param channel int32_t *
* @param isHidden bool *
* @return (true if ok)
*/
bool ESP8266WiFiScanClass::getNetworkInfo(uint8_t i, String &ssid, uint8_t &encType, int32_t &rssi, uint8_t* &bssid, int32_t &channel, bool &isHidden) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return false;
}
ssid = (const char*) it->ssid;
encType = encryptionType(i);
rssi = it->rssi;
bssid = it->bssid; // move ptr
channel = it->channel;
isHidden = (it->is_hidden != 0);
return true;
}
/**
* Return the SSID discovered during the network scan.
* @param i specify from which network item want to get the information
* @return ssid string of the specified item on the networks scanned list
*/
String ESP8266WiFiScanClass::SSID(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return "";
}
return String(reinterpret_cast<const char*>(it->ssid));
}
/**
* Return the encryption type of the networks discovered during the scanNetworks
* @param i specify from which network item want to get the information
* @return encryption type (enum wl_enc_type) of the specified item on the networks scanned list
*/
uint8_t ESP8266WiFiScanClass::encryptionType(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return -1;
}
switch(it->authmode) {
case AUTH_OPEN:
return ENC_TYPE_NONE;
case AUTH_WEP:
return ENC_TYPE_WEP;
case AUTH_WPA_PSK:
return ENC_TYPE_TKIP;
case AUTH_WPA2_PSK:
return ENC_TYPE_CCMP;
case AUTH_WPA_WPA2_PSK:
return ENC_TYPE_AUTO;
default:
return -1;
}
}
/**
* Return the RSSI of the networks discovered during the scanNetworks
* @param i specify from which network item want to get the information
* @return signed value of RSSI of the specified item on the networks scanned list
*/
int32_t ESP8266WiFiScanClass::RSSI(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->rssi;
}
/**
* return MAC / BSSID of scanned wifi
* @param i specify from which network item want to get the information
* @return uint8_t * MAC / BSSID of scanned wifi
*/
uint8_t * ESP8266WiFiScanClass::BSSID(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->bssid;
}
/**
* return MAC / BSSID of scanned wifi
* @param i specify from which network item want to get the information
* @return String MAC / BSSID of scanned wifi
*/
String ESP8266WiFiScanClass::BSSIDstr(uint8_t i) {
char mac[18] = { 0 };
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return String("");
}
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]);
return String(mac);
}
int32_t ESP8266WiFiScanClass::channel(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return 0;
}
return it->channel;
}
/**
* return if the scanned wifi is Hidden (no SSID)
* @param networkItem specify from which network item want to get the information
* @return bool (true == hidden)
*/
bool ESP8266WiFiScanClass::isHidden(uint8_t i) {
struct bss_info* it = reinterpret_cast<struct bss_info*>(_getScanInfoByIndex(i));
if(!it) {
return false;
}
return (it->is_hidden != 0);
}
/**
* private
* scan callback
* @param result void *arg
* @param status STATUS
*/
void ESP8266WiFiScanClass::_scanDone(void* result, int status) {
if(status != OK) {
ESP8266WiFiScanClass::_scanCount = 0;
ESP8266WiFiScanClass::_scanResult = 0;
} else {
int i = 0;
bss_info* head = reinterpret_cast<bss_info*>(result);
for(bss_info* it = head; it; it = STAILQ_NEXT(it, next), ++i)
;
ESP8266WiFiScanClass::_scanCount = i;
if(i == 0) {
ESP8266WiFiScanClass::_scanResult = 0;
} else {
bss_info* copied_info = new bss_info[i];
i = 0;
for(bss_info* it = head; it; it = STAILQ_NEXT(it, next), ++i) {
memcpy(copied_info + i, it, sizeof(bss_info));
}
ESP8266WiFiScanClass::_scanResult = copied_info;
}
}
ESP8266WiFiScanClass::_scanStarted = false;
ESP8266WiFiScanClass::_scanComplete = true;
if(!ESP8266WiFiScanClass::_scanAsync) {
esp_schedule();
}
}
/**
*
* @param i specify from which network item want to get the information
* @return bss_info *
*/
void * ESP8266WiFiScanClass::_getScanInfoByIndex(int i) {
if(!ESP8266WiFiScanClass::_scanResult || (size_t) i > ESP8266WiFiScanClass::_scanCount) {
return 0;
}
return reinterpret_cast<bss_info*>(ESP8266WiFiScanClass::_scanResult) + i;
}
<|endoftext|> |
<commit_before>#ifndef CXX_CONVERSIONS_HXX
# define CXX_CONVERSIONS_HXX
# include <libport/assert.hh>
# include <libport/symbol.hh>
# include <object/cxx-object.hh>
# include <object/float.hh>
# include <object/list.hh>
# include <object/string.hh>
# include <object/tag.hh>
# include <scheduler/tag.hh>
namespace object
{
// Nothing to do for objects
template <>
class CxxConvert<libport::shared_ptr<Object, true> >
{
public:
static rObject
to(const rObject& o, const libport::Symbol&, unsigned)
{
return o;
}
static rObject
from(rObject o, const libport::Symbol&)
{
if (!o)
return void_class;
return o;
}
};
// Convert between Urbi types
template <typename Urbi>
struct CxxConvert<libport::shared_ptr<Urbi, true> >
{
typedef libport::shared_ptr<Urbi, true> T;
static T
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, Urbi::proto, idx);
return o->as<Urbi>();
}
static rObject
from(const T& v, const libport::Symbol&)
{
return v;
}
};
// Convert between Urbi types pointers
template <typename Urbi>
struct CxxConvert<Urbi*>
{
static Urbi*
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, Urbi::proto, idx);
return o->as<Urbi>().get();
}
static rObject
from(Urbi* v, const libport::Symbol&)
{
return v;
}
};
// Conversion with int
template<>
struct CxxConvert<int>
{
static int
to(const rObject& o, const libport::Symbol& name, unsigned idx)
{
type_check(o, Float::proto, idx);
return o->as<Float>()->to_int(name);
}
static rObject
from(const int& v, const libport::Symbol&)
{
return new Float(v);
}
};
// Conversion with unsigned int
template<>
struct CxxConvert<unsigned int>
{
static unsigned int
to(const rObject& o, const libport::Symbol& name, unsigned idx)
{
type_check(o, Float::proto, idx);
return o->as<Float>()->to_unsigned_int(name);
}
static rObject
from(const unsigned int& v, const libport::Symbol&)
{
return new Float(v);
}
};
// Conversion with floating point
template<>
struct CxxConvert<Float::value_type>
{
static Float::value_type
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, Float::proto, idx);
return o->as<Float>()->value_get();
}
static rObject
from(const Float::value_type& v, const libport::Symbol&)
{
return new Float(v);
}
};
// Conversion with std::strings
template <>
struct CxxConvert<std::string>
{
static std::string
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, String::proto, idx);
return o->as<String>()->value_get();
}
static rObject
from(const std::string& v, const libport::Symbol&)
{
return new String(v);
}
};
// Conversion with libport::Symbols
template <>
struct CxxConvert<libport::Symbol>
{
static libport::Symbol
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, String::proto, idx);
return libport::Symbol(o->as<String>()->value_get());
}
static rObject
from(const libport::Symbol& v, const libport::Symbol&)
{
return new String(v.name_get());
}
};
// Conversion with bools
template <>
struct CxxConvert<bool>
{
static bool
to(const rObject& o, const libport::Symbol& name, unsigned)
{
return is_true(o, name);
}
static rObject
from(bool v, const libport::Symbol&)
{
return v ? true_class : false_class;
}
};
// Conversion with tags_type
template <>
struct CxxConvert<scheduler::tags_type>
{
static scheduler::tags_type
to(const rObject&, const libport::Symbol& name, unsigned)
{
(void)name;
pabort(name);
}
static rObject
from(const scheduler::tags_type& v, const libport::Symbol&)
{
List::value_type res;
foreach (const scheduler::rTag& tag, v)
res.push_back(new Tag(tag));
return new List(res);
}
};
}
#endif
<commit_msg>Add C++/Urbi conversion for std::sets.<commit_after>#ifndef CXX_CONVERSIONS_HXX
# define CXX_CONVERSIONS_HXX
# include <libport/assert.hh>
# include <libport/symbol.hh>
# include <object/cxx-object.hh>
# include <object/float.hh>
# include <object/list.hh>
# include <object/string.hh>
# include <object/tag.hh>
# include <scheduler/tag.hh>
namespace object
{
// Nothing to do for objects
template <>
class CxxConvert<libport::shared_ptr<Object, true> >
{
public:
static rObject
to(const rObject& o, const libport::Symbol&, unsigned)
{
return o;
}
static rObject
from(rObject o, const libport::Symbol&)
{
if (!o)
return void_class;
return o;
}
};
// Convert between Urbi types
template <typename Urbi>
struct CxxConvert<libport::shared_ptr<Urbi, true> >
{
typedef libport::shared_ptr<Urbi, true> T;
static T
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, Urbi::proto, idx);
return o->as<Urbi>();
}
static rObject
from(const T& v, const libport::Symbol&)
{
return v;
}
};
// Convert between Urbi types pointers
template <typename Urbi>
struct CxxConvert<Urbi*>
{
static Urbi*
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, Urbi::proto, idx);
return o->as<Urbi>().get();
}
static rObject
from(Urbi* v, const libport::Symbol&)
{
return v;
}
};
// Conversion with int
template<>
struct CxxConvert<int>
{
static int
to(const rObject& o, const libport::Symbol& name, unsigned idx)
{
type_check(o, Float::proto, idx);
return o->as<Float>()->to_int(name);
}
static rObject
from(const int& v, const libport::Symbol&)
{
return new Float(v);
}
};
// Conversion with unsigned int
template<>
struct CxxConvert<unsigned int>
{
static unsigned int
to(const rObject& o, const libport::Symbol& name, unsigned idx)
{
type_check(o, Float::proto, idx);
return o->as<Float>()->to_unsigned_int(name);
}
static rObject
from(const unsigned int& v, const libport::Symbol&)
{
return new Float(v);
}
};
// Conversion with floating point
template<>
struct CxxConvert<Float::value_type>
{
static Float::value_type
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, Float::proto, idx);
return o->as<Float>()->value_get();
}
static rObject
from(const Float::value_type& v, const libport::Symbol&)
{
return new Float(v);
}
};
// Conversion with std::strings
template <>
struct CxxConvert<std::string>
{
static std::string
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, String::proto, idx);
return o->as<String>()->value_get();
}
static rObject
from(const std::string& v, const libport::Symbol&)
{
return new String(v);
}
};
// Conversion with libport::Symbols
template <>
struct CxxConvert<libport::Symbol>
{
static libport::Symbol
to(const rObject& o, const libport::Symbol&, unsigned idx)
{
type_check(o, String::proto, idx);
return libport::Symbol(o->as<String>()->value_get());
}
static rObject
from(const libport::Symbol& v, const libport::Symbol&)
{
return new String(v.name_get());
}
};
// Conversion with bools
template <>
struct CxxConvert<bool>
{
static bool
to(const rObject& o, const libport::Symbol& name, unsigned)
{
return is_true(o, name);
}
static rObject
from(bool v, const libport::Symbol&)
{
return v ? true_class : false_class;
}
};
// Conversion with tags_type
template <>
struct CxxConvert<scheduler::tags_type>
{
static scheduler::tags_type
to(const rObject&, const libport::Symbol& name, unsigned)
{
(void)name;
pabort(name);
}
static rObject
from(const scheduler::tags_type& v, const libport::Symbol&)
{
List::value_type res;
foreach (const scheduler::rTag& tag, v)
res.push_back(new Tag(tag));
return new List(res);
}
};
// Conversion with std::set
template <typename T>
struct CxxConvert<std::set<T> >
{
static std::set<T>
to(const rObject& o, const libport::Symbol& name, unsigned idx)
{
type_check(o, List::proto);
std::set<T> res;
foreach (const rObject& elt, o->as<List>()->value_get())
res.insert(CxxConvert<T>::to(elt, name, idx));
return res;
}
static rObject
from(const std::set<T>& v, const libport::Symbol& name)
{
objects_type res;
foreach (const T& elt, v)
res.push_back(CxxConvert<T>::from(elt, name));
return new List(res);
}
};
}
#endif
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright (c) 2012, Dougal J. Sutherland ([email protected]). *
* 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 Carnegie Mellon University nor the *
* names of the 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 "sdm/basics.hpp"
#include "sdm/sdm.hpp"
#include "sdm/kernels/linear.hpp"
#include "sdm/kernels/polynomial.hpp"
#include "sdm/kernels/gaussian.hpp"
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <boost/utility.hpp>
#include <flann/flann.hpp>
#include <np-divs/matrix_io.hpp>
#include <np-divs/div-funcs/from_str.hpp>
// TODO: support CV
// TODO: warn about dumb parameter combos, like linear kernel with distance df
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::string;
using std::vector;
namespace po = boost::program_options;
// TODO: leaks memory everywhere, but whatever...
struct ProgOpts : boost::noncopyable {
string train_bags_file;
string test_bags_file;
npdivs::DivFunc * div_func;
sdm::KernelGroup * kernel_group;
size_t k;
size_t num_threads;
size_t tuning_folds;
bool prob;
flann::IndexParams * index_params;
flann::SearchParams * search_params;
void parse_div_func(const string spec) {
div_func = npdivs::div_func_from_str(spec);
}
void parse_kernel(const string name) {
// TODO: support specifying cs / sigmas / degrees / etc
if (name == "gaussian") {
kernel_group = new sdm::GaussianKernelGroup;
} else if (name == "linear") {
kernel_group = new sdm::LinearKernelGroup;
} else if (name == "polynomial") {
kernel_group = new sdm::PolynomialKernelGroup;
} else {
throw std::domain_error((
boost::format("unknown kernel type %s") % name).str());
}
}
void parse_index(const string name) {
// TODO: more index types, support arguments
if (name == "linear" || name == "brute") {
index_params = new flann::LinearIndexParams;
} else if (name == "kdtree" || name == "kd") {
index_params = new flann::KDTreeSingleIndexParams;
} else {
throw std::domain_error((
boost::format("unknown index type %s") % name).str());
}
}
};
bool parse_args(int argc, char ** argv, ProgOpts& opts);
int main(int argc, char ** argv) {
typedef flann::Matrix<double> Matrix;
try {
ProgOpts opts;
if (!parse_args(argc, argv, opts))
return 1;
// TODO: gracefully handle nonexisting files
// TODO: more robust input checking
// load training bags
size_t num_train;
Matrix* train_bags;
vector<string> train_labels;
if (opts.train_bags_file == "-") {
cout << "Enter training distributions in CSV-like "
"format: an initial string label for each distribution, one "
"line with comma-separated floating-point values for each "
"point, one blank line between distributions, and an extra "
"blank line when done.\n";
train_bags = npdivs::labeled_matrices_from_csv(
std::cin, num_train, train_labels);
} else {
ifstream ifs(opts.train_bags_file.c_str(), ifstream::in);
train_bags = npdivs::labeled_matrices_from_csv(
ifs, num_train, train_labels);
}
// load test
size_t num_test;
Matrix* test_bags;
vector<string> test_labels;
if (opts.test_bags_file == "-") {
cout << "Enter testing distributions in CSV-like "
"format: an initial string label for each distribution, one "
"line with comma-separated floating-point values for each "
"point, one blank line between distributions, and an extra "
"blank line when done.\n";
test_bags = npdivs::labeled_matrices_from_csv(
cin, num_test, test_labels);
} else {
ifstream ifs(opts.test_bags_file.c_str(), ifstream::in);
test_bags = npdivs::labeled_matrices_from_csv(
ifs, num_test, test_labels);
}
// convert labels into integers
// make maps to convert between int / string labels
int this_label = -1;
std::map<string,int> labels_to_int;
std::map<int,string> labels_to_string;
std::vector<int> train_labels_ints;
train_labels_ints.reserve(num_train);
for (size_t i = 0; i < num_train; i++) {
const string &lbl = train_labels[i];
if (labels_to_int.count(lbl) == 0) {
labels_to_int[lbl] = ++this_label;
labels_to_string[this_label] = lbl;
}
train_labels_ints.push_back(labels_to_int[lbl]);
}
std::vector<int> test_labels_ints;
test_labels_ints.reserve(num_test);
for (size_t i = 0; i < num_train; i++) {
const string &lbl = test_labels[i];
if (labels_to_int.count(lbl) == 0) {
labels_to_int[lbl] = ++this_label;
labels_to_string[this_label] = lbl;
}
test_labels_ints.push_back(labels_to_int[lbl]);
}
// div params
npdivs::DivParams div_params(opts.k,
*opts.index_params, *opts.search_params,
opts.num_threads);
// svm params
svm_parameter svm_params(sdm::default_svm_params);
svm_params.probability = (int) opts.prob;
// train the model
sdm::SDM<double>* model = train_sdm(
train_bags, num_train, train_labels_ints,
*opts.div_func, *opts.kernel_group, div_params,
sdm::default_c_vals, svm_params, opts.tuning_folds);
// predict on test data
const std::vector<int> &preds = model->predict(test_bags, num_test);
// output predictions // TODO: optionally into file?
cout << "Predicted labels:\n";
for (size_t i = 0; i < num_test; i++) {
cout << labels_to_string[preds[i]] << endl;
}
// test accuracy, if available
size_t num_correct = 0;
for (size_t i = 0; i < num_test; i++)
if (preds[i] == test_labels_ints[i])
num_correct++;
cout << "Accuracy: " << num_correct * 100. / num_test << "%\n";
// clean up
model->destroyModelAndProb();
delete model;
delete[] train_bags;
} catch (std::exception &e) {
cerr << "Error: " << e.what() << endl;
return 1;
}
}
bool parse_args(int argc, char ** argv, ProgOpts& opts) {
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce this help message.")
("train-bags,b",
po::value<string>(&opts.train_bags_file)->default_value("-"),
"CSV-like file containing matrices separated by blank lines, "
"with a string label on its own line before each matrix; "
"- means stdin.")
("test-bags,t",
po::value<string>(&opts.test_bags_file)->default_value("-"),
"CSV-style file containing matrices separated by blank lines; "
"- means stdin.")
("div-func,d",
po::value<string>()->default_value("l2")->notifier(
boost::bind(&ProgOpts::parse_div_func, boost::ref(opts), _1)),
"Divergence function to use. Format is name[:arg1[:arg2...]]. "
"Options include alpha, bc, hellinger, l2, linear, renyi. "
"alpha and renyi take an optional second argument, so that "
"e.g. renyi:.8 is the Renyi-.8 divergence. All options take a "
"last argument that specifies how large intermediate values are "
"normalized; the default .99 means to cap certain values at the "
"99th percentile of their distribution, and 1 means not to do "
" this.")
("kernel,k",
po::value<string>()->default_value("gaussian")->notifier(
boost::bind(&ProgOpts::parse_kernel, boost::ref(opts), _1)),
"Kernel type to use. Options are gaussian, linear, polynomial. "
"Note that cross-validation is done to select gaussian kernel "
"width or polynomial degree, in combination with SVM C; this is "
"not yet configurable through this interface.")
("tuning-folds,f",
po::value<size_t>(&opts.tuning_folds)->default_value(3),
"The number of folds to use for the parameter tuning "
"cross-validation.")
("probability,P",
po::value<bool>(&opts.prob)->zero_tokens(),
"Use probability estimates in the trained SVMs.")
("num-threads,T",
po::value<size_t>(&opts.num_threads)->default_value(0),
"Number of threads to use for calculations. 0 means one per core "
"if compiled with recent-enough boost, or one thread otherwise.")
("neighbors,K",
po::value<size_t>(&opts.k)->default_value(3),
"The k for k-nearest-neighbor calculations.")
("index,i",
po::value<string>()->default_value("kdtree")->notifier(
boost::bind(&ProgOpts::parse_index, boost::ref(opts), _1)),
"The nearest-neighbor index to use. Options: linear, kdtree. "
"Note that this can have a large effect on calculation time: "
"use kdtree for low-dimensional data and linear for relatively "
"sparse high-dimensional data (about about 10).")
;
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
if (vm.count("help")) {
cout << desc << endl;
std::exit(0);
}
po::notify(vm);
} catch (std::exception &e) {
cerr << "Error: " << e.what() << endl;
return false;
}
opts.search_params = new flann::SearchParams(64);
return true;
}
<commit_msg>CLI interface niceties<commit_after>/*******************************************************************************
* Copyright (c) 2012, Dougal J. Sutherland ([email protected]). *
* 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 Carnegie Mellon University nor the *
* names of the 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 "sdm/basics.hpp"
#include "sdm/sdm.hpp"
#include "sdm/kernels/linear.hpp"
#include "sdm/kernels/polynomial.hpp"
#include "sdm/kernels/gaussian.hpp"
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <boost/utility.hpp>
#include <flann/flann.hpp>
#include <np-divs/matrix_io.hpp>
#include <np-divs/div-funcs/from_str.hpp>
// TODO: support CV
// TODO: warn about dumb parameter combos, like linear kernel with distance df
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::string;
using std::vector;
namespace po = boost::program_options;
// TODO: leaks memory everywhere, but whatever...
struct ProgOpts : boost::noncopyable {
string train_bags_file;
string test_bags_file;
npdivs::DivFunc * div_func;
sdm::KernelGroup * kernel_group;
size_t k;
size_t num_threads;
size_t tuning_folds;
bool prob;
flann::IndexParams * index_params;
flann::SearchParams * search_params;
void parse_div_func(const string spec) {
div_func = npdivs::div_func_from_str(spec);
}
void parse_kernel(const string name) {
// TODO: support specifying cs / sigmas / degrees / etc
if (name == "gaussian") {
kernel_group = new sdm::GaussianKernelGroup;
} else if (name == "linear") {
kernel_group = new sdm::LinearKernelGroup;
} else if (name == "polynomial") {
kernel_group = new sdm::PolynomialKernelGroup;
} else {
throw std::domain_error((
boost::format("unknown kernel type %s") % name).str());
}
}
void parse_index(const string name) {
// TODO: more index types, support arguments
if (name == "linear" || name == "brute") {
index_params = new flann::LinearIndexParams;
} else if (name == "kdtree" || name == "kd") {
index_params = new flann::KDTreeSingleIndexParams;
} else {
throw std::domain_error((
boost::format("unknown index type %s") % name).str());
}
}
};
bool parse_args(int argc, char ** argv, ProgOpts& opts);
int main(int argc, char ** argv) {
typedef flann::Matrix<double> Matrix;
try {
ProgOpts opts;
if (!parse_args(argc, argv, opts))
return 1;
// TODO: gracefully handle nonexisting files
// TODO: more robust input checking
// load training bags
size_t num_train;
Matrix* train_bags;
vector<string> train_labels;
if (opts.train_bags_file == "-") {
cout << "Enter training distributions in CSV-like "
"format: an initial string label for each distribution, one "
"line with comma-separated floating-point values for each "
"point, one blank line between distributions, and an extra "
"blank line when done.\n";
train_bags = npdivs::labeled_matrices_from_csv(
std::cin, num_train, train_labels);
} else {
ifstream ifs(opts.train_bags_file.c_str(), ifstream::in);
train_bags = npdivs::labeled_matrices_from_csv(
ifs, num_train, train_labels);
}
// load test
size_t num_test;
Matrix* test_bags;
vector<string> test_labels;
if (opts.test_bags_file == "-") {
cout << "Enter testing distributions in CSV-like "
"format: an initial string label for each distribution, one "
"line with comma-separated floating-point values for each "
"point, one blank line between distributions, and an extra "
"blank line when done.\n";
test_bags = npdivs::labeled_matrices_from_csv(
cin, num_test, test_labels);
} else {
ifstream ifs(opts.test_bags_file.c_str(), ifstream::in);
test_bags = npdivs::labeled_matrices_from_csv(
ifs, num_test, test_labels);
}
// convert labels into integers
// make maps to convert between int / string labels
int this_label = -1;
std::map<string,int> labels_to_int;
std::map<int,string> labels_to_string;
labels_to_int[""] = -1;
labels_to_int["?"] = -1;
labels_to_string[-1] = "?";
std::vector<int> train_labels_ints;
train_labels_ints.reserve(num_train);
for (size_t i = 0; i < num_train; i++) {
const string &lbl = train_labels[i];
if (labels_to_int.count(lbl) == 0) {
labels_to_int[lbl] = ++this_label;
labels_to_string[this_label] = lbl;
}
train_labels_ints.push_back(labels_to_int[lbl]);
}
std::vector<int> test_labels_ints;
test_labels_ints.reserve(num_test);
for (size_t i = 0; i < num_train; i++) {
const string &lbl = test_labels[i];
if (labels_to_int.count(lbl) == 0) {
labels_to_int[lbl] = ++this_label;
labels_to_string[this_label] = lbl;
}
test_labels_ints.push_back(labels_to_int[lbl]);
}
// div params
npdivs::DivParams div_params(opts.k,
*opts.index_params, *opts.search_params,
opts.num_threads);
// svm params
svm_parameter svm_params(sdm::default_svm_params);
svm_params.probability = (int) opts.prob;
// train the model
sdm::SDM<double>* model = train_sdm(
train_bags, num_train, train_labels_ints,
*opts.div_func, *opts.kernel_group, div_params,
sdm::default_c_vals, svm_params, opts.tuning_folds);
// predict on test data
const std::vector<int> &preds = model->predict(test_bags, num_test);
// output predictions // TODO: optionally into file?
cout << "Predicted labels:\n";
for (size_t i = 0; i < num_test; i++) {
cout << labels_to_string[preds[i]] << endl;
}
// test accuracy, if available
size_t num_correct = 0;
size_t total = num_test;
for (size_t i = 0; i < num_test; i++) {
if (test_labels_ints[i] == -1) {
total--;
} else if (preds[i] == test_labels_ints[i]) {
num_correct++;
}
}
if (total > 0) {
cout << "Accuracy on " << total << " labeled test points: "
<< num_correct * 100. / total << "%\n";
}
// clean up
model->destroyModelAndProb();
delete model;
delete[] train_bags;
} catch (std::exception &e) {
cerr << "Error: " << e.what() << endl;
return 1;
}
}
bool parse_args(int argc, char ** argv, ProgOpts& opts) {
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce this help message.")
("train-bags,b",
po::value<string>(&opts.train_bags_file)->default_value("-"),
"CSV-like file containing matrices separated by blank lines, "
"with a string label on its own line before each matrix; "
"- means stdin.")
("test-bags,t",
po::value<string>(&opts.test_bags_file)->default_value("-"),
"CSV-style file containing matrices separated by blank lines, "
"with a string label on its own line before each matrix."
"- means stdin. "
"Use a blank line or ? as the label if it's not known. If any "
"test distributions are labeled, will report accuracy on them.")
("div-func,d",
po::value<string>()->default_value("l2")->notifier(
boost::bind(&ProgOpts::parse_div_func, boost::ref(opts), _1)),
"Divergence function to use. Format is name[:arg1[:arg2...]]. "
"Options include alpha, bc, hellinger, l2, linear, renyi. "
"\nalpha and renyi take an optional second argument, so that "
"e.g. renyi:.8 is the Renyi-.8 divergence."
"\nAll options take a last argument that specifies how large "
" intermediate values are normalized; the default .99 means to "
"cap certain values at the 99th percentile of their distribution, "
"and 1 means not to do this.")
("kernel,k",
po::value<string>()->default_value("gaussian")->notifier(
boost::bind(&ProgOpts::parse_kernel, boost::ref(opts), _1)),
"Kernel type to use. Options are gaussian, linear, polynomial. "
"\nUse '-k linear' or '-k polynomial' only with '-d linear'; any "
"of the other -d arguments should be used with '-k gaussian' "
"in order to get a meaningful kernel. "
"\nNote that cross-validation is done to select gaussian kernel "
"width or polynomial degree, in combination with SVM C; this is "
"not yet configurable through this interface.")
("tuning-folds,f",
po::value<size_t>(&opts.tuning_folds)->default_value(3),
"The number of folds to use for the parameter tuning "
"cross-validation.")
("probability,P",
po::value<bool>(&opts.prob)->zero_tokens(),
"Use probability estimates in the trained SVMs.")
("num-threads,T",
po::value<size_t>(&opts.num_threads)->default_value(0),
"Number of threads to use for calculations. 0 means one per core "
"if compiled with recent-enough boost, or one thread otherwise.")
("neighbors,K",
po::value<size_t>(&opts.k)->default_value(3),
"The k for k-nearest-neighbor calculations.")
("index,i",
po::value<string>()->default_value("kdtree")->notifier(
boost::bind(&ProgOpts::parse_index, boost::ref(opts), _1)),
"The nearest-neighbor index to use. Options: linear, kdtree. "
"\nNote that this can have a large effect on calculation time: "
"use kdtree for low-dimensional data and linear for relatively "
"sparse high-dimensional data (about about 10).")
;
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);
if (vm.count("help")) {
cout << desc << endl;
std::exit(0);
}
po::notify(vm);
} catch (std::exception &e) {
cerr << "Error: " << e.what() << endl;
return false;
}
opts.search_params = new flann::SearchParams(64);
return true;
}
<|endoftext|> |
<commit_before>#include "wiVersion.h"
#include <sstream>
namespace wiVersion
{
// main engine core
const int major = 0;
// minor features, major updates
const int minor = 38;
// minor bug fixes, alterations, refactors, updates
const int revision = 7;
long GetVersion()
{
return major * 1000000 + minor * 1000 + revision;
}
int GetMajor()
{
return major;
}
int GetMinor()
{
return minor;
}
int GetRevision()
{
return revision;
}
std::string GetVersionString()
{
std::stringstream ss("");
ss << GetMajor() << "." << GetMinor() << "." << GetRevision();
return ss.str();
}
}
<commit_msg>Update wiVersion.cpp<commit_after>#include "wiVersion.h"
#include <sstream>
namespace wiVersion
{
// main engine core
const int major = 0;
// minor features, major updates
const int minor = 38;
// minor bug fixes, alterations, refactors, updates
const int revision = 8;
long GetVersion()
{
return major * 1000000 + minor * 1000 + revision;
}
int GetMajor()
{
return major;
}
int GetMinor()
{
return minor;
}
int GetRevision()
{
return revision;
}
std::string GetVersionString()
{
std::stringstream ss("");
ss << GetMajor() << "." << GetMinor() << "." << GetRevision();
return ss.str();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_registry.hxx"
#include "registry/registry.hxx"
#include "registry/reflread.hxx"
#include "fileurl.hxx"
#include "options.hxx"
#include "rtl/ustring.hxx"
#include "osl/diagnose.h"
#include <stdio.h>
#include <string.h>
#include <vector>
#include <string>
using namespace rtl;
using namespace registry::tools;
#define U2S( s ) \
OUStringToOString(s, RTL_TEXTENCODING_UTF8).getStr()
#define S2U( s ) \
OStringToOUString(s, RTL_TEXTENCODING_UTF8)
class Options_Impl : public Options
{
public:
explicit Options_Impl(char const * program)
: Options (program), m_bForceOutput(false)
{}
std::string const & getIndexReg() const
{ return m_indexRegName; }
std::string const & getTypeReg() const
{ return m_typeRegName; }
bool hasBase() const
{ return (m_base.getLength() > 0); }
const OString & getBase() const
{ return m_base; }
bool forceOutput() const
{ return m_bForceOutput; }
protected:
virtual void printUsage_Impl() const;
virtual bool initOptions_Impl (std::vector< std::string > & rArgs);
std::string m_indexRegName;
std::string m_typeRegName;
OString m_base;
bool m_bForceOutput;
};
// virtual
void Options_Impl::printUsage_Impl() const
{
std::string const & rProgName = getProgramName();
fprintf(stderr,
"Usage: %s -r<filename> -o<filename> [-options] | @<filename>\n", rProgName.c_str()
);
fprintf(stderr,
" -o<filename> = filename specifies the name of the new singleton index registry.\n"
" -r<filename> = filename specifies the name of the type registry.\n"
" @<filename> = filename specifies a command file.\n"
"Options:\n"
" -b<name> = name specifies the name of a start key. The types will be searched\n"
" under this key in the type registry.\n"
" -f = force the output of all found singletons.\n"
" -h|-? = print this help message and exit.\n"
);
fprintf(stderr,
"\nSun Microsystems (R) %s Version 1.0\n\n", rProgName.c_str()
);
}
// virtual
bool Options_Impl::initOptions_Impl(std::vector< std::string > & rArgs)
{
std::vector< std::string >::const_iterator first = rArgs.begin(), last = rArgs.end();
for (; first != last; ++first)
{
std::string option (*first);
if ((*first)[0] != '-')
{
return badOption("invalid", option.c_str());
}
switch ((*first)[1])
{
case 'r':
case 'R':
{
if (!((++first != last) && ((*first)[0] != '-')))
{
return badOption("invalid", option.c_str());
}
m_typeRegName = OString((*first).c_str(), (*first).size());
break;
}
case 'o':
case 'O':
{
if (!((++first != last) && ((*first)[0] != '-')))
{
return badOption("invalid", option.c_str());
}
m_indexRegName = (*first);
break;
}
case 'b':
case 'B':
{
if (!((++first != last) && ((*first)[0] != '-')))
{
return badOption("invalid", option.c_str());
}
m_base = OString((*first).c_str(), (*first).size());
break;
}
case 'f':
case 'F':
{
if ((*first).size() > 2)
{
return badOption("invalid", option.c_str());
}
m_bForceOutput = sal_True;
break;
}
case 'h':
case '?':
{
if ((*first).size() > 2)
{
return badOption("invalid", option.c_str());
}
return printUsage();
break;
}
default:
return badOption("unknown", option.c_str());
break;
}
}
return true;
}
static sal_Bool checkSingletons(Options_Impl const & options, RegistryKey& singletonKey, RegistryKey& typeKey)
{
RegValueType valueType = RG_VALUETYPE_NOT_DEFINED;
sal_uInt32 size = 0;
OUString tmpName;
sal_Bool bRet = sal_False;
RegError e = typeKey.getValueInfo(tmpName, &valueType, &size);
if ((e != REG_VALUE_NOT_EXISTS) && (e != REG_INVALID_VALUE) && (valueType == RG_VALUETYPE_BINARY))
{
std::vector< sal_uInt8 > value(size);
typeKey.getValue(tmpName, &value[0]); // @@@ broken api: write to buffer w/o buffer size.
RegistryTypeReader reader(&value[0], value.size(), sal_False);
if ( reader.isValid() && reader.getTypeClass() == RT_TYPE_SINGLETON )
{
RegistryKey entryKey;
OUString singletonName = reader.getTypeName().replace('/', '.');
if ( singletonKey.createKey(singletonName, entryKey) )
{
fprintf(stderr, "%s: could not create SINGLETONS entry for \"%s\"\n",
options.getProgramName().c_str(), U2S( singletonName ));
}
else
{
bRet = sal_True;
OUString value2 = reader.getSuperTypeName();
if ( entryKey.setValue(tmpName, RG_VALUETYPE_UNICODE,
(RegValue)value2.getStr(), sizeof(sal_Unicode)* (value2.getLength()+1)) )
{
fprintf(stderr, "%s: could not create data entry for singleton \"%s\"\n",
options.getProgramName().c_str(), U2S( singletonName ));
}
if ( options.forceOutput() )
{
fprintf(stderr, "%s: create SINGLETON entry for \"%s\" -> \"%s\"\n",
options.getProgramName().c_str(), U2S( singletonName ), U2S(value2));
}
}
}
}
RegistryKeyArray subKeys;
typeKey.openSubKeys(tmpName, subKeys);
sal_uInt32 length = subKeys.getLength();
for (sal_uInt32 i = 0; i < length; i++)
{
RegistryKey elementKey = subKeys.getElement(i);
if ( checkSingletons(options, singletonKey, elementKey) )
{
bRet = sal_True;
}
}
return bRet;
}
#if (defined UNX) || (defined OS2) || (defined __MINGW32__)
int main( int argc, char * argv[] )
#else
int _cdecl main( int argc, char * argv[] )
#endif
{
std::vector< std::string > args;
for (int i = 1; i < argc; i++)
{
int result = Options::checkArgument(args, argv[i], strlen(argv[i]));
if (result != 0)
{
// failure.
return (result);
}
}
Options_Impl options(argv[0]);
if (!options.initOptions(args))
{
options.printUsage();
return (1);
}
OUString indexRegName( convertToFileUrl(options.getIndexReg().c_str(), options.getIndexReg().size()) );
Registry indexReg;
if ( indexReg.open(indexRegName, REG_READWRITE) )
{
if ( indexReg.create(indexRegName) )
{
fprintf(stderr, "%s: open registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (2);
}
}
OUString typeRegName( convertToFileUrl(options.getTypeReg().c_str(), options.getTypeReg().size()) );
Registry typeReg;
if ( typeReg.open(typeRegName, REG_READONLY) )
{
fprintf(stderr, "%s: open registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (3);
}
RegistryKey indexRoot;
if ( indexReg.openRootKey(indexRoot) )
{
fprintf(stderr, "%s: open root key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (4);
}
RegistryKey typeRoot;
if ( typeReg.openRootKey(typeRoot) )
{
fprintf(stderr, "%s: open root key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (5);
}
RegistryKey typeKey;
if ( options.hasBase() )
{
if ( typeRoot.openKey(S2U(options.getBase()), typeKey) )
{
fprintf(stderr, "%s: open base key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (6);
}
}
else
{
typeKey = typeRoot;
}
RegistryKey singletonKey;
if ( indexRoot.createKey(OUString::createFromAscii("SINGLETONS"), singletonKey) )
{
fprintf(stderr, "%s: open/create SINGLETONS key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (7);
}
sal_Bool bSingletonsExist = checkSingletons(options, singletonKey, typeKey);
indexRoot.releaseKey();
typeRoot.releaseKey();
typeKey.releaseKey();
singletonKey.releaseKey();
if ( indexReg.close() )
{
fprintf(stderr, "%s: closing registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (9);
}
if ( !bSingletonsExist )
{
if ( indexReg.destroy(OUString()) )
{
fprintf(stderr, "%s: destroy registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (10);
}
}
if ( typeReg.close() )
{
fprintf(stderr, "%s: closing registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (11);
}
}
<commit_msg>#i115784# registry/tools: fix unreachable break statement after return.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_registry.hxx"
#include "registry/registry.hxx"
#include "registry/reflread.hxx"
#include "fileurl.hxx"
#include "options.hxx"
#include "rtl/ustring.hxx"
#include "osl/diagnose.h"
#include <stdio.h>
#include <string.h>
#include <vector>
#include <string>
using namespace rtl;
using namespace registry::tools;
#define U2S( s ) \
OUStringToOString(s, RTL_TEXTENCODING_UTF8).getStr()
#define S2U( s ) \
OStringToOUString(s, RTL_TEXTENCODING_UTF8)
class Options_Impl : public Options
{
public:
explicit Options_Impl(char const * program)
: Options (program), m_bForceOutput(false)
{}
std::string const & getIndexReg() const
{ return m_indexRegName; }
std::string const & getTypeReg() const
{ return m_typeRegName; }
bool hasBase() const
{ return (m_base.getLength() > 0); }
const OString & getBase() const
{ return m_base; }
bool forceOutput() const
{ return m_bForceOutput; }
protected:
virtual void printUsage_Impl() const;
virtual bool initOptions_Impl (std::vector< std::string > & rArgs);
std::string m_indexRegName;
std::string m_typeRegName;
OString m_base;
bool m_bForceOutput;
};
// virtual
void Options_Impl::printUsage_Impl() const
{
std::string const & rProgName = getProgramName();
fprintf(stderr,
"Usage: %s -r<filename> -o<filename> [-options] | @<filename>\n", rProgName.c_str()
);
fprintf(stderr,
" -o<filename> = filename specifies the name of the new singleton index registry.\n"
" -r<filename> = filename specifies the name of the type registry.\n"
" @<filename> = filename specifies a command file.\n"
"Options:\n"
" -b<name> = name specifies the name of a start key. The types will be searched\n"
" under this key in the type registry.\n"
" -f = force the output of all found singletons.\n"
" -h|-? = print this help message and exit.\n"
);
fprintf(stderr,
"\nSun Microsystems (R) %s Version 1.0\n\n", rProgName.c_str()
);
}
// virtual
bool Options_Impl::initOptions_Impl(std::vector< std::string > & rArgs)
{
std::vector< std::string >::const_iterator first = rArgs.begin(), last = rArgs.end();
for (; first != last; ++first)
{
std::string option (*first);
if ((*first)[0] != '-')
{
return badOption("invalid", option.c_str());
}
switch ((*first)[1])
{
case 'r':
case 'R':
{
if (!((++first != last) && ((*first)[0] != '-')))
{
return badOption("invalid", option.c_str());
}
m_typeRegName = OString((*first).c_str(), (*first).size());
break;
}
case 'o':
case 'O':
{
if (!((++first != last) && ((*first)[0] != '-')))
{
return badOption("invalid", option.c_str());
}
m_indexRegName = (*first);
break;
}
case 'b':
case 'B':
{
if (!((++first != last) && ((*first)[0] != '-')))
{
return badOption("invalid", option.c_str());
}
m_base = OString((*first).c_str(), (*first).size());
break;
}
case 'f':
case 'F':
{
if ((*first).size() > 2)
{
return badOption("invalid", option.c_str());
}
m_bForceOutput = sal_True;
break;
}
case 'h':
case '?':
{
if ((*first).size() > 2)
{
return badOption("invalid", option.c_str());
}
return printUsage();
// break; // unreachable
}
default:
return badOption("unknown", option.c_str());
// break; // unreachable
}
}
return true;
}
static sal_Bool checkSingletons(Options_Impl const & options, RegistryKey& singletonKey, RegistryKey& typeKey)
{
RegValueType valueType = RG_VALUETYPE_NOT_DEFINED;
sal_uInt32 size = 0;
OUString tmpName;
sal_Bool bRet = sal_False;
RegError e = typeKey.getValueInfo(tmpName, &valueType, &size);
if ((e != REG_VALUE_NOT_EXISTS) && (e != REG_INVALID_VALUE) && (valueType == RG_VALUETYPE_BINARY))
{
std::vector< sal_uInt8 > value(size);
typeKey.getValue(tmpName, &value[0]); // @@@ broken api: write to buffer w/o buffer size.
RegistryTypeReader reader(&value[0], value.size(), sal_False);
if ( reader.isValid() && reader.getTypeClass() == RT_TYPE_SINGLETON )
{
RegistryKey entryKey;
OUString singletonName = reader.getTypeName().replace('/', '.');
if ( singletonKey.createKey(singletonName, entryKey) )
{
fprintf(stderr, "%s: could not create SINGLETONS entry for \"%s\"\n",
options.getProgramName().c_str(), U2S( singletonName ));
}
else
{
bRet = sal_True;
OUString value2 = reader.getSuperTypeName();
if ( entryKey.setValue(tmpName, RG_VALUETYPE_UNICODE,
(RegValue)value2.getStr(), sizeof(sal_Unicode)* (value2.getLength()+1)) )
{
fprintf(stderr, "%s: could not create data entry for singleton \"%s\"\n",
options.getProgramName().c_str(), U2S( singletonName ));
}
if ( options.forceOutput() )
{
fprintf(stderr, "%s: create SINGLETON entry for \"%s\" -> \"%s\"\n",
options.getProgramName().c_str(), U2S( singletonName ), U2S(value2));
}
}
}
}
RegistryKeyArray subKeys;
typeKey.openSubKeys(tmpName, subKeys);
sal_uInt32 length = subKeys.getLength();
for (sal_uInt32 i = 0; i < length; i++)
{
RegistryKey elementKey = subKeys.getElement(i);
if ( checkSingletons(options, singletonKey, elementKey) )
{
bRet = sal_True;
}
}
return bRet;
}
#if (defined UNX) || (defined OS2) || (defined __MINGW32__)
int main( int argc, char * argv[] )
#else
int _cdecl main( int argc, char * argv[] )
#endif
{
std::vector< std::string > args;
for (int i = 1; i < argc; i++)
{
int result = Options::checkArgument(args, argv[i], strlen(argv[i]));
if (result != 0)
{
// failure.
return (result);
}
}
Options_Impl options(argv[0]);
if (!options.initOptions(args))
{
options.printUsage();
return (1);
}
OUString indexRegName( convertToFileUrl(options.getIndexReg().c_str(), options.getIndexReg().size()) );
Registry indexReg;
if ( indexReg.open(indexRegName, REG_READWRITE) )
{
if ( indexReg.create(indexRegName) )
{
fprintf(stderr, "%s: open registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (2);
}
}
OUString typeRegName( convertToFileUrl(options.getTypeReg().c_str(), options.getTypeReg().size()) );
Registry typeReg;
if ( typeReg.open(typeRegName, REG_READONLY) )
{
fprintf(stderr, "%s: open registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (3);
}
RegistryKey indexRoot;
if ( indexReg.openRootKey(indexRoot) )
{
fprintf(stderr, "%s: open root key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (4);
}
RegistryKey typeRoot;
if ( typeReg.openRootKey(typeRoot) )
{
fprintf(stderr, "%s: open root key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (5);
}
RegistryKey typeKey;
if ( options.hasBase() )
{
if ( typeRoot.openKey(S2U(options.getBase()), typeKey) )
{
fprintf(stderr, "%s: open base key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (6);
}
}
else
{
typeKey = typeRoot;
}
RegistryKey singletonKey;
if ( indexRoot.createKey(OUString::createFromAscii("SINGLETONS"), singletonKey) )
{
fprintf(stderr, "%s: open/create SINGLETONS key of registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (7);
}
sal_Bool bSingletonsExist = checkSingletons(options, singletonKey, typeKey);
indexRoot.releaseKey();
typeRoot.releaseKey();
typeKey.releaseKey();
singletonKey.releaseKey();
if ( indexReg.close() )
{
fprintf(stderr, "%s: closing registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (9);
}
if ( !bSingletonsExist )
{
if ( indexReg.destroy(OUString()) )
{
fprintf(stderr, "%s: destroy registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getIndexReg().c_str());
return (10);
}
}
if ( typeReg.close() )
{
fprintf(stderr, "%s: closing registry \"%s\" failed\n",
options.getProgramName().c_str(), options.getTypeReg().c_str());
return (11);
}
}
<|endoftext|> |
<commit_before>/**
* @file consensushash.cpp
*
* This file contains the function to generate consensus hashes.
*/
#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/mdex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"
#include <stdint.h>
#include <string>
#include <openssl/sha.h>
namespace mastercore
{
/**
* Calculates the total number of from the tally map
*
* Note - faster than using getTotalTokens() as doesn't require loading SP from database
**/
int64_t GetTallyPropertyTotal(uint32_t propertyId)
{
int64_t totalTokens = 0;
for (std::map<std::string, CMPTally>::const_iterator it = mp_tally_map.begin(); it != mp_tally_map.end(); ++it) {
const CMPTally& tally = it->second;
totalTokens += tally.getMoney(propertyId, BALANCE);
totalTokens += tally.getMoney(propertyId, SELLOFFER_RESERVE);
totalTokens += tally.getMoney(propertyId, ACCEPT_RESERVE);
totalTokens += tally.getMoney(propertyId, METADEX_RESERVE);
}
return totalTokens;
}
/**
* Obtains a hash of all balances to use for consensus verification and checkpointing.
*
* For increased flexibility, so other implementations like OmniWallet and OmniChest can
* also apply this methodology without necessarily using the same exact data types (which
* would be needed to hash the data bytes directly), create a string in the following
* format for each address/property identifier combo to use for hashing:
*
* Format specifiers:
* "%s|%d|%d|%d|%d|%d"
*
* With placeholders:
* "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
*
* Example:
* SHA256 round 1: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|31|8000|0|0|0"
* SHA256 round 2: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|2147483657|0|0|0|234235245"
* SHA256 round 3: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|1|0|100|0|0"
* SHA256 round 4: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|2|0|0|0|50000"
* SHA256 round 5: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|10|0|0|1|0"
* SHA256 round 6: "3CwZ7FiQ4MqBenRdCkjjc41M5bnoKQGC2b|1|12345|5|777|9000"
*
* Result:
* "3580e94167f75620dfa8c267862aa47af46164ed8edaec3a800d732050ec0607"
*
* The byte order is important, and in the example we assume:
* SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
*
* Note: empty balance records and the pending tally are ignored. Addresses are sorted based
* on lexicographical order, and balance records are sorted by the property identifiers.
*/
uint256 GetConsensusHash()
{
// allocate and init a SHA256_CTX
SHA256_CTX shaCtx;
SHA256_Init(&shaCtx);
LOCK(cs_tally);
if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");
// Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
const std::string& address = my_it->first;
CMPTally& tally = my_it->second;
tally.init();
uint32_t propertyId = 0;
while (0 != (propertyId = (tally.next()))) {
int64_t balance = tally.getMoney(propertyId, BALANCE);
int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);
// skip this entry if all balances are empty
if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;
std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// DEx sell offers - loop through the DEx and add each sell offer to the consensus hash
for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
const CMPOffer& selloffer = it->second;
const std::string& sellCombo = it->first;
uint32_t propertyId = selloffer.getProperty();
std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
// "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d|%d|%d",
selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit(),
getMPbalance(seller, propertyId, SELLOFFER_RESERVE), getMPbalance(seller, propertyId, ACCEPT_RESERVE));
if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// DEx accepts - loop through the accepts map and add each accept to the consensus hash
for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) {
const CMPAccept& accept = it->second;
const std::string& acceptCombo = it->first;
std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1)));
// "buyer|matchedselloffertxid|acceptamount|acceptamountremaining|acceptblock"
std::string dataStr = strprintf("%s|%s|%d|%d|%d",
buyer, accept.getHash().GetHex(), accept.getAcceptAmount(), accept.getAcceptAmountRemaining(), accept.getAcceptBlock());
if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash
for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
const md_PricesMap& prices = my_it->second;
for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) {
const md_Set& indexes = it->second;
for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
const CMPMetaDEx& obj = *it;
// "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
obj.getHash().GetHex(), obj.getAddr(), obj.getProperty(), obj.getAmountForSale(),
obj.getDesProperty(), obj.getAmountDesired(), obj.getAmountRemaining());
if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
}
// Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID)
// Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to
// avoid additionalal loading of SP entries from the database
// Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
std::vector<std::pair<uint32_t, std::string> > crowdOrder;
for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) {
const CMPCrowd& crowd = it->second;
uint32_t propertyId = crowd.getPropertyId();
std::string dataStr = strprintf("%d|%d|%d|%d|%d",
crowd.getPropertyId(), crowd.getCurrDes(), crowd.getDeadline(), crowd.getUserCreated(), crowd.getIssuerCreated());
crowdOrder.push_back(std::make_pair(propertyId, dataStr));
}
std::sort (crowdOrder.begin(), crowdOrder.end());
for (std::vector<std::pair<uint32_t, std::string> >::iterator it = crowdOrder.begin(); it != crowdOrder.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// Properties - loop through each property calculating the number of total tokens (ordered by property ID)
// Note: avoiding use of getTotalTokens() here to avoid additional loading of SP entries from the database
// Placeholders: "propertyid|totaltokens"
for (uint8_t ecosystem = 1; ecosystem <= 2; ecosystem++) {
uint32_t startPropertyId = (ecosystem == 1) ? 1 : TEST_ECO_PROPERTY_1;
for (uint32_t propertyId = startPropertyId; propertyId < _my_sps->peekNextSPID(ecosystem); propertyId++) {
std::string dataStr = strprintf("%d|%d", propertyId, GetTallyPropertyTotal(propertyId));
if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// extract the final result and return the hash
uint256 consensusHash;
SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex());
return consensusHash;
}
} // namespace mastercore
<commit_msg>Order DEx offers and MetaDEx trades by txid in consensus hash<commit_after>/**
* @file consensushash.cpp
*
* This file contains the function to generate consensus hashes.
*/
#include "omnicore/consensushash.h"
#include "omnicore/dex.h"
#include "omnicore/mdex.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/sp.h"
#include <stdint.h>
#include <string>
#include <openssl/sha.h>
namespace mastercore
{
/**
* Calculates the total number of from the tally map
*
* Note - faster than using getTotalTokens() as doesn't require loading SP from database
**/
int64_t GetTallyPropertyTotal(uint32_t propertyId)
{
int64_t totalTokens = 0;
for (std::map<std::string, CMPTally>::const_iterator it = mp_tally_map.begin(); it != mp_tally_map.end(); ++it) {
const CMPTally& tally = it->second;
totalTokens += tally.getMoney(propertyId, BALANCE);
totalTokens += tally.getMoney(propertyId, SELLOFFER_RESERVE);
totalTokens += tally.getMoney(propertyId, ACCEPT_RESERVE);
totalTokens += tally.getMoney(propertyId, METADEX_RESERVE);
}
return totalTokens;
}
/**
* Obtains a hash of all balances to use for consensus verification and checkpointing.
*
* For increased flexibility, so other implementations like OmniWallet and OmniChest can
* also apply this methodology without necessarily using the same exact data types (which
* would be needed to hash the data bytes directly), create a string in the following
* format for each address/property identifier combo to use for hashing:
*
* Format specifiers:
* "%s|%d|%d|%d|%d|%d"
*
* With placeholders:
* "address|propertyid|balance|selloffer_reserve|accept_reserve|metadex_reserve"
*
* Example:
* SHA256 round 1: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|31|8000|0|0|0"
* SHA256 round 2: "1LCShN3ntEbeRrj8XBFWdScGqw5NgDXL5R|2147483657|0|0|0|234235245"
* SHA256 round 3: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|1|0|100|0|0"
* SHA256 round 4: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|2|0|0|0|50000"
* SHA256 round 5: "1LP7G6uiHPaG8jm64aconFF8CLBAnRGYcb|10|0|0|1|0"
* SHA256 round 6: "3CwZ7FiQ4MqBenRdCkjjc41M5bnoKQGC2b|1|12345|5|777|9000"
*
* Result:
* "3580e94167f75620dfa8c267862aa47af46164ed8edaec3a800d732050ec0607"
*
* The byte order is important, and in the example we assume:
* SHA256("abc") = "ad1500f261ff10b49c7a1796a36103b02322ae5dde404141eacf018fbf1678ba"
*
* Note: empty balance records and the pending tally are ignored. Addresses are sorted based
* on lexicographical order, and balance records are sorted by the property identifiers.
*/
uint256 GetConsensusHash()
{
// allocate and init a SHA256_CTX
SHA256_CTX shaCtx;
SHA256_Init(&shaCtx);
LOCK(cs_tally);
if (msc_debug_consensus_hash) PrintToLog("Beginning generation of current consensus hash...\n");
// Balances - loop through the tally map, updating the sha context with the data from each balance and tally type
for (std::map<string, CMPTally>::iterator my_it = mp_tally_map.begin(); my_it != mp_tally_map.end(); ++my_it) {
const std::string& address = my_it->first;
CMPTally& tally = my_it->second;
tally.init();
uint32_t propertyId = 0;
while (0 != (propertyId = (tally.next()))) {
int64_t balance = tally.getMoney(propertyId, BALANCE);
int64_t sellOfferReserve = tally.getMoney(propertyId, SELLOFFER_RESERVE);
int64_t acceptReserve = tally.getMoney(propertyId, ACCEPT_RESERVE);
int64_t metaDExReserve = tally.getMoney(propertyId, METADEX_RESERVE);
// skip this entry if all balances are empty
if (!balance && !sellOfferReserve && !acceptReserve && !metaDExReserve) continue;
std::string dataStr = strprintf("%s|%d|%d|%d|%d|%d",
address, propertyId, balance, sellOfferReserve, acceptReserve, metaDExReserve);
if (msc_debug_consensus_hash) PrintToLog("Adding balance data to consensus hash: %s\n", dataStr);
// update the sha context with the data string
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// DEx sell offers - loop through the DEx and add each sell offer to the consensus hash (ordered by txid)
// Placeholders: "txid|address|propertyid|offeramount|btcdesired|minfee|timelimit|availableamount|acceptedamount"
std::vector<std::pair<uint256, std::string> > vecDExOffers;
for (OfferMap::iterator it = my_offers.begin(); it != my_offers.end(); ++it) {
const CMPOffer& selloffer = it->second;
const std::string& sellCombo = it->first;
uint32_t propertyId = selloffer.getProperty();
std::string seller = sellCombo.substr(0, sellCombo.size() - 2);
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d|%d|%d",
selloffer.getHash().GetHex(), seller, propertyId, selloffer.getOfferAmountOriginal(),
selloffer.getBTCDesiredOriginal(), selloffer.getMinFee(), selloffer.getBlockTimeLimit(),
getMPbalance(seller, propertyId, SELLOFFER_RESERVE), getMPbalance(seller, propertyId, ACCEPT_RESERVE));
vecDExOffers.push_back(std::make_pair(selloffer.getHash(), dataStr));
}
std::sort (vecDExOffers.begin(), vecDExOffers.end());
for (std::vector<std::pair<uint256, std::string> >::iterator it = vecDExOffers.begin(); it != vecDExOffers.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding DEx offer data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// DEx accepts - loop through the accepts map and add each accept to the consensus hash
for (AcceptMap::const_iterator it = my_accepts.begin(); it != my_accepts.end(); ++it) {
const CMPAccept& accept = it->second;
const std::string& acceptCombo = it->first;
std::string buyer = acceptCombo.substr((acceptCombo.find("+") + 1), (acceptCombo.size()-(acceptCombo.find("+") + 1)));
// "buyer|matchedselloffertxid|acceptamount|acceptamountremaining|acceptblock"
std::string dataStr = strprintf("%s|%s|%d|%d|%d",
buyer, accept.getHash().GetHex(), accept.getAcceptAmount(), accept.getAcceptAmountRemaining(), accept.getAcceptBlock());
if (msc_debug_consensus_hash) PrintToLog("Adding DEx accept to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// MetaDEx trades - loop through the MetaDEx maps and add each open trade to the consensus hash (ordered by txid)
// Placeholders: "txid|address|propertyidforsale|amountforsale|propertyiddesired|amountdesired|amountremaining"
std::vector<std::pair<uint256, std::string> > vecMetaDExTrades;
for (md_PropertiesMap::const_iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) {
const md_PricesMap& prices = my_it->second;
for (md_PricesMap::const_iterator it = prices.begin(); it != prices.end(); ++it) {
const md_Set& indexes = it->second;
for (md_Set::const_iterator it = indexes.begin(); it != indexes.end(); ++it) {
const CMPMetaDEx& obj = *it;
std::string dataStr = strprintf("%s|%s|%d|%d|%d|%d|%d",
obj.getHash().GetHex(), obj.getAddr(), obj.getProperty(), obj.getAmountForSale(),
obj.getDesProperty(), obj.getAmountDesired(), obj.getAmountRemaining());
vecMetaDExTrades.push_back(std::make_pair(obj.getHash(), dataStr));
}
}
}
std::sort (vecMetaDExTrades.begin(), vecMetaDExTrades.end());
for (std::vector<std::pair<uint256, std::string> >::iterator it = vecMetaDExTrades.begin(); it != vecMetaDExTrades.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding MetaDEx trade data to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// Crowdsales - loop through open crowdsales and add to the consensus hash (ordered by property ID)
// Note: the variables of the crowdsale (amount, bonus etc) are not part of the crowdsale map and not included here to
// avoid additionalal loading of SP entries from the database
// Placeholders: "propertyid|propertyiddesired|deadline|usertokens|issuertokens"
std::vector<std::pair<uint32_t, std::string> > crowdOrder;
for (CrowdMap::const_iterator it = my_crowds.begin(); it != my_crowds.end(); ++it) {
const CMPCrowd& crowd = it->second;
uint32_t propertyId = crowd.getPropertyId();
std::string dataStr = strprintf("%d|%d|%d|%d|%d",
crowd.getPropertyId(), crowd.getCurrDes(), crowd.getDeadline(), crowd.getUserCreated(), crowd.getIssuerCreated());
crowdOrder.push_back(std::make_pair(propertyId, dataStr));
}
std::sort (crowdOrder.begin(), crowdOrder.end());
for (std::vector<std::pair<uint32_t, std::string> >::iterator it = crowdOrder.begin(); it != crowdOrder.end(); ++it) {
std::string dataStr = (*it).second;
if (msc_debug_consensus_hash) PrintToLog("Adding Crowdsale entry to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
// Properties - loop through each property calculating the number of total tokens (ordered by property ID)
// Note: avoiding use of getTotalTokens() here to avoid additional loading of SP entries from the database
// Placeholders: "propertyid|totaltokens"
for (uint8_t ecosystem = 1; ecosystem <= 2; ecosystem++) {
uint32_t startPropertyId = (ecosystem == 1) ? 1 : TEST_ECO_PROPERTY_1;
for (uint32_t propertyId = startPropertyId; propertyId < _my_sps->peekNextSPID(ecosystem); propertyId++) {
std::string dataStr = strprintf("%d|%d", propertyId, GetTallyPropertyTotal(propertyId));
if (msc_debug_consensus_hash) PrintToLog("Adding property to consensus hash: %s\n", dataStr);
SHA256_Update(&shaCtx, dataStr.c_str(), dataStr.length());
}
}
// extract the final result and return the hash
uint256 consensusHash;
SHA256_Final((unsigned char*)&consensusHash, &shaCtx);
if (msc_debug_consensus_hash) PrintToLog("Finished generation of consensus hash. Result: %s\n", consensusHash.GetHex());
return consensusHash;
}
} // namespace mastercore
<|endoftext|> |
<commit_before>// --- ROOT system
#include <TFile.h>
#include <TClonesArray.h>
#include <TList.h>
#include <TObjString.h>
#include <TTimeStamp.h>
#include "AliZDCPreprocessor.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliAlignObj.h"
#include "AliAlignObjAngles.h"
#include "AliLog.h"
#include "AliZDCDataDCS.h"
#include "AliZDCCalibData.h"
//
// Class implementing ZDC pre-processor.
// It takes data from DCS and passes it to the class AliZDCDataDCS.
// The class is then written to the CDB.
//
ClassImp(AliZDCPreprocessor)
//______________________________________________________________________________________________
AliZDCPreprocessor::AliZDCPreprocessor(const char* detector, AliShuttleInterface* shuttle) :
AliPreprocessor(detector, shuttle),
fData(0)
{
// constructor
}
//______________________________________________________________________________________________
AliZDCPreprocessor::~AliZDCPreprocessor()
{
// destructor
}
//______________________________________________________________________________________________
void AliZDCPreprocessor::Initialize(Int_t run, UInt_t startTime,
UInt_t endTime)
{
// Creates AliZDCDataDCS object
AliPreprocessor::Initialize(run, startTime, endTime);
Log(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
fRun = run;
fStartTime = startTime;
fEndTime = endTime;
fData = new AliZDCDataDCS(fRun, fStartTime, fEndTime);
}
//______________________________________________________________________________________________
UInt_t AliZDCPreprocessor::Process(TMap* dcsAliasMap)
{
// *************** From DCS ******************
// Fills data into a AliZDCDataDCS object
if(!dcsAliasMap) return 0;
// The processing of the DCS input data is forwarded to AliZDCDataDCS
Float_t DCSValues[26];
fData->ProcessData(*dcsAliasMap, DCSValues);
//dcsAliasMap->Print("");
//
// --- Writing ZDC table positions into alignment object
TClonesArray *array = new TClonesArray("AliAlignObjAngles",10);
TClonesArray &alobj = *array;
AliAlignObjAngles a;
Double_t dx=0., dz=0., dpsi=0., dtheta=0., dphi=0.;
// Vertical table position in mm from DCS
Double_t dyZN1 = (Double_t) (DCSValues[0]/10.);
Double_t dyZP1 = (Double_t) (DCSValues[1]/10.);
Double_t dyZN2 = (Double_t) (DCSValues[2]/10.);
Double_t dyZP2 = (Double_t) (DCSValues[3]/10.);
const char *ZDCn1="ZDC/NeutronZDC1";
const char *ZDCp1="ZDC/ProtonZDC1";
const char *ZDCn2="ZDC/NeutronZDC2";
const char *ZDCp2="ZDC/ProtonZDC2";
UShort_t iIndex=0;
AliAlignObj::ELayerID iLayer = AliAlignObj::kInvalidLayer;
UShort_t volid = AliAlignObj::LayerToVolUID(iLayer,iIndex);
//
new(alobj[0]) AliAlignObjAngles(ZDCn1, volid, dx, dyZN1, dz, dpsi, dtheta, dphi, kTRUE);
new(alobj[1]) AliAlignObjAngles(ZDCp1, volid, dx, dyZP1, dz, dpsi, dtheta, dphi, kTRUE);
new(alobj[2]) AliAlignObjAngles(ZDCn2, volid, dx, dyZN2, dz, dpsi, dtheta, dphi, kTRUE);
new(alobj[3]) AliAlignObjAngles(ZDCp2, volid, dx, dyZP2, dz, dpsi, dtheta, dphi, kTRUE);
// save in CDB storage
AliCDBMetaData md;
md.SetResponsible("Chiara Oppedisano");
md.SetComment("Alignment object for ZDC");
UInt_t resultAl = 0;
resultAl = Store("Align","Data", array, &md, 0, 0);
// --- Writing ZDC PTMs HV values into calibration object
AliZDCCalibData *calibdata = new AliZDCCalibData("ZDC");
for(Int_t j=0; j<22; j++)
calibdata->SetPMTHVVal(j,DCSValues[j+4]);
// *************** From DAQ ******************
// [a] PEDESTALS
TList* daqSources = GetFileSources(kDAQ, "PEDESTALS");
if(!daqSources){
Log(Form("No source for PEDESTALS run %d !", fRun));
return 0;
}
Log("\t List of sources for PEDESTALS");
daqSources->Print();
//
TIter iter(daqSources);
TObjString* source = 0;
Int_t i=0;
while((source = dynamic_cast<TObjString*> (iter.Next()))){
Log(Form("\n\t Getting file #%d\n",++i));
TString stringPedFileName = GetFile(kDAQ, "PEDESTALS", source->GetName());
if(stringPedFileName.Length() <= 0){
Log(Form("No PEDESTAL file from source %s!", source->GetName()));
return 0;
}
const char* PedFileName = stringPedFileName.Data();
const Int_t NZDCch = 44;
if(PedFileName){
FILE *file;
if((file = fopen(PedFileName,"r")) == NULL){
printf("Cannot open file %s \n",PedFileName);
return 0;
}
Log(Form("File %s connected to analyze pedestal events", PedFileName));
Float_t PedVal[(3*NZDCch)][2];
for(Int_t i=0; i<(3*NZDCch); i++){
for(Int_t j=0; j<2; j++){
fscanf(file,"%f",&PedVal[i][j]);
//if(j==1) printf("PedVal[%d] -> %f, %f \n",i,PedVal[i][0],PedVal[i][1]);
}
if(i<NZDCch){
calibdata->SetMeanPed(i,PedVal[i][0]);
calibdata->SetMeanPedWidth(i,PedVal[i][1]);
}
else if(i>=NZDCch && i<(2*NZDCch)){
calibdata->SetOOTPed(i-NZDCch,PedVal[i][0]);
calibdata->SetOOTPedWidth(i-NZDCch,PedVal[i][1]);
}
else if(i>=(2*NZDCch) && i<(3*NZDCch)){
calibdata->SetPedCorrCoeff(i-(2*NZDCch),PedVal[i][0],PedVal[i][1]);
}
}
}
else{
Log(Form("File %s not found", PedFileName));
return 0;
}
//
//calibdata->Print("");
}
delete daqSources; daqSources = 0;
// [a] EMD EVENTS
daqSources = GetFileSources(kDAQ, "EMDCALIB");
if(!daqSources){
AliError(Form("No sources for EMDCALIB run %d !", fRun));
return 0;
}
Log("\t List of sources for EMDCALIB");
daqSources->Print();
//
TIter iter2(daqSources);
source = 0;
Int_t j=0;
while((source = dynamic_cast<TObjString*> (iter2.Next()))){
Log(Form("\n\t Getting file #%d\n",++j));
TString stringEMDFileName = GetFile(kDAQ, "EMDCALIB", source->GetName());
if(stringEMDFileName.Length() <= 0){
Log(Form("No EMDCALIB file from source %s!", source->GetName()));
return 0;
}
const char* EMDFileName = stringEMDFileName.Data();
if(EMDFileName){
FILE *file;
if((file = fopen(EMDFileName,"r")) == NULL){
printf("Cannot open file %s \n",EMDFileName);
return 0;
}
Log(Form("File %s connected to analyze EM dissociation events", EMDFileName));
Float_t EMDFitVal[2];
for(Int_t j=0; j<2; j++){
fscanf(file,"%f",&EMDFitVal[j]);
}
calibdata->SetEnCalib(EMDFitVal);
}
else{
Log(Form("File %s not found", EMDFileName));
return 0;
}
//calibdata->Print("");
}
// note that the parameters are returned as character strings!
const char* nEvents = GetRunParameter("totalEvents");
if(nEvents) Log(Form("Number of events for run %d: %s",fRun, nEvents));
else Log(Form("Number of events not put in logbook!"));
// Storing the final CDB file
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Chiara");
metaData.SetComment("Filling AliZDCCalibData object");
UInt_t resultCal = 0;
resultCal = Store("Calib","Data",calibdata, &metaData, 0, 0);
UInt_t result = 0;
if(resultAl!=0 && resultCal!=0){
if(resultAl==1 && resultCal==1) result = 1;
else result = 2;
}
return result;
}
<commit_msg>Setting validityInfinite parameter of Store function to 1<commit_after>// --- ROOT system
#include <TFile.h>
#include <TClonesArray.h>
#include <TList.h>
#include <TObjString.h>
#include <TTimeStamp.h>
#include "AliZDCPreprocessor.h"
#include "AliCDBManager.h"
#include "AliCDBEntry.h"
#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliAlignObj.h"
#include "AliAlignObjAngles.h"
#include "AliLog.h"
#include "AliZDCDataDCS.h"
#include "AliZDCCalibData.h"
//
// Class implementing ZDC pre-processor.
// It takes data from DCS and passes it to the class AliZDCDataDCS.
// The class is then written to the CDB.
//
ClassImp(AliZDCPreprocessor)
//______________________________________________________________________________________________
AliZDCPreprocessor::AliZDCPreprocessor(const char* detector, AliShuttleInterface* shuttle) :
AliPreprocessor(detector, shuttle),
fData(0)
{
// constructor
}
//______________________________________________________________________________________________
AliZDCPreprocessor::~AliZDCPreprocessor()
{
// destructor
}
//______________________________________________________________________________________________
void AliZDCPreprocessor::Initialize(Int_t run, UInt_t startTime,
UInt_t endTime)
{
// Creates AliZDCDataDCS object
AliPreprocessor::Initialize(run, startTime, endTime);
Log(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run,
TTimeStamp(startTime).AsString(),
TTimeStamp(endTime).AsString()));
fRun = run;
fStartTime = startTime;
fEndTime = endTime;
fData = new AliZDCDataDCS(fRun, fStartTime, fEndTime);
}
//______________________________________________________________________________________________
UInt_t AliZDCPreprocessor::Process(TMap* dcsAliasMap)
{
// *************** From DCS ******************
// Fills data into a AliZDCDataDCS object
if(!dcsAliasMap) return 0;
// The processing of the DCS input data is forwarded to AliZDCDataDCS
Float_t DCSValues[26];
fData->ProcessData(*dcsAliasMap, DCSValues);
//dcsAliasMap->Print("");
//
// --- Writing ZDC table positions into alignment object
TClonesArray *array = new TClonesArray("AliAlignObjAngles",10);
TClonesArray &alobj = *array;
AliAlignObjAngles a;
Double_t dx=0., dz=0., dpsi=0., dtheta=0., dphi=0.;
// Vertical table position in mm from DCS
Double_t dyZN1 = (Double_t) (DCSValues[0]/10.);
Double_t dyZP1 = (Double_t) (DCSValues[1]/10.);
Double_t dyZN2 = (Double_t) (DCSValues[2]/10.);
Double_t dyZP2 = (Double_t) (DCSValues[3]/10.);
const char *ZDCn1="ZDC/NeutronZDC1";
const char *ZDCp1="ZDC/ProtonZDC1";
const char *ZDCn2="ZDC/NeutronZDC2";
const char *ZDCp2="ZDC/ProtonZDC2";
UShort_t iIndex=0;
AliAlignObj::ELayerID iLayer = AliAlignObj::kInvalidLayer;
UShort_t volid = AliAlignObj::LayerToVolUID(iLayer,iIndex);
//
new(alobj[0]) AliAlignObjAngles(ZDCn1, volid, dx, dyZN1, dz, dpsi, dtheta, dphi, kTRUE);
new(alobj[1]) AliAlignObjAngles(ZDCp1, volid, dx, dyZP1, dz, dpsi, dtheta, dphi, kTRUE);
new(alobj[2]) AliAlignObjAngles(ZDCn2, volid, dx, dyZN2, dz, dpsi, dtheta, dphi, kTRUE);
new(alobj[3]) AliAlignObjAngles(ZDCp2, volid, dx, dyZP2, dz, dpsi, dtheta, dphi, kTRUE);
// save in CDB storage
AliCDBMetaData md;
md.SetResponsible("Chiara Oppedisano");
md.SetComment("Alignment object for ZDC");
UInt_t resultAl = 0;
resultAl = Store("Align","Data", array, &md, 0, 0);
// --- Writing ZDC PTMs HV values into calibration object
AliZDCCalibData *calibdata = new AliZDCCalibData("ZDC");
for(Int_t j=0; j<22; j++)
calibdata->SetPMTHVVal(j,DCSValues[j+4]);
// *************** From DAQ ******************
// [a] PEDESTALS
TList* daqSources = GetFileSources(kDAQ, "PEDESTALS");
if(!daqSources){
Log(Form("No source for PEDESTALS run %d !", fRun));
return 0;
}
Log("\t List of sources for PEDESTALS");
daqSources->Print();
//
TIter iter(daqSources);
TObjString* source = 0;
Int_t i=0;
while((source = dynamic_cast<TObjString*> (iter.Next()))){
Log(Form("\n\t Getting file #%d\n",++i));
TString stringPedFileName = GetFile(kDAQ, "PEDESTALS", source->GetName());
if(stringPedFileName.Length() <= 0){
Log(Form("No PEDESTAL file from source %s!", source->GetName()));
return 0;
}
const char* PedFileName = stringPedFileName.Data();
const Int_t NZDCch = 44;
if(PedFileName){
FILE *file;
if((file = fopen(PedFileName,"r")) == NULL){
printf("Cannot open file %s \n",PedFileName);
return 0;
}
Log(Form("File %s connected to analyze pedestal events", PedFileName));
Float_t PedVal[(3*NZDCch)][2];
for(Int_t i=0; i<(3*NZDCch); i++){
for(Int_t j=0; j<2; j++){
fscanf(file,"%f",&PedVal[i][j]);
//if(j==1) printf("PedVal[%d] -> %f, %f \n",i,PedVal[i][0],PedVal[i][1]);
}
if(i<NZDCch){
calibdata->SetMeanPed(i,PedVal[i][0]);
calibdata->SetMeanPedWidth(i,PedVal[i][1]);
}
else if(i>=NZDCch && i<(2*NZDCch)){
calibdata->SetOOTPed(i-NZDCch,PedVal[i][0]);
calibdata->SetOOTPedWidth(i-NZDCch,PedVal[i][1]);
}
else if(i>=(2*NZDCch) && i<(3*NZDCch)){
calibdata->SetPedCorrCoeff(i-(2*NZDCch),PedVal[i][0],PedVal[i][1]);
}
}
}
else{
Log(Form("File %s not found", PedFileName));
return 0;
}
//
//calibdata->Print("");
}
delete daqSources; daqSources = 0;
// [a] EMD EVENTS
daqSources = GetFileSources(kDAQ, "EMDCALIB");
if(!daqSources){
AliError(Form("No sources for EMDCALIB run %d !", fRun));
return 0;
}
Log("\t List of sources for EMDCALIB");
daqSources->Print();
//
TIter iter2(daqSources);
source = 0;
Int_t j=0;
while((source = dynamic_cast<TObjString*> (iter2.Next()))){
Log(Form("\n\t Getting file #%d\n",++j));
TString stringEMDFileName = GetFile(kDAQ, "EMDCALIB", source->GetName());
if(stringEMDFileName.Length() <= 0){
Log(Form("No EMDCALIB file from source %s!", source->GetName()));
return 0;
}
const char* EMDFileName = stringEMDFileName.Data();
if(EMDFileName){
FILE *file;
if((file = fopen(EMDFileName,"r")) == NULL){
printf("Cannot open file %s \n",EMDFileName);
return 0;
}
Log(Form("File %s connected to analyze EM dissociation events", EMDFileName));
Float_t EMDFitVal[2];
for(Int_t j=0; j<2; j++){
fscanf(file,"%f",&EMDFitVal[j]);
}
calibdata->SetEnCalib(EMDFitVal);
}
else{
Log(Form("File %s not found", EMDFileName));
return 0;
}
//calibdata->Print("");
}
// note that the parameters are returned as character strings!
const char* nEvents = GetRunParameter("totalEvents");
if(nEvents) Log(Form("Number of events for run %d: %s",fRun, nEvents));
else Log(Form("Number of events not put in logbook!"));
// Storing the final CDB file
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Chiara");
metaData.SetComment("Filling AliZDCCalibData object");
UInt_t resultCal = 0;
resultCal = Store("Calib","Data",calibdata, &metaData, 0, 1);
UInt_t result = 0;
if(resultAl!=0 && resultCal!=0){
if(resultAl==1 && resultCal==1) result = 1;
else result = 2;
}
return result;
}
<|endoftext|> |
<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include <ventura/open.hpp>
#include <ventura/file_operations.hpp>
#include <ventura/read_file.hpp>
#include <silicium/sink/file_sink.hpp>
#include <silicium/sink/throwing_sink.hpp>
#include <silicium/html/tree.hpp>
#include "tags.hpp"
namespace
{
template <std::size_t N>
auto anchor_attributes(char const(&name)[N])
{
return Si::html::attribute("name", name) +
Si::html::attribute("href", std::string("#") + name);
}
template <std::size_t N>
auto link(std::string const &protocol,
char const(&address_without_protocol)[N])
{
using namespace Si::html;
return tag("a", attribute("href", protocol + address_without_protocol),
text(address_without_protocol));
}
enum class token_type
{
identifier,
string,
eof,
other
};
struct token
{
std::string content;
token_type type;
};
template <class InputIterator>
token find_next_token(InputIterator begin, InputIterator end)
{
if (begin == end)
{
return {"", token_type::eof};
}
if (isalnum(*begin))
{
return {std::string(begin, std::find_if(begin + 1, end,
[](char c)
{
return !isalnum(c);
})),
token_type::identifier};
}
if (*begin == '"' || *begin == '\'')
{
char first = *begin;
bool escaped = false;
InputIterator endIndex =
std::find_if(begin + 1, end, [&escaped, first](char c)
{
if (c == '\\')
{
escaped = true;
}
if (!escaped)
{
return c == first;
}
else
{
escaped = false;
}
return true;
});
if (endIndex == end)
{
throw std::invalid_argument("Number of quotes must be even");
}
return {std::string(begin, endIndex + 1), token_type::string};
}
return {std::string(begin, std::find_if(begin + 1, end,
[](char c)
{
return isalnum(c) ||
c == '"' ||
c == '\'';
})),
token_type::other};
}
template <class StringLike>
auto make_code_snippet(StringLike const &code)
{
using namespace Si::html;
std::size_t const lines =
std::count(std::begin(code), std::end(code), '\n') + 1;
std::string line_numbers;
for (std::size_t i = 1; i <= lines; ++i)
{
line_numbers += boost::lexical_cast<std::string>(i);
line_numbers += '\n';
}
auto codeTag = tag(
"code",
dynamic([code](code_sink &sink)
{
static const std::string keywords[] = {
"alignas", "alignof",
"and", "and_eq",
"asm", "auto",
"bitand", "bitor",
"bool", "break",
"case", "catch",
"char", "char16_t",
"char32_t", "class",
"compl", "const",
"constexpr", "const_cast",
"continue", "decltype",
"default", "delete",
"do", "double",
"dynamic_cast", "else",
"enum", "explicit",
"export", "extern",
"false", "float",
"for", "friend",
"goto", "if",
"inline", "int",
"long", "mutable",
"namespace", "new",
"noexcept", "not",
"not_eq", "nullptr",
"operator", "or",
"or_eq", "private",
"protected", "public",
"register", "reinterpret_cast",
"return", "short",
"signed", "sizeof",
"static", "static_assert",
"static_cast", "struct",
"switch", "template",
"this", "thread_local",
"throw", "true",
"try", "typedef",
"typeid", "typename",
"union", "unsigned",
"using", "virtual",
"void", "volatile",
"wchar_t", "while",
"xor", "xor_eq",
"override", "final"};
auto i = code.begin();
for (;;)
{
token t = find_next_token(i, code.end());
switch (t.type)
{
case token_type::eof:
return;
case token_type::other:
text(t.content).generate(sink);
break;
case token_type::string:
span(attribute("class", "stringLiteral"),
text(t.content))
.generate(sink);
break;
case token_type::identifier:
if (std::find(std::begin(keywords),
std::end(keywords),
t.content) != std::end(keywords))
{
span(attribute("class", "keyword"),
text(t.content))
.generate(sink);
}
else
{
text(t.content).generate(sink);
}
}
i += t.content.size();
}
}));
return div(cl("sourcecodeSnippet"),
pre(cl("lineNumbers"), text(std::move(line_numbers))) +
pre(cl("code"), codeTag) + br());
}
auto snippet_from_file(ventura::absolute_path const &snippets_source_code,
char const *name)
{
ventura::absolute_path const full_name =
snippets_source_code / ventura::relative_path(name);
Si::variant<std::vector<char>, boost::system::error_code,
ventura::read_file_problem> read_result =
ventura::read_file(ventura::safe_c_str(to_os_string(full_name)));
std::vector<char> content;
Si::visit<void>(
read_result,
[&content](std::vector<char> &read_content)
{
content = std::move(read_content);
},
[&full_name](boost::system::error_code const error)
{
boost::throw_exception(std::runtime_error(
"Could not read file " + to_utf8_string(full_name) + ": " +
boost::lexical_cast<std::string>(error)));
},
[&full_name](ventura::read_file_problem const problem)
{
switch (problem)
{
case ventura::read_file_problem::file_too_large_for_memory:
boost::throw_exception(
std::runtime_error("File " + to_utf8_string(full_name) +
" cannot be read into memory"));
case ventura::read_file_problem::concurrent_write_detected:
boost::throw_exception(std::runtime_error(
"File " + to_utf8_string(full_name) +
" cannot be read because it seems to be accessed "
"concurrently"));
}
});
std::string clean;
for (char c : content)
{
switch (c)
{
case '\t':
clean += " ";
break;
case '\r':
break;
default:
clean += c;
break;
}
}
return make_code_snippet(clean);
}
boost::system::error_code
generate_all_html(ventura::absolute_path const &snippets_source_code,
ventura::absolute_path const &existing_output_root,
std::string const fileName)
{
ventura::absolute_path const index_path =
existing_output_root / ventura::relative_path(fileName);
Si::error_or<Si::file_handle> const index = ventura::overwrite_file(
ventura::safe_c_str(to_os_string(index_path)));
if (index.is_error())
{
std::cerr << "Could not overwrite file " << index_path << '\n';
return index.error();
}
Si::file_sink index_sink(index.get().handle);
using namespace Si::html;
std::string siteTitle = "TyRoXx' blog (" + fileName + ")";
auto articles =
h2("Articles") + p("Sorry, there are no finished articles yet.");
auto drafts = h2("Drafts") +
#include "pages/input-validation.hpp"
+
#include "pages/throwing-constructor.hpp"
;
auto menu = dynamic(
[&fileName](code_sink &sink)
{
if (fileName == "contact.html")
{
tag("menu",
ul(li(link("https://", "github.com/TyRoXx")) +
li(link("https://", "twitter.com/tyroxxxx")) +
li(link("mailto:", "[email protected]")) +
li(tag("a", attribute("href", "index.html"),
text("Back")))))
.generate(sink);
}
else
{
tag("menu",
ul(li(tag("a", attribute("href", "contact.html"),
text("Contacts")))))
.generate(sink);
}
});
auto todo =
h2("Technical to do list") +
ul(li("compile the code snippets") + li("color the code snippets") +
li("clang-format the code snippets"));
auto style = "body {\n"
" font-size: 16px;\n"
" width: 90%;\n"
" margin: auto;\n"
"}\n"
"a{ color: white; }"
"a:visted{ color: white; }"
"menu{\n"
" left: 0; top: 0;"
" padding: 0;"
" width: 100%;"
" background-color: black;"
"}\n"
"menu ul{\n"
" padding: 0; margin: 0;"
" padding: 20px 0;"
" list-style: none;"
"}\n"
"menu li{\n"
" display: inline-block;"
" width: 25%;"
" text-align: center;"
"}\n"
"menu li p{"
" line-height: 1;"
"}"
"p {\n"
" line-height: 1.6;\n"
"}\n"
".sourcecodeSnippet{\n"
" overflow: auto;"
" white-space: nowrap;"
"}\n"
".sourcecodeSnippet .lineNumbers{\n"
" display:inline-block;\n"
" text-align: right;"
" padding: 0 .5em;"
" border-right: 1px solid black;"
"}\n"
".sourcecodeSnippet .code{\n"
" display: inline-block;\n"
" margin-left: 1em;"
"}\n"
"code .keyword{\n"
" color: blue;\n"
" font-weight: bold;\n"
"}\n"
"code .stringLiteral{\n"
" color: #46A346;\n"
"}\n";
auto headContent =
head(tag("meta", attribute("charset", "utf-8"), empty) +
title(siteTitle) + tag("style", text(style)));
auto bodyContent =
body(std::move(menu) + h1(siteTitle) + std::move(articles) +
std::move(drafts) + std::move(todo));
auto const document =
raw("<!DOCTYPE html>") +
html(std::move(headContent) + std::move(bodyContent));
auto erased_sink = Si::Sink<char, Si::success>::erase(
Si::make_throwing_sink(index_sink));
try
{
document.generate(erased_sink);
return {};
}
catch (boost::system::system_error const &ex)
{
// TODO: do this without an exception
return ex.code();
}
}
}
int main(int argc, char **argv)
{
std::string output_option;
boost::program_options::options_description desc("Allowed options");
desc.add_options()("help", "produce help message")(
"output", boost::program_options::value(&output_option),
"a directory to put the HTML files into");
boost::program_options::positional_options_description positional;
positional.add("output", 1);
boost::program_options::variables_map vm;
try
{
boost::program_options::store(
boost::program_options::command_line_parser(argc, argv)
.options(desc)
.positional(positional)
.run(),
vm);
}
catch (boost::program_options::error const &ex)
{
std::cerr << ex.what() << '\n' << desc << "\n";
return 1;
}
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cerr << desc << "\n";
return 1;
}
Si::optional<ventura::absolute_path> const output_root =
ventura::absolute_path::create(output_option);
if (!output_root)
{
std::cerr
<< "The output directory must be given as an absolute path.\n";
std::cerr << desc << "\n";
return 1;
}
{
boost::system::error_code const ec =
ventura::create_directories(*output_root, Si::return_);
if (!!ec)
{
std::cerr << ec << '\n';
return 1;
}
}
{
boost::system::error_code const ec =
generate_all_html(*ventura::parent(*ventura::parent(
*ventura::absolute_path::create(__FILE__))) /
ventura::relative_path("snippets"),
*output_root, "index.html");
boost::system::error_code const ec2 =
generate_all_html(*ventura::parent(*ventura::parent(
*ventura::absolute_path::create(__FILE__))) /
ventura::relative_path("snippets"),
*output_root, "contact.html");
if (!!ec && !!ec2)
{
std::cerr << ec << '\n';
return 1;
}
}
}
<commit_msg>normal links are visible again<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include <ventura/open.hpp>
#include <ventura/file_operations.hpp>
#include <ventura/read_file.hpp>
#include <silicium/sink/file_sink.hpp>
#include <silicium/sink/throwing_sink.hpp>
#include <silicium/html/tree.hpp>
#include "tags.hpp"
namespace
{
template <std::size_t N>
auto anchor_attributes(char const(&name)[N])
{
return Si::html::attribute("name", name) +
Si::html::attribute("href", std::string("#") + name);
}
template <std::size_t N>
auto link(std::string const &protocol,
char const(&address_without_protocol)[N])
{
using namespace Si::html;
return tag("a", attribute("href", protocol + address_without_protocol),
text(address_without_protocol));
}
enum class token_type
{
identifier,
string,
eof,
other
};
struct token
{
std::string content;
token_type type;
};
template <class InputIterator>
token find_next_token(InputIterator begin, InputIterator end)
{
if (begin == end)
{
return {"", token_type::eof};
}
if (isalnum(*begin))
{
return {std::string(begin, std::find_if(begin + 1, end,
[](char c)
{
return !isalnum(c);
})),
token_type::identifier};
}
if (*begin == '"' || *begin == '\'')
{
char first = *begin;
bool escaped = false;
InputIterator endIndex =
std::find_if(begin + 1, end, [&escaped, first](char c)
{
if (c == '\\')
{
escaped = true;
}
if (!escaped)
{
return c == first;
}
else
{
escaped = false;
}
return true;
});
if (endIndex == end)
{
throw std::invalid_argument("Number of quotes must be even");
}
return {std::string(begin, endIndex + 1), token_type::string};
}
return {std::string(begin, std::find_if(begin + 1, end,
[](char c)
{
return isalnum(c) ||
c == '"' ||
c == '\'';
})),
token_type::other};
}
template <class StringLike>
auto make_code_snippet(StringLike const &code)
{
using namespace Si::html;
std::size_t const lines =
std::count(std::begin(code), std::end(code), '\n') + 1;
std::string line_numbers;
for (std::size_t i = 1; i <= lines; ++i)
{
line_numbers += boost::lexical_cast<std::string>(i);
line_numbers += '\n';
}
auto codeTag = tag(
"code",
dynamic([code](code_sink &sink)
{
static const std::string keywords[] = {
"alignas", "alignof",
"and", "and_eq",
"asm", "auto",
"bitand", "bitor",
"bool", "break",
"case", "catch",
"char", "char16_t",
"char32_t", "class",
"compl", "const",
"constexpr", "const_cast",
"continue", "decltype",
"default", "delete",
"do", "double",
"dynamic_cast", "else",
"enum", "explicit",
"export", "extern",
"false", "float",
"for", "friend",
"goto", "if",
"inline", "int",
"long", "mutable",
"namespace", "new",
"noexcept", "not",
"not_eq", "nullptr",
"operator", "or",
"or_eq", "private",
"protected", "public",
"register", "reinterpret_cast",
"return", "short",
"signed", "sizeof",
"static", "static_assert",
"static_cast", "struct",
"switch", "template",
"this", "thread_local",
"throw", "true",
"try", "typedef",
"typeid", "typename",
"union", "unsigned",
"using", "virtual",
"void", "volatile",
"wchar_t", "while",
"xor", "xor_eq",
"override", "final"};
auto i = code.begin();
for (;;)
{
token t = find_next_token(i, code.end());
switch (t.type)
{
case token_type::eof:
return;
case token_type::other:
text(t.content).generate(sink);
break;
case token_type::string:
span(attribute("class", "stringLiteral"),
text(t.content))
.generate(sink);
break;
case token_type::identifier:
if (std::find(std::begin(keywords),
std::end(keywords),
t.content) != std::end(keywords))
{
span(attribute("class", "keyword"),
text(t.content))
.generate(sink);
}
else
{
text(t.content).generate(sink);
}
}
i += t.content.size();
}
}));
return div(cl("sourcecodeSnippet"),
pre(cl("lineNumbers"), text(std::move(line_numbers))) +
pre(cl("code"), codeTag) + br());
}
auto snippet_from_file(ventura::absolute_path const &snippets_source_code,
char const *name)
{
ventura::absolute_path const full_name =
snippets_source_code / ventura::relative_path(name);
Si::variant<std::vector<char>, boost::system::error_code,
ventura::read_file_problem> read_result =
ventura::read_file(ventura::safe_c_str(to_os_string(full_name)));
std::vector<char> content;
Si::visit<void>(
read_result,
[&content](std::vector<char> &read_content)
{
content = std::move(read_content);
},
[&full_name](boost::system::error_code const error)
{
boost::throw_exception(std::runtime_error(
"Could not read file " + to_utf8_string(full_name) + ": " +
boost::lexical_cast<std::string>(error)));
},
[&full_name](ventura::read_file_problem const problem)
{
switch (problem)
{
case ventura::read_file_problem::file_too_large_for_memory:
boost::throw_exception(
std::runtime_error("File " + to_utf8_string(full_name) +
" cannot be read into memory"));
case ventura::read_file_problem::concurrent_write_detected:
boost::throw_exception(std::runtime_error(
"File " + to_utf8_string(full_name) +
" cannot be read because it seems to be accessed "
"concurrently"));
}
});
std::string clean;
for (char c : content)
{
switch (c)
{
case '\t':
clean += " ";
break;
case '\r':
break;
default:
clean += c;
break;
}
}
return make_code_snippet(clean);
}
boost::system::error_code
generate_all_html(ventura::absolute_path const &snippets_source_code,
ventura::absolute_path const &existing_output_root,
std::string const fileName)
{
ventura::absolute_path const index_path =
existing_output_root / ventura::relative_path(fileName);
Si::error_or<Si::file_handle> const index = ventura::overwrite_file(
ventura::safe_c_str(to_os_string(index_path)));
if (index.is_error())
{
std::cerr << "Could not overwrite file " << index_path << '\n';
return index.error();
}
Si::file_sink index_sink(index.get().handle);
using namespace Si::html;
std::string siteTitle = "TyRoXx' blog (" + fileName + ")";
auto articles =
h2("Articles") + p("Sorry, there are no finished articles yet.");
auto drafts = h2("Drafts") +
#include "pages/input-validation.hpp"
+
#include "pages/throwing-constructor.hpp"
;
auto menu = dynamic(
[&fileName](code_sink &sink)
{
if (fileName == "contact.html")
{
tag("menu",
ul(li(link("https://", "github.com/TyRoXx")) +
li(link("https://", "twitter.com/tyroxxxx")) +
li(link("mailto:", "[email protected]")) +
li(tag("a", attribute("href", "index.html"),
text("Back")))))
.generate(sink);
}
else
{
tag("menu",
ul(li(tag("a", attribute("href", "contact.html"),
text("Contacts")))))
.generate(sink);
}
});
auto todo =
h2("Technical to do list") +
ul(li("compile the code snippets") + li("color the code snippets") +
li("clang-format the code snippets"));
auto style = "body {\n"
" font-size: 16px;\n"
" width: 90%;\n"
" margin: auto;\n"
"}\n"
"menu a{ color: white; }"
"menu a:visted{ color: white; }"
"menu{\n"
" left: 0; top: 0;"
" padding: 0;"
" width: 100%;"
" background-color: black;"
"}\n"
"menu ul{\n"
" padding: 0; margin: 0;"
" padding: 20px 0;"
" list-style: none;"
"}\n"
"menu li{\n"
" display: inline-block;"
" width: 25%;"
" text-align: center;"
"}\n"
"menu li p{"
" line-height: 1;"
"}"
"p {\n"
" line-height: 1.6;\n"
"}\n"
".sourcecodeSnippet{\n"
" overflow: auto;"
" white-space: nowrap;"
"}\n"
".sourcecodeSnippet .lineNumbers{\n"
" display:inline-block;\n"
" text-align: right;"
" padding: 0 .5em;"
" border-right: 1px solid black;"
"}\n"
".sourcecodeSnippet .code{\n"
" display: inline-block;\n"
" margin-left: 1em;"
"}\n"
"code .keyword{\n"
" color: blue;\n"
" font-weight: bold;\n"
"}\n"
"code .stringLiteral{\n"
" color: #46A346;\n"
"}\n";
auto headContent =
head(tag("meta", attribute("charset", "utf-8"), empty) +
title(siteTitle) + tag("style", text(style)));
auto bodyContent =
body(std::move(menu) + h1(siteTitle) + std::move(articles) +
std::move(drafts) + std::move(todo));
auto const document =
raw("<!DOCTYPE html>") +
html(std::move(headContent) + std::move(bodyContent));
auto erased_sink = Si::Sink<char, Si::success>::erase(
Si::make_throwing_sink(index_sink));
try
{
document.generate(erased_sink);
return {};
}
catch (boost::system::system_error const &ex)
{
// TODO: do this without an exception
return ex.code();
}
}
}
int main(int argc, char **argv)
{
std::string output_option;
boost::program_options::options_description desc("Allowed options");
desc.add_options()("help", "produce help message")(
"output", boost::program_options::value(&output_option),
"a directory to put the HTML files into");
boost::program_options::positional_options_description positional;
positional.add("output", 1);
boost::program_options::variables_map vm;
try
{
boost::program_options::store(
boost::program_options::command_line_parser(argc, argv)
.options(desc)
.positional(positional)
.run(),
vm);
}
catch (boost::program_options::error const &ex)
{
std::cerr << ex.what() << '\n' << desc << "\n";
return 1;
}
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cerr << desc << "\n";
return 1;
}
Si::optional<ventura::absolute_path> const output_root =
ventura::absolute_path::create(output_option);
if (!output_root)
{
std::cerr
<< "The output directory must be given as an absolute path.\n";
std::cerr << desc << "\n";
return 1;
}
{
boost::system::error_code const ec =
ventura::create_directories(*output_root, Si::return_);
if (!!ec)
{
std::cerr << ec << '\n';
return 1;
}
}
{
boost::system::error_code const ec =
generate_all_html(*ventura::parent(*ventura::parent(
*ventura::absolute_path::create(__FILE__))) /
ventura::relative_path("snippets"),
*output_root, "index.html");
boost::system::error_code const ec2 =
generate_all_html(*ventura::parent(*ventura::parent(
*ventura::absolute_path::create(__FILE__))) /
ventura::relative_path("snippets"),
*output_root, "contact.html");
if (!!ec && !!ec2)
{
std::cerr << ec << '\n';
return 1;
}
}
}
<|endoftext|> |
<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include "config.h"
#include "fsstorage.h"
#include "logger.h"
namespace po = boost::program_options;
int main(int argc, char **argv) {
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("config,c", po::value<std::string>()->required(), "toml configuration file")
("images-root", "Outputs root.json from images repo")
("images-target", "Outputs targets.json from images repo")
("director-root", "Outputs root.json from director repo")
("director-target", "Outputs targets.json from director repo");
// clang-format on
try {
loggerSetSeverity(LVL_error);
po::variables_map vm;
po::basic_parsed_options<char> parsed_options = po::command_line_parser(argc, argv).options(desc).run();
po::store(parsed_options, vm);
po::notify(vm);
std::string sota_config_file = vm["config"].as<std::string>();
boost::filesystem::path sota_config_path(sota_config_file);
if (false == boost::filesystem::exists(sota_config_path)) {
std::cout << "configuration file " << boost::filesystem::absolute(sota_config_path) << " not found. Exiting."
<< std::endl;
exit(EXIT_FAILURE);
}
Config config(sota_config_path.string());
FSStorage storage(config);
Uptane::MetaPack pack;
if (!storage.loadMetadata(&pack)) {
std::cout << "could not load metadata" << std::endl;
return EXIT_FAILURE;
}
if (vm.count("images-root")) {
std::cout << "image root.json content:" << std::endl;
std::cout << pack.image_root.toJson();
}
if (vm.count("images-target")) {
std::cout << "image targets.json content:" << std::endl;
std::cout << pack.image_targets.toJson();
}
if (vm.count("director-root")) {
std::cout << "director root.json content:" << std::endl;
std::cout << pack.director_root.toJson();
}
if (vm.count("director-target")) {
std::cout << "director targets.json content:" << std::endl;
std::cout << pack.director_targets.toJson();
}
if (vm.size() == 1) {
std::string device_id;
storage.loadDeviceId(&device_id);
std::vector<std::pair<std::string, std::string> > serials;
storage.loadEcuSerials(&serials);
std::cout << "Device ID: " << device_id << std::endl;
std::cout << "Primary ecu serial ID: " << serials[0].first << std::endl;
}
} catch (const po::error &o) {
std::cout << o.what();
std::cout << desc;
return EXIT_FAILURE;
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<commit_msg>Add newline to usage information<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include "config.h"
#include "fsstorage.h"
#include "logger.h"
namespace po = boost::program_options;
int main(int argc, char **argv) {
po::options_description desc("Allowed options");
// clang-format off
desc.add_options()
("config,c", po::value<std::string>()->required(), "toml configuration file")
("images-root", "Outputs root.json from images repo")
("images-target", "Outputs targets.json from images repo")
("director-root", "Outputs root.json from director repo")
("director-target", "Outputs targets.json from director repo");
// clang-format on
try {
loggerSetSeverity(LVL_error);
po::variables_map vm;
po::basic_parsed_options<char> parsed_options = po::command_line_parser(argc, argv).options(desc).run();
po::store(parsed_options, vm);
po::notify(vm);
std::string sota_config_file = vm["config"].as<std::string>();
boost::filesystem::path sota_config_path(sota_config_file);
if (false == boost::filesystem::exists(sota_config_path)) {
std::cout << "configuration file " << boost::filesystem::absolute(sota_config_path) << " not found. Exiting."
<< std::endl;
exit(EXIT_FAILURE);
}
Config config(sota_config_path.string());
FSStorage storage(config);
Uptane::MetaPack pack;
if (!storage.loadMetadata(&pack)) {
std::cout << "could not load metadata" << std::endl;
return EXIT_FAILURE;
}
if (vm.count("images-root")) {
std::cout << "image root.json content:" << std::endl;
std::cout << pack.image_root.toJson();
}
if (vm.count("images-target")) {
std::cout << "image targets.json content:" << std::endl;
std::cout << pack.image_targets.toJson();
}
if (vm.count("director-root")) {
std::cout << "director root.json content:" << std::endl;
std::cout << pack.director_root.toJson();
}
if (vm.count("director-target")) {
std::cout << "director targets.json content:" << std::endl;
std::cout << pack.director_targets.toJson();
}
if (vm.size() == 1) {
std::string device_id;
storage.loadDeviceId(&device_id);
std::vector<std::pair<std::string, std::string> > serials;
storage.loadEcuSerials(&serials);
std::cout << "Device ID: " << device_id << std::endl;
std::cout << "Primary ecu serial ID: " << serials[0].first << std::endl;
}
} catch (const po::error &o) {
std::cout << o.what() << std::endl;
std::cout << desc;
return EXIT_FAILURE;
}
}
// vim: set tabstop=2 shiftwidth=2 expandtab:
<|endoftext|> |
<commit_before>//===--- AttributeList.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the AttributeList class implementation
//
//===----------------------------------------------------------------------===//
#include "clang/Parse/AttributeList.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
AttributeList::AttributeList(IdentifierInfo *aName, SourceLocation aLoc,
IdentifierInfo *sName, SourceLocation sLoc,
IdentifierInfo *pName, SourceLocation pLoc,
ActionBase::ExprTy **ExprList, unsigned numArgs,
AttributeList *n, bool declspec, bool cxx0x)
: AttrName(aName), AttrLoc(aLoc), ScopeName(sName), ScopeLoc(sLoc),
ParmName(pName), ParmLoc(pLoc), NumArgs(numArgs), Next(n),
DeclspecAttribute(declspec), CXX0XAttribute(cxx0x) {
if (numArgs == 0)
Args = 0;
else {
Args = new ActionBase::ExprTy*[numArgs];
memcpy(Args, ExprList, numArgs*sizeof(Args[0]));
}
}
AttributeList::~AttributeList() {
if (Args) {
// FIXME: before we delete the vector, we need to make sure the Expr's
// have been deleted. Since ActionBase::ExprTy is "void", we are dependent
// on the actions module for actually freeing the memory. The specific
// hooks are ActOnDeclarator, ActOnTypeName, ActOnParamDeclaratorType,
// ParseField, ParseTag. Once these routines have freed the expression,
// they should zero out the Args slot (to indicate the memory has been
// freed). If any element of the vector is non-null, we should assert.
delete [] Args;
}
delete Next;
}
AttributeList::Kind AttributeList::getKind(const IdentifierInfo *Name) {
llvm::StringRef AttrName = Name->getName();
// Normalize the attribute name, __foo__ becomes foo.
if (AttrName.startswith("__") && AttrName.endswith("__"))
AttrName = AttrName.substr(2, AttrName.size() - 4);
return llvm::StringSwitch<AttributeList::Kind>(AttrName)
.Case("weak", AT_weak)
.Case("weakref", AT_weakref)
.Case("pure", AT_pure)
.Case("mode", AT_mode)
.Case("used", AT_used)
.Case("alias", AT_alias)
.Case("align", AT_aligned)
.Case("final", AT_final)
.Case("cdecl", AT_cdecl)
.Case("const", AT_const)
.Case("blocks", AT_blocks)
.Case("format", AT_format)
.Case("hiding", AT_hiding)
.Case("malloc", AT_malloc)
.Case("packed", AT_packed)
.Case("unused", AT_unused)
.Case("aligned", AT_aligned)
.Case("cleanup", AT_cleanup)
.Case("nodebug", AT_nodebug)
.Case("nonnull", AT_nonnull)
.Case("nothrow", AT_nothrow)
.Case("objc_gc", AT_objc_gc)
.Case("regparm", AT_regparm)
.Case("section", AT_section)
.Case("stdcall", AT_stdcall)
.Case("annotate", AT_annotate)
.Case("fastcall", AT_fastcall)
.Case("ibaction", AT_IBAction)
.Case("iboutlet", AT_IBOutlet)
.Case("noreturn", AT_noreturn)
.Case("noinline", AT_noinline)
.Case("override", AT_override)
.Case("sentinel", AT_sentinel)
.Case("NSObject", AT_nsobject)
.Case("dllimport", AT_dllimport)
.Case("dllexport", AT_dllexport)
.Case("may_alias", IgnoredAttribute) // FIXME: TBAA
.Case("base_check", AT_base_check)
.Case("deprecated", AT_deprecated)
.Case("visibility", AT_visibility)
.Case("destructor", AT_destructor)
.Case("format_arg", AT_format_arg)
.Case("gnu_inline", AT_gnu_inline)
.Case("weak_import", AT_weak_import)
.Case("vector_size", AT_vector_size)
.Case("constructor", AT_constructor)
.Case("unavailable", AT_unavailable)
.Case("overloadable", AT_overloadable)
.Case("address_space", AT_address_space)
.Case("always_inline", AT_always_inline)
.Case("vec_type_hint", IgnoredAttribute)
.Case("objc_exception", AT_objc_exception)
.Case("ext_vector_type", AT_ext_vector_type)
.Case("transparent_union", AT_transparent_union)
.Case("analyzer_noreturn", AT_analyzer_noreturn)
.Case("warn_unused_result", AT_warn_unused_result)
.Case("carries_dependency", AT_carries_dependency)
.Case("ns_returns_not_retained", AT_ns_returns_not_retained)
.Case("ns_returns_retained", AT_ns_returns_retained)
.Case("cf_returns_not_retained", AT_cf_returns_not_retained)
.Case("cf_returns_retained", AT_cf_returns_retained)
.Case("reqd_work_group_size", AT_reqd_wg_size)
.Case("no_instrument_function", AT_no_instrument_function)
.Default(UnknownAttribute);
}
<commit_msg>other half of r101005<commit_after>//===--- AttributeList.cpp --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the AttributeList class implementation
//
//===----------------------------------------------------------------------===//
#include "clang/Parse/AttributeList.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
AttributeList::AttributeList(IdentifierInfo *aName, SourceLocation aLoc,
IdentifierInfo *sName, SourceLocation sLoc,
IdentifierInfo *pName, SourceLocation pLoc,
ActionBase::ExprTy **ExprList, unsigned numArgs,
AttributeList *n, bool declspec, bool cxx0x)
: AttrName(aName), AttrLoc(aLoc), ScopeName(sName), ScopeLoc(sLoc),
ParmName(pName), ParmLoc(pLoc), NumArgs(numArgs), Next(n),
DeclspecAttribute(declspec), CXX0XAttribute(cxx0x) {
if (numArgs == 0)
Args = 0;
else {
Args = new ActionBase::ExprTy*[numArgs];
memcpy(Args, ExprList, numArgs*sizeof(Args[0]));
}
}
AttributeList::~AttributeList() {
if (Args) {
// FIXME: before we delete the vector, we need to make sure the Expr's
// have been deleted. Since ActionBase::ExprTy is "void", we are dependent
// on the actions module for actually freeing the memory. The specific
// hooks are ActOnDeclarator, ActOnTypeName, ActOnParamDeclaratorType,
// ParseField, ParseTag. Once these routines have freed the expression,
// they should zero out the Args slot (to indicate the memory has been
// freed). If any element of the vector is non-null, we should assert.
delete [] Args;
}
delete Next;
}
AttributeList::Kind AttributeList::getKind(const IdentifierInfo *Name) {
llvm::StringRef AttrName = Name->getName();
// Normalize the attribute name, __foo__ becomes foo.
if (AttrName.startswith("__") && AttrName.endswith("__"))
AttrName = AttrName.substr(2, AttrName.size() - 4);
return llvm::StringSwitch<AttributeList::Kind>(AttrName)
.Case("weak", AT_weak)
.Case("weakref", AT_weakref)
.Case("pure", AT_pure)
.Case("mode", AT_mode)
.Case("used", AT_used)
.Case("alias", AT_alias)
.Case("align", AT_aligned)
.Case("final", AT_final)
.Case("cdecl", AT_cdecl)
.Case("const", AT_const)
.Case("blocks", AT_blocks)
.Case("format", AT_format)
.Case("hiding", AT_hiding)
.Case("malloc", AT_malloc)
.Case("packed", AT_packed)
.Case("unused", AT_unused)
.Case("aligned", AT_aligned)
.Case("cleanup", AT_cleanup)
.Case("nodebug", AT_nodebug)
.Case("nonnull", AT_nonnull)
.Case("nothrow", AT_nothrow)
.Case("objc_gc", AT_objc_gc)
.Case("regparm", AT_regparm)
.Case("section", AT_section)
.Case("stdcall", AT_stdcall)
.Case("annotate", AT_annotate)
.Case("fastcall", AT_fastcall)
.Case("ibaction", AT_IBAction)
.Case("iboutlet", AT_IBOutlet)
.Case("noreturn", AT_noreturn)
.Case("noinline", AT_noinline)
.Case("override", AT_override)
.Case("sentinel", AT_sentinel)
.Case("NSObject", AT_nsobject)
.Case("dllimport", AT_dllimport)
.Case("dllexport", AT_dllexport)
.Case("may_alias", IgnoredAttribute) // FIXME: TBAA
.Case("base_check", AT_base_check)
.Case("deprecated", AT_deprecated)
.Case("visibility", AT_visibility)
.Case("destructor", AT_destructor)
.Case("format_arg", AT_format_arg)
.Case("gnu_inline", AT_gnu_inline)
.Case("weak_import", AT_weak_import)
.Case("vector_size", AT_vector_size)
.Case("constructor", AT_constructor)
.Case("unavailable", AT_unavailable)
.Case("overloadable", AT_overloadable)
.Case("address_space", AT_address_space)
.Case("always_inline", AT_always_inline)
.Case("returns_twice", IgnoredAttribute)
.Case("vec_type_hint", IgnoredAttribute)
.Case("objc_exception", AT_objc_exception)
.Case("ext_vector_type", AT_ext_vector_type)
.Case("transparent_union", AT_transparent_union)
.Case("analyzer_noreturn", AT_analyzer_noreturn)
.Case("warn_unused_result", AT_warn_unused_result)
.Case("carries_dependency", AT_carries_dependency)
.Case("ns_returns_not_retained", AT_ns_returns_not_retained)
.Case("ns_returns_retained", AT_ns_returns_retained)
.Case("cf_returns_not_retained", AT_cf_returns_not_retained)
.Case("cf_returns_retained", AT_cf_returns_retained)
.Case("reqd_work_group_size", AT_reqd_wg_size)
.Case("no_instrument_function", AT_no_instrument_function)
.Default(UnknownAttribute);
}
<|endoftext|> |
<commit_before>#ifndef VG_ALGORITHMS_THREE_EDGE_CONNECTED_COMPONENTS_HPP_INCLUDED
#define VG_ALGORITHMS_THREE_EDGE_CONNECTED_COMPONENTS_HPP_INCLUDED
#include <functional>
#include <vector>
#include <unordered_map>
namespace vg {
namespace algorithms {
using namespace std;
// Interface
/**
* Get the three-edge-connected components of an arbitrary graph (not
* necessarily a handle graph). Only recognizes one kind of edge and one kind
* of node. Nodes are arbitrary value types (which may need to be hashable).
*
* Takes a function that loops an iteratee over all nodes, and a function that,
* given a node, loops an iteratee over all nodes connected to it.
*
* For each component identified, calls the given callback with a function that
* iterates over all nodes in the component.
*
* If you have a graph where you can easily rank the nodes, don't use this. Use
* three_edge_connected_components_dense() instead. The first thing this
* function does is asign nodes a dense, 0-based rank space.
*/
template<typename TECCNode>
void three_edge_connected_components(const function<void(const function<void(TECCNode)>&)>& for_each_node,
const function<void(TECCNode, const function<void(TECCNode)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(TECCNode)>&)>&)>& component_callback);
/**
* Get the three-edge-connected components of an arbitrary graph (not
* necessarily a handle graph). Only recognizes one kind of edge and one kind
* of node. Nodes are dense positive integers starting with 0.
*
* Takes a total node count, a suggested root (or 0), and a function that,
* given a node, loops an iteratee over all nodes connected to it.
*
* Calls same_component with pairs of nodes in (at least) a spanning tree of
* the set of nodes in each component (not restricted to the input graph).
* Doing merge operations on a union-find can get
* you the set of components.
*/
void three_edge_connected_component_merges_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(size_t, size_t)>& same_component);
/**
* Get the three-edge-connected components of an arbitrary graph (not
* necessarily a handle graph). Only recognizes one kind of edge and one kind
* of node. Nodes are dense positive integers starting with 0.
*
* Takes a total node count, a suggested root (or 0), and a function that,
* given a node, loops an iteratee over all nodes connected to it.
*
* For each component identified, calls the given callback with a function that
* iterates over all nodes in the component.
*/
void three_edge_connected_components_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(size_t)>&)>&)>& component_callback);
// Implementation
template<typename TECCNode>
void three_edge_connected_components(const function<void(const function<void(TECCNode)>&)>& for_each_node,
const function<void(TECCNode, const function<void(TECCNode)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(TECCNode)>&)>&)>& component_callback) {
// Convert to small positive integers
vector<TECCNode> rank_to_node;
unordered_map<TECCNode, size_t> node_to_rank;
for_each_node([&](TECCNode node) {
// Populate the rank/node translation.
// TODO: can we condense this?
node_to_rank[node] = rank_to_node.size();
rank_to_node.push_back(node);
});
three_edge_connected_components_dense(rank_to_node.size(), 0, [&](size_t rank, const function<void(size_t)> visit_connected) {
// Translate the rank we are asked about into a node
for_each_connected_node(rank_to_node[rank], [&](TECCNode connected) {
// And translate the node back into a rank
visit_connected(node_to_rank[connected]);
});
}, [&](const function<void(const function<void(size_t)>&)>& for_each_component_member) {
// When we get a component
// Call our component callback with a function that takes the iteratee
component_callback([&](const function<void(TECCNode)>& iteratee) {
for_each_component_member([&](size_t member) {
// And for each member of the component we got, translate it and send it off.
iteratee(rank_to_node[member]);
});
});
});
}
}
}
#endif
<commit_msg>Add back wrapper over pinchesAndCacti to test against<commit_after>#ifndef VG_ALGORITHMS_THREE_EDGE_CONNECTED_COMPONENTS_HPP_INCLUDED
#define VG_ALGORITHMS_THREE_EDGE_CONNECTED_COMPONENTS_HPP_INCLUDED
#include <functional>
#include <vector>
#include <unordered_map>
namespace vg {
namespace algorithms {
using namespace std;
// Interface
/**
* Get the three-edge-connected components of an arbitrary graph (not
* necessarily a handle graph). Only recognizes one kind of edge and one kind
* of node. Nodes are arbitrary value types (which may need to be hashable).
*
* Takes a function that loops an iteratee over all nodes, and a function that,
* given a node, loops an iteratee over all nodes connected to it.
*
* For each component identified, calls the given callback with a function that
* iterates over all nodes in the component.
*
* If you have a graph where you can easily rank the nodes, don't use this. Use
* three_edge_connected_components_dense() instead. The first thing this
* function does is asign nodes a dense, 0-based rank space.
*/
template<typename TECCNode>
void three_edge_connected_components(const function<void(const function<void(TECCNode)>&)>& for_each_node,
const function<void(TECCNode, const function<void(TECCNode)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(TECCNode)>&)>&)>& component_callback);
/**
* Get the three-edge-connected components of an arbitrary graph (not
* necessarily a handle graph). Only recognizes one kind of edge and one kind
* of node. Nodes are dense positive integers starting with 0.
*
* Takes a total node count, a suggested root (or 0), and a function that,
* given a node, loops an iteratee over all nodes connected to it.
*
* Calls same_component with pairs of nodes in (at least) a spanning tree of
* the set of nodes in each component (not restricted to the input graph).
* Doing merge operations on a union-find can get
* you the set of components.
*/
void three_edge_connected_component_merges_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(size_t, size_t)>& same_component);
/**
* Get the three-edge-connected components of an arbitrary graph (not
* necessarily a handle graph). Only recognizes one kind of edge and one kind
* of node. Nodes are dense positive integers starting with 0.
*
* Takes a total node count, a suggested root (or 0), and a function that,
* given a node, loops an iteratee over all nodes connected to it.
*
* For each component identified, calls the given callback with a function that
* iterates over all nodes in the component.
*/
void three_edge_connected_components_dense(size_t node_count, size_t first_root,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(size_t)>&)>&)>& component_callback);
/**
* Get the three-edge-connected components of an arbitrary graph (not
* necessarily a handle graph). Only recognizes one kind of edge and one kind
* of node. Nodes are dense positive integers starting with 0.
*
* Wraps the known good the 3 edge connected components algorithm from the
* pinchesAndCacti library.
*
* Takes a total node count, and a function that, given a node, loops an
* iteratee over all nodes connected to it.
*
* For each component identified, calls the given callback with a function that
* iterates over all nodes in the component.
*/
void three_edge_connected_components_dense_cactus(size_t node_count,
const function<void(size_t, const function<void(size_t)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(size_t)>&)>&)>& component_callback);
// Implementation
template<typename TECCNode>
void three_edge_connected_components(const function<void(const function<void(TECCNode)>&)>& for_each_node,
const function<void(TECCNode, const function<void(TECCNode)>&)>& for_each_connected_node,
const function<void(const function<void(const function<void(TECCNode)>&)>&)>& component_callback) {
// Convert to small positive integers
vector<TECCNode> rank_to_node;
unordered_map<TECCNode, size_t> node_to_rank;
for_each_node([&](TECCNode node) {
// Populate the rank/node translation.
// TODO: can we condense this?
node_to_rank[node] = rank_to_node.size();
rank_to_node.push_back(node);
});
three_edge_connected_components_dense(rank_to_node.size(), 0, [&](size_t rank, const function<void(size_t)> visit_connected) {
// Translate the rank we are asked about into a node
for_each_connected_node(rank_to_node[rank], [&](TECCNode connected) {
// And translate the node back into a rank
visit_connected(node_to_rank[connected]);
});
}, [&](const function<void(const function<void(size_t)>&)>& for_each_component_member) {
// When we get a component
// Call our component callback with a function that takes the iteratee
component_callback([&](const function<void(TECCNode)>& iteratee) {
for_each_component_member([&](size_t member) {
// And for each member of the component we got, translate it and send it off.
iteratee(rank_to_node[member]);
});
});
});
}
}
}
#endif
<|endoftext|> |
<commit_before>#include <pcl/kdtree/kdtree_flann.h>
#include "CompetitionController.h"
using namespace IGVC::Sensors;
using namespace std;
namespace IGVC
{
namespace Control
{
CompetitionController::CompetitionController(IGVC::Sensors::GPS* gps,
Event<pcl::PointCloud<pcl::PointXYZ> >* mapSource,
WaypointReader* waypointReader,
MotorDriver* driver,
string fileName)
: _hasAllData(false),
GPS_BUFFER_SIZE(5),
LOnNewGPSData(this),
LOnNewIMUData(this),
LOnNewMapFrame(this),
_viewer("Map and Path"),
_logFile()
{
_gps = gps;
if(_gps)
_gps->onNewData += &LOnNewGPSData;
else
_hasAllData = true;
_waypointReader = waypointReader;
_waypointReader->Next();
_currentHeading = 0;
_driver = driver;
(*mapSource) += &LOnNewMapFrame;
_logFile.open(fileName.c_str());
MaxW = 0.8;
DeltaT = 1.5;
}
bool CompetitionController::isRunning()
{
return true;
}
void CompetitionController::OnNewGPSData(GPSData data)
{
std::cout << "Compcon gps" << std::endl;
if(_gpsBuffer.size() >= GPS_BUFFER_SIZE)
{
_gpsBuffer.push_back(data);
GPSData last = _gpsBuffer.back();
_currentAvgGPS.Lat(_currentAvgGPS.Lat() - ( last.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() - ( last.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() - ( last.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() - ( last.Speed() / GPS_BUFFER_SIZE ));
_gpsBuffer.erase(_gpsBuffer.begin());
}
else
{
_gpsBuffer.push_back(data);
}
_currentAvgGPS.Lat(_currentAvgGPS.Lat() + ( data.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() + ( data.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() + ( data.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() + ( data.Speed() / GPS_BUFFER_SIZE ));
_hasAllData = true;
}
void CompetitionController::OnNewIMUData(IMURawData data)
{
std::cout << "Compcon imu" << std::endl;
_currentHeading = data.heading;
}
/*
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
cout << mapFrame.points.size() << " points recieved." << endl;
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spin();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
using namespace std;
cout << "Loading possible actions" << endl;
double v = 0.4;
for(double w = -MaxW; w <= MaxW; w += 0.5)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v);
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.01, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
available_actions.push_back(pair<double,double>(v, w));
}
}
cout << "Checking possible actions..." << endl;
pair<double, double> minPair;
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
}
*/
double CompetitionController::weighting(double delta)
{
if (delta !=0 )
{
//return 1/pow(delta,2);
return 1/delta;
}
else
{
std::cout << "input to weighting function was 0. This should not have happened" << std::endl;
return 0;
}
}
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
//cout << mapFrame.points.size() << " points recieved." << endl;
//Bunch of Visualization stuff
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spinOnce();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
//cout << "Loading possible actions" << endl;
//Find Potential Routes
double v = 0.4; //meters per second
double wInc = 0.05; //step size between possible omegas
int i=0; //servers as an iterator for scores so the desired index doesnt have to be rederied from w
double deltaDeltaT=0.1;
const int nPaths = floor((2*MaxW)/wInc);
std::vector<double> scores;
scores.assign(nPaths,0);
double minDeltaT = Robot::CurrentRobot().Dist2Front()/v;
for(double w = -MaxW; w <= MaxW; w += wInc)
{
for(double T = deltaDeltaT;T<=DeltaT;T+=deltaDeltaT)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v,T);
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.1, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
}
else
{
cout << "object found!" << endl;
scores[i]+=weighting(T);
}
}
i++;
}
int minArg = 0;
int secondMinArg = 0;
int min = 50000;
int currentScore;
for(int j=0;j<nPaths;j++)
{
currentScore = scores[j];
if (currentScore<min)
{
secondMinArg = minArg;
minArg = j;
min = currentScore;
}
}
cout << "minArg is" << minArg<< endl;
cout << "This means the robot wants to travel at" << -MaxW + wInc*minArg << endl;
cout << "largest distractor is " << MaxW + wInc*secondMinArg << endl;
_logFile << -MaxW + wInc*minArg << endl;
//available_actions.push_back(pair<double,double>(v, w));
pair<double, double> minPair;
minPair.first = v;
minPair.second = -MaxW+wInc*minArg;
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
if(_driver)
_driver->setVelocities(Vl, Vr);
/*
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
*/
}
double CompetitionController::headingFromAToB(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return atan2(dy, dx);
}
double CompetitionController::distBetween(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::distBetween(pair<double, double> A, pair<double, double> B)
{
double dy = B.second - A.second;
double dx = B.first - A.first;
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::GPSdX(GPSData A, GPSData B)
{
return cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
}
double CompetitionController::GPSdY(GPSData A, GPSData B)
{
return B.Lat() - A.Lat();
}
pair<double, double> CompetitionController::result(double W, double V)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*DeltaT;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * DeltaT;
}
return pair<double, double> (endLocation[0], endLocation[1]);
}
pair<double, double> CompetitionController::result(double W, double V, double dt)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*dt;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * dt;
}
return pair<double, double> (endLocation[0], endLocation[1]);
}
CompetitionController::~CompetitionController()
{
if(_gps)
_gps->onNewData -= &LOnNewGPSData;
}
}
}
<commit_msg>Things started working.<commit_after>#include <pcl/kdtree/kdtree_flann.h>
#include "CompetitionController.h"
#include <sstream>
using namespace IGVC::Sensors;
using namespace std;
namespace IGVC
{
namespace Control
{
CompetitionController::CompetitionController(IGVC::Sensors::GPS* gps,
Event<pcl::PointCloud<pcl::PointXYZ> >* mapSource,
WaypointReader* waypointReader,
MotorDriver* driver,
string fileName)
: _hasAllData(false),
GPS_BUFFER_SIZE(5),
LOnNewGPSData(this),
LOnNewIMUData(this),
LOnNewMapFrame(this),
_viewer("Map and Path"),
_logFile()
{
_gps = gps;
if(_gps)
_gps->onNewData += &LOnNewGPSData;
else
_hasAllData = true;
_waypointReader = waypointReader;
_waypointReader->Next();
_currentHeading = 0;
_driver = driver;
(*mapSource) += &LOnNewMapFrame;
_logFile.open(fileName.c_str());
MaxW = 0.8;
DeltaT = 7;
}
bool CompetitionController::isRunning()
{
return true;
}
void CompetitionController::OnNewGPSData(GPSData data)
{
std::cout << "Compcon gps" << std::endl;
if(_gpsBuffer.size() >= GPS_BUFFER_SIZE)
{
_gpsBuffer.push_back(data);
GPSData last = _gpsBuffer.back();
_currentAvgGPS.Lat(_currentAvgGPS.Lat() - ( last.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() - ( last.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() - ( last.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() - ( last.Speed() / GPS_BUFFER_SIZE ));
_gpsBuffer.erase(_gpsBuffer.begin());
}
else
{
_gpsBuffer.push_back(data);
}
_currentAvgGPS.Lat(_currentAvgGPS.Lat() + ( data.Lat() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Long(_currentAvgGPS.Long() + ( data.Long() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Heading(_currentAvgGPS.Heading() + ( data.Heading() / GPS_BUFFER_SIZE ));
_currentAvgGPS.Speed(_currentAvgGPS.Speed() + ( data.Speed() / GPS_BUFFER_SIZE ));
_hasAllData = true;
}
void CompetitionController::OnNewIMUData(IMURawData data)
{
std::cout << "Compcon imu" << std::endl;
_currentHeading = data.heading;
}
/*
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
cout << mapFrame.points.size() << " points recieved." << endl;
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spin();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
using namespace std;
cout << "Loading possible actions" << endl;
double v = 0.4;
for(double w = -MaxW; w <= MaxW; w += 0.5)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v);
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.01, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
available_actions.push_back(pair<double,double>(v, w));
}
}
cout << "Checking possible actions..." << endl;
pair<double, double> minPair;
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
}
*/
double CompetitionController::weighting(double delta)
{
if (delta !=0 )
{
//return 1/pow(delta,2);
return 1/delta;
}
else
{
std::cout << "input to weighting function was 0. This should not have happened" << std::endl;
return 0;
}
}
void CompetitionController::OnNewMapFrame(pcl::PointCloud<pcl::PointXYZ> mapFrame)
{
//cout << mapFrame.points.size() << " points recieved." << endl;
//Bunch of Visualization stuff
if(!_hasAllData)
return;
_viewer.removeAllPointClouds(0);
_viewer.removeAllShapes();
_viewer.addPointCloud(mapFrame.makeShared(), "map");
_viewer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "map");
_viewer.spinOnce();
std::cout << "Compcon newMap" << std::endl;
vector< pair<double, double> > available_actions;
//cout << "Loading possible actions" << endl;
//Find Potential Routes
double v = 0.4; //meters per second
double wInc = 0.1; //step size between possible omegas
int i=0; //servers as an iterator for scores so the desired index doesnt have to be rederied from w
double deltaDeltaT=0.5;
const int nPaths = floor((2*MaxW)/wInc);
std::vector<double> scores;
scores.assign(nPaths,0);
double minDeltaT = Robot::CurrentRobot().Dist2Front()/v;
for(double w = -MaxW; w <= MaxW; w += wInc)
{
for(double T = deltaDeltaT;T<=DeltaT;T+=deltaDeltaT)
{
pcl::KdTreeFLANN<pcl::PointXYZ> kdtree;
kdtree.setInputCloud(mapFrame.makeShared());
pair<double, double> end = result(w,v,T);
/*stringstream name;
name << "Sphere" << w << T;
_viewer.addSphere(pcl::PointXYZ(end.first, end.second, 0), 0.1, name.str(), 0);*/
pcl::PointXYZ searchPoint(end.first, end.second, 0);
std::vector<int> pointIdxRadiusSearch;
std::vector<float> pointRadiusSquaredDistance;
if(kdtree.radiusSearch(searchPoint, 0.1, pointIdxRadiusSearch, pointRadiusSquaredDistance) == 0)
{
}
else
{
cout << "object found!" << endl;
scores[i]+=weighting(T);
}
}
i++;
}
//_viewer.spin();
int minArg = 0;
int secondMinArg = 0;
int min = scores[0];
int currentScore;
for(int j=0;j<nPaths;j++)
{
currentScore = scores[j];
if (currentScore<min)
{
secondMinArg = minArg;
minArg = j;
min = currentScore;
}
}
cout << "minArg is" << minArg<< endl;
cout << "This means the robot wants to travel at" << -MaxW + wInc*minArg << endl;
cout << "largest distractor is " << -MaxW + wInc*secondMinArg << endl;
_logFile << -MaxW + wInc*minArg << endl;
//available_actions.push_back(pair<double,double>(v, w));
pair<double, double> minPair;
minPair.first = v;
minPair.second = -MaxW+wInc*minArg;
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
if(_driver)
_driver->setVelocities(Vl, Vr);
/*
double minDist = -1;
for(vector< pair<double, double> >::iterator iter = available_actions.begin(); iter != available_actions.end(); iter++)
{
pair<double, double> action = (*iter);
cout << "Action done" << endl;
pair<double, double> waypointCoords;
cout << _waypointReader->Current().Lat() << endl;
waypointCoords.first = GPSdX(_currentAvgGPS, _waypointReader->Current());
waypointCoords.second = GPSdY(_currentAvgGPS, _waypointReader->Current());
cout << "loaded" << endl;
pair<double, double> endLoc = result(action.second, action.first);
cout << "resulted" << endl;
double dist = distBetween(waypointCoords, endLoc);
cout << "dist" << endl;
if(minDist == -1 || dist < minDist)
{
minPair = action;
minDist = dist;
}
}
cout << "Computing velocities..." << endl;
double Baseline = Robot::CurrentRobot().Baseline();
double Vr = minPair.first + (Baseline/2.0)*minPair.second;
double Vl = minPair.first - (Baseline/2.0)*minPair.second;
cout << "Decided on Vl=" << Vl << " and Vr=" << Vr << endl;
_driver->setVelocities(Vl, Vr);
*/
}
double CompetitionController::headingFromAToB(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return atan2(dy, dx);
}
double CompetitionController::distBetween(GPSData A, GPSData B)
{
double dy = B.Lat() - A.Lat();
double dx = cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::distBetween(pair<double, double> A, pair<double, double> B)
{
double dy = B.second - A.second;
double dx = B.first - A.first;
return sqrt(dx*dx + dy*dy);
}
double CompetitionController::GPSdX(GPSData A, GPSData B)
{
return cos(M_PI/180.0*A.Lat())*(B.Long() - A.Long());
}
double CompetitionController::GPSdY(GPSData A, GPSData B)
{
return B.Lat() - A.Lat();
}
pair<double, double> CompetitionController::result(double W, double V)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*DeltaT;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * DeltaT;
}
return pair<double, double> (-endLocation[0], endLocation[1]);
}
pair<double, double> CompetitionController::result(double W, double V, double dt)
{
Eigen::Vector3d endLocation;
if(W != 0)
{
double R = V / W;
double ICCx = cos(- M_PI/2.0) * R;
double ICCy = sin(- M_PI/2.0) * R;
using namespace Eigen;
Matrix3d T;
double wdt = W*dt;
T << cos(wdt), -sin(wdt), 0, sin(wdt), cos(wdt), 0, 0, 0, 1;
Vector3d a(-ICCx, -ICCy, 0);
Vector3d b(ICCx, ICCy, wdt);
endLocation = T * a + b;
}
else
{
endLocation[0] = 0;
endLocation[1] = V * dt;
}
return pair<double, double> (-endLocation[0], endLocation[1]);
}
CompetitionController::~CompetitionController()
{
if(_gps)
_gps->onNewData -= &LOnNewGPSData;
}
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 Crytek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/os_specific.h"
#include "serialise/string_utils.h"
#include "common/threading.h"
#include <windows.h>
#include <tlhelp32.h>
#include <algorithm>
#include <vector>
#include <map>
using std::vector;
using std::map;
struct FunctionHook
{
FunctionHook(const char *f, void **o, void *d)
: function(f), origptr(o), hookptr(d), excludeModule(NULL)
{}
bool operator <(const FunctionHook &h)
{
return function < h.function;
}
bool ApplyHook(void **IATentry)
{
DWORD oldProtection = PAGE_EXECUTE;
if(*IATentry == hookptr)
return false;
BOOL success = TRUE;
success = VirtualProtect(IATentry, sizeof(void*), PAGE_READWRITE, &oldProtection);
if(!success)
{
RDCERR("Failed to make IAT entry writeable 0x%p", IATentry);
return false;
}
if(origptr && *origptr == NULL) *origptr = *IATentry;
*IATentry = hookptr;
success = VirtualProtect(IATentry, sizeof(void*), oldProtection, &oldProtection);
if(!success)
{
RDCERR("Failed to restore IAT entry protection 0x%p", IATentry);
return false;
}
return true;
}
string function;
void **origptr;
void *hookptr;
HMODULE excludeModule;
};
struct DllHookset
{
DllHookset() : module(NULL) {}
HMODULE module;
vector<FunctionHook> FunctionHooks;
};
struct CachedHookData
{
map<string, DllHookset> DllHooks;
HMODULE module;
Threading::CriticalSection lock;
char lowername[512];
void ApplyHooks(const char *modName, HMODULE module)
{
{
size_t i=0;
while(modName[i])
{
lowername[i] = (char)tolower(modName[i]);
i++;
}
lowername[i] = 0;
}
// fraps seems to non-safely modify the assembly around the hook function, if
// we modify its import descriptors it leads to a crash as it hooks OUR functions.
// instead, skip modifying the import descriptors, it will hook the 'real' d3d functions
// and we can call them and have fraps + renderdoc playing nicely together
if(strstr(lowername, "fraps"))
return;
// for safety (and because we don't need to), ignore these modules
if(!_stricmp(modName, "kernel32.dll") ||
!_stricmp(modName, "powrprof.dll") ||
strstr(lowername, "msvcr") == lowername ||
strstr(lowername, "msvcp") == lowername)
return;
// set module pointer if we are hooking exports from this module
for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it)
if(!_stricmp(it->first.c_str(), modName))
it->second.module = module;
byte *baseAddress = (byte *)module;
PIMAGE_DOS_HEADER dosheader = (PIMAGE_DOS_HEADER)baseAddress;
if(dosheader->e_magic != 0x5a4d)
{
RDCDEBUG("Ignoring module %s, since magic is 0x%04x not 0x%04x", modName, (uint32_t)dosheader->e_magic, 0x5a4dU);
return;
}
char *PE00 = (char *)(baseAddress + dosheader->e_lfanew);
PIMAGE_FILE_HEADER fileHeader = (PIMAGE_FILE_HEADER)(PE00+4);
PIMAGE_OPTIONAL_HEADER optHeader = (PIMAGE_OPTIONAL_HEADER)((BYTE *)fileHeader+sizeof(IMAGE_FILE_HEADER));
DWORD iatSize = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
DWORD iatOffset = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
IMAGE_IMPORT_DESCRIPTOR *importDesc = (IMAGE_IMPORT_DESCRIPTOR *)(baseAddress + iatOffset);
while(iatOffset && importDesc->FirstThunk)
{
const char *dllName = (const char *)(baseAddress + importDesc->Name);
DllHookset *hookset = NULL;
for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it)
if(!_stricmp(it->first.c_str(), dllName))
hookset = &it->second;
if(hookset && importDesc->OriginalFirstThunk > 0 && importDesc->FirstThunk > 0)
{
IMAGE_THUNK_DATA *origFirst = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->OriginalFirstThunk);
IMAGE_THUNK_DATA *first = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->FirstThunk);
while(origFirst->u1.AddressOfData)
{
#ifdef WIN64
if(origFirst->u1.AddressOfData & 0x8000000000000000)
#else
if(origFirst->u1.AddressOfData & 0x80000000)
#endif
{
// low bits of origFirst->u1.AddressOfData contain an ordinal
origFirst++;
first++;
continue;
}
IMAGE_IMPORT_BY_NAME *import = (IMAGE_IMPORT_BY_NAME *)(baseAddress + origFirst->u1.AddressOfData);
void **IATentry = (void **)&first->u1.AddressOfData;
struct hook_find
{
bool operator() (const FunctionHook &a, const char *b)
{ return strcmp(a.function.c_str(), b) < 0; }
};
const char *importName = (const char *)import->Name;
auto found = std::lower_bound(hookset->FunctionHooks.begin(), hookset->FunctionHooks.end(), importName, hook_find());
if(found != hookset->FunctionHooks.end() && !strcmp(found->function.c_str(), importName) && found->excludeModule != module)
{
SCOPED_LOCK(lock);
bool applied = found->ApplyHook(IATentry);
if(!applied)
return;
}
origFirst++;
first++;
}
}
importDesc++;
}
}
};
static CachedHookData *s_HookData = NULL;
static void HookAllModules()
{
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
// up to 10 retries
for(int i=0; i < 10; i++)
{
hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if(hModuleSnap == INVALID_HANDLE_VALUE)
{
DWORD err = GetLastError();
RDCWARN("CreateToolhelp32Snapshot() -> 0x%08x", err);
// retry if error is ERROR_BAD_LENGTH
if(err == ERROR_BAD_LENGTH)
continue;
}
// didn't retry, or succeeded
break;
}
if(hModuleSnap == INVALID_HANDLE_VALUE)
{
RDCERR("Couldn't create toolhelp dump of modules in process");
return;
}
#ifdef UNICODE
#undef MODULEENTRY32
#undef Module32First
#undef Module32Next
#endif
MODULEENTRY32 me32;
RDCEraseEl(me32);
me32.dwSize = sizeof(MODULEENTRY32);
BOOL success = Module32First(hModuleSnap, &me32);
if(success == FALSE)
{
DWORD err = GetLastError();
RDCERR("Couldn't get first module in process: 0x%08x", err);
CloseHandle(hModuleSnap);
return;
}
uintptr_t ret = 0;
int numModules = 0;
do
{
s_HookData->ApplyHooks(me32.szModule, me32.hModule);
} while(ret == 0 && Module32Next(hModuleSnap, &me32));
CloseHandle(hModuleSnap);
}
HMODULE WINAPI Hooked_LoadLibraryExA(LPCSTR lpLibFileName, HANDLE fileHandle, DWORD flags)
{
// we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module
// was excluded from IAT patching
HMODULE mod = LoadLibraryExA(lpLibFileName, fileHandle, flags);
HookAllModules();
return mod;
}
HMODULE WINAPI Hooked_LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE fileHandle, DWORD flags)
{
// we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module
// was excluded from IAT patching
HMODULE mod = LoadLibraryExW(lpLibFileName, fileHandle, flags);
HookAllModules();
return mod;
}
HMODULE WINAPI Hooked_LoadLibraryA(LPCSTR lpLibFileName)
{
return Hooked_LoadLibraryExA(lpLibFileName, NULL, 0);
}
HMODULE WINAPI Hooked_LoadLibraryW(LPCWSTR lpLibFileName)
{
return Hooked_LoadLibraryExW(lpLibFileName, NULL, 0);
}
static bool OrdinalAsString(void *func)
{
return uint64_t(func) <= 0xffff;
}
FARPROC WINAPI Hooked_GetProcAddress(HMODULE mod, LPCSTR func)
{
if(mod == NULL || func == NULL)
return (FARPROC)NULL;
if(mod == s_HookData->module || OrdinalAsString((void *)func))
return GetProcAddress(mod, func);
for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
{
if(it->second.module == NULL)
it->second.module = GetModuleHandleA(it->first.c_str());
if(mod == it->second.module)
{
FunctionHook search(func, NULL, NULL);
auto found = std::lower_bound(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end(), search);
if(found != it->second.FunctionHooks.end() && !(search < *found))
{
if(found->origptr && *found->origptr == NULL)
*found->origptr = (void *)GetProcAddress(mod, func);
return (FARPROC)found->hookptr;
}
}
}
return GetProcAddress(mod, func);
}
void Win32_IAT_BeginHooks()
{
s_HookData = new CachedHookData;
RDCASSERT(s_HookData->DllHooks.empty());
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryA", NULL, &Hooked_LoadLibraryA));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryW", NULL, &Hooked_LoadLibraryW));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExA", NULL, &Hooked_LoadLibraryExA));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExW", NULL, &Hooked_LoadLibraryExW));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("GetProcAddress", NULL, &Hooked_GetProcAddress));
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)&s_HookData,
&s_HookData->module);
for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
for(size_t i=0; i < it->second.FunctionHooks.size(); i++)
it->second.FunctionHooks[i].excludeModule = s_HookData->module;
}
// hook all functions for currently loaded modules.
// some of these hooks (as above) will hook LoadLibrary/GetProcAddress, to protect
void Win32_IAT_EndHooks()
{
for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
std::sort(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end());
HookAllModules();
}
bool Win32_IAT_Hook(void **orig_function_ptr, const char *module_name, const char *function, void *destination_function_ptr)
{
if(!_stricmp(module_name, "kernel32.dll"))
{
if(!strcmp(function, "LoadLibraryA") ||
!strcmp(function, "LoadLibraryW") ||
!strcmp(function, "LoadLibraryExA") ||
!strcmp(function, "LoadLibraryExW") ||
!strcmp(function, "GetProcAddress"))
{
RDCERR("Cannot hook LoadLibrary* or GetProcAddress, as these are hooked internally");
return false;
}
}
s_HookData->DllHooks[strlower(string(module_name))].FunctionHooks.push_back(FunctionHook(function, orig_function_ptr, destination_function_ptr));
return true;
}
<commit_msg>Exclude steam's overlay dll. Credit to roalercon. Closes #114<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 Crytek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/os_specific.h"
#include "serialise/string_utils.h"
#include "common/threading.h"
#include <windows.h>
#include <tlhelp32.h>
#include <algorithm>
#include <vector>
#include <map>
using std::vector;
using std::map;
struct FunctionHook
{
FunctionHook(const char *f, void **o, void *d)
: function(f), origptr(o), hookptr(d), excludeModule(NULL)
{}
bool operator <(const FunctionHook &h)
{
return function < h.function;
}
bool ApplyHook(void **IATentry)
{
DWORD oldProtection = PAGE_EXECUTE;
if(*IATentry == hookptr)
return false;
BOOL success = TRUE;
success = VirtualProtect(IATentry, sizeof(void*), PAGE_READWRITE, &oldProtection);
if(!success)
{
RDCERR("Failed to make IAT entry writeable 0x%p", IATentry);
return false;
}
if(origptr && *origptr == NULL) *origptr = *IATentry;
*IATentry = hookptr;
success = VirtualProtect(IATentry, sizeof(void*), oldProtection, &oldProtection);
if(!success)
{
RDCERR("Failed to restore IAT entry protection 0x%p", IATentry);
return false;
}
return true;
}
string function;
void **origptr;
void *hookptr;
HMODULE excludeModule;
};
struct DllHookset
{
DllHookset() : module(NULL) {}
HMODULE module;
vector<FunctionHook> FunctionHooks;
};
struct CachedHookData
{
map<string, DllHookset> DllHooks;
HMODULE module;
Threading::CriticalSection lock;
char lowername[512];
void ApplyHooks(const char *modName, HMODULE module)
{
{
size_t i=0;
while(modName[i])
{
lowername[i] = (char)tolower(modName[i]);
i++;
}
lowername[i] = 0;
}
// fraps seems to non-safely modify the assembly around the hook function, if
// we modify its import descriptors it leads to a crash as it hooks OUR functions.
// instead, skip modifying the import descriptors, it will hook the 'real' d3d functions
// and we can call them and have fraps + renderdoc playing nicely together.
// we also exclude some other overlay renderers here, such as steam's
if(strstr(lowername, "fraps") ||
strstr(lowername, "gameoverlayrenderer"))
return;
// for safety (and because we don't need to), ignore these modules
if(!_stricmp(modName, "kernel32.dll") ||
!_stricmp(modName, "powrprof.dll") ||
strstr(lowername, "msvcr") == lowername ||
strstr(lowername, "msvcp") == lowername)
return;
// set module pointer if we are hooking exports from this module
for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it)
if(!_stricmp(it->first.c_str(), modName))
it->second.module = module;
byte *baseAddress = (byte *)module;
PIMAGE_DOS_HEADER dosheader = (PIMAGE_DOS_HEADER)baseAddress;
if(dosheader->e_magic != 0x5a4d)
{
RDCDEBUG("Ignoring module %s, since magic is 0x%04x not 0x%04x", modName, (uint32_t)dosheader->e_magic, 0x5a4dU);
return;
}
char *PE00 = (char *)(baseAddress + dosheader->e_lfanew);
PIMAGE_FILE_HEADER fileHeader = (PIMAGE_FILE_HEADER)(PE00+4);
PIMAGE_OPTIONAL_HEADER optHeader = (PIMAGE_OPTIONAL_HEADER)((BYTE *)fileHeader+sizeof(IMAGE_FILE_HEADER));
DWORD iatSize = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size;
DWORD iatOffset = optHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
IMAGE_IMPORT_DESCRIPTOR *importDesc = (IMAGE_IMPORT_DESCRIPTOR *)(baseAddress + iatOffset);
while(iatOffset && importDesc->FirstThunk)
{
const char *dllName = (const char *)(baseAddress + importDesc->Name);
DllHookset *hookset = NULL;
for(auto it=DllHooks.begin(); it != DllHooks.end(); ++it)
if(!_stricmp(it->first.c_str(), dllName))
hookset = &it->second;
if(hookset && importDesc->OriginalFirstThunk > 0 && importDesc->FirstThunk > 0)
{
IMAGE_THUNK_DATA *origFirst = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->OriginalFirstThunk);
IMAGE_THUNK_DATA *first = (IMAGE_THUNK_DATA *)(baseAddress + importDesc->FirstThunk);
while(origFirst->u1.AddressOfData)
{
#ifdef WIN64
if(origFirst->u1.AddressOfData & 0x8000000000000000)
#else
if(origFirst->u1.AddressOfData & 0x80000000)
#endif
{
// low bits of origFirst->u1.AddressOfData contain an ordinal
origFirst++;
first++;
continue;
}
IMAGE_IMPORT_BY_NAME *import = (IMAGE_IMPORT_BY_NAME *)(baseAddress + origFirst->u1.AddressOfData);
void **IATentry = (void **)&first->u1.AddressOfData;
struct hook_find
{
bool operator() (const FunctionHook &a, const char *b)
{ return strcmp(a.function.c_str(), b) < 0; }
};
const char *importName = (const char *)import->Name;
auto found = std::lower_bound(hookset->FunctionHooks.begin(), hookset->FunctionHooks.end(), importName, hook_find());
if(found != hookset->FunctionHooks.end() && !strcmp(found->function.c_str(), importName) && found->excludeModule != module)
{
SCOPED_LOCK(lock);
bool applied = found->ApplyHook(IATentry);
if(!applied)
return;
}
origFirst++;
first++;
}
}
importDesc++;
}
}
};
static CachedHookData *s_HookData = NULL;
static void HookAllModules()
{
HANDLE hModuleSnap = INVALID_HANDLE_VALUE;
// up to 10 retries
for(int i=0; i < 10; i++)
{
hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());
if(hModuleSnap == INVALID_HANDLE_VALUE)
{
DWORD err = GetLastError();
RDCWARN("CreateToolhelp32Snapshot() -> 0x%08x", err);
// retry if error is ERROR_BAD_LENGTH
if(err == ERROR_BAD_LENGTH)
continue;
}
// didn't retry, or succeeded
break;
}
if(hModuleSnap == INVALID_HANDLE_VALUE)
{
RDCERR("Couldn't create toolhelp dump of modules in process");
return;
}
#ifdef UNICODE
#undef MODULEENTRY32
#undef Module32First
#undef Module32Next
#endif
MODULEENTRY32 me32;
RDCEraseEl(me32);
me32.dwSize = sizeof(MODULEENTRY32);
BOOL success = Module32First(hModuleSnap, &me32);
if(success == FALSE)
{
DWORD err = GetLastError();
RDCERR("Couldn't get first module in process: 0x%08x", err);
CloseHandle(hModuleSnap);
return;
}
uintptr_t ret = 0;
int numModules = 0;
do
{
s_HookData->ApplyHooks(me32.szModule, me32.hModule);
} while(ret == 0 && Module32Next(hModuleSnap, &me32));
CloseHandle(hModuleSnap);
}
HMODULE WINAPI Hooked_LoadLibraryExA(LPCSTR lpLibFileName, HANDLE fileHandle, DWORD flags)
{
// we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module
// was excluded from IAT patching
HMODULE mod = LoadLibraryExA(lpLibFileName, fileHandle, flags);
HookAllModules();
return mod;
}
HMODULE WINAPI Hooked_LoadLibraryExW(LPCWSTR lpLibFileName, HANDLE fileHandle, DWORD flags)
{
// we can use the function naked, as when setting up the hook for LoadLibraryExA, our own module
// was excluded from IAT patching
HMODULE mod = LoadLibraryExW(lpLibFileName, fileHandle, flags);
HookAllModules();
return mod;
}
HMODULE WINAPI Hooked_LoadLibraryA(LPCSTR lpLibFileName)
{
return Hooked_LoadLibraryExA(lpLibFileName, NULL, 0);
}
HMODULE WINAPI Hooked_LoadLibraryW(LPCWSTR lpLibFileName)
{
return Hooked_LoadLibraryExW(lpLibFileName, NULL, 0);
}
static bool OrdinalAsString(void *func)
{
return uint64_t(func) <= 0xffff;
}
FARPROC WINAPI Hooked_GetProcAddress(HMODULE mod, LPCSTR func)
{
if(mod == NULL || func == NULL)
return (FARPROC)NULL;
if(mod == s_HookData->module || OrdinalAsString((void *)func))
return GetProcAddress(mod, func);
for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
{
if(it->second.module == NULL)
it->second.module = GetModuleHandleA(it->first.c_str());
if(mod == it->second.module)
{
FunctionHook search(func, NULL, NULL);
auto found = std::lower_bound(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end(), search);
if(found != it->second.FunctionHooks.end() && !(search < *found))
{
if(found->origptr && *found->origptr == NULL)
*found->origptr = (void *)GetProcAddress(mod, func);
return (FARPROC)found->hookptr;
}
}
}
return GetProcAddress(mod, func);
}
void Win32_IAT_BeginHooks()
{
s_HookData = new CachedHookData;
RDCASSERT(s_HookData->DllHooks.empty());
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryA", NULL, &Hooked_LoadLibraryA));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryW", NULL, &Hooked_LoadLibraryW));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExA", NULL, &Hooked_LoadLibraryExA));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("LoadLibraryExW", NULL, &Hooked_LoadLibraryExW));
s_HookData->DllHooks["kernel32.dll"].FunctionHooks.push_back(FunctionHook("GetProcAddress", NULL, &Hooked_GetProcAddress));
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCTSTR)&s_HookData,
&s_HookData->module);
for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
for(size_t i=0; i < it->second.FunctionHooks.size(); i++)
it->second.FunctionHooks[i].excludeModule = s_HookData->module;
}
// hook all functions for currently loaded modules.
// some of these hooks (as above) will hook LoadLibrary/GetProcAddress, to protect
void Win32_IAT_EndHooks()
{
for(auto it=s_HookData->DllHooks.begin(); it != s_HookData->DllHooks.end(); ++it)
std::sort(it->second.FunctionHooks.begin(), it->second.FunctionHooks.end());
HookAllModules();
}
bool Win32_IAT_Hook(void **orig_function_ptr, const char *module_name, const char *function, void *destination_function_ptr)
{
if(!_stricmp(module_name, "kernel32.dll"))
{
if(!strcmp(function, "LoadLibraryA") ||
!strcmp(function, "LoadLibraryW") ||
!strcmp(function, "LoadLibraryExA") ||
!strcmp(function, "LoadLibraryExW") ||
!strcmp(function, "GetProcAddress"))
{
RDCERR("Cannot hook LoadLibrary* or GetProcAddress, as these are hooked internally");
return false;
}
}
s_HookData->DllHooks[strlower(string(module_name))].FunctionHooks.push_back(FunctionHook(function, orig_function_ptr, destination_function_ptr));
return true;
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/Common/AliasProcessor.h>
#include <osvr/Common/PathTree.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Util/Flag.h>
#include <osvr/Util/TreeTraversalVisitor.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Common/ParseAlias.h>
#include <osvr/Common/RoutingKeys.h>
#include "PathParseAndRetrieve.h"
// Library/third-party includes
#include <boost/noncopyable.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/erase.hpp>
// Standard includes
// - none
namespace osvr {
namespace common {
namespace {
static const char PRIORITY_KEY[] = "$priority";
static const char WILDCARD_SUFFIX[] = "/*";
static const size_t WILDCARD_SUFFIX_LEN = sizeof(WILDCARD_SUFFIX) - 1;
/// @brief Handles wildcards with a functor of your choice: it should
/// take in a PathNode& node, std::string const& relPath
/// where relPath is relative to the parent of the wildcard.
template <typename T>
inline void applyWildcard(PathNode &node,
std::string const &pathWithWildcard,
T functor) {
auto startingPath = pathWithWildcard;
boost::algorithm::erase_tail(startingPath, WILDCARD_SUFFIX_LEN);
auto &startingNode = treePathRetrieve(node, startingPath);
auto absoluteStartingPath = getFullPath(startingNode);
auto absoluteStartingPathLen = absoluteStartingPath.length();
util::traverseWith(startingNode, [&](PathNode &node) {
// Don't visit null nodes
if (elements::isNull(node.value())) {
return;
}
auto visitPath = getFullPath(node);
/// This is relative to the initial starting path stem: where we
/// started the traversal.
auto relPath = visitPath;
boost::algorithm::erase_head(relPath,
absoluteStartingPathLen + 1);
functor(node, relPath);
});
}
/// @brief Predicate that checks if this path contains a wildcard.
inline bool doesPathContainWildcard(std::string const &path) {
return boost::algorithm::ends_with(path, WILDCARD_SUFFIX);
}
/// @brief Implementation functor for AliasProcessor.
class AutomaticAliases : boost::noncopyable {
public:
AutomaticAliases(PathNode &devNode,
detail::AliasProcessorOptions opts)
: m_devNode(devNode), m_opts(opts) {}
/// @brief Function call operator: pass any Json::Value. If it is an
/// object with aliases, or an array of objects with aliases, it
/// will handle them.
/// @return whether any changes were made to the tree
util::Flag operator()(Json::Value const &val) {
if (val.isArray()) {
m_processArray(val);
} else if (val.isObject()) {
m_processObject(val);
}
return m_flag;
}
private:
/// @brief Takes in an array of objects, and passes them each, in
/// order, to m_processObject()
void m_processArray(Json::Value const &arr) {
for (auto const &elt : arr) {
if (elt.isObject()) {
m_processObject(elt);
}
}
}
/// @brief Takes in an object, retrieves the priority specified by
/// the PRIORITY_KEY, if any, then passes all other entries in
/// the object to m_processEntry() along with the default or
/// retrieved priority.
void m_processObject(Json::Value const &obj) {
AliasPriority priority{m_opts.defaultPriority};
if (obj.isMember(PRIORITY_KEY)) {
priority =
static_cast<AliasPriority>(obj[PRIORITY_KEY].asInt());
}
for (auto const &key : obj.getMemberNames()) {
if (PRIORITY_KEY == key) {
continue;
}
m_processEntry(key, obj[key], priority);
}
}
/// @brief Process a name:value entry in an alias description
/// object, with the given priority. Calls m_processSingleEntry() to
/// actually complete its work.
void m_processEntry(std::string const &path,
Json::Value const &source,
AliasPriority priority) {
if (!m_opts.permitRelativePath && !isPathAbsolute(path)) {
OSVR_DEV_VERBOSE(
"Got a non-permitted relative path: " << path);
return;
}
ParsedAlias parsedSource(source);
auto leaf = parsedSource.getLeaf();
if (!m_opts.permitRelativeSource && !isPathAbsolute(leaf)) {
OSVR_DEV_VERBOSE(
"Got a non-permitted relative source leaf: " << leaf);
return;
}
if (!doesPathContainWildcard(leaf)) {
/// Handle the simple ones first.
m_processSingleEntry(path, parsedSource.getAlias(),
priority);
return;
}
/// OK, handle wildcard here
if (!m_opts.permitWildcard) {
OSVR_DEV_VERBOSE(
"Got a non-permitted wildcard in the source leaf of: "
<< parsedSource.getAlias());
}
if (parsedSource.isSimple()) {
applyWildcard(
m_devNode, leaf,
[&](PathNode &node, std::string const &relPath) {
m_processSingleEntry(path + getPathSeparator() +
relPath,
getFullPath(node), priority);
});
return;
}
applyWildcard(m_devNode, leaf, [&](PathNode &node,
std::string const &relPath) {
parsedSource.setLeaf(getFullPath(node));
m_processSingleEntry(path + getPathSeparator() + relPath,
parsedSource.getAlias(), priority);
});
}
/// @brief Called for each individual alias path to be processed for
/// (and potentially added to/updated in) the path tree.
void m_processSingleEntry(std::string const &path,
std::string const &source,
AliasPriority priority) {
m_flag += addAliasFromSourceAndRelativeDest(m_devNode, source,
path, priority);
}
PathNode &m_devNode;
detail::AliasProcessorOptions m_opts;
util::Flag m_flag;
};
} // namespace
bool AliasProcessor::process(PathNode &node, Json::Value const &val) {
AutomaticAliases processor{node, m_opts};
return processor(val).get();
}
Json::Value createJSONAlias(std::string const &path,
Json::Value const &destination) {
Json::Value ret{Json::nullValue};
if (path.empty()) {
return ret;
}
if (destination.isNull()) {
return ret;
}
ret = Json::objectValue;
ret[path] = destination;
return ret;
}
Json::Value convertRouteToAlias(Json::Value const &val) {
Json::Value ret = val;
if (!val.isObject()) {
// Can't be a route if it's not an object.
return ret;
}
if (val.isMember(routing_keys::destination()) &&
val.isMember(routing_keys::source())) {
// By golly this is an old-fashioned route.
ret = createJSONAlias(val[routing_keys::destination()].asString(),
val[routing_keys::source()]);
}
return ret;
}
Json::Value applyPriorityToAlias(Json::Value const &alias,
AliasPriority priority) {
Json::Value ret{alias};
if (ret.isObject()) {
ret[PRIORITY_KEY] = priority;
}
return ret;
}
} // namespace common
} // namespace osvr<commit_msg>Use uniform initialization<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include <osvr/Common/AliasProcessor.h>
#include <osvr/Common/PathTree.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Util/Flag.h>
#include <osvr/Util/TreeTraversalVisitor.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Common/ParseAlias.h>
#include <osvr/Common/RoutingKeys.h>
#include "PathParseAndRetrieve.h"
// Library/third-party includes
#include <boost/noncopyable.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/erase.hpp>
// Standard includes
// - none
namespace osvr {
namespace common {
namespace {
static const char PRIORITY_KEY[] = "$priority";
static const char WILDCARD_SUFFIX[] = "/*";
static const size_t WILDCARD_SUFFIX_LEN = sizeof(WILDCARD_SUFFIX) - 1;
/// @brief Handles wildcards with a functor of your choice: it should
/// take in a PathNode& node, std::string const& relPath
/// where relPath is relative to the parent of the wildcard.
template <typename T>
inline void applyWildcard(PathNode &node,
std::string const &pathWithWildcard,
T functor) {
auto startingPath = pathWithWildcard;
boost::algorithm::erase_tail(startingPath, WILDCARD_SUFFIX_LEN);
auto &startingNode = treePathRetrieve(node, startingPath);
auto absoluteStartingPath = getFullPath(startingNode);
auto absoluteStartingPathLen = absoluteStartingPath.length();
util::traverseWith(startingNode, [&](PathNode &node) {
// Don't visit null nodes
if (elements::isNull(node.value())) {
return;
}
auto visitPath = getFullPath(node);
/// This is relative to the initial starting path stem: where we
/// started the traversal.
auto relPath = visitPath;
boost::algorithm::erase_head(relPath,
absoluteStartingPathLen + 1);
functor(node, relPath);
});
}
/// @brief Predicate that checks if this path contains a wildcard.
inline bool doesPathContainWildcard(std::string const &path) {
return boost::algorithm::ends_with(path, WILDCARD_SUFFIX);
}
/// @brief Implementation functor for AliasProcessor.
class AutomaticAliases : boost::noncopyable {
public:
AutomaticAliases(PathNode &devNode,
detail::AliasProcessorOptions opts)
: m_devNode(devNode), m_opts(opts) {}
/// @brief Function call operator: pass any Json::Value. If it is an
/// object with aliases, or an array of objects with aliases, it
/// will handle them.
/// @return whether any changes were made to the tree
util::Flag operator()(Json::Value const &val) {
if (val.isArray()) {
m_processArray(val);
} else if (val.isObject()) {
m_processObject(val);
}
return m_flag;
}
private:
/// @brief Takes in an array of objects, and passes them each, in
/// order, to m_processObject()
void m_processArray(Json::Value const &arr) {
for (auto const &elt : arr) {
if (elt.isObject()) {
m_processObject(elt);
}
}
}
/// @brief Takes in an object, retrieves the priority specified by
/// the PRIORITY_KEY, if any, then passes all other entries in
/// the object to m_processEntry() along with the default or
/// retrieved priority.
void m_processObject(Json::Value const &obj) {
AliasPriority priority{m_opts.defaultPriority};
if (obj.isMember(PRIORITY_KEY)) {
priority =
static_cast<AliasPriority>(obj[PRIORITY_KEY].asInt());
}
for (auto const &key : obj.getMemberNames()) {
if (PRIORITY_KEY == key) {
continue;
}
m_processEntry(key, obj[key], priority);
}
}
/// @brief Process a name:value entry in an alias description
/// object, with the given priority. Calls m_processSingleEntry() to
/// actually complete its work.
void m_processEntry(std::string const &path,
Json::Value const &source,
AliasPriority priority) {
if (!m_opts.permitRelativePath && !isPathAbsolute(path)) {
OSVR_DEV_VERBOSE(
"Got a non-permitted relative path: " << path);
return;
}
ParsedAlias parsedSource(source);
auto leaf = parsedSource.getLeaf();
if (!m_opts.permitRelativeSource && !isPathAbsolute(leaf)) {
OSVR_DEV_VERBOSE(
"Got a non-permitted relative source leaf: " << leaf);
return;
}
if (!doesPathContainWildcard(leaf)) {
/// Handle the simple ones first.
m_processSingleEntry(path, parsedSource.getAlias(),
priority);
return;
}
/// OK, handle wildcard here
if (!m_opts.permitWildcard) {
OSVR_DEV_VERBOSE(
"Got a non-permitted wildcard in the source leaf of: "
<< parsedSource.getAlias());
}
if (parsedSource.isSimple()) {
applyWildcard(
m_devNode, leaf,
[&](PathNode &node, std::string const &relPath) {
m_processSingleEntry(path + getPathSeparator() +
relPath,
getFullPath(node), priority);
});
return;
}
applyWildcard(m_devNode, leaf, [&](PathNode &node,
std::string const &relPath) {
parsedSource.setLeaf(getFullPath(node));
m_processSingleEntry(path + getPathSeparator() + relPath,
parsedSource.getAlias(), priority);
});
}
/// @brief Called for each individual alias path to be processed for
/// (and potentially added to/updated in) the path tree.
void m_processSingleEntry(std::string const &path,
std::string const &source,
AliasPriority priority) {
m_flag += addAliasFromSourceAndRelativeDest(m_devNode, source,
path, priority);
}
PathNode &m_devNode;
detail::AliasProcessorOptions m_opts;
util::Flag m_flag;
};
} // namespace
bool AliasProcessor::process(PathNode &node, Json::Value const &val) {
AutomaticAliases processor{node, m_opts};
return processor(val).get();
}
Json::Value createJSONAlias(std::string const &path,
Json::Value const &destination) {
Json::Value ret{Json::nullValue};
if (path.empty()) {
return ret;
}
if (destination.isNull()) {
return ret;
}
ret = Json::objectValue;
ret[path] = destination;
return ret;
}
Json::Value convertRouteToAlias(Json::Value const &val) {
Json::Value ret{val};
if (!val.isObject()) {
// Can't be a route if it's not an object.
return ret;
}
if (val.isMember(routing_keys::destination()) &&
val.isMember(routing_keys::source())) {
// By golly this is an old-fashioned route.
ret = createJSONAlias(val[routing_keys::destination()].asString(),
val[routing_keys::source()]);
}
return ret;
}
Json::Value applyPriorityToAlias(Json::Value const &alias,
AliasPriority priority) {
Json::Value ret{alias};
if (ret.isObject()) {
ret[PRIORITY_KEY] = priority;
}
return ret;
}
} // namespace common
} // namespace osvr<|endoftext|> |
<commit_before>//===- lib/Trace/FunctionState.cpp ----------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Trace/FunctionState.hpp"
#include "seec/Trace/GetCurrentRuntimeValue.hpp"
#include "seec/Trace/MemoryState.hpp"
#include "seec/Trace/ThreadState.hpp"
#include "seec/Trace/ProcessState.hpp"
#include "seec/Util/ModuleIndex.hpp"
#include "llvm/Support/raw_ostream.h"
namespace seec {
namespace trace {
//===------------------------------------------------------------------------===
// AllocaState
//===------------------------------------------------------------------------===
llvm::AllocaInst const *AllocaState::getInstruction() const {
auto &Lookup = Parent->getFunctionLookup();
auto Inst = Lookup.getInstruction(InstructionIndex);
assert(Inst && llvm::isa<llvm::AllocaInst>(Inst));
return llvm::cast<llvm::AllocaInst>(Inst);
}
MemoryState::Region AllocaState::getMemoryRegion() const {
auto &Thread = Parent->getParent();
auto &Process = Thread.getParent();
auto &Memory = Process.getMemory();
return Memory.getRegion(MemoryArea(Address, getTotalSize()));
}
//===------------------------------------------------------------------------===
// RuntimeErrorState
//===------------------------------------------------------------------------===
llvm::Instruction const *RuntimeErrorState::getInstruction() const {
auto Index = Parent.getFunctionLookup();
return Index.getInstruction(InstructionIndex);
}
bool RuntimeErrorState::isActive() const {
return ThreadTime == getParent().getParent().getThreadTime();
}
//===------------------------------------------------------------------------===
// FunctionState
//===------------------------------------------------------------------------===
FunctionState::FunctionState(ThreadState &Parent,
uint32_t Index,
FunctionIndex const &Function,
FunctionTrace Trace)
: Parent(&Parent),
FunctionLookup(Parent.getParent().getModule().getFunctionIndex(Index)),
Index(Index),
Trace(Trace),
ActiveInstruction(),
InstructionValues(Function.getInstructionCount()),
Allocas(),
ParamByVals(),
RuntimeErrors()
{
assert(FunctionLookup);
}
llvm::Function const *FunctionState::getFunction() const {
return Parent->getParent().getModule().getFunction(Index);
}
llvm::Instruction const *FunctionState::getInstruction(uint32_t Index) const {
if (Index >= InstructionValues.size())
return nullptr;
return FunctionLookup->getInstruction(Index);
}
llvm::Instruction const *FunctionState::getActiveInstruction() const {
if (!ActiveInstruction.assigned())
return nullptr;
return FunctionLookup->getInstruction(ActiveInstruction.get<0>());
}
seec::Maybe<MemoryArea>
FunctionState::getContainingMemoryArea(uintptr_t Address) const {
auto const Alloca = getAllocaContaining(Address);
if (Alloca)
return MemoryArea(Alloca->getAddress(), Alloca->getTotalSize());
for (auto const &ParamByVal : ParamByVals)
if (ParamByVal.getArea().contains(Address))
return ParamByVal.getArea();
return seec::Maybe<MemoryArea>();
}
uintptr_t FunctionState::getRuntimeAddress(llvm::Function const *F) const {
return Parent->getParent().getRuntimeAddress(F);
}
uintptr_t
FunctionState::getRuntimeAddress(llvm::GlobalVariable const *GV) const {
return Parent->getParent().getRuntimeAddress(GV);
}
RuntimeValue const *
FunctionState::getCurrentRuntimeValue(llvm::Instruction const *I) const {
auto const MaybeIndex = FunctionLookup->getIndexOfInstruction(I);
if (!MaybeIndex.assigned())
return nullptr;
return getCurrentRuntimeValue(MaybeIndex.get<0>());
}
std::vector<std::reference_wrapper<AllocaState const>>
FunctionState::getVisibleAllocas() const {
std::vector<std::reference_wrapper<AllocaState const>> RetVal;
if (!ActiveInstruction.assigned(0))
return RetVal;
auto const ActiveIdx = ActiveInstruction.get<0>();
for (auto const &Alloca : Allocas) {
auto const Inst = Alloca.getInstruction();
auto const MaybeIdx = FunctionLookup->getIndexOfDbgDeclareFor(Inst);
// If the index of the llvm.dbg.declare is greater than our active index,
// then do not show this alloca.
if (MaybeIdx.assigned(0) && MaybeIdx.get<0>() > ActiveIdx)
continue;
RetVal.emplace_back(Alloca);
}
return RetVal;
}
auto
FunctionState::getRuntimeErrorsActive() const
-> seec::Range<decltype(RuntimeErrors)::const_iterator>
{
auto const It = std::find_if(RuntimeErrors.begin(), RuntimeErrors.end(),
[] (RuntimeErrorState const &Err) {
return Err.isActive();
});
return seec::Range<decltype(RuntimeErrors)::const_iterator>
(It, RuntimeErrors.end());
}
void
FunctionState::
addRuntimeError(std::unique_ptr<seec::runtime_errors::RunError> Error) {
assert(ActiveInstruction.assigned(0)
&& "Runtime error with no active instruction.");
RuntimeErrors.emplace_back(*this,
ActiveInstruction.get<0>(),
std::move(Error),
getParent().getThreadTime());
}
void FunctionState::removeLastRuntimeError() {
assert(!RuntimeErrors.empty() && "No runtime error to remove.");
RuntimeErrors.pop_back();
}
void FunctionState::addByValArea(unsigned ArgumentNumber,
uintptr_t Address,
std::size_t Size)
{
auto const Fn = getFunction();
assert(ArgumentNumber < Fn->arg_size());
auto ArgIt = Fn->arg_begin();
std::advance(ArgIt, ArgumentNumber);
ParamByVals.emplace_back(&*ArgIt, MemoryArea(Address, Size));
}
void FunctionState::removeByValArea(uintptr_t Address)
{
auto const It = std::find_if(ParamByVals.begin(),
ParamByVals.end(),
[=] (ParamByValState const &P) {
return P.getArea().contains(Address);
});
if (It != ParamByVals.end())
ParamByVals.erase(It);
}
/// Print a textual description of a FunctionState.
llvm::raw_ostream &operator<<(llvm::raw_ostream &Out,
FunctionState const &State) {
Out << " Function [Index=" << State.getIndex() << "]\n";
Out << " Allocas:\n";
for (auto const &Alloca : State.getAllocas()) {
Out << " " << Alloca.getInstructionIndex()
<< " =[" << Alloca.getElementCount()
<< "x" << Alloca.getElementSize()
<< "] @" << Alloca.getAddress()
<< "\n";
}
Out << " Instruction values [Active=";
if (State.getActiveInstructionIndex().assigned(0))
Out << State.getActiveInstructionIndex().get<0>();
else
Out << "unassigned";
Out << "]:\n";
auto const InstructionCount = State.getInstructionCount();
for (std::size_t i = 0; i < InstructionCount; ++i) {
auto const Value = State.getCurrentRuntimeValue(i);
if (!Value || !Value->assigned())
continue;
auto Type = State.getInstruction(i)->getType();
Out << " " << i << " = ";
if (llvm::isa<llvm::IntegerType>(Type)) {
Out << "(int64_t)" << getAs<int64_t>(*Value, Type)
<< ", (uint64_t)" << getAs<uint64_t>(*Value, Type);
}
else if (Type->isFloatTy()) {
Out << "(float)" << getAs<float>(*Value, Type);
}
else if (Type->isDoubleTy()) {
Out << "(double)" << getAs<double>(*Value, Type);
}
else if (Type->isPointerTy()) {
Out << "(? *)" << getAs<void *>(*Value, Type);
}
else {
Out << "(unknown type)";
}
Out << "\n";
}
return Out;
}
} // namespace trace (in seec)
} // namespace seec
<commit_msg>When determining alloca visibility in seec::trace::FunctionState, if the llvm.dbg.declare associated with an alloca is the very next Instruction, then treat the alloca as visible.<commit_after>//===- lib/Trace/FunctionState.cpp ----------------------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Trace/FunctionState.hpp"
#include "seec/Trace/GetCurrentRuntimeValue.hpp"
#include "seec/Trace/MemoryState.hpp"
#include "seec/Trace/ThreadState.hpp"
#include "seec/Trace/ProcessState.hpp"
#include "seec/Util/ModuleIndex.hpp"
#include "llvm/Support/raw_ostream.h"
namespace seec {
namespace trace {
//===------------------------------------------------------------------------===
// AllocaState
//===------------------------------------------------------------------------===
llvm::AllocaInst const *AllocaState::getInstruction() const {
auto &Lookup = Parent->getFunctionLookup();
auto Inst = Lookup.getInstruction(InstructionIndex);
assert(Inst && llvm::isa<llvm::AllocaInst>(Inst));
return llvm::cast<llvm::AllocaInst>(Inst);
}
MemoryState::Region AllocaState::getMemoryRegion() const {
auto &Thread = Parent->getParent();
auto &Process = Thread.getParent();
auto &Memory = Process.getMemory();
return Memory.getRegion(MemoryArea(Address, getTotalSize()));
}
//===------------------------------------------------------------------------===
// RuntimeErrorState
//===------------------------------------------------------------------------===
llvm::Instruction const *RuntimeErrorState::getInstruction() const {
auto Index = Parent.getFunctionLookup();
return Index.getInstruction(InstructionIndex);
}
bool RuntimeErrorState::isActive() const {
return ThreadTime == getParent().getParent().getThreadTime();
}
//===------------------------------------------------------------------------===
// FunctionState
//===------------------------------------------------------------------------===
FunctionState::FunctionState(ThreadState &Parent,
uint32_t Index,
FunctionIndex const &Function,
FunctionTrace Trace)
: Parent(&Parent),
FunctionLookup(Parent.getParent().getModule().getFunctionIndex(Index)),
Index(Index),
Trace(Trace),
ActiveInstruction(),
InstructionValues(Function.getInstructionCount()),
Allocas(),
ParamByVals(),
RuntimeErrors()
{
assert(FunctionLookup);
}
llvm::Function const *FunctionState::getFunction() const {
return Parent->getParent().getModule().getFunction(Index);
}
llvm::Instruction const *FunctionState::getInstruction(uint32_t Index) const {
if (Index >= InstructionValues.size())
return nullptr;
return FunctionLookup->getInstruction(Index);
}
llvm::Instruction const *FunctionState::getActiveInstruction() const {
if (!ActiveInstruction.assigned())
return nullptr;
return FunctionLookup->getInstruction(ActiveInstruction.get<0>());
}
seec::Maybe<MemoryArea>
FunctionState::getContainingMemoryArea(uintptr_t Address) const {
auto const Alloca = getAllocaContaining(Address);
if (Alloca)
return MemoryArea(Alloca->getAddress(), Alloca->getTotalSize());
for (auto const &ParamByVal : ParamByVals)
if (ParamByVal.getArea().contains(Address))
return ParamByVal.getArea();
return seec::Maybe<MemoryArea>();
}
uintptr_t FunctionState::getRuntimeAddress(llvm::Function const *F) const {
return Parent->getParent().getRuntimeAddress(F);
}
uintptr_t
FunctionState::getRuntimeAddress(llvm::GlobalVariable const *GV) const {
return Parent->getParent().getRuntimeAddress(GV);
}
RuntimeValue const *
FunctionState::getCurrentRuntimeValue(llvm::Instruction const *I) const {
auto const MaybeIndex = FunctionLookup->getIndexOfInstruction(I);
if (!MaybeIndex.assigned())
return nullptr;
return getCurrentRuntimeValue(MaybeIndex.get<0>());
}
std::vector<std::reference_wrapper<AllocaState const>>
FunctionState::getVisibleAllocas() const {
std::vector<std::reference_wrapper<AllocaState const>> RetVal;
if (!ActiveInstruction.assigned(0))
return RetVal;
auto const ActiveIdx = ActiveInstruction.get<0>();
for (auto const &Alloca : Allocas) {
auto const Inst = Alloca.getInstruction();
auto const MaybeIdx = FunctionLookup->getIndexOfDbgDeclareFor(Inst);
// If the index of the llvm.dbg.declare is greater than our active index,
// then do not show this alloca. If the llvm.dbg.declare is the very next
// instruction, then we should still show this (hence the ActiveIdx + 1).
if (MaybeIdx.assigned(0) && MaybeIdx.get<0>() > ActiveIdx + 1)
continue;
RetVal.emplace_back(Alloca);
}
return RetVal;
}
auto
FunctionState::getRuntimeErrorsActive() const
-> seec::Range<decltype(RuntimeErrors)::const_iterator>
{
auto const It = std::find_if(RuntimeErrors.begin(), RuntimeErrors.end(),
[] (RuntimeErrorState const &Err) {
return Err.isActive();
});
return seec::Range<decltype(RuntimeErrors)::const_iterator>
(It, RuntimeErrors.end());
}
void
FunctionState::
addRuntimeError(std::unique_ptr<seec::runtime_errors::RunError> Error) {
assert(ActiveInstruction.assigned(0)
&& "Runtime error with no active instruction.");
RuntimeErrors.emplace_back(*this,
ActiveInstruction.get<0>(),
std::move(Error),
getParent().getThreadTime());
}
void FunctionState::removeLastRuntimeError() {
assert(!RuntimeErrors.empty() && "No runtime error to remove.");
RuntimeErrors.pop_back();
}
void FunctionState::addByValArea(unsigned ArgumentNumber,
uintptr_t Address,
std::size_t Size)
{
auto const Fn = getFunction();
assert(ArgumentNumber < Fn->arg_size());
auto ArgIt = Fn->arg_begin();
std::advance(ArgIt, ArgumentNumber);
ParamByVals.emplace_back(&*ArgIt, MemoryArea(Address, Size));
}
void FunctionState::removeByValArea(uintptr_t Address)
{
auto const It = std::find_if(ParamByVals.begin(),
ParamByVals.end(),
[=] (ParamByValState const &P) {
return P.getArea().contains(Address);
});
if (It != ParamByVals.end())
ParamByVals.erase(It);
}
/// Print a textual description of a FunctionState.
llvm::raw_ostream &operator<<(llvm::raw_ostream &Out,
FunctionState const &State) {
Out << " Function [Index=" << State.getIndex() << "]\n";
Out << " Allocas:\n";
for (auto const &Alloca : State.getAllocas()) {
Out << " " << Alloca.getInstructionIndex()
<< " =[" << Alloca.getElementCount()
<< "x" << Alloca.getElementSize()
<< "] @" << Alloca.getAddress()
<< "\n";
}
Out << " Instruction values [Active=";
if (State.getActiveInstructionIndex().assigned(0))
Out << State.getActiveInstructionIndex().get<0>();
else
Out << "unassigned";
Out << "]:\n";
auto const InstructionCount = State.getInstructionCount();
for (std::size_t i = 0; i < InstructionCount; ++i) {
auto const Value = State.getCurrentRuntimeValue(i);
if (!Value || !Value->assigned())
continue;
auto Type = State.getInstruction(i)->getType();
Out << " " << i << " = ";
if (llvm::isa<llvm::IntegerType>(Type)) {
Out << "(int64_t)" << getAs<int64_t>(*Value, Type)
<< ", (uint64_t)" << getAs<uint64_t>(*Value, Type);
}
else if (Type->isFloatTy()) {
Out << "(float)" << getAs<float>(*Value, Type);
}
else if (Type->isDoubleTy()) {
Out << "(double)" << getAs<double>(*Value, Type);
}
else if (Type->isPointerTy()) {
Out << "(? *)" << getAs<void *>(*Value, Type);
}
else {
Out << "(unknown type)";
}
Out << "\n";
}
return Out;
}
} // namespace trace (in seec)
} // namespace seec
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/sparse.h>
#include <af/array.h>
#include <af/algorithm.h>
#include <sparse_handle.hpp>
#include <sparse.hpp>
#include <handle.hpp>
#include <backend.hpp>
#include <err_common.hpp>
#include <arith.hpp>
#include <lookup.hpp>
#include <platform.hpp>
using namespace detail;
using namespace common;
using af::dim4;
const SparseArrayBase& getSparseArrayBase(const af_array in, bool device_check)
{
const SparseArrayBase *base = static_cast<SparseArrayBase*>(reinterpret_cast<void *>(in));
if(!base->isSparse()) {
AF_ERROR("Input is not a SparseArray and cannot be used in Sparse functions",
AF_ERR_ARG);
}
if (device_check && base->getDevId() != detail::getActiveDeviceId()) {
AF_ERROR("Input Array not created on current device", AF_ERR_DEVICE);
}
return *base;
}
////////////////////////////////////////////////////////////////////////////////
// Sparse Creation
////////////////////////////////////////////////////////////////////////////////
template<typename T>
af_array createSparseArrayFromData(const af::dim4 &dims, const af_array values,
const af_array rowIdx, const af_array colIdx,
const af::storage stype)
{
SparseArray<T> sparse = common::createArrayDataSparseArray(
dims, getArray<T>(values),
getArray<int>(rowIdx), getArray<int>(colIdx),
stype);
return getHandle(sparse);
}
af_err af_create_sparse_array(
af_array *out,
const dim_t nRows, const dim_t nCols,
const af_array values, const af_array rowIdx, const af_array colIdx,
const af_storage stype)
{
try {
// Checks:
// rowIdx and colIdx arrays are of s32 type
// values is of floating point type
// if COO, rowIdx, colIdx and values should have same dims
// if CRS, colIdx and values should have same dims, rowIdx.dims = nRows
// if CRC, rowIdx and values should have same dims, colIdx.dims = nCols
// stype is within acceptable range
// type is floating type
if(!(stype == AF_STORAGE_CSR
|| stype == AF_STORAGE_CSC
|| stype == AF_STORAGE_COO)) {
AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
ArrayInfo vInfo = getInfo(values);
ArrayInfo rInfo = getInfo(rowIdx);
ArrayInfo cInfo = getInfo(colIdx);
TYPE_ASSERT(vInfo.isFloating());
DIM_ASSERT(4, vInfo.isLinear());
DIM_ASSERT(5, rInfo.isLinear());
DIM_ASSERT(6, cInfo.isLinear());
af_array output = 0;
af::dim4 dims(nRows, nCols);
switch(vInfo.getType()) {
case f32: output = createSparseArrayFromData<float >(dims, values, rowIdx, colIdx, stype); break;
case f64: output = createSparseArrayFromData<double >(dims, values, rowIdx, colIdx, stype); break;
case c32: output = createSparseArrayFromData<cfloat >(dims, values, rowIdx, colIdx, stype); break;
case c64: output = createSparseArrayFromData<cdouble>(dims, values, rowIdx, colIdx, stype); break;
default : TYPE_ERROR(1, vInfo.getType());
}
std::swap(*out, output);
} CATCHALL;
return AF_SUCCESS;
}
template<typename T>
af_array createSparseArrayFromPtr(
const af::dim4 &dims, const dim_t nNZ,
const T * const values, const int * const rowIdx, const int * const colIdx,
const af::storage stype, const af::source source)
{
SparseArray<T> sparse = createEmptySparseArray<T>(dims, nNZ, stype);
if(source == afHost)
sparse = common::createHostDataSparseArray(
dims, nNZ, values, rowIdx, colIdx, stype);
else if (source == afDevice)
sparse = common::createDeviceDataSparseArray(
dims, nNZ, values, rowIdx, colIdx, stype);
return getHandle(sparse);
}
af_err af_create_sparse_array_from_ptr(
af_array *out,
const dim_t nRows, const dim_t nCols, const dim_t nNZ,
const void * const values, const int * const rowIdx, const int * const colIdx,
const af_dtype type, const af_storage stype,
const af_source source)
{
try {
// Checks:
// rowIdx and colIdx arrays are of s32 type
// values is of floating point type
// if COO, rowIdx, colIdx and values should have same dims
// if CRS, colIdx and values should have same dims, rowIdx.dims = nRows
// if CRC, rowIdx and values should have same dims, colIdx.dims = nCols
// stype is within acceptable range
// type is floating type
if(!(stype == AF_STORAGE_CSR
|| stype == AF_STORAGE_CSC
|| stype == AF_STORAGE_COO)) {
AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
TYPE_ASSERT(type == f32 || type == f64
|| type == c32 || type == c64);
af_array output = 0;
af::dim4 dims(nRows, nCols);
switch(type) {
case f32: output = createSparseArrayFromPtr<float >
(dims, nNZ, static_cast<const float *>(values), rowIdx, colIdx, stype, source);
break;
case f64: output = createSparseArrayFromPtr<double >
(dims, nNZ, static_cast<const double *>(values), rowIdx, colIdx, stype, source);
break;
case c32: output = createSparseArrayFromPtr<cfloat >
(dims, nNZ, static_cast<const cfloat *>(values), rowIdx, colIdx, stype, source);
break;
case c64: output = createSparseArrayFromPtr<cdouble>
(dims, nNZ, static_cast<const cdouble*>(values), rowIdx, colIdx, stype, source);
break;
default : TYPE_ERROR(1, type);
}
std::swap(*out, output);
} CATCHALL;
return AF_SUCCESS;
}
template<typename T>
af_array createSparseArrayFromDense(
const af::dim4 &dims, const af_array _in,
const af_storage stype)
{
const Array<T> in = getArray<T>(_in);
switch(stype) {
case AF_STORAGE_CSR:
return getHandle(sparseConvertDenseToStorage<T, AF_STORAGE_CSR>(in));
case AF_STORAGE_CSC:
return getHandle(sparseConvertDenseToStorage<T, AF_STORAGE_CSC>(in));
case AF_STORAGE_COO:
return getHandle(sparseConvertDenseToStorage<T, AF_STORAGE_COO>(in));
default: AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
}
af_err af_create_sparse_array_from_dense(af_array *out, const af_array in,
const af_storage stype)
{
try {
// Checks:
// stype is within acceptable range
// values is of floating point type
ArrayInfo info = getInfo(in);
if(!(stype == AF_STORAGE_CSR
|| stype == AF_STORAGE_CSC
|| stype == AF_STORAGE_COO)) {
AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
// Only matrices allowed
DIM_ASSERT(1, info.ndims() == 2);
TYPE_ASSERT(info.isFloating());
af::dim4 dims(info.dims()[0], info.dims()[1]);
af_array output = 0;
switch(info.getType()) {
case f32: output = createSparseArrayFromDense<float >(dims, in, stype); break;
case f64: output = createSparseArrayFromDense<double >(dims, in, stype); break;
case c32: output = createSparseArrayFromDense<cfloat >(dims, in, stype); break;
case c64: output = createSparseArrayFromDense<cdouble>(dims, in, stype); break;
default: TYPE_ERROR(1, info.getType());
}
std::swap(*out, output);
} CATCHALL;
return AF_SUCCESS;
}
template<typename T>
af_array sparseConvertStorage(const af_array in_, const af_storage destStorage)
{
const SparseArray<T> in = getSparseArray<T>(in_);
// Only destStorage == AF_STORAGE_DENSE is supported
// All the other calls are for future when conversions are supported in
// the backend
if(destStorage == AF_STORAGE_DENSE) {
// Returns a regular af_array, not sparse
switch(in.getStorage()) {
case AF_STORAGE_CSR:
return getHandle(detail::sparseConvertStorageToDense<T, AF_STORAGE_CSR>(in));
case AF_STORAGE_CSC:
return getHandle(detail::sparseConvertStorageToDense<T, AF_STORAGE_CSC>(in));
case AF_STORAGE_COO:
return getHandle(detail::sparseConvertStorageToDense<T, AF_STORAGE_COO>(in));
default:
AF_ERROR("Invalid storage type of input array", AF_ERR_ARG);
}
} else if(destStorage == AF_STORAGE_CSR) {
// Returns a sparse af_array
switch(in.getStorage()) {
case AF_STORAGE_CSR:
return retainSparseHandle<T>(in_);
case AF_STORAGE_CSC:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_CSR, AF_STORAGE_CSC>(in));
case AF_STORAGE_COO:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_CSR, AF_STORAGE_COO>(in));
default:
AF_ERROR("Invalid storage type of input array", AF_ERR_ARG);
}
} else if(destStorage == AF_STORAGE_CSC) {
// Returns a sparse af_array
switch(in.getStorage()) {
case AF_STORAGE_CSR:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_CSC, AF_STORAGE_CSR>(in));
case AF_STORAGE_CSC:
return retainSparseHandle<T>(in_);
case AF_STORAGE_COO:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_CSC, AF_STORAGE_COO>(in));
default:
AF_ERROR("Invalid storage type of input array", AF_ERR_ARG);
}
} else if(destStorage == AF_STORAGE_COO) {
// Returns a sparse af_array
switch(in.getStorage()) {
case AF_STORAGE_CSR:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_COO, AF_STORAGE_CSR>(in));
case AF_STORAGE_CSC:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_COO, AF_STORAGE_CSC>(in));
case AF_STORAGE_COO:
return retainSparseHandle<T>(in_);
default:
AF_ERROR("Invalid storage type of input array", AF_ERR_ARG);
}
}
// Shoud never come here
return NULL;
}
af_err af_sparse_convert_to(af_array *out, const af_array in,
const af_storage destStorage)
{
try {
af_array output = 0;
const SparseArrayBase base = getSparseArrayBase(in);
// Dense not allowed as input -> Should never happen with SparseArrayBase
// CSC is currently not supported
ARG_ASSERT(1, base.getStorage() != AF_STORAGE_DENSE
&& base.getStorage() != AF_STORAGE_CSC);
// Conversion to and from CSC is not supported
ARG_ASSERT(2, destStorage != AF_STORAGE_CSC);
if(base.getStorage() == destStorage) {
// Return a reference
AF_CHECK(af_retain_array(out, in));
return AF_SUCCESS;
}
switch(base.getType()) {
case f32: output = sparseConvertStorage<float >(in, destStorage); break;
case f64: output = sparseConvertStorage<double >(in, destStorage); break;
case c32: output = sparseConvertStorage<cfloat >(in, destStorage); break;
case c64: output = sparseConvertStorage<cdouble>(in, destStorage); break;
default : AF_ERROR("Output storage type is not valid", AF_ERR_ARG);
}
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_to_dense(af_array *out, const af_array in)
{
try {
af_array output = 0;
const SparseArrayBase base = getSparseArrayBase(in);
// Dense not allowed as input -> Should never happen
// To convert from dense to type, use the create* functions
ARG_ASSERT(1, base.getStorage() != AF_STORAGE_DENSE);
switch(base.getType()) {
case f32: output = sparseConvertStorage<float >(in, AF_STORAGE_DENSE); break;
case f64: output = sparseConvertStorage<double >(in, AF_STORAGE_DENSE); break;
case c32: output = sparseConvertStorage<cfloat >(in, AF_STORAGE_DENSE); break;
case c64: output = sparseConvertStorage<cdouble>(in, AF_STORAGE_DENSE); break;
default : AF_ERROR("Output storage type is not valid", AF_ERR_ARG);
}
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Get Functions
////////////////////////////////////////////////////////////////////////////////
template<typename T>
af_array getSparseValues(const af_array in)
{
return getHandle(getSparseArray<T>(in).getValues());
}
af_err af_sparse_get_info(af_array *values, af_array *rows, af_array *cols, af_storage *stype,
const af_array in)
{
try {
if(values != NULL) AF_CHECK(af_sparse_get_values(values, in));
if(rows != NULL) AF_CHECK(af_sparse_get_row_idx(rows , in));
if(cols != NULL) AF_CHECK(af_sparse_get_col_idx(cols , in));
if(stype != NULL) AF_CHECK(af_sparse_get_storage(stype, in));
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_values(af_array *out, const af_array in)
{
try{
const SparseArrayBase base = getSparseArrayBase(in);
af_array output = 0;
switch(base.getType()) {
case f32: output = getSparseValues<float >(in); break;
case f64: output = getSparseValues<double >(in); break;
case c32: output = getSparseValues<cfloat >(in); break;
case c64: output = getSparseValues<cdouble>(in); break;
default : TYPE_ERROR(1, base.getType());
}
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_row_idx(af_array *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = getHandle(base.getRowIdx());
} CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_col_idx(af_array *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = getHandle(base.getColIdx());
} CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_nnz(dim_t *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = base.getNNZ();
} CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_storage(af_storage *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = base.getStorage();
} CATCHALL;
return AF_SUCCESS;
}
<commit_msg>Remove CSC placeholders for conversions<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/sparse.h>
#include <af/array.h>
#include <af/algorithm.h>
#include <sparse_handle.hpp>
#include <sparse.hpp>
#include <handle.hpp>
#include <backend.hpp>
#include <err_common.hpp>
#include <arith.hpp>
#include <lookup.hpp>
#include <platform.hpp>
using namespace detail;
using namespace common;
using af::dim4;
const SparseArrayBase& getSparseArrayBase(const af_array in, bool device_check)
{
const SparseArrayBase *base = static_cast<SparseArrayBase*>(reinterpret_cast<void *>(in));
if(!base->isSparse()) {
AF_ERROR("Input is not a SparseArray and cannot be used in Sparse functions",
AF_ERR_ARG);
}
if (device_check && base->getDevId() != detail::getActiveDeviceId()) {
AF_ERROR("Input Array not created on current device", AF_ERR_DEVICE);
}
return *base;
}
////////////////////////////////////////////////////////////////////////////////
// Sparse Creation
////////////////////////////////////////////////////////////////////////////////
template<typename T>
af_array createSparseArrayFromData(const af::dim4 &dims, const af_array values,
const af_array rowIdx, const af_array colIdx,
const af::storage stype)
{
SparseArray<T> sparse = common::createArrayDataSparseArray(
dims, getArray<T>(values),
getArray<int>(rowIdx), getArray<int>(colIdx),
stype);
return getHandle(sparse);
}
af_err af_create_sparse_array(
af_array *out,
const dim_t nRows, const dim_t nCols,
const af_array values, const af_array rowIdx, const af_array colIdx,
const af_storage stype)
{
try {
// Checks:
// rowIdx and colIdx arrays are of s32 type
// values is of floating point type
// if COO, rowIdx, colIdx and values should have same dims
// if CRS, colIdx and values should have same dims, rowIdx.dims = nRows
// if CRC, rowIdx and values should have same dims, colIdx.dims = nCols
// stype is within acceptable range
// type is floating type
if(!(stype == AF_STORAGE_CSR
|| stype == AF_STORAGE_CSC
|| stype == AF_STORAGE_COO)) {
AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
ArrayInfo vInfo = getInfo(values);
ArrayInfo rInfo = getInfo(rowIdx);
ArrayInfo cInfo = getInfo(colIdx);
TYPE_ASSERT(vInfo.isFloating());
DIM_ASSERT(4, vInfo.isLinear());
DIM_ASSERT(5, rInfo.isLinear());
DIM_ASSERT(6, cInfo.isLinear());
af_array output = 0;
af::dim4 dims(nRows, nCols);
switch(vInfo.getType()) {
case f32: output = createSparseArrayFromData<float >(dims, values, rowIdx, colIdx, stype); break;
case f64: output = createSparseArrayFromData<double >(dims, values, rowIdx, colIdx, stype); break;
case c32: output = createSparseArrayFromData<cfloat >(dims, values, rowIdx, colIdx, stype); break;
case c64: output = createSparseArrayFromData<cdouble>(dims, values, rowIdx, colIdx, stype); break;
default : TYPE_ERROR(1, vInfo.getType());
}
std::swap(*out, output);
} CATCHALL;
return AF_SUCCESS;
}
template<typename T>
af_array createSparseArrayFromPtr(
const af::dim4 &dims, const dim_t nNZ,
const T * const values, const int * const rowIdx, const int * const colIdx,
const af::storage stype, const af::source source)
{
SparseArray<T> sparse = createEmptySparseArray<T>(dims, nNZ, stype);
if(source == afHost)
sparse = common::createHostDataSparseArray(
dims, nNZ, values, rowIdx, colIdx, stype);
else if (source == afDevice)
sparse = common::createDeviceDataSparseArray(
dims, nNZ, values, rowIdx, colIdx, stype);
return getHandle(sparse);
}
af_err af_create_sparse_array_from_ptr(
af_array *out,
const dim_t nRows, const dim_t nCols, const dim_t nNZ,
const void * const values, const int * const rowIdx, const int * const colIdx,
const af_dtype type, const af_storage stype,
const af_source source)
{
try {
// Checks:
// rowIdx and colIdx arrays are of s32 type
// values is of floating point type
// if COO, rowIdx, colIdx and values should have same dims
// if CRS, colIdx and values should have same dims, rowIdx.dims = nRows
// if CRC, rowIdx and values should have same dims, colIdx.dims = nCols
// stype is within acceptable range
// type is floating type
if(!(stype == AF_STORAGE_CSR
|| stype == AF_STORAGE_CSC
|| stype == AF_STORAGE_COO)) {
AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
TYPE_ASSERT(type == f32 || type == f64
|| type == c32 || type == c64);
af_array output = 0;
af::dim4 dims(nRows, nCols);
switch(type) {
case f32: output = createSparseArrayFromPtr<float >
(dims, nNZ, static_cast<const float *>(values), rowIdx, colIdx, stype, source);
break;
case f64: output = createSparseArrayFromPtr<double >
(dims, nNZ, static_cast<const double *>(values), rowIdx, colIdx, stype, source);
break;
case c32: output = createSparseArrayFromPtr<cfloat >
(dims, nNZ, static_cast<const cfloat *>(values), rowIdx, colIdx, stype, source);
break;
case c64: output = createSparseArrayFromPtr<cdouble>
(dims, nNZ, static_cast<const cdouble*>(values), rowIdx, colIdx, stype, source);
break;
default : TYPE_ERROR(1, type);
}
std::swap(*out, output);
} CATCHALL;
return AF_SUCCESS;
}
template<typename T>
af_array createSparseArrayFromDense(
const af::dim4 &dims, const af_array _in,
const af_storage stype)
{
const Array<T> in = getArray<T>(_in);
switch(stype) {
case AF_STORAGE_CSR:
return getHandle(sparseConvertDenseToStorage<T, AF_STORAGE_CSR>(in));
case AF_STORAGE_COO:
return getHandle(sparseConvertDenseToStorage<T, AF_STORAGE_COO>(in));
case AF_STORAGE_CSC:
//return getHandle(sparseConvertDenseToStorage<T, AF_STORAGE_CSC>(in));
default: AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
}
af_err af_create_sparse_array_from_dense(af_array *out, const af_array in,
const af_storage stype)
{
try {
// Checks:
// stype is within acceptable range
// values is of floating point type
ArrayInfo info = getInfo(in);
if(!(stype == AF_STORAGE_CSR
|| stype == AF_STORAGE_CSC
|| stype == AF_STORAGE_COO)) {
AF_ERROR("Storage type is out of range/unsupported", AF_ERR_ARG);
}
// Only matrices allowed
DIM_ASSERT(1, info.ndims() == 2);
TYPE_ASSERT(info.isFloating());
af::dim4 dims(info.dims()[0], info.dims()[1]);
af_array output = 0;
switch(info.getType()) {
case f32: output = createSparseArrayFromDense<float >(dims, in, stype); break;
case f64: output = createSparseArrayFromDense<double >(dims, in, stype); break;
case c32: output = createSparseArrayFromDense<cfloat >(dims, in, stype); break;
case c64: output = createSparseArrayFromDense<cdouble>(dims, in, stype); break;
default: TYPE_ERROR(1, info.getType());
}
std::swap(*out, output);
} CATCHALL;
return AF_SUCCESS;
}
template<typename T>
af_array sparseConvertStorage(const af_array in_, const af_storage destStorage)
{
const SparseArray<T> in = getSparseArray<T>(in_);
if(destStorage == AF_STORAGE_DENSE) {
// Returns a regular af_array, not sparse
switch(in.getStorage()) {
case AF_STORAGE_CSR:
return getHandle(detail::sparseConvertStorageToDense<T, AF_STORAGE_CSR>(in));
case AF_STORAGE_COO:
return getHandle(detail::sparseConvertStorageToDense<T, AF_STORAGE_COO>(in));
default:
AF_ERROR("Invalid storage type of input array", AF_ERR_ARG);
}
} else if(destStorage == AF_STORAGE_CSR) {
// Returns a sparse af_array
switch(in.getStorage()) {
case AF_STORAGE_CSR:
return retainSparseHandle<T>(in_);
case AF_STORAGE_COO:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_CSR, AF_STORAGE_COO>(in));
default:
AF_ERROR("Invalid storage type of input array", AF_ERR_ARG);
}
} else if(destStorage == AF_STORAGE_COO) {
// Returns a sparse af_array
switch(in.getStorage()) {
case AF_STORAGE_CSR:
return getHandle(detail::sparseConvertStorageToStorage<T, AF_STORAGE_COO, AF_STORAGE_CSR>(in));
case AF_STORAGE_COO:
return retainSparseHandle<T>(in_);
default:
AF_ERROR("Invalid storage type of input array", AF_ERR_ARG);
}
}
// Shoud never come here
return NULL;
}
af_err af_sparse_convert_to(af_array *out, const af_array in,
const af_storage destStorage)
{
try {
af_array output = 0;
const SparseArrayBase base = getSparseArrayBase(in);
// Dense not allowed as input -> Should never happen with SparseArrayBase
// CSC is currently not supported
ARG_ASSERT(1, base.getStorage() != AF_STORAGE_DENSE
&& base.getStorage() != AF_STORAGE_CSC);
// Conversion to and from CSC is not supported
ARG_ASSERT(2, destStorage != AF_STORAGE_CSC);
if(base.getStorage() == destStorage) {
// Return a reference
AF_CHECK(af_retain_array(out, in));
return AF_SUCCESS;
}
switch(base.getType()) {
case f32: output = sparseConvertStorage<float >(in, destStorage); break;
case f64: output = sparseConvertStorage<double >(in, destStorage); break;
case c32: output = sparseConvertStorage<cfloat >(in, destStorage); break;
case c64: output = sparseConvertStorage<cdouble>(in, destStorage); break;
default : AF_ERROR("Output storage type is not valid", AF_ERR_ARG);
}
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_to_dense(af_array *out, const af_array in)
{
try {
af_array output = 0;
const SparseArrayBase base = getSparseArrayBase(in);
// Dense not allowed as input -> Should never happen
// To convert from dense to type, use the create* functions
ARG_ASSERT(1, base.getStorage() != AF_STORAGE_DENSE);
switch(base.getType()) {
case f32: output = sparseConvertStorage<float >(in, AF_STORAGE_DENSE); break;
case f64: output = sparseConvertStorage<double >(in, AF_STORAGE_DENSE); break;
case c32: output = sparseConvertStorage<cfloat >(in, AF_STORAGE_DENSE); break;
case c64: output = sparseConvertStorage<cdouble>(in, AF_STORAGE_DENSE); break;
default : AF_ERROR("Output storage type is not valid", AF_ERR_ARG);
}
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Get Functions
////////////////////////////////////////////////////////////////////////////////
template<typename T>
af_array getSparseValues(const af_array in)
{
return getHandle(getSparseArray<T>(in).getValues());
}
af_err af_sparse_get_info(af_array *values, af_array *rows, af_array *cols, af_storage *stype,
const af_array in)
{
try {
if(values != NULL) AF_CHECK(af_sparse_get_values(values, in));
if(rows != NULL) AF_CHECK(af_sparse_get_row_idx(rows , in));
if(cols != NULL) AF_CHECK(af_sparse_get_col_idx(cols , in));
if(stype != NULL) AF_CHECK(af_sparse_get_storage(stype, in));
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_values(af_array *out, const af_array in)
{
try{
const SparseArrayBase base = getSparseArrayBase(in);
af_array output = 0;
switch(base.getType()) {
case f32: output = getSparseValues<float >(in); break;
case f64: output = getSparseValues<double >(in); break;
case c32: output = getSparseValues<cfloat >(in); break;
case c64: output = getSparseValues<cdouble>(in); break;
default : TYPE_ERROR(1, base.getType());
}
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_row_idx(af_array *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = getHandle(base.getRowIdx());
} CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_col_idx(af_array *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = getHandle(base.getColIdx());
} CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_nnz(dim_t *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = base.getNNZ();
} CATCHALL;
return AF_SUCCESS;
}
af_err af_sparse_get_storage(af_storage *out, const af_array in)
{
try {
const SparseArrayBase base = getSparseArrayBase(in);
*out = base.getStorage();
} CATCHALL;
return AF_SUCCESS;
}
<|endoftext|> |
<commit_before>//===-- iConstPool.cpp - Implement ConstPool instructions --------*- C++ -*--=//
//
// This file implements the ConstPool* classes...
//
//===----------------------------------------------------------------------===//
#define __STDC_LIMIT_MACROS // Get defs for INT64_MAX and friends...
#include "llvm/ConstPoolVals.h"
#include "llvm/ConstantPool.h"
#include "llvm/Tools/StringExtras.h" // itostr
#include "llvm/DerivedTypes.h"
#include "llvm/SymbolTable.h"
#include <algorithm>
#include <assert.h>
//===----------------------------------------------------------------------===//
// ConstantPool Class
//===----------------------------------------------------------------------===//
void ConstantPool::setParent(SymTabValue *STV) {
Parent = STV;
for (unsigned i = 0; i < Planes.size(); i++)
Planes[i]->setParent(Parent);
}
const Value *ConstantPool::getParentV() const { return Parent->getSTVParent(); }
Value *ConstantPool::getParentV() { return Parent->getSTVParent(); }
// Constant getPlane - Returns true if the type plane does not exist, otherwise
// updates the pointer to point to the correct plane.
//
bool ConstantPool::getPlane(const Type *T, const PlaneType *&Plane) const {
unsigned Ty = T->getUniqueID();
if (Ty >= Planes.size()) return true;
Plane = Planes[Ty];
return false;
}
// Constant getPlane - Returns true if the type plane does not exist, otherwise
// updates the pointer to point to the correct plane.
//
bool ConstantPool::getPlane(const Type *T, PlaneType *&Plane) {
unsigned Ty = T->getUniqueID();
if (Ty >= Planes.size()) return true;
Plane = Planes[Ty];
return false;
}
void ConstantPool::resize(unsigned size) {
unsigned oldSize = Planes.size();
Planes.resize(size, 0);
while (oldSize < size)
Planes[oldSize++] = new PlaneType(Parent, Parent);
}
ConstantPool::PlaneType &ConstantPool::getPlane(const Type *T) {
unsigned Ty = T->getUniqueID();
if (Ty >= Planes.size()) resize(Ty+1);
return *Planes[Ty];
}
// insert - Add constant into the symbol table...
void ConstantPool::insert(ConstPoolVal *N) {
unsigned Ty = N->getType()->getUniqueID();
if (Ty >= Planes.size()) resize(Ty+1);
Planes[Ty]->push_back(N);
}
bool ConstantPool::remove(ConstPoolVal *N) {
unsigned Ty = N->getType()->getUniqueID();
if (Ty >= Planes.size()) return true; // Doesn't contain any of that type
PlaneType::iterator I = ::find(Planes[Ty]->begin(), Planes[Ty]->end(), N);
if (I == Planes[Ty]->end()) return true;
Planes[Ty]->remove(I);
return false;
}
void ConstantPool::delete_all() {
dropAllReferences();
for (unsigned i = 0; i < Planes.size(); i++) {
Planes[i]->delete_all();
Planes[i]->setParent(0);
delete Planes[i];
}
Planes.clear();
}
void ConstantPool::dropAllReferences() {
for (unsigned i = 0; i < Planes.size(); i++)
for_each(Planes[i]->begin(), Planes[i]->end(),
mem_fun(&ConstPoolVal::dropAllReferences));
}
struct EqualsConstant {
const ConstPoolVal *v;
inline EqualsConstant(const ConstPoolVal *V) { v = V; }
inline bool operator()(const ConstPoolVal *V) const {
return v->equals(V);
}
};
ConstPoolVal *ConstantPool::find(const ConstPoolVal *V) {
const PlaneType *P;
if (getPlane(V->getType(), P)) return 0;
PlaneType::const_iterator PI = find_if(P->begin(), P->end(),
EqualsConstant(V));
if (PI == P->end()) return 0;
return *PI;
}
const ConstPoolVal *ConstantPool::find(const ConstPoolVal *V) const {
const PlaneType *P;
if (getPlane(V->getType(), P)) return 0;
PlaneType::const_iterator PI = find_if(P->begin(), P->end(),
EqualsConstant(V));
if (PI == P->end()) return 0;
return *PI;
}
ConstPoolVal *ConstantPool::find(const Type *Ty) {
const PlaneType *P;
if (getPlane(Type::TypeTy, P)) return 0;
// TODO: This is kinda silly
ConstPoolType V(Ty);
PlaneType::const_iterator PI =
find_if(P->begin(), P->end(), EqualsConstant(&V));
if (PI == P->end()) return 0;
return *PI;
}
const ConstPoolVal *ConstantPool::find(const Type *Ty) const {
const PlaneType *P;
if (getPlane(Type::TypeTy, P)) return 0;
// TODO: This is kinda silly
ConstPoolType V(Ty);
PlaneType::const_iterator PI =
find_if(P->begin(), P->end(), EqualsConstant(&V));
if (PI == P->end()) return 0;
return *PI;
}
//===----------------------------------------------------------------------===//
// ConstPoolVal Class
//===----------------------------------------------------------------------===//
// Specialize setName to take care of symbol table majik
void ConstPoolVal::setName(const string &name) {
SymTabValue *P;
if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
Value::setName(name);
if (P && hasName()) P->getSymbolTable()->insert(this);
}
// Static constructor to create a '0' constant of arbitrary type...
ConstPoolVal *ConstPoolVal::getNullConstant(const Type *Ty) {
switch (Ty->getPrimitiveID()) {
case Type::BoolTyID: return new ConstPoolBool(false);
case Type::SByteTyID:
case Type::ShortTyID:
case Type::IntTyID:
case Type::LongTyID: return new ConstPoolSInt(Ty, 0);
case Type::UByteTyID:
case Type::UShortTyID:
case Type::UIntTyID:
case Type::ULongTyID: return new ConstPoolUInt(Ty, 0);
case Type::FloatTyID:
case Type::DoubleTyID: return new ConstPoolFP(Ty, 0);
default:
return 0;
}
}
//===----------------------------------------------------------------------===//
// ConstPoolXXX Classes
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Normal Constructors
ConstPoolBool::ConstPoolBool(bool V, const string &Name = "")
: ConstPoolVal(Type::BoolTy, Name) {
Val = V;
}
ConstPoolSInt::ConstPoolSInt(const Type *Ty, int64_t V, const string &Name)
: ConstPoolVal(Ty, Name) {
//cerr << "value = " << (int)V << ": " << Ty->getName() << endl;
assert(isValueValidForType(Ty, V) && "Value to large for type!");
Val = V;
}
ConstPoolUInt::ConstPoolUInt(const Type *Ty, uint64_t V, const string &Name)
: ConstPoolVal(Ty, Name) {
//cerr << "Uvalue = " << (int)V << ": " << Ty->getName() << endl;
assert(isValueValidForType(Ty, V) && "Value to large for type!");
Val = V;
}
ConstPoolFP::ConstPoolFP(const Type *Ty, double V, const string &Name)
: ConstPoolVal(Ty, Name) {
assert(isValueValidForType(Ty, V) && "Value to large for type!");
Val = V;
}
ConstPoolType::ConstPoolType(const Type *V, const string &Name)
: ConstPoolVal(Type::TypeTy, Name), Val(V) {
}
ConstPoolArray::ConstPoolArray(const ArrayType *T,
vector<ConstPoolVal*> &V,
const string &Name)
: ConstPoolVal(T, Name) {
for (unsigned i = 0; i < V.size(); i++) {
assert(V[i]->getType() == T->getElementType());
Operands.push_back(Use(V[i], this));
}
}
ConstPoolStruct::ConstPoolStruct(const StructType *T,
vector<ConstPoolVal*> &V,
const string &Name)
: ConstPoolVal(T, Name) {
const StructType::ElementTypes &ETypes = T->getElementTypes();
for (unsigned i = 0; i < V.size(); i++) {
assert(V[i]->getType() == ETypes[i]);
Operands.push_back(Use(V[i], this));
}
}
//===----------------------------------------------------------------------===//
// Copy Constructors
ConstPoolBool::ConstPoolBool(const ConstPoolBool &CPB)
: ConstPoolVal(Type::BoolTy) {
Val = CPB.Val;
}
ConstPoolSInt::ConstPoolSInt(const ConstPoolSInt &CPSI)
: ConstPoolVal(CPSI.getType()) {
Val = CPSI.Val;
}
ConstPoolUInt::ConstPoolUInt(const ConstPoolUInt &CPUI)
: ConstPoolVal(CPUI.getType()) {
Val = CPUI.Val;
}
ConstPoolFP::ConstPoolFP(const ConstPoolFP &CPFP)
: ConstPoolVal(CPFP.getType()) {
Val = CPFP.Val;
}
ConstPoolType::ConstPoolType(const ConstPoolType &CPT)
: ConstPoolVal(Type::TypeTy), Val(CPT.Val) {
}
ConstPoolArray::ConstPoolArray(const ConstPoolArray &CPA)
: ConstPoolVal(CPA.getType()) {
for (unsigned i = 0; i < CPA.Operands.size(); i++)
Operands.push_back(Use(CPA.Operands[i], this));
}
ConstPoolStruct::ConstPoolStruct(const ConstPoolStruct &CPS)
: ConstPoolVal(CPS.getType()) {
for (unsigned i = 0; i < CPS.Operands.size(); i++)
Operands.push_back(Use(CPS.Operands[i], this));
}
//===----------------------------------------------------------------------===//
// getStrValue implementations
string ConstPoolBool::getStrValue() const {
return Val ? "true" : "false";
}
string ConstPoolSInt::getStrValue() const {
return itostr(Val);
}
string ConstPoolUInt::getStrValue() const {
return utostr(Val);
}
string ConstPoolFP::getStrValue() const {
return ftostr(Val);
}
string ConstPoolType::getStrValue() const {
return Val->getName();
}
string ConstPoolArray::getStrValue() const {
string Result = "[";
if (Operands.size()) {
Result += " " + Operands[0]->getType()->getName() +
" " + Operands[0]->castConstantAsserting()->getStrValue();
for (unsigned i = 1; i < Operands.size(); i++)
Result += ", " + Operands[i]->getType()->getName() +
" " + Operands[i]->castConstantAsserting()->getStrValue();
}
return Result + " ]";
}
string ConstPoolStruct::getStrValue() const {
string Result = "{";
if (Operands.size()) {
Result += " " + Operands[0]->getType()->getName() +
" " + Operands[0]->castConstantAsserting()->getStrValue();
for (unsigned i = 1; i < Operands.size(); i++)
Result += ", " + Operands[i]->getType()->getName() +
" " + Operands[i]->castConstantAsserting()->getStrValue();
}
return Result + " }";
}
//===----------------------------------------------------------------------===//
// equals implementations
bool ConstPoolBool::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolBool*)V)->getValue() == Val;
}
bool ConstPoolSInt::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolSInt*)V)->getValue() == Val;
}
bool ConstPoolUInt::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolUInt*)V)->getValue() == Val;
}
bool ConstPoolFP::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolFP*)V)->getValue() == Val;
}
bool ConstPoolType::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolType*)V)->getValue() == Val;
}
bool ConstPoolArray::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
ConstPoolArray *AV = (ConstPoolArray*)V;
if (Operands.size() != AV->Operands.size()) return false;
for (unsigned i = 0; i < Operands.size(); i++)
if (!Operands[i]->castConstantAsserting()->equals(
AV->Operands[i]->castConstantAsserting()))
return false;
return true;
}
bool ConstPoolStruct::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
ConstPoolStruct *SV = (ConstPoolStruct*)V;
if (Operands.size() != SV->Operands.size()) return false;
for (unsigned i = 0; i < Operands.size(); i++)
if (!Operands[i]->castConstantAsserting()->equals(
SV->Operands[i]->castConstantAsserting()))
return false;
return true;
}
//===----------------------------------------------------------------------===//
// isValueValidForType implementations
bool ConstPoolSInt::isValueValidForType(const Type *Ty, int64_t Val) {
switch (Ty->getPrimitiveID()) {
default:
return false; // These can't be represented as integers!!!
// Signed types...
case Type::SByteTyID:
return (Val <= INT8_MAX && Val >= INT8_MIN);
case Type::ShortTyID:
return (Val <= INT16_MAX && Val >= INT16_MIN);
case Type::IntTyID:
return (Val <= INT32_MAX && Val >= INT32_MIN);
case Type::LongTyID:
return true; // This is the largest type...
}
assert(0 && "WTF?");
return false;
}
bool ConstPoolUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
switch (Ty->getPrimitiveID()) {
default:
return false; // These can't be represented as integers!!!
// Unsigned types...
case Type::UByteTyID:
return (Val <= UINT8_MAX);
case Type::UShortTyID:
return (Val <= UINT16_MAX);
case Type::UIntTyID:
return (Val <= UINT32_MAX);
case Type::ULongTyID:
return true; // This is the largest type...
}
assert(0 && "WTF?");
return false;
}
bool ConstPoolFP::isValueValidForType(const Type *Ty, double Val) {
switch (Ty->getPrimitiveID()) {
default:
return false; // These can't be represented as floating point!
// TODO: Figure out how to test if a double can be cast to a float!
case Type::FloatTyID:
/*
return (Val <= UINT8_MAX);
*/
case Type::DoubleTyID:
return true; // This is the largest type...
}
};
<commit_msg>Implement ensureTypeAvailable Implement ConstPoolInt class<commit_after>//===-- iConstPool.cpp - Implement ConstPool instructions --------*- C++ -*--=//
//
// This file implements the ConstPool* classes...
//
//===----------------------------------------------------------------------===//
#define __STDC_LIMIT_MACROS // Get defs for INT64_MAX and friends...
#include "llvm/ConstPoolVals.h"
#include "llvm/ConstantPool.h"
#include "llvm/Tools/StringExtras.h" // itostr
#include "llvm/DerivedTypes.h"
#include "llvm/SymbolTable.h"
#include <algorithm>
#include <assert.h>
//===----------------------------------------------------------------------===//
// ConstantPool Class
//===----------------------------------------------------------------------===//
void ConstantPool::setParent(SymTabValue *STV) {
Parent = STV;
for (unsigned i = 0; i < Planes.size(); i++)
Planes[i]->setParent(Parent);
}
const Value *ConstantPool::getParentV() const { return Parent->getSTVParent(); }
Value *ConstantPool::getParentV() { return Parent->getSTVParent(); }
// Constant getPlane - Returns true if the type plane does not exist, otherwise
// updates the pointer to point to the correct plane.
//
bool ConstantPool::getPlane(const Type *T, const PlaneType *&Plane) const {
unsigned Ty = T->getUniqueID();
if (Ty >= Planes.size()) return true;
Plane = Planes[Ty];
return false;
}
// Constant getPlane - Returns true if the type plane does not exist, otherwise
// updates the pointer to point to the correct plane.
//
bool ConstantPool::getPlane(const Type *T, PlaneType *&Plane) {
unsigned Ty = T->getUniqueID();
if (Ty >= Planes.size()) return true;
Plane = Planes[Ty];
return false;
}
void ConstantPool::resize(unsigned size) {
unsigned oldSize = Planes.size();
Planes.resize(size, 0);
while (oldSize < size)
Planes[oldSize++] = new PlaneType(Parent, Parent);
}
ConstantPool::PlaneType &ConstantPool::getPlane(const Type *T) {
unsigned Ty = T->getUniqueID();
if (Ty >= Planes.size()) resize(Ty+1);
return *Planes[Ty];
}
// insert - Add constant into the symbol table...
void ConstantPool::insert(ConstPoolVal *N) {
unsigned Ty = N->getType()->getUniqueID();
if (Ty >= Planes.size()) resize(Ty+1);
Planes[Ty]->push_back(N);
}
bool ConstantPool::remove(ConstPoolVal *N) {
unsigned Ty = N->getType()->getUniqueID();
if (Ty >= Planes.size()) return true; // Doesn't contain any of that type
PlaneType::iterator I = ::find(Planes[Ty]->begin(), Planes[Ty]->end(), N);
if (I == Planes[Ty]->end()) return true;
Planes[Ty]->remove(I);
return false;
}
void ConstantPool::delete_all() {
dropAllReferences();
for (unsigned i = 0; i < Planes.size(); i++) {
Planes[i]->delete_all();
Planes[i]->setParent(0);
delete Planes[i];
}
Planes.clear();
}
void ConstantPool::dropAllReferences() {
for (unsigned i = 0; i < Planes.size(); i++)
for_each(Planes[i]->begin(), Planes[i]->end(),
mem_fun(&ConstPoolVal::dropAllReferences));
}
struct EqualsConstant {
const ConstPoolVal *v;
inline EqualsConstant(const ConstPoolVal *V) { v = V; }
inline bool operator()(const ConstPoolVal *V) const {
return v->equals(V);
}
};
ConstPoolVal *ConstantPool::find(const ConstPoolVal *V) {
const PlaneType *P;
if (getPlane(V->getType(), P)) return 0;
PlaneType::const_iterator PI = find_if(P->begin(), P->end(),
EqualsConstant(V));
if (PI == P->end()) return 0;
return *PI;
}
const ConstPoolVal *ConstantPool::find(const ConstPoolVal *V) const {
const PlaneType *P;
if (getPlane(V->getType(), P)) return 0;
PlaneType::const_iterator PI = find_if(P->begin(), P->end(),
EqualsConstant(V));
if (PI == P->end()) return 0;
return *PI;
}
ConstPoolVal *ConstantPool::find(const Type *Ty) {
const PlaneType *P;
if (getPlane(Type::TypeTy, P)) return 0;
// TODO: This is kinda silly
ConstPoolType V(Ty);
PlaneType::const_iterator PI =
find_if(P->begin(), P->end(), EqualsConstant(&V));
if (PI == P->end()) return 0;
return *PI;
}
const ConstPoolVal *ConstantPool::find(const Type *Ty) const {
const PlaneType *P;
if (getPlane(Type::TypeTy, P)) return 0;
// TODO: This is kinda silly
ConstPoolType V(Ty);
PlaneType::const_iterator PI =
find_if(P->begin(), P->end(), EqualsConstant(&V));
if (PI == P->end()) return 0;
return *PI;
}
struct EqualsType {
const Type *T;
inline EqualsType(const Type *t) { T = t; }
inline bool operator()(const ConstPoolVal *CPV) const {
return static_cast<const ConstPoolType*>(CPV)->getValue() == T;
}
};
// ensureTypeAvailable - This is used to make sure that the specified type is
// in the constant pool. If it is not already in the constant pool, it is
// added.
//
const Type *ConstantPool::ensureTypeAvailable(const Type *Ty) {
// Get the type type plane...
PlaneType &P = getPlane(Type::TypeTy);
PlaneType::const_iterator PI = find_if(P.begin(), P.end(), EqualsType(Ty));
if (PI == P.end()) {
ConstPoolVal *CPT = new ConstPoolType(Ty);
insert(CPT);
}
return Ty;
}
//===----------------------------------------------------------------------===//
// ConstPoolVal Class
//===----------------------------------------------------------------------===//
// Specialize setName to take care of symbol table majik
void ConstPoolVal::setName(const string &name) {
SymTabValue *P;
if ((P = getParent()) && hasName()) P->getSymbolTable()->remove(this);
Value::setName(name);
if (P && hasName()) P->getSymbolTable()->insert(this);
}
// Static constructor to create a '0' constant of arbitrary type...
ConstPoolVal *ConstPoolVal::getNullConstant(const Type *Ty) {
switch (Ty->getPrimitiveID()) {
case Type::BoolTyID: return new ConstPoolBool(false);
case Type::SByteTyID:
case Type::ShortTyID:
case Type::IntTyID:
case Type::LongTyID: return new ConstPoolSInt(Ty, 0);
case Type::UByteTyID:
case Type::UShortTyID:
case Type::UIntTyID:
case Type::ULongTyID: return new ConstPoolUInt(Ty, 0);
case Type::FloatTyID:
case Type::DoubleTyID: return new ConstPoolFP(Ty, 0);
default:
return 0;
}
}
//===----------------------------------------------------------------------===//
// ConstPoolXXX Classes
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Normal Constructors
ConstPoolBool::ConstPoolBool(bool V, const string &Name = "")
: ConstPoolVal(Type::BoolTy, Name) {
Val = V;
}
ConstPoolInt::ConstPoolInt(const Type *Ty, uint64_t V, const string &Name)
: ConstPoolVal(Ty, Name) { Val.Unsigned = V; }
ConstPoolInt::ConstPoolInt(const Type *Ty, int64_t V, const string &Name)
: ConstPoolVal(Ty, Name) { Val.Signed = V; }
ConstPoolSInt::ConstPoolSInt(const Type *Ty, int64_t V, const string &Name)
: ConstPoolInt(Ty, V, Name) {
//cerr << "value = " << (int)V << ": " << Ty->getName() << endl;
assert(isValueValidForType(Ty, V) && "Value too large for type!");
}
ConstPoolUInt::ConstPoolUInt(const Type *Ty, uint64_t V, const string &Name)
: ConstPoolInt(Ty, V, Name) {
//cerr << "Uvalue = " << (int)V << ": " << Ty->getName() << endl;
assert(isValueValidForType(Ty, V) && "Value too large for type!");
}
ConstPoolFP::ConstPoolFP(const Type *Ty, double V, const string &Name)
: ConstPoolVal(Ty, Name) {
assert(isValueValidForType(Ty, V) && "Value too large for type!");
Val = V;
}
ConstPoolType::ConstPoolType(const Type *V, const string &Name)
: ConstPoolVal(Type::TypeTy, Name), Val(V) {
}
ConstPoolArray::ConstPoolArray(const ArrayType *T,
vector<ConstPoolVal*> &V,
const string &Name)
: ConstPoolVal(T, Name) {
for (unsigned i = 0; i < V.size(); i++) {
assert(V[i]->getType() == T->getElementType());
Operands.push_back(Use(V[i], this));
}
}
ConstPoolStruct::ConstPoolStruct(const StructType *T,
vector<ConstPoolVal*> &V,
const string &Name)
: ConstPoolVal(T, Name) {
const StructType::ElementTypes &ETypes = T->getElementTypes();
for (unsigned i = 0; i < V.size(); i++) {
assert(V[i]->getType() == ETypes[i]);
Operands.push_back(Use(V[i], this));
}
}
//===----------------------------------------------------------------------===//
// Copy Constructors
ConstPoolBool::ConstPoolBool(const ConstPoolBool &CPB)
: ConstPoolVal(Type::BoolTy) {
Val = CPB.Val;
}
ConstPoolInt::ConstPoolInt(const ConstPoolInt &CPI)
: ConstPoolVal(CPI.getType()) {
Val.Signed = CPI.Val.Signed;
}
ConstPoolFP::ConstPoolFP(const ConstPoolFP &CPFP)
: ConstPoolVal(CPFP.getType()) {
Val = CPFP.Val;
}
ConstPoolType::ConstPoolType(const ConstPoolType &CPT)
: ConstPoolVal(Type::TypeTy), Val(CPT.Val) {
}
ConstPoolArray::ConstPoolArray(const ConstPoolArray &CPA)
: ConstPoolVal(CPA.getType()) {
for (unsigned i = 0; i < CPA.Operands.size(); i++)
Operands.push_back(Use(CPA.Operands[i], this));
}
ConstPoolStruct::ConstPoolStruct(const ConstPoolStruct &CPS)
: ConstPoolVal(CPS.getType()) {
for (unsigned i = 0; i < CPS.Operands.size(); i++)
Operands.push_back(Use(CPS.Operands[i], this));
}
//===----------------------------------------------------------------------===//
// getStrValue implementations
string ConstPoolBool::getStrValue() const {
return Val ? "true" : "false";
}
string ConstPoolSInt::getStrValue() const {
return itostr(Val.Signed);
}
string ConstPoolUInt::getStrValue() const {
return utostr(Val.Unsigned);
}
string ConstPoolFP::getStrValue() const {
return ftostr(Val);
}
string ConstPoolType::getStrValue() const {
return Val->getName();
}
string ConstPoolArray::getStrValue() const {
string Result = "[";
if (Operands.size()) {
Result += " " + Operands[0]->getType()->getName() +
" " + Operands[0]->castConstantAsserting()->getStrValue();
for (unsigned i = 1; i < Operands.size(); i++)
Result += ", " + Operands[i]->getType()->getName() +
" " + Operands[i]->castConstantAsserting()->getStrValue();
}
return Result + " ]";
}
string ConstPoolStruct::getStrValue() const {
string Result = "{";
if (Operands.size()) {
Result += " " + Operands[0]->getType()->getName() +
" " + Operands[0]->castConstantAsserting()->getStrValue();
for (unsigned i = 1; i < Operands.size(); i++)
Result += ", " + Operands[i]->getType()->getName() +
" " + Operands[i]->castConstantAsserting()->getStrValue();
}
return Result + " }";
}
//===----------------------------------------------------------------------===//
// equals implementations
bool ConstPoolBool::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolBool*)V)->getValue() == Val;
}
bool ConstPoolInt::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolInt*)V)->Val.Signed == Val.Signed;
}
bool ConstPoolFP::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolFP*)V)->getValue() == Val;
}
bool ConstPoolType::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
return ((ConstPoolType*)V)->getValue() == Val;
}
bool ConstPoolArray::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
ConstPoolArray *AV = (ConstPoolArray*)V;
if (Operands.size() != AV->Operands.size()) return false;
for (unsigned i = 0; i < Operands.size(); i++)
if (!Operands[i]->castConstantAsserting()->equals(
AV->Operands[i]->castConstantAsserting()))
return false;
return true;
}
bool ConstPoolStruct::equals(const ConstPoolVal *V) const {
assert(getType() == V->getType());
ConstPoolStruct *SV = (ConstPoolStruct*)V;
if (Operands.size() != SV->Operands.size()) return false;
for (unsigned i = 0; i < Operands.size(); i++)
if (!Operands[i]->castConstantAsserting()->equals(
SV->Operands[i]->castConstantAsserting()))
return false;
return true;
}
//===----------------------------------------------------------------------===//
// isValueValidForType implementations
bool ConstPoolSInt::isValueValidForType(const Type *Ty, int64_t Val) {
switch (Ty->getPrimitiveID()) {
default:
return false; // These can't be represented as integers!!!
// Signed types...
case Type::SByteTyID:
return (Val <= INT8_MAX && Val >= INT8_MIN);
case Type::ShortTyID:
return (Val <= INT16_MAX && Val >= INT16_MIN);
case Type::IntTyID:
return (Val <= INT32_MAX && Val >= INT32_MIN);
case Type::LongTyID:
return true; // This is the largest type...
}
assert(0 && "WTF?");
return false;
}
bool ConstPoolUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
switch (Ty->getPrimitiveID()) {
default:
return false; // These can't be represented as integers!!!
// Unsigned types...
case Type::UByteTyID:
return (Val <= UINT8_MAX);
case Type::UShortTyID:
return (Val <= UINT16_MAX);
case Type::UIntTyID:
return (Val <= UINT32_MAX);
case Type::ULongTyID:
return true; // This is the largest type...
}
assert(0 && "WTF?");
return false;
}
bool ConstPoolFP::isValueValidForType(const Type *Ty, double Val) {
switch (Ty->getPrimitiveID()) {
default:
return false; // These can't be represented as floating point!
// TODO: Figure out how to test if a double can be cast to a float!
case Type::FloatTyID:
/*
return (Val <= UINT8_MAX);
*/
case Type::DoubleTyID:
return true; // This is the largest type...
}
};
//===----------------------------------------------------------------------===//
// Extra Method implementations
ConstPoolInt *ConstPoolInt::get(const Type *Ty, unsigned char V) {
assert(V <= 127 && "equals: Can only be used with very small constants!");
if (Ty->isSigned()) return new ConstPoolSInt(Ty, V);
return new ConstPoolUInt(Ty, V);
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <af/array.h>
#include <ArrayInfo.hpp>
#include <handle.hpp>
#include <backend.hpp>
#include <err_common.hpp>
#include <type_util.hpp>
#include <af/index.h>
using namespace detail;
#define STREAM_FORMAT_VERSION 0x1
static const char sfv_char = STREAM_FORMAT_VERSION;
template<typename T>
static int save(const char *key, const af_array arr, const char *filename, const bool append = false)
{
// (char ) Version (Once)
// (int ) No. of Arrays (Once)
// (int ) Length of the key
// (cstring) Key
// (intl ) Offset bytes to next array (type + dims + data)
// (char ) Type
// (intl ) dim4 (x 4)
// (T ) data (x elements)
// Setup all the data structures that need to be written to file
///////////////////////////////////////////////////////////////////////////
std::string k(key);
int klen = k.size();
const ArrayInfo info = getInfo(arr);
std::vector<T> data(info.elements());
AF_CHECK(af_get_data_ptr(&data.front(), arr));
char type = info.getType();
intl odims[4];
for(int i = 0; i < 4; i++) {
odims[i] = info.dims()[i];
}
intl offset = sizeof(char) + 4 * sizeof(intl) + info.elements() * sizeof(T);
///////////////////////////////////////////////////////////////////////////
std::fstream fs;
int n_arrays = 0;
if(append) {
std::ifstream checkIfExists(filename);
bool exists = checkIfExists.good();
checkIfExists.close();
if(exists) {
fs.open(filename, std::fstream::in | std::fstream::out | std::fstream::binary);
} else {
fs.open(filename, std::fstream::out | std::fstream::binary);
}
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
// Assert Version
if(fs.peek() == std::fstream::traits_type::eof()) {
// File is empty
fs.clear();
} else {
char prev_version = 0;
fs.read(&prev_version, sizeof(char));
AF_ASSERT(prev_version == sfv_char, "ArrayFire data format has changed. Can't append to file");
fs.read((char*)&n_arrays, sizeof(int));
}
} else {
fs.open(filename, std::fstream::out | std::fstream::binary | std::fstream::trunc);
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
}
n_arrays++;
// Write version and n_arrays to top of file
fs.seekp(0);
fs.write(&sfv_char, 1);
fs.write((char*)&n_arrays, sizeof(int));
// Write array to end of file. Irrespective of new or append
fs.seekp(0, std::ios_base::end);
fs.write((char*)&klen, sizeof(int));
fs.write(k.c_str(), klen);
fs.write((char*)&offset, sizeof(intl));
fs.write(&type, sizeof(char));
fs.write((char*)&odims, sizeof(intl) * 4);
fs.write((char*)&data.front(), sizeof(T) * data.size());
fs.close();
return n_arrays - 1;
}
af_err af_save_array(int *index, const char *key, const af_array arr, const char *filename, const bool append)
{
try {
ARG_ASSERT(0, key != NULL);
ARG_ASSERT(2, filename != NULL);
ArrayInfo info = getInfo(arr);
af_dtype type = info.getType();
int id = -1;
switch(type) {
case f32: id = save<float> (key, arr, filename, append); break;
case c32: id = save<cfloat> (key, arr, filename, append); break;
case f64: id = save<double> (key, arr, filename, append); break;
case c64: id = save<cdouble> (key, arr, filename, append); break;
case b8: id = save<char> (key, arr, filename, append); break;
case s32: id = save<int> (key, arr, filename, append); break;
case u32: id = save<unsigned>(key, arr, filename, append); break;
case u8: id = save<uchar> (key, arr, filename, append); break;
case s64: id = save<intl> (key, arr, filename, append); break;
case u64: id = save<uintl> (key, arr, filename, append); break;
case s16: id = save<short> (key, arr, filename, append); break;
case u16: id = save<ushort> (key, arr, filename, append); break;
default: TYPE_ERROR(1, type);
}
std::swap(*index, id);
}
CATCHALL;
return AF_SUCCESS;
}
template<typename T>
static af_array readDataToArray(std::fstream &fs)
{
intl dims[4];
fs.read((char*)&dims, 4 * sizeof(intl));
dim4 d;
for(int i = 0; i < 4; i++) {
d[i] = dims[i];
}
intl size = d.elements();
std::vector<T> data(size);
fs.read((char*)&data.front(), size * sizeof(T));
return getHandle(createHostDataArray<T>(d, &data.front()));
}
static af_array readArrayV1(const char *filename, const unsigned index)
{
char version = 0;
int n_arrays = 0;
std::fstream fs(filename, std::fstream::in | std::fstream::binary);
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
if(fs.peek() == std::fstream::traits_type::eof()) {
AF_ERROR("File is empty", AF_ERR_ARG);
}
fs.read(&version, sizeof(char));
fs.read((char*)&n_arrays, sizeof(int));
AF_ASSERT((int)index < n_arrays, "Index out of bounds");
for(int i = 0; i < (int)index; i++) {
// (int ) Length of the key
// (cstring) Key
// (intl ) Offset bytes to next array (type + dims + data)
// (char ) Type
// (intl ) dim4 (x 4)
// (T ) data (x elements)
int klen = -1;
fs.read((char*)&klen, sizeof(int));
//char* key = new char[klen];
//fs.read((char*)&key, klen * sizeof(char));
// Skip the array name tag
fs.seekg(klen, std::ios_base::cur);
// Read data offset
intl offset = -1;
fs.read((char*)&offset, sizeof(intl));
// Skip data
fs.seekg(offset, std::ios_base::cur);
}
int klen = -1;
fs.read((char*)&klen, sizeof(int));
//char* key = new char[klen];
//fs.read((char*)&key, klen * sizeof(char));
// Skip the array name tag
fs.seekg(klen, std::ios_base::cur);
// Read data offset
intl offset = -1;
fs.read((char*)&offset, sizeof(intl));
// Read type and dims
char type_ = -1;
fs.read(&type_, sizeof(char));
af_dtype type = (af_dtype)type_;
af_array out;
switch(type) {
case f32 : out = readDataToArray<float> (fs); break;
case c32 : out = readDataToArray<cfloat> (fs); break;
case f64 : out = readDataToArray<double> (fs); break;
case c64 : out = readDataToArray<cdouble>(fs); break;
case b8 : out = readDataToArray<char> (fs); break;
case s32 : out = readDataToArray<int> (fs); break;
case u32 : out = readDataToArray<uint> (fs); break;
case u8 : out = readDataToArray<uchar> (fs); break;
case s64 : out = readDataToArray<intl> (fs); break;
case u64 : out = readDataToArray<uintl> (fs); break;
case s16 : out = readDataToArray<short> (fs); break;
case u16 : out = readDataToArray<ushort> (fs); break;
default: TYPE_ERROR(1, type);
}
fs.close();
return out;
}
static af_array checkVersionAndRead(const char *filename, const unsigned index)
{
char version = 0;
std::fstream fs(filename, std::fstream::in | std::fstream::binary);
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
if(fs.peek() == std::fstream::traits_type::eof()) {
AF_ERROR("File is empty", AF_ERR_ARG);
} else {
fs.read(&version, sizeof(char));
}
fs.close();
switch(version) {
case 1: return readArrayV1(filename, index);
default: AF_ERROR("Invalid version", AF_ERR_ARG);
}
}
int checkVersionAndFindIndex(const char *filename, const char *k)
{
char version = 0;
std::string key(k);
std::ifstream fs(filename, std::ifstream::in | std::ifstream::binary);
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
if(fs.peek() == std::ifstream::traits_type::eof()) {
AF_ERROR("File is empty", AF_ERR_ARG);
} else {
fs.read(&version, sizeof(char));
}
int index = -1;
if(version == 1) {
int n_arrays = -1;
fs.read((char*)&n_arrays, sizeof(int));
for(int i = 0; i < n_arrays; i++) {
int klen = -1;
fs.read((char*)&klen, sizeof(int));
char *readKey = new char[klen + 1];
fs.read(readKey, klen);
readKey[klen] = '\0';
if(key == readKey) {
// Ket matches, break
index = i;
delete [] readKey;
break;
} else {
// Key doesn't match. Skip the data
intl offset = -1;
fs.read((char*)&offset, sizeof(intl));
fs.seekg(offset, std::ios_base::cur);
delete [] readKey;
}
}
} else {
AF_ERROR("Invalid version", AF_ERR_ARG);
}
fs.close();
return index;
}
af_err af_read_array_index(af_array *out, const char *filename, const unsigned index)
{
try {
AF_CHECK(af_init());
ARG_ASSERT(1, filename != NULL);
af_array output = checkVersionAndRead(filename, index);
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_read_array_key(af_array *out, const char *filename, const char *key)
{
try {
AF_CHECK(af_init());
ARG_ASSERT(1, filename != NULL);
ARG_ASSERT(2, key != NULL);
// Find index of key. Then call read by index
int index = checkVersionAndFindIndex(filename, key);
if(index == -1)
AF_ERROR("Key not found", AF_ERR_INVALID_ARRAY);
af_array output = checkVersionAndRead(filename, index);
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_read_array_key_check(int *index, const char *filename, const char* key)
{
try {
ARG_ASSERT(1, filename != NULL);
ARG_ASSERT(2, key != NULL);
AF_CHECK(af_init());
// Find index of key. Then call read by index
int id = checkVersionAndFindIndex(filename, key);
std::swap(*index, id);
}
CATCHALL;
return AF_SUCCESS;
}
<commit_msg>Cleaning up error messages in loading and saving files<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <af/array.h>
#include <ArrayInfo.hpp>
#include <handle.hpp>
#include <backend.hpp>
#include <err_common.hpp>
#include <type_util.hpp>
#include <af/index.h>
using namespace detail;
#define STREAM_FORMAT_VERSION 0x1
static const char sfv_char = STREAM_FORMAT_VERSION;
template<typename T>
static int save(const char *key, const af_array arr, const char *filename, const bool append = false)
{
// (char ) Version (Once)
// (int ) No. of Arrays (Once)
// (int ) Length of the key
// (cstring) Key
// (intl ) Offset bytes to next array (type + dims + data)
// (char ) Type
// (intl ) dim4 (x 4)
// (T ) data (x elements)
// Setup all the data structures that need to be written to file
///////////////////////////////////////////////////////////////////////////
std::string k(key);
int klen = k.size();
const ArrayInfo info = getInfo(arr);
std::vector<T> data(info.elements());
AF_CHECK(af_get_data_ptr(&data.front(), arr));
char type = info.getType();
intl odims[4];
for(int i = 0; i < 4; i++) {
odims[i] = info.dims()[i];
}
intl offset = sizeof(char) + 4 * sizeof(intl) + info.elements() * sizeof(T);
///////////////////////////////////////////////////////////////////////////
std::fstream fs;
int n_arrays = 0;
if(append) {
std::ifstream checkIfExists(filename);
bool exists = checkIfExists.good();
checkIfExists.close();
if(exists) {
fs.open(filename, std::fstream::in | std::fstream::out | std::fstream::binary);
} else {
fs.open(filename, std::fstream::out | std::fstream::binary);
}
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
// Assert Version
if(fs.peek() == std::fstream::traits_type::eof()) {
// File is empty
fs.clear();
} else {
char prev_version = 0;
fs.read(&prev_version, sizeof(char));
AF_ASSERT(prev_version == sfv_char, "ArrayFire data format has changed. Can't append to file");
fs.read((char*)&n_arrays, sizeof(int));
}
} else {
fs.open(filename, std::fstream::out | std::fstream::binary | std::fstream::trunc);
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
}
n_arrays++;
// Write version and n_arrays to top of file
fs.seekp(0);
fs.write(&sfv_char, 1);
fs.write((char*)&n_arrays, sizeof(int));
// Write array to end of file. Irrespective of new or append
fs.seekp(0, std::ios_base::end);
fs.write((char*)&klen, sizeof(int));
fs.write(k.c_str(), klen);
fs.write((char*)&offset, sizeof(intl));
fs.write(&type, sizeof(char));
fs.write((char*)&odims, sizeof(intl) * 4);
fs.write((char*)&data.front(), sizeof(T) * data.size());
fs.close();
return n_arrays - 1;
}
af_err af_save_array(int *index, const char *key, const af_array arr, const char *filename, const bool append)
{
try {
ARG_ASSERT(0, key != NULL);
ARG_ASSERT(2, filename != NULL);
ArrayInfo info = getInfo(arr);
af_dtype type = info.getType();
int id = -1;
switch(type) {
case f32: id = save<float> (key, arr, filename, append); break;
case c32: id = save<cfloat> (key, arr, filename, append); break;
case f64: id = save<double> (key, arr, filename, append); break;
case c64: id = save<cdouble> (key, arr, filename, append); break;
case b8: id = save<char> (key, arr, filename, append); break;
case s32: id = save<int> (key, arr, filename, append); break;
case u32: id = save<unsigned>(key, arr, filename, append); break;
case u8: id = save<uchar> (key, arr, filename, append); break;
case s64: id = save<intl> (key, arr, filename, append); break;
case u64: id = save<uintl> (key, arr, filename, append); break;
case s16: id = save<short> (key, arr, filename, append); break;
case u16: id = save<ushort> (key, arr, filename, append); break;
default: TYPE_ERROR(1, type);
}
std::swap(*index, id);
}
CATCHALL;
return AF_SUCCESS;
}
template<typename T>
static af_array readDataToArray(std::fstream &fs)
{
intl dims[4];
fs.read((char*)&dims, 4 * sizeof(intl));
dim4 d;
for(int i = 0; i < 4; i++) {
d[i] = dims[i];
}
intl size = d.elements();
std::vector<T> data(size);
fs.read((char*)&data.front(), size * sizeof(T));
return getHandle(createHostDataArray<T>(d, &data.front()));
}
static af_array readArrayV1(const char *filename, const unsigned index)
{
char version = 0;
int n_arrays = 0;
std::fstream fs(filename, std::fstream::in | std::fstream::binary);
// Throw exception if file is not open
if(!fs.is_open()) AF_ERROR("File failed to open", AF_ERR_ARG);
if(fs.peek() == std::fstream::traits_type::eof()) {
AF_ERROR("File is empty", AF_ERR_ARG);
}
fs.read(&version, sizeof(char));
fs.read((char*)&n_arrays, sizeof(int));
AF_ASSERT((int)index < n_arrays, "Index out of bounds");
for(int i = 0; i < (int)index; i++) {
// (int ) Length of the key
// (cstring) Key
// (intl ) Offset bytes to next array (type + dims + data)
// (char ) Type
// (intl ) dim4 (x 4)
// (T ) data (x elements)
int klen = -1;
fs.read((char*)&klen, sizeof(int));
//char* key = new char[klen];
//fs.read((char*)&key, klen * sizeof(char));
// Skip the array name tag
fs.seekg(klen, std::ios_base::cur);
// Read data offset
intl offset = -1;
fs.read((char*)&offset, sizeof(intl));
// Skip data
fs.seekg(offset, std::ios_base::cur);
}
int klen = -1;
fs.read((char*)&klen, sizeof(int));
//char* key = new char[klen];
//fs.read((char*)&key, klen * sizeof(char));
// Skip the array name tag
fs.seekg(klen, std::ios_base::cur);
// Read data offset
intl offset = -1;
fs.read((char*)&offset, sizeof(intl));
// Read type and dims
char type_ = -1;
fs.read(&type_, sizeof(char));
af_dtype type = (af_dtype)type_;
af_array out;
switch(type) {
case f32 : out = readDataToArray<float> (fs); break;
case c32 : out = readDataToArray<cfloat> (fs); break;
case f64 : out = readDataToArray<double> (fs); break;
case c64 : out = readDataToArray<cdouble>(fs); break;
case b8 : out = readDataToArray<char> (fs); break;
case s32 : out = readDataToArray<int> (fs); break;
case u32 : out = readDataToArray<uint> (fs); break;
case u8 : out = readDataToArray<uchar> (fs); break;
case s64 : out = readDataToArray<intl> (fs); break;
case u64 : out = readDataToArray<uintl> (fs); break;
case s16 : out = readDataToArray<short> (fs); break;
case u16 : out = readDataToArray<ushort> (fs); break;
default: TYPE_ERROR(1, type);
}
fs.close();
return out;
}
static af_array checkVersionAndRead(const char *filename, const unsigned index)
{
char version = 0;
std::string filenameStr = std::string(filename);
std::fstream fs(filenameStr, std::fstream::in | std::fstream::binary);
// Throw exception if file is not open
if(!fs.is_open()) {
std::string errStr = "Failed to open: " + filenameStr;
AF_ERROR(errStr.c_str(), AF_ERR_ARG);
}
if(fs.peek() == std::fstream::traits_type::eof()) {
std::string errStr = filenameStr + " is empty";
AF_ERROR(errStr.c_str(), AF_ERR_ARG);
} else {
fs.read(&version, sizeof(char));
}
fs.close();
switch(version) {
case 1: return readArrayV1(filename, index);
default: AF_ERROR("Invalid version", AF_ERR_ARG);
}
}
int checkVersionAndFindIndex(const char *filename, const char *k)
{
char version = 0;
std::string key(k);
std::string filenameStr(filename);
std::ifstream fs(filenameStr, std::ifstream::in | std::ifstream::binary);
// Throw exception if file is not open
if(!fs.is_open()) {
std::string errStr = "Failed to open: " + filenameStr;
AF_ERROR(errStr.c_str(), AF_ERR_ARG);
}
if(fs.peek() == std::ifstream::traits_type::eof()) {
std::string errStr = filenameStr + " is empty";
AF_ERROR(errStr.c_str(), AF_ERR_ARG);
} else {
fs.read(&version, sizeof(char));
}
int index = -1;
if(version == 1) {
int n_arrays = -1;
fs.read((char*)&n_arrays, sizeof(int));
for(int i = 0; i < n_arrays; i++) {
int klen = -1;
fs.read((char*)&klen, sizeof(int));
char *readKey = new char[klen + 1];
fs.read(readKey, klen);
readKey[klen] = '\0';
if(key == readKey) {
// Ket matches, break
index = i;
delete [] readKey;
break;
} else {
// Key doesn't match. Skip the data
intl offset = -1;
fs.read((char*)&offset, sizeof(intl));
fs.seekg(offset, std::ios_base::cur);
delete [] readKey;
}
}
} else {
AF_ERROR("Invalid version", AF_ERR_ARG);
}
fs.close();
return index;
}
af_err af_read_array_index(af_array *out, const char *filename, const unsigned index)
{
try {
AF_CHECK(af_init());
ARG_ASSERT(1, filename != NULL);
af_array output = checkVersionAndRead(filename, index);
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_read_array_key(af_array *out, const char *filename, const char *key)
{
try {
AF_CHECK(af_init());
ARG_ASSERT(1, filename != NULL);
ARG_ASSERT(2, key != NULL);
// Find index of key. Then call read by index
int index = checkVersionAndFindIndex(filename, key);
if(index == -1)
AF_ERROR("Key not found", AF_ERR_INVALID_ARRAY);
af_array output = checkVersionAndRead(filename, index);
std::swap(*out, output);
}
CATCHALL;
return AF_SUCCESS;
}
af_err af_read_array_key_check(int *index, const char *filename, const char* key)
{
try {
ARG_ASSERT(1, filename != NULL);
ARG_ASSERT(2, key != NULL);
AF_CHECK(af_init());
// Find index of key. Then call read by index
int id = checkVersionAndFindIndex(filename, key);
std::swap(*index, id);
}
CATCHALL;
return AF_SUCCESS;
}
<|endoftext|> |
<commit_before>// This simple utility can periodically print various stats about a drive
#include <inttypes.h>
#include <stdio.h>
#include "kinetic/kinetic.h"
using kinetic::DriveLog;
using kinetic::Capacity;
using kinetic::OperationStatistic;
using kinetic::Utilization;
using kinetic::Temperature;
using std::unique_ptr;
void dump_all_information(const DriveLog& drive_log);
void print_temp_report(const DriveLog& drive_log, bool print_headers);
void print_utilization_report(const DriveLog& drive_log, bool print_headers);
void print_operation_stats_report(const DriveLog& drive_log, bool print_headers);
int main(int argc, char* argv[]) {
(void) argc;
if (argc < 2 || argc > 4) {
printf("Usage: %s <host>\n", argv[0]);
printf(" %s <host> log", argv[0]);
printf(" %s <host> <temp|utilization|stat> <interval>\n", argv[0]);
return 1;
}
kinetic::ConnectionOptions options;
options.host = std::string(argv[1]);
options.port = 8123;
options.user_id = 1;
options.hmac_key = "asdfasdf";
kinetic::KineticConnectionFactory kinetic_connection_factory = kinetic::NewKineticConnectionFactory();
unique_ptr<kinetic::ConnectionHandle> connection;
if(!kinetic_connection_factory.NewConnection(options, 5, connection).ok()) {
printf("Unable to connect\n");
return 1;
}
if (argc == 2) {
// User just specified host so dump everything
unique_ptr<DriveLog> drive_log;
if(!connection->blocking().GetLog(drive_log).ok()) {
printf("Unable to get log\n");
return 1;
}
dump_all_information(*drive_log);
} else if(argc == 3) {
// User wants the logs
unique_ptr<DriveLog> drive_log;
if(!connection->blocking().GetLog(drive_log).ok()) {
printf("Unable to get log\n");
return 1;
}
printf("%s\n", drive_log->messages.c_str());
} else {
// User wants to poll host so figure out the information so start
// the polling
std::string report_type(argv[2]);
int report_interval = atoi(argv[3]);
int report_number = 0;
while (true) {
unique_ptr<DriveLog> drive_log;
if(!connection->blocking().GetLog(drive_log).ok()) {
printf("Unable to get log\n");
return 1;
}
bool print_headers = report_number % 5 == 0;
if (report_type == "temp") {
print_temp_report(*drive_log, print_headers);
} else if (report_type == "utilization") {
print_utilization_report(*drive_log, print_headers);
} else if (report_type == "stat") {
print_operation_stats_report(*drive_log, print_headers);
}
printf("\n");
sleep(report_interval);
report_number++;
}
}
return 0;
}
void dump_all_information(const DriveLog& drive_log) {
printf("Configuration:\n");
printf(" Vendor: %s\n", drive_log.configuration.vendor.c_str());
printf(" Model: %s\n", drive_log.configuration.model.c_str());
printf(" SN: %s\n", drive_log.configuration.serial_number.c_str());
printf(" Version: %s\n", drive_log.configuration.version.c_str());
printf(" Compilation Date: %s\n", drive_log.configuration.compilation_date.c_str());
printf(" Source Hash: %s\n", drive_log.configuration.source_hash.c_str());
printf(" Port: %d\n", drive_log.configuration.port);
printf(" TLS Port: %d\n", drive_log.configuration.tls_port);
printf("\n");
printf("Capacity: %.0f bytes remaining / %.0f bytes\n\n",
drive_log.capacity.remaining_bytes, drive_log.capacity.total_bytes);
printf("Statistics:\n");
for (auto it = drive_log.operation_statistics.begin();
it != drive_log.operation_statistics.end();
++it) {
printf(" %s: %" PRId64 " times %" PRId64 " bytes\n", it->name.c_str(), it->count,
it->bytes);
}
printf("\n");
printf("Utilizations:\n");
for (auto it = drive_log.utilizations.begin();
it != drive_log.utilizations.end();
++it) {
printf(" %s: %.02f%%\n", it->name.c_str(), it->percent);
}
printf("\n");
printf("Temperatures:\n");
for (auto it = drive_log.temperatures.begin();
it != drive_log.temperatures.end();
++it) {
printf(" %s: %.0f\u00B0C\n", it->name.c_str(), it->current_degc);
}
printf("\nMessages:\n");
printf("%s\n", drive_log.messages.c_str());
}
void print_temp_report(const DriveLog& drive_log, bool print_headers) {
if (print_headers) {
for (auto it = drive_log.temperatures.begin();
it != drive_log.temperatures.end();
++it) {
printf("%7s \u00B0C ", it->name.c_str());
}
printf("\n");
}
for (auto it = drive_log.temperatures.begin();
it != drive_log.temperatures.end();
++it) {
printf("%10.0f ", it->current_degc);
}
}
void print_utilization_report(const DriveLog& drive_log, bool print_headers) {
if (print_headers) {
for (auto it = drive_log.utilizations.begin();
it != drive_log.utilizations.end();
++it) {
printf("%8s %% ", it->name.c_str());
}
printf("\n");
}
for (auto it = drive_log.utilizations.begin();
it != drive_log.utilizations.end();
++it) {
printf("%10.0f ", 100 * it->percent);
}
}
void print_operation_stats_report(const DriveLog& drive_log, bool print_headers) {
for (auto it = drive_log.operation_statistics.begin();
it != drive_log.operation_statistics.end();
++it) {
printf("%25s: %" PRId64 "\n", it->name.c_str(), it->count);
}
}
<commit_msg>Updated kineticstat<commit_after>// This simple utility can periodically print various stats about a drive
#include <inttypes.h>
#include <stdio.h>
#include "kinetic/kinetic.h"
#include "gflags/gflags.h"
using kinetic::DriveLog;
using kinetic::Capacity;
using kinetic::OperationStatistic;
using kinetic::Utilization;
using kinetic::Temperature;
using std::unique_ptr;
void dump_all_information(const DriveLog& drive_log);
void print_temp_report(const DriveLog& drive_log, bool print_headers);
void print_utilization_report(const DriveLog& drive_log, bool print_headers);
void print_operation_stats_report(const DriveLog& drive_log, bool print_headers);
DEFINE_string(type, "all", "Stat type (all|log|temp|utilization|stat)");
DEFINE_uint64(interval, 5, "Refresh interval");
int example_main(std::unique_ptr<kinetic::ConnectionHandle> connection, int argc, char** argv) {
if (FLAGS_type == "all") {
unique_ptr<DriveLog> drive_log;
if(!connection->blocking().GetLog(drive_log).ok()) {
printf("Unable to get log\n");
return 1;
}
dump_all_information(*drive_log);
} else if (FLAGS_type == "log") {
unique_ptr<DriveLog> drive_log;
if(!connection->blocking().GetLog(drive_log).ok()) {
printf("Unable to get log\n");
return 1;
}
printf("%s\n", drive_log->messages.c_str());
} else {
int report_number = 0;
while (true) {
unique_ptr<DriveLog> drive_log;
if(!connection->blocking().GetLog(drive_log).ok()) {
printf("Unable to get log\n");
return 1;
}
bool print_headers = report_number % 5 == 0;
if (FLAGS_type == "temp") {
print_temp_report(*drive_log, print_headers);
} else if (FLAGS_type == "utilization") {
print_utilization_report(*drive_log, print_headers);
} else if (FLAGS_type == "stat") {
print_operation_stats_report(*drive_log, print_headers);
}
printf("\n");
sleep(FLAGS_interval);
report_number++;
}
}
return 0;
}
void dump_all_information(const DriveLog& drive_log) {
printf("Configuration:\n");
printf(" Vendor: %s\n", drive_log.configuration.vendor.c_str());
printf(" Model: %s\n", drive_log.configuration.model.c_str());
printf(" SN: %s\n", drive_log.configuration.serial_number.c_str());
printf(" Version: %s\n", drive_log.configuration.version.c_str());
printf(" Compilation Date: %s\n", drive_log.configuration.compilation_date.c_str());
printf(" Source Hash: %s\n", drive_log.configuration.source_hash.c_str());
printf(" Port: %d\n", drive_log.configuration.port);
printf(" TLS Port: %d\n", drive_log.configuration.tls_port);
printf("\n");
printf("Capacity: %.0f bytes remaining / %.0f bytes\n\n",
drive_log.capacity.remaining_bytes, drive_log.capacity.total_bytes);
printf("Statistics:\n");
for (auto it = drive_log.operation_statistics.begin();
it != drive_log.operation_statistics.end();
++it) {
printf(" %s: %" PRId64 " times %" PRId64 " bytes\n", it->name.c_str(), it->count,
it->bytes);
}
printf("\n");
printf("Utilizations:\n");
for (auto it = drive_log.utilizations.begin();
it != drive_log.utilizations.end();
++it) {
printf(" %s: %.02f%%\n", it->name.c_str(), it->percent);
}
printf("\n");
printf("Temperatures:\n");
for (auto it = drive_log.temperatures.begin();
it != drive_log.temperatures.end();
++it) {
printf(" %s: %.0f\u00B0C\n", it->name.c_str(), it->current_degc);
}
printf("\nMessages:\n");
printf("%s\n", drive_log.messages.c_str());
}
void print_temp_report(const DriveLog& drive_log, bool print_headers) {
if (print_headers) {
for (auto it = drive_log.temperatures.begin();
it != drive_log.temperatures.end();
++it) {
printf("%7s \u00B0C ", it->name.c_str());
}
printf("\n");
}
for (auto it = drive_log.temperatures.begin();
it != drive_log.temperatures.end();
++it) {
printf("%10.0f ", it->current_degc);
}
}
void print_utilization_report(const DriveLog& drive_log, bool print_headers) {
if (print_headers) {
for (auto it = drive_log.utilizations.begin();
it != drive_log.utilizations.end();
++it) {
printf("%8s %% ", it->name.c_str());
}
printf("\n");
}
for (auto it = drive_log.utilizations.begin();
it != drive_log.utilizations.end();
++it) {
printf("%10.0f ", 100 * it->percent);
}
}
void print_operation_stats_report(const DriveLog& drive_log, bool print_headers) {
for (auto it = drive_log.operation_statistics.begin();
it != drive_log.operation_statistics.end();
++it) {
printf("%25s: %" PRId64 "\n", it->name.c_str(), it->count);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbOGRDataSourceWrapper.h"
// standard includes
#include <cassert>
#include <numeric>
#include <algorithm>
#include <clocale> // toupper
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
// ITK includes
#include "itkMacro.h" // itkExceptionMacro
#include "itkMetaDataObject.h"
#include "itkExceptionObject.h"
#include "itksys/SystemTools.hxx"
// OTB includes
#include "otbMacro.h"
#include "otbMetaDataKey.h"
#include "otbOGRDriversInit.h"
#include "otbSystem.h"
// OGR includes
#include "ogrsf_frmts.h"
void
otb::ogr::DataSource
::SetProjectionRef(const std::string& projectionRef)
{
itk::MetaDataDictionary& dict = this->GetMetaDataDictionary();
itk::EncapsulateMetaData<std::string>(
dict, MetaDataKey::ProjectionRefKey, projectionRef);
this->Modified();
}
std::string
otb::ogr::DataSource
::GetProjectionRef() const
{
const itk::MetaDataDictionary& dict = this->GetMetaDataDictionary();
std::string projectionRef;
itk::ExposeMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef);
return projectionRef;
}
/*===========================================================================*/
/*=======================[ construction/destruction ]========================*/
/*===========================================================================*/
bool otb::ogr::DataSource::Clear()
{
Reset(0);
return true;
}
void otb::ogr::DataSource::Reset(OGRDataSource * source)
{
if (m_DataSource) {
// OGR makes a pointless check for non-nullity in
// OGRDataSource::DestroyDataSource (pointless because "delete 0" is
// perfectly valid -> it's a no-op)
OGRDataSource::DestroyDataSource(m_DataSource); // void, noexcept
}
m_DataSource = source;
}
namespace { // Anonymous namespace
/**\ingroup GeometryInternals
* \brief Type for associating filename extension with OGR driver names.
* \since OTB v 3.14.0
*/
struct ExtensionDriverAssociation
{
char const* extension;
char const* driverName;
bool Matches(std::string const& ext) const
{
return ext == extension;
}
};
/**\ingroup GeometryInternals
* \brief Associative table of filename extension -> OGR driver names.
* \since OTB v 3.14.0
*/
const ExtensionDriverAssociation k_ExtensionDriverMap[] =
{
{"SHP", "ESRI Shapefile"},
{"TAB", "MapInfo File"},
{"GML", "GML"},
{"GPX", "GPX"},
{"SQLITE", "SQLite"},
{"KML", "KML"},
};
/**\ingroup GeometryInternals
* \brief Returns the OGR driver name associated to a filename.
* \since OTB v 3.14.0
* \note Relies on the driver name associated to the filename extension in \c
* k_ExtensionDriverMap.
* \note As a special case, filenames starting with "PG:" are bound to
* "PostgreSQL".
*/
char const* DeduceDriverName(std::string filename)
{
std::transform(filename.begin(), filename.end(), filename.begin(), (int (*)(int))toupper);
if (0 == strncmp(filename.c_str(), "PG:", 3))
{
return "PostgreSQL";
}
const std::string extension = otb::System::GetExtension(filename);
ExtensionDriverAssociation const* whichIt =
std::find_if(
boost::begin(k_ExtensionDriverMap), boost::end(k_ExtensionDriverMap),
boost::bind(&ExtensionDriverAssociation::Matches, _1, extension));
if (whichIt == boost::end(k_ExtensionDriverMap))
{
return 0; // nothing found
}
return whichIt->driverName;
}
} // Anonymous namespace
otb::ogr::DataSource::DataSource()
: m_DataSource(0)
{
Drivers::Init();
OGRSFDriver * d = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("Memory");
assert(d && "OGR Memory driver not found");
m_DataSource = d->CreateDataSource("in-memory");
if (!m_DataSource) {
itkExceptionMacro(<< "Failed to create OGRMemDataSource: " << CPLGetLastErrorMsg());
}
m_DataSource->SetDriver(d);
}
otb::ogr::DataSource::DataSource(OGRDataSource * source)
: m_DataSource(source)
{
}
otb::ogr::DataSource::Pointer
otb::ogr::DataSource::New(std::string const& filename, Modes::type mode)
{
Drivers::Init();
const bool update = mode & Modes::write;
// std::cout << "Opening datasource " << filename << " update=" << update << "\n";
if (itksys::SystemTools::FileExists(filename.c_str()))
{
OGRDataSource * source = OGRSFDriverRegistrar::Open(filename.c_str(), update);
if (!source)
{
itkGenericExceptionMacro(<< "Failed to open OGRDataSource file "
<< filename<<": " << CPLGetLastErrorMsg());
}
Pointer res = new DataSource(source);
res->UnRegister();
return res;
}
else
{
if (! update)
{
itkGenericExceptionMacro(<< "No DataSource named <"<<filename<<"> exists,"
" and the file opening mode does not permit updates. DataSource creation is thus aborted.");
}
// Hand made factory based on file extension.
char const* driverName = DeduceDriverName(filename);
if (!driverName)
{
itkGenericExceptionMacro(<< "No OGR driver known to OTB to create and handle a DataSource named <"
<<filename<<">.");
}
OGRSFDriver * d = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driverName);
assert(d && "OGR driver not found");
OGRDataSource * source = d->CreateDataSource(filename.c_str());
if (!source) {
itkGenericExceptionMacro(<< "Failed to create OGRDataSource <"<<filename
<<"> (driver name: " << driverName<<">: " << CPLGetLastErrorMsg());
}
source->SetDriver(d);
Pointer res = new DataSource(source);
res->UnRegister();
return res;
}
}
/*static*/
otb::ogr::DataSource::Pointer
otb::ogr::DataSource::New(OGRDataSource * source)
{
Pointer res = new DataSource(source);
res->UnRegister();
return res;
}
/*virtual*/ otb::ogr::DataSource::~DataSource()
{
Clear();
}
/*===========================================================================*/
/*================================[ layers ]=================================*/
/*===========================================================================*/
otb::ogr::DataSource::const_iterator otb::ogr::DataSource::cbegin() const
{
return const_iterator(*this, 0);
}
otb::ogr::DataSource::const_iterator otb::ogr::DataSource::cend() const
{
return const_iterator(*this, GetLayersCount());
}
otb::ogr::DataSource::iterator otb::ogr::DataSource::begin()
{
return iterator(*this, 0);
}
otb::ogr::DataSource::iterator otb::ogr::DataSource::end()
{
return iterator(*this, GetLayersCount());
}
otb::ogr::Layer otb::ogr::DataSource::CreateLayer(
std::string const& name,
OGRSpatialReference * poSpatialRef/* = NULL */,
OGRwkbGeometryType eGType/* = wkbUnknown */,
char ** papszOptions/* = NULL */)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * ol = m_DataSource->CreateLayer(
name.c_str(), poSpatialRef, eGType, papszOptions);
if (!ol)
{
itkGenericExceptionMacro(<< "Failed to create the layer <"<<name
<< "> in the OGRDataSource file <" << m_DataSource->GetName()
<<">: " << CPLGetLastErrorMsg());
}
Layer l(ol, this);
return l;
}
otb::ogr::Layer otb::ogr::DataSource::CopyLayer(
Layer & srcLayer,
std::string const& newName,
char ** papszOptions/* = NULL */)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * l0 = &srcLayer.ogr();
OGRLayer * ol = m_DataSource->CopyLayer(l0, newName.c_str(), papszOptions);
if (!ol)
{
itkGenericExceptionMacro(<< "Failed to copy the layer <"
<< srcLayer.GetName() << "> into the new layer <" <<newName
<< "> in the OGRDataSource file <" << m_DataSource->GetName()
<<">: " << CPLGetLastErrorMsg());
}
Layer l(ol, this);
return l;
}
void otb::ogr::DataSource::DeleteLayer(size_t i)
{
const int nb_layers = GetLayersCount();
if (int(i) >= nb_layers)
{
itkExceptionMacro(<< "Cannot delete " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << "> as it contains only " << nb_layers << "layers.");
}
const OGRErr err = m_DataSource->DeleteLayer(int(i));
if (err != OGRERR_NONE)
{
itkExceptionMacro(<< "Cannot delete " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
}
}
otb::ogr::Layer otb::ogr::DataSource::GetLayerChecked(size_t i)
{
const int nb_layers = GetLayersCount();
if (int(i) >= nb_layers)
{
itkExceptionMacro(<< "Cannot fetch " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << "> as it contains only " << nb_layers << "layers.");
}
OGRLayer * layer_ptr = m_DataSource->GetLayer(int(i));
if (!layer_ptr)
{
itkExceptionMacro( << "Unexpected error: cannot fetch " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
}
return otb::ogr::Layer(layer_ptr, this);
}
OGRLayer* otb::ogr::DataSource::GetLayerUnchecked(size_t i)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->GetLayer(int(i));
return layer_ptr;
}
otb::ogr::Layer otb::ogr::DataSource::GetLayer(std::string const& name)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->GetLayerByName(name.c_str());
return otb::ogr::Layer(layer_ptr, this);
}
otb::ogr::Layer otb::ogr::DataSource::GetLayerChecked(std::string const& name)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->GetLayerByName(name.c_str());
if (!layer_ptr)
{
itkExceptionMacro( << "Cannot fetch any layer named <" << name
<< "> in the OGRDataSource <" << m_DataSource->GetName() << ">: "
<< CPLGetLastErrorMsg());
}
return otb::ogr::Layer(layer_ptr, this);
}
int otb::ogr::DataSource::GetLayersCount() const
{
assert(m_DataSource && "Datasource not initialized");
return m_DataSource->GetLayerCount();
}
otb::ogr::Layer otb::ogr::DataSource::ExecuteSQL(
std::string const& statement,
OGRGeometry * poSpatialFilter,
char const* pszDialect)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->ExecuteSQL(
statement.c_str(), poSpatialFilter, pszDialect);
if (!layer_ptr)
{
#if defined(PREFER_EXCEPTION)
itkExceptionMacro( << "Unexpected error: cannot execute the SQL request <" << statement
<< "> in the OGRDataSource <" << m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
#else
// Cannot use the deleter made for result sets obtained from
// OGRDataSource::ExecuteSQL because it checks for non-nullity....
// *sigh*
return otb::ogr::Layer(0, 0);
#endif
}
return otb::ogr::Layer(layer_ptr, *m_DataSource);
}
/*===========================================================================*/
/*===============================[ features ]================================*/
/*===========================================================================*/
namespace { // Anonymous namespace
/**\ingroup GeometryInternals
* \brief %Functor used to accumulate the sizes of the layers in a \c DataSource.
* \since OTB v 3.14.0
*/
struct AccuLayersSizes
{
AccuLayersSizes(bool doForceComputation)
: m_doForceComputation(doForceComputation) { }
int operator()(int accumulated, otb::ogr::Layer const& layer) const
{
const int loc_size = layer.GetFeatureCount(m_doForceComputation);
return loc_size < 0 ? loc_size : loc_size+accumulated;
}
private:
bool m_doForceComputation;
};
} // Anonymous namespace
int otb::ogr::DataSource::Size(bool doForceComputation) const
{
return std::accumulate(begin(),end(), 0, AccuLayersSizes(doForceComputation));
}
/*===========================================================================*/
/*=================================[ Misc ]==================================*/
/*===========================================================================*/
void otb::ogr::DataSource::GetGlobalExtent(double & ulx,
double & uly,
double & lrx,
double & lry,
bool force) const
{
OGREnvelope sExtent;
const_iterator lit = this->begin();
const OGRErr res = lit->ogr().GetExtent(&sExtent,force);
if(res!= OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot retrieve extent of layer <"
<<lit->GetName()<<">: " << CPLGetLastErrorMsg());
}
++lit;
for(; lit!=this->end();++lit)
{
OGREnvelope cExtent;
const OGRErr cres = lit->ogr().GetExtent(&cExtent,force);
if(cres!= OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot retrieve extent of layer <"
<<lit->GetName()<<">: " << CPLGetLastErrorMsg());
}
// Merge with previous layer
sExtent.Merge(cExtent);
}
ulx = sExtent.MinX;
uly = sExtent.MinY;
lrx = sExtent.MaxX;
lry = sExtent.MaxY;
}
/*virtual*/
void otb::ogr::DataSource::PrintSelf(
std::ostream& os, itk::Indent indent) const
{
assert(m_DataSource && "Datasource not initialized");
BOOST_FOREACH(Layer const& l, *this)
{
l.PrintSelf(os, indent);
}
}
/*virtual*/ void otb::ogr::DataSource::Graft(const itk::DataObject * data)
{
assert(! "Disabled to check if it makes sense...");
}
bool otb::ogr::DataSource::HasCapability(std::string const& capabilityName) const
{
assert(m_DataSource && "Datasource not initialized");
return m_DataSource->TestCapability(capabilityName.c_str());
}
void otb::ogr::DataSource::SyncToDisk()
{
assert(m_DataSource && "Datasource not initialized");
const OGRErr res= m_DataSource->SyncToDisk();
if (res != OGRERR_NONE)
{
itkExceptionMacro( << "Cannot flush the pending of the OGRDataSource <"
<< m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
}
}
<commit_msg>BUG: Fixing potential bug on number of layers in dataset<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbOGRDataSourceWrapper.h"
// standard includes
#include <cassert>
#include <numeric>
#include <algorithm>
#include <clocale> // toupper
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
// ITK includes
#include "itkMacro.h" // itkExceptionMacro
#include "itkMetaDataObject.h"
#include "itkExceptionObject.h"
#include "itksys/SystemTools.hxx"
// OTB includes
#include "otbMacro.h"
#include "otbMetaDataKey.h"
#include "otbOGRDriversInit.h"
#include "otbSystem.h"
// OGR includes
#include "ogrsf_frmts.h"
void
otb::ogr::DataSource
::SetProjectionRef(const std::string& projectionRef)
{
itk::MetaDataDictionary& dict = this->GetMetaDataDictionary();
itk::EncapsulateMetaData<std::string>(
dict, MetaDataKey::ProjectionRefKey, projectionRef);
this->Modified();
}
std::string
otb::ogr::DataSource
::GetProjectionRef() const
{
const itk::MetaDataDictionary& dict = this->GetMetaDataDictionary();
std::string projectionRef;
itk::ExposeMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef);
return projectionRef;
}
/*===========================================================================*/
/*=======================[ construction/destruction ]========================*/
/*===========================================================================*/
bool otb::ogr::DataSource::Clear()
{
Reset(0);
return true;
}
void otb::ogr::DataSource::Reset(OGRDataSource * source)
{
if (m_DataSource) {
// OGR makes a pointless check for non-nullity in
// OGRDataSource::DestroyDataSource (pointless because "delete 0" is
// perfectly valid -> it's a no-op)
OGRDataSource::DestroyDataSource(m_DataSource); // void, noexcept
}
m_DataSource = source;
}
namespace { // Anonymous namespace
/**\ingroup GeometryInternals
* \brief Type for associating filename extension with OGR driver names.
* \since OTB v 3.14.0
*/
struct ExtensionDriverAssociation
{
char const* extension;
char const* driverName;
bool Matches(std::string const& ext) const
{
return ext == extension;
}
};
/**\ingroup GeometryInternals
* \brief Associative table of filename extension -> OGR driver names.
* \since OTB v 3.14.0
*/
const ExtensionDriverAssociation k_ExtensionDriverMap[] =
{
{"SHP", "ESRI Shapefile"},
{"TAB", "MapInfo File"},
{"GML", "GML"},
{"GPX", "GPX"},
{"SQLITE", "SQLite"},
{"KML", "KML"},
};
/**\ingroup GeometryInternals
* \brief Returns the OGR driver name associated to a filename.
* \since OTB v 3.14.0
* \note Relies on the driver name associated to the filename extension in \c
* k_ExtensionDriverMap.
* \note As a special case, filenames starting with "PG:" are bound to
* "PostgreSQL".
*/
char const* DeduceDriverName(std::string filename)
{
std::transform(filename.begin(), filename.end(), filename.begin(), (int (*)(int))toupper);
if (0 == strncmp(filename.c_str(), "PG:", 3))
{
return "PostgreSQL";
}
const std::string extension = otb::System::GetExtension(filename);
ExtensionDriverAssociation const* whichIt =
std::find_if(
boost::begin(k_ExtensionDriverMap), boost::end(k_ExtensionDriverMap),
boost::bind(&ExtensionDriverAssociation::Matches, _1, extension));
if (whichIt == boost::end(k_ExtensionDriverMap))
{
return 0; // nothing found
}
return whichIt->driverName;
}
} // Anonymous namespace
otb::ogr::DataSource::DataSource()
: m_DataSource(0)
{
Drivers::Init();
OGRSFDriver * d = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName("Memory");
assert(d && "OGR Memory driver not found");
m_DataSource = d->CreateDataSource("in-memory");
if (!m_DataSource) {
itkExceptionMacro(<< "Failed to create OGRMemDataSource: " << CPLGetLastErrorMsg());
}
m_DataSource->SetDriver(d);
}
otb::ogr::DataSource::DataSource(OGRDataSource * source)
: m_DataSource(source)
{
}
otb::ogr::DataSource::Pointer
otb::ogr::DataSource::New(std::string const& filename, Modes::type mode)
{
Drivers::Init();
const bool update = mode & Modes::write;
// std::cout << "Opening datasource " << filename << " update=" << update << "\n";
if (itksys::SystemTools::FileExists(filename.c_str()))
{
OGRDataSource * source = OGRSFDriverRegistrar::Open(filename.c_str(), update);
if (!source)
{
itkGenericExceptionMacro(<< "Failed to open OGRDataSource file "
<< filename<<": " << CPLGetLastErrorMsg());
}
Pointer res = new DataSource(source);
res->UnRegister();
return res;
}
else
{
if (! update)
{
itkGenericExceptionMacro(<< "No DataSource named <"<<filename<<"> exists,"
" and the file opening mode does not permit updates. DataSource creation is thus aborted.");
}
// Hand made factory based on file extension.
char const* driverName = DeduceDriverName(filename);
if (!driverName)
{
itkGenericExceptionMacro(<< "No OGR driver known to OTB to create and handle a DataSource named <"
<<filename<<">.");
}
OGRSFDriver * d = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(driverName);
assert(d && "OGR driver not found");
OGRDataSource * source = d->CreateDataSource(filename.c_str());
if (!source) {
itkGenericExceptionMacro(<< "Failed to create OGRDataSource <"<<filename
<<"> (driver name: " << driverName<<">: " << CPLGetLastErrorMsg());
}
source->SetDriver(d);
Pointer res = new DataSource(source);
res->UnRegister();
return res;
}
}
/*static*/
otb::ogr::DataSource::Pointer
otb::ogr::DataSource::New(OGRDataSource * source)
{
Pointer res = new DataSource(source);
res->UnRegister();
return res;
}
/*virtual*/ otb::ogr::DataSource::~DataSource()
{
Clear();
}
/*===========================================================================*/
/*================================[ layers ]=================================*/
/*===========================================================================*/
otb::ogr::DataSource::const_iterator otb::ogr::DataSource::cbegin() const
{
return const_iterator(*this, 0);
}
otb::ogr::DataSource::const_iterator otb::ogr::DataSource::cend() const
{
return const_iterator(*this, GetLayersCount());
}
otb::ogr::DataSource::iterator otb::ogr::DataSource::begin()
{
return iterator(*this, 0);
}
otb::ogr::DataSource::iterator otb::ogr::DataSource::end()
{
return iterator(*this, GetLayersCount());
}
otb::ogr::Layer otb::ogr::DataSource::CreateLayer(
std::string const& name,
OGRSpatialReference * poSpatialRef/* = NULL */,
OGRwkbGeometryType eGType/* = wkbUnknown */,
char ** papszOptions/* = NULL */)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * ol = m_DataSource->CreateLayer(
name.c_str(), poSpatialRef, eGType, papszOptions);
if (!ol)
{
itkGenericExceptionMacro(<< "Failed to create the layer <"<<name
<< "> in the OGRDataSource file <" << m_DataSource->GetName()
<<">: " << CPLGetLastErrorMsg());
}
Layer l(ol, this);
return l;
}
otb::ogr::Layer otb::ogr::DataSource::CopyLayer(
Layer & srcLayer,
std::string const& newName,
char ** papszOptions/* = NULL */)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * l0 = &srcLayer.ogr();
OGRLayer * ol = m_DataSource->CopyLayer(l0, newName.c_str(), papszOptions);
if (!ol)
{
itkGenericExceptionMacro(<< "Failed to copy the layer <"
<< srcLayer.GetName() << "> into the new layer <" <<newName
<< "> in the OGRDataSource file <" << m_DataSource->GetName()
<<">: " << CPLGetLastErrorMsg());
}
Layer l(ol, this);
return l;
}
void otb::ogr::DataSource::DeleteLayer(size_t i)
{
const int nb_layers = GetLayersCount();
if (int(i) >= nb_layers)
{
itkExceptionMacro(<< "Cannot delete " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << "> as it contains only " << nb_layers << "layers.");
}
const OGRErr err = m_DataSource->DeleteLayer(int(i));
if (err != OGRERR_NONE)
{
itkExceptionMacro(<< "Cannot delete " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
}
}
otb::ogr::Layer otb::ogr::DataSource::GetLayerChecked(size_t i)
{
const int nb_layers = GetLayersCount();
if (int(i) >= nb_layers)
{
itkExceptionMacro(<< "Cannot fetch " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << "> as it contains only " << nb_layers << "layers.");
}
OGRLayer * layer_ptr = m_DataSource->GetLayer(int(i));
if (!layer_ptr)
{
itkExceptionMacro( << "Unexpected error: cannot fetch " << i << "th layer in the OGRDataSource <"
<< m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
}
return otb::ogr::Layer(layer_ptr, this);
}
OGRLayer* otb::ogr::DataSource::GetLayerUnchecked(size_t i)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->GetLayer(int(i));
return layer_ptr;
}
otb::ogr::Layer otb::ogr::DataSource::GetLayer(std::string const& name)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->GetLayerByName(name.c_str());
return otb::ogr::Layer(layer_ptr, this);
}
otb::ogr::Layer otb::ogr::DataSource::GetLayerChecked(std::string const& name)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->GetLayerByName(name.c_str());
if (!layer_ptr)
{
itkExceptionMacro( << "Cannot fetch any layer named <" << name
<< "> in the OGRDataSource <" << m_DataSource->GetName() << ">: "
<< CPLGetLastErrorMsg());
}
return otb::ogr::Layer(layer_ptr, this);
}
int otb::ogr::DataSource::GetLayersCount() const
{
assert(m_DataSource && "Datasource not initialized");
return m_DataSource->GetLayerCount();
}
otb::ogr::Layer otb::ogr::DataSource::ExecuteSQL(
std::string const& statement,
OGRGeometry * poSpatialFilter,
char const* pszDialect)
{
assert(m_DataSource && "Datasource not initialized");
OGRLayer * layer_ptr = m_DataSource->ExecuteSQL(
statement.c_str(), poSpatialFilter, pszDialect);
if (!layer_ptr)
{
#if defined(PREFER_EXCEPTION)
itkExceptionMacro( << "Unexpected error: cannot execute the SQL request <" << statement
<< "> in the OGRDataSource <" << m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
#else
// Cannot use the deleter made for result sets obtained from
// OGRDataSource::ExecuteSQL because it checks for non-nullity....
// *sigh*
return otb::ogr::Layer(0, 0);
#endif
}
return otb::ogr::Layer(layer_ptr, *m_DataSource);
}
/*===========================================================================*/
/*===============================[ features ]================================*/
/*===========================================================================*/
namespace { // Anonymous namespace
/**\ingroup GeometryInternals
* \brief %Functor used to accumulate the sizes of the layers in a \c DataSource.
* \since OTB v 3.14.0
*/
struct AccuLayersSizes
{
AccuLayersSizes(bool doForceComputation)
: m_doForceComputation(doForceComputation) { }
int operator()(int accumulated, otb::ogr::Layer const& layer) const
{
const int loc_size = layer.GetFeatureCount(m_doForceComputation);
return loc_size < 0 ? loc_size : loc_size+accumulated;
}
private:
bool m_doForceComputation;
};
} // Anonymous namespace
int otb::ogr::DataSource::Size(bool doForceComputation) const
{
return std::accumulate(begin(),end(), 0, AccuLayersSizes(doForceComputation));
}
/*===========================================================================*/
/*=================================[ Misc ]==================================*/
/*===========================================================================*/
void otb::ogr::DataSource::GetGlobalExtent(double & ulx,
double & uly,
double & lrx,
double & lry,
bool force) const
{
OGREnvelope sExtent;
const_iterator lit = this->begin();
if(lit==this->end())
{
itkGenericExceptionMacro(<< "Cannot compute global extent because there are no layers in the DataSource");
}
const OGRErr res = lit->ogr().GetExtent(&sExtent,force);
if(res!= OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot retrieve extent of layer <"
<<lit->GetName()<<">: " << CPLGetLastErrorMsg());
}
++lit;
for(; lit!=this->end();++lit)
{
OGREnvelope cExtent;
const OGRErr cres = lit->ogr().GetExtent(&cExtent,force);
if(cres!= OGRERR_NONE)
{
itkGenericExceptionMacro(<< "Cannot retrieve extent of layer <"
<<lit->GetName()<<">: " << CPLGetLastErrorMsg());
}
// Merge with previous layer
sExtent.Merge(cExtent);
}
ulx = sExtent.MinX;
uly = sExtent.MinY;
lrx = sExtent.MaxX;
lry = sExtent.MaxY;
}
/*virtual*/
void otb::ogr::DataSource::PrintSelf(
std::ostream& os, itk::Indent indent) const
{
assert(m_DataSource && "Datasource not initialized");
BOOST_FOREACH(Layer const& l, *this)
{
l.PrintSelf(os, indent);
}
}
/*virtual*/ void otb::ogr::DataSource::Graft(const itk::DataObject * data)
{
assert(! "Disabled to check if it makes sense...");
}
bool otb::ogr::DataSource::HasCapability(std::string const& capabilityName) const
{
assert(m_DataSource && "Datasource not initialized");
return m_DataSource->TestCapability(capabilityName.c_str());
}
void otb::ogr::DataSource::SyncToDisk()
{
assert(m_DataSource && "Datasource not initialized");
const OGRErr res= m_DataSource->SyncToDisk();
if (res != OGRERR_NONE)
{
itkExceptionMacro( << "Cannot flush the pending of the OGRDataSource <"
<< m_DataSource->GetName() << ">: " << CPLGetLastErrorMsg());
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DisplayGLX.h: GLX implementation of egl::Display
#define GLX_GLXEXT_PROTOTYPES
#include "libANGLE/renderer/gl/glx/DisplayGLX.h"
#include <GL/glxext.h>
#include <EGL/eglext.h>
#include <algorithm>
#include "common/debug.h"
#include "libANGLE/Config.h"
#include "libANGLE/Display.h"
#include "libANGLE/Surface.h"
#include "libANGLE/renderer/gl/glx/WindowSurfaceGLX.h"
namespace rx
{
class FunctionsGLGLX : public FunctionsGL
{
public:
FunctionsGLGLX(PFNGLXGETPROCADDRESSPROC getProc)
: mGetProc(getProc)
{
}
virtual ~FunctionsGLGLX()
{
}
private:
void *loadProcAddress(const std::string &function) override
{
return reinterpret_cast<void*>(mGetProc(reinterpret_cast<const unsigned char*>(function.c_str())));
}
PFNGLXGETPROCADDRESSPROC mGetProc;
};
DisplayGLX::DisplayGLX()
: DisplayGL(),
mFunctionsGL(nullptr),
mContext(nullptr),
mDummyPbuffer(0),
mEGLDisplay(nullptr),
mXDisplay(nullptr)
{
}
DisplayGLX::~DisplayGLX()
{
}
egl::Error DisplayGLX::initialize(egl::Display *display)
{
mEGLDisplay = display;
mXDisplay = display->getNativeDisplayId();
egl::Error glxInitResult = mGLX.initialize(mXDisplay);
if (glxInitResult.isError())
{
return glxInitResult;
}
// Check we have the needed extensions
{
if (mGLX.minorVersion == 3 && !mGLX.hasExtension("GLX_ARB_multisample"))
{
return egl::Error(EGL_NOT_INITIALIZED, "GLX doesn't support ARB_multisample.");
}
// Require ARB_create_context which has been supported since Mesa 9 unconditionnaly
// and is present in Mesa 8 in an almost always on compile flag. Also assume proprietary
// drivers have it.
if (!mGLX.hasExtension("GLX_ARB_create_context"))
{
return egl::Error(EGL_NOT_INITIALIZED, "GLX doesn't support ARB_create_context.");
}
}
GLXFBConfig contextConfig;
// When glXMakeCurrent is called the visual of the context FBConfig and of
// the drawable must match. This means that when generating the list of EGL
// configs, they must all have the same visual id as our unique GL context.
// Here we find a GLX framebuffer config we like to create our GL context
// so that we are sure there is a decent config given back to the application
// when it queries EGL.
{
int nConfigs;
int attribList[] =
{
// We want at least RGBA8 and DEPTH24_STENCIL8
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_STENCIL_SIZE, 8,
// We want RGBA rendering (vs COLOR_INDEX) and doublebuffer
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DOUBLEBUFFER, True,
// All of these must be supported for full EGL support
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT | GLX_PBUFFER_BIT | GLX_PIXMAP_BIT,
// This makes sure the config have an associated visual Id
GLX_X_RENDERABLE, True,
GLX_CONFIG_CAVEAT, GLX_NONE,
None
};
GLXFBConfig* candidates = mGLX.chooseFBConfig(mXDisplay, DefaultScreen(mXDisplay), attribList, &nConfigs);
if (nConfigs == 0)
{
XFree(candidates);
return egl::Error(EGL_NOT_INITIALIZED, "Could not find a decent GLX FBConfig to create the context.");
}
contextConfig = candidates[0];
XFree(candidates);
}
mContextVisualId = getGLXFBConfigAttrib(contextConfig, GLX_VISUAL_ID);
mContext = mGLX.createContextAttribsARB(mXDisplay, contextConfig, nullptr, True, nullptr);
if (!mContext)
{
return egl::Error(EGL_NOT_INITIALIZED, "Could not create GL context.");
}
// FunctionsGL and DisplayGL need to make a few GL calls, for example to
// query the version of the context so we need to make the context current.
// glXMakeCurrent requires a GLXDrawable so we create a temporary Pbuffer
// (of size 0, 0) for the duration of these calls.
// TODO(cwallez) error checking here
// TODO(cwallez) during the initialization of ANGLE we need a gl context current
// to query things like limits. Ideally we would want to unset the current context
// and destroy the pbuffer before going back to the application but this is TODO
mDummyPbuffer = mGLX.createPbuffer(mXDisplay, contextConfig, nullptr);
mGLX.makeCurrent(mXDisplay, mDummyPbuffer, mContext);
mFunctionsGL = new FunctionsGLGLX(mGLX.getProc);
mFunctionsGL->initialize();
return DisplayGL::initialize(display);
}
void DisplayGLX::terminate()
{
DisplayGL::terminate();
if (mDummyPbuffer)
{
mGLX.destroyPbuffer(mXDisplay, mDummyPbuffer);
mDummyPbuffer = 0;
}
if (mContext)
{
mGLX.destroyContext(mXDisplay, mContext);
mContext = nullptr;
}
mGLX.terminate();
SafeDelete(mFunctionsGL);
}
SurfaceImpl *DisplayGLX::createWindowSurface(const egl::Config *configuration,
EGLNativeWindowType window,
const egl::AttributeMap &attribs)
{
ASSERT(configIdToGLXConfig.count(configuration->configID) > 0);
GLXFBConfig fbConfig = configIdToGLXConfig[configuration->configID];
return new WindowSurfaceGLX(mGLX, window, mXDisplay, mContext, fbConfig);
}
SurfaceImpl *DisplayGLX::createPbufferSurface(const egl::Config *configuration,
const egl::AttributeMap &attribs)
{
//TODO(cwallez) WGL implements it
UNIMPLEMENTED();
return nullptr;
}
SurfaceImpl* DisplayGLX::createPbufferFromClientBuffer(const egl::Config *configuration,
EGLClientBuffer shareHandle,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
SurfaceImpl *DisplayGLX::createPixmapSurface(const egl::Config *configuration,
NativePixmapType nativePixmap,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
egl::Error DisplayGLX::getDevice(DeviceImpl **device)
{
UNIMPLEMENTED();
return egl::Error(EGL_BAD_DISPLAY);
}
egl::ConfigSet DisplayGLX::generateConfigs() const
{
egl::ConfigSet configs;
configIdToGLXConfig.clear();
// GLX_EXT_texture_from_pixmap is required for the "bind to rgb(a)" attributes
bool hasTextureFromPixmap = mGLX.hasExtension("GLX_EXT_texture_from_pixmap");
int glxConfigCount;
GLXFBConfig *glxConfigs = mGLX.getFBConfigs(mXDisplay, DefaultScreen(mXDisplay), &glxConfigCount);
for (int i = 0; i < glxConfigCount; i++)
{
GLXFBConfig glxConfig = glxConfigs[i];
egl::Config config;
// Native stuff
int visualId = getGLXFBConfigAttrib(glxConfig, GLX_VISUAL_ID);
if (visualId != mContextVisualId)
{
// Filter out the configs that are incompatible with our GL context
continue;
}
config.nativeVisualID = visualId;
config.nativeVisualType = getGLXFBConfigAttrib(glxConfig, GLX_X_VISUAL_TYPE);
config.nativeRenderable = EGL_TRUE;
// Buffer sizes
config.redSize = getGLXFBConfigAttrib(glxConfig, GLX_RED_SIZE);
config.greenSize = getGLXFBConfigAttrib(glxConfig, GLX_GREEN_SIZE);
config.blueSize = getGLXFBConfigAttrib(glxConfig, GLX_BLUE_SIZE);
config.alphaSize = getGLXFBConfigAttrib(glxConfig, GLX_ALPHA_SIZE);
config.depthSize = getGLXFBConfigAttrib(glxConfig, GLX_DEPTH_SIZE);
config.stencilSize = getGLXFBConfigAttrib(glxConfig, GLX_STENCIL_SIZE);
config.colorBufferType = EGL_RGB_BUFFER;
config.luminanceSize = 0;
config.alphaMaskSize = 0;
config.bufferSize = config.redSize + config.greenSize + config.blueSize + config.alphaSize;
// Transparency
if (getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_TYPE) == GLX_TRANSPARENT_RGB)
{
config.transparentType = EGL_TRANSPARENT_RGB;
config.transparentRedValue = getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_RED_VALUE);
config.transparentGreenValue = getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_GREEN_VALUE);
config.transparentBlueValue = getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_BLUE_VALUE);
}
else
{
config.transparentType = EGL_NONE;
}
// Pbuffer
config.maxPBufferWidth = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_WIDTH);
config.maxPBufferHeight = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_HEIGHT);
config.maxPBufferPixels = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_PIXELS);
// Caveat
config.configCaveat = EGL_NONE;
int caveat = getGLXFBConfigAttrib(glxConfig, GLX_CONFIG_CAVEAT);
if (caveat == GLX_SLOW_CONFIG)
{
config.configCaveat = EGL_SLOW_CONFIG;
}
else if (caveat == GLX_NON_CONFORMANT_CONFIG)
{
continue;
}
// Misc
config.sampleBuffers = getGLXFBConfigAttrib(glxConfig, GLX_SAMPLE_BUFFERS);
config.samples = getGLXFBConfigAttrib(glxConfig, GLX_SAMPLES);
config.level = getGLXFBConfigAttrib(glxConfig, GLX_LEVEL);
config.bindToTextureRGB = EGL_FALSE;
config.bindToTextureRGBA = EGL_FALSE;
if (hasTextureFromPixmap)
{
config.bindToTextureRGB = getGLXFBConfigAttrib(glxConfig, GLX_BIND_TO_TEXTURE_RGB_EXT);
config.bindToTextureRGBA = getGLXFBConfigAttrib(glxConfig, GLX_BIND_TO_TEXTURE_RGBA_EXT);
}
int glxDrawable = getGLXFBConfigAttrib(glxConfig, GLX_DRAWABLE_TYPE);
config.surfaceType = 0 |
(glxDrawable & GLX_WINDOW_BIT ? EGL_WINDOW_BIT : 0) |
(glxDrawable & GLX_PBUFFER_BIT ? EGL_PBUFFER_BIT : 0) |
(glxDrawable & GLX_PIXMAP_BIT ? EGL_PIXMAP_BIT : 0);
// In GLX_EXT_swap_control querying these is done on a GLXWindow so we just set a default value.
config.maxSwapInterval = 1;
config.minSwapInterval = 1;
// TODO(cwallez) wildly guessing these formats, another TODO says they should be removed anyway
config.renderTargetFormat = GL_RGBA8;
config.depthStencilFormat = GL_DEPTH24_STENCIL8;
// TODO(cwallez) Fill after determining the GL version we are using and what ES version it supports
config.conformant = EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT_KHR;
config.renderableType = EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT_KHR;
// TODO(cwallez) I have no idea what this is
config.matchNativePixmap = EGL_NONE;
int id = configs.add(config);
configIdToGLXConfig[id] = glxConfig;
}
return configs;
}
bool DisplayGLX::isDeviceLost() const
{
// UNIMPLEMENTED();
return false;
}
bool DisplayGLX::testDeviceLost()
{
// UNIMPLEMENTED();
return false;
}
egl::Error DisplayGLX::restoreLostDevice()
{
UNIMPLEMENTED();
return egl::Error(EGL_BAD_DISPLAY);
}
bool DisplayGLX::isValidNativeWindow(EGLNativeWindowType window) const
{
// There is no function in Xlib to check the validity of a Window directly.
// However a small number of functions used to obtain window information
// return a status code (0 meaning failure) and guarantee that they will
// fail if the window doesn't exist (the rational is that these function
// are used by window managers). Out of these function we use XQueryTree
// as it seems to be the simplest; a drawback is that it will allocate
// memory for the list of children, becasue we use a child window for
// WindowSurface.
Window root;
Window parent;
Window *children = nullptr;
unsigned nChildren;
int status = XQueryTree(mXDisplay, window, &root, &parent, &children, &nChildren);
if (children)
{
XFree(children);
}
return status != 0;
}
std::string DisplayGLX::getVendorString() const
{
// UNIMPLEMENTED();
return "";
}
const FunctionsGL *DisplayGLX::getFunctionsGL() const
{
return mFunctionsGL;
}
void DisplayGLX::generateExtensions(egl::DisplayExtensions *outExtensions) const
{
// UNIMPLEMENTED();
}
void DisplayGLX::generateCaps(egl::Caps *outCaps) const
{
// UNIMPLEMENTED();
outCaps->textureNPOT = true;
}
int DisplayGLX::getGLXFBConfigAttrib(GLXFBConfig config, int attrib) const
{
int result;
mGLX.getFBConfigAttrib(mXDisplay, config, attrib, &result);
return result;
}
}
<commit_msg>DisplayGLX: handle EGL_DEFAULT_DISPLAY for ANGLE_platform_angle<commit_after>//
// Copyright (c) 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DisplayGLX.h: GLX implementation of egl::Display
#define GLX_GLXEXT_PROTOTYPES
#include "libANGLE/renderer/gl/glx/DisplayGLX.h"
#include <GL/glxext.h>
#include <EGL/eglext.h>
#include <algorithm>
#include "common/debug.h"
#include "libANGLE/Config.h"
#include "libANGLE/Display.h"
#include "libANGLE/Surface.h"
#include "libANGLE/renderer/gl/glx/WindowSurfaceGLX.h"
namespace rx
{
class FunctionsGLGLX : public FunctionsGL
{
public:
FunctionsGLGLX(PFNGLXGETPROCADDRESSPROC getProc)
: mGetProc(getProc)
{
}
virtual ~FunctionsGLGLX()
{
}
private:
void *loadProcAddress(const std::string &function) override
{
return reinterpret_cast<void*>(mGetProc(reinterpret_cast<const unsigned char*>(function.c_str())));
}
PFNGLXGETPROCADDRESSPROC mGetProc;
};
DisplayGLX::DisplayGLX()
: DisplayGL(),
mFunctionsGL(nullptr),
mContext(nullptr),
mDummyPbuffer(0),
mEGLDisplay(nullptr),
mXDisplay(nullptr)
{
}
DisplayGLX::~DisplayGLX()
{
}
egl::Error DisplayGLX::initialize(egl::Display *display)
{
mEGLDisplay = display;
mXDisplay = display->getNativeDisplayId();
// ANGLE_platform_angle allows the creation of a default display
// using EGL_DEFAULT_DISPLAY (= nullptr). In this case just open
// the display specified by the DISPLAY environment variable.
if (mXDisplay == EGL_DEFAULT_DISPLAY)
{
mXDisplay = XOpenDisplay(NULL);
if (!mXDisplay)
{
return egl::Error(EGL_NOT_INITIALIZED, "Could not open the default X display.");
}
}
egl::Error glxInitResult = mGLX.initialize(mXDisplay);
if (glxInitResult.isError())
{
return glxInitResult;
}
// Check we have the needed extensions
{
if (mGLX.minorVersion == 3 && !mGLX.hasExtension("GLX_ARB_multisample"))
{
return egl::Error(EGL_NOT_INITIALIZED, "GLX doesn't support ARB_multisample.");
}
// Require ARB_create_context which has been supported since Mesa 9 unconditionnaly
// and is present in Mesa 8 in an almost always on compile flag. Also assume proprietary
// drivers have it.
if (!mGLX.hasExtension("GLX_ARB_create_context"))
{
return egl::Error(EGL_NOT_INITIALIZED, "GLX doesn't support ARB_create_context.");
}
}
GLXFBConfig contextConfig;
// When glXMakeCurrent is called the visual of the context FBConfig and of
// the drawable must match. This means that when generating the list of EGL
// configs, they must all have the same visual id as our unique GL context.
// Here we find a GLX framebuffer config we like to create our GL context
// so that we are sure there is a decent config given back to the application
// when it queries EGL.
{
int nConfigs;
int attribList[] =
{
// We want at least RGBA8 and DEPTH24_STENCIL8
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_STENCIL_SIZE, 8,
// We want RGBA rendering (vs COLOR_INDEX) and doublebuffer
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DOUBLEBUFFER, True,
// All of these must be supported for full EGL support
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT | GLX_PBUFFER_BIT | GLX_PIXMAP_BIT,
// This makes sure the config have an associated visual Id
GLX_X_RENDERABLE, True,
GLX_CONFIG_CAVEAT, GLX_NONE,
None
};
GLXFBConfig* candidates = mGLX.chooseFBConfig(mXDisplay, DefaultScreen(mXDisplay), attribList, &nConfigs);
if (nConfigs == 0)
{
XFree(candidates);
return egl::Error(EGL_NOT_INITIALIZED, "Could not find a decent GLX FBConfig to create the context.");
}
contextConfig = candidates[0];
XFree(candidates);
}
mContextVisualId = getGLXFBConfigAttrib(contextConfig, GLX_VISUAL_ID);
mContext = mGLX.createContextAttribsARB(mXDisplay, contextConfig, nullptr, True, nullptr);
if (!mContext)
{
return egl::Error(EGL_NOT_INITIALIZED, "Could not create GL context.");
}
// FunctionsGL and DisplayGL need to make a few GL calls, for example to
// query the version of the context so we need to make the context current.
// glXMakeCurrent requires a GLXDrawable so we create a temporary Pbuffer
// (of size 0, 0) for the duration of these calls.
// TODO(cwallez) error checking here
// TODO(cwallez) during the initialization of ANGLE we need a gl context current
// to query things like limits. Ideally we would want to unset the current context
// and destroy the pbuffer before going back to the application but this is TODO
mDummyPbuffer = mGLX.createPbuffer(mXDisplay, contextConfig, nullptr);
mGLX.makeCurrent(mXDisplay, mDummyPbuffer, mContext);
mFunctionsGL = new FunctionsGLGLX(mGLX.getProc);
mFunctionsGL->initialize();
return DisplayGL::initialize(display);
}
void DisplayGLX::terminate()
{
DisplayGL::terminate();
if (mDummyPbuffer)
{
mGLX.destroyPbuffer(mXDisplay, mDummyPbuffer);
mDummyPbuffer = 0;
}
if (mContext)
{
mGLX.destroyContext(mXDisplay, mContext);
mContext = nullptr;
}
mGLX.terminate();
SafeDelete(mFunctionsGL);
}
SurfaceImpl *DisplayGLX::createWindowSurface(const egl::Config *configuration,
EGLNativeWindowType window,
const egl::AttributeMap &attribs)
{
ASSERT(configIdToGLXConfig.count(configuration->configID) > 0);
GLXFBConfig fbConfig = configIdToGLXConfig[configuration->configID];
return new WindowSurfaceGLX(mGLX, window, mXDisplay, mContext, fbConfig);
}
SurfaceImpl *DisplayGLX::createPbufferSurface(const egl::Config *configuration,
const egl::AttributeMap &attribs)
{
//TODO(cwallez) WGL implements it
UNIMPLEMENTED();
return nullptr;
}
SurfaceImpl* DisplayGLX::createPbufferFromClientBuffer(const egl::Config *configuration,
EGLClientBuffer shareHandle,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
SurfaceImpl *DisplayGLX::createPixmapSurface(const egl::Config *configuration,
NativePixmapType nativePixmap,
const egl::AttributeMap &attribs)
{
UNIMPLEMENTED();
return nullptr;
}
egl::Error DisplayGLX::getDevice(DeviceImpl **device)
{
UNIMPLEMENTED();
return egl::Error(EGL_BAD_DISPLAY);
}
egl::ConfigSet DisplayGLX::generateConfigs() const
{
egl::ConfigSet configs;
configIdToGLXConfig.clear();
// GLX_EXT_texture_from_pixmap is required for the "bind to rgb(a)" attributes
bool hasTextureFromPixmap = mGLX.hasExtension("GLX_EXT_texture_from_pixmap");
int glxConfigCount;
GLXFBConfig *glxConfigs = mGLX.getFBConfigs(mXDisplay, DefaultScreen(mXDisplay), &glxConfigCount);
for (int i = 0; i < glxConfigCount; i++)
{
GLXFBConfig glxConfig = glxConfigs[i];
egl::Config config;
// Native stuff
int visualId = getGLXFBConfigAttrib(glxConfig, GLX_VISUAL_ID);
if (visualId != mContextVisualId)
{
// Filter out the configs that are incompatible with our GL context
continue;
}
config.nativeVisualID = visualId;
config.nativeVisualType = getGLXFBConfigAttrib(glxConfig, GLX_X_VISUAL_TYPE);
config.nativeRenderable = EGL_TRUE;
// Buffer sizes
config.redSize = getGLXFBConfigAttrib(glxConfig, GLX_RED_SIZE);
config.greenSize = getGLXFBConfigAttrib(glxConfig, GLX_GREEN_SIZE);
config.blueSize = getGLXFBConfigAttrib(glxConfig, GLX_BLUE_SIZE);
config.alphaSize = getGLXFBConfigAttrib(glxConfig, GLX_ALPHA_SIZE);
config.depthSize = getGLXFBConfigAttrib(glxConfig, GLX_DEPTH_SIZE);
config.stencilSize = getGLXFBConfigAttrib(glxConfig, GLX_STENCIL_SIZE);
config.colorBufferType = EGL_RGB_BUFFER;
config.luminanceSize = 0;
config.alphaMaskSize = 0;
config.bufferSize = config.redSize + config.greenSize + config.blueSize + config.alphaSize;
// Transparency
if (getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_TYPE) == GLX_TRANSPARENT_RGB)
{
config.transparentType = EGL_TRANSPARENT_RGB;
config.transparentRedValue = getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_RED_VALUE);
config.transparentGreenValue = getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_GREEN_VALUE);
config.transparentBlueValue = getGLXFBConfigAttrib(glxConfig, GLX_TRANSPARENT_BLUE_VALUE);
}
else
{
config.transparentType = EGL_NONE;
}
// Pbuffer
config.maxPBufferWidth = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_WIDTH);
config.maxPBufferHeight = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_HEIGHT);
config.maxPBufferPixels = getGLXFBConfigAttrib(glxConfig, GLX_MAX_PBUFFER_PIXELS);
// Caveat
config.configCaveat = EGL_NONE;
int caveat = getGLXFBConfigAttrib(glxConfig, GLX_CONFIG_CAVEAT);
if (caveat == GLX_SLOW_CONFIG)
{
config.configCaveat = EGL_SLOW_CONFIG;
}
else if (caveat == GLX_NON_CONFORMANT_CONFIG)
{
continue;
}
// Misc
config.sampleBuffers = getGLXFBConfigAttrib(glxConfig, GLX_SAMPLE_BUFFERS);
config.samples = getGLXFBConfigAttrib(glxConfig, GLX_SAMPLES);
config.level = getGLXFBConfigAttrib(glxConfig, GLX_LEVEL);
config.bindToTextureRGB = EGL_FALSE;
config.bindToTextureRGBA = EGL_FALSE;
if (hasTextureFromPixmap)
{
config.bindToTextureRGB = getGLXFBConfigAttrib(glxConfig, GLX_BIND_TO_TEXTURE_RGB_EXT);
config.bindToTextureRGBA = getGLXFBConfigAttrib(glxConfig, GLX_BIND_TO_TEXTURE_RGBA_EXT);
}
int glxDrawable = getGLXFBConfigAttrib(glxConfig, GLX_DRAWABLE_TYPE);
config.surfaceType = 0 |
(glxDrawable & GLX_WINDOW_BIT ? EGL_WINDOW_BIT : 0) |
(glxDrawable & GLX_PBUFFER_BIT ? EGL_PBUFFER_BIT : 0) |
(glxDrawable & GLX_PIXMAP_BIT ? EGL_PIXMAP_BIT : 0);
// In GLX_EXT_swap_control querying these is done on a GLXWindow so we just set a default value.
config.maxSwapInterval = 1;
config.minSwapInterval = 1;
// TODO(cwallez) wildly guessing these formats, another TODO says they should be removed anyway
config.renderTargetFormat = GL_RGBA8;
config.depthStencilFormat = GL_DEPTH24_STENCIL8;
// TODO(cwallez) Fill after determining the GL version we are using and what ES version it supports
config.conformant = EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT_KHR;
config.renderableType = EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT_KHR;
// TODO(cwallez) I have no idea what this is
config.matchNativePixmap = EGL_NONE;
int id = configs.add(config);
configIdToGLXConfig[id] = glxConfig;
}
return configs;
}
bool DisplayGLX::isDeviceLost() const
{
// UNIMPLEMENTED();
return false;
}
bool DisplayGLX::testDeviceLost()
{
// UNIMPLEMENTED();
return false;
}
egl::Error DisplayGLX::restoreLostDevice()
{
UNIMPLEMENTED();
return egl::Error(EGL_BAD_DISPLAY);
}
bool DisplayGLX::isValidNativeWindow(EGLNativeWindowType window) const
{
// There is no function in Xlib to check the validity of a Window directly.
// However a small number of functions used to obtain window information
// return a status code (0 meaning failure) and guarantee that they will
// fail if the window doesn't exist (the rational is that these function
// are used by window managers). Out of these function we use XQueryTree
// as it seems to be the simplest; a drawback is that it will allocate
// memory for the list of children, becasue we use a child window for
// WindowSurface.
Window root;
Window parent;
Window *children = nullptr;
unsigned nChildren;
int status = XQueryTree(mXDisplay, window, &root, &parent, &children, &nChildren);
if (children)
{
XFree(children);
}
return status != 0;
}
std::string DisplayGLX::getVendorString() const
{
// UNIMPLEMENTED();
return "";
}
const FunctionsGL *DisplayGLX::getFunctionsGL() const
{
return mFunctionsGL;
}
void DisplayGLX::generateExtensions(egl::DisplayExtensions *outExtensions) const
{
// UNIMPLEMENTED();
}
void DisplayGLX::generateCaps(egl::Caps *outCaps) const
{
// UNIMPLEMENTED();
outCaps->textureNPOT = true;
}
int DisplayGLX::getGLXFBConfigAttrib(GLXFBConfig config, int attrib) const
{
int result;
mGLX.getFBConfigAttrib(mXDisplay, config, attrib, &result);
return result;
}
}
<|endoftext|> |
<commit_before><commit_msg>:shirt:<commit_after><|endoftext|> |
<commit_before>#include "./label_node.h"
#include <QPainter>
#include <QPoint>
#include "./importer.h"
#include "./mesh.h"
LabelNode::LabelNode(Label label) : label(label)
{
Importer importer;
anchorMesh = importer.import("../assets/sphere.dae", 0);
}
LabelNode::~LabelNode()
{
}
void LabelNode::render(Gl *gl, RenderData renderData)
{
anchorMesh->render(gl, renderData.projectionMatrix, renderData.viewMatrix);
QPainter painter;
painter.begin(gl->paintDevice);
painter.setPen(Qt::blue);
painter.setFont(QFont("Arial", 16));
painter.drawText(QRectF(10, 30, 300, 20), Qt::AlignLeft, "Label 1");
Eigen::Vector4f anchorPosition4D;
anchorPosition4D.head<3>() = label.anchorPosition;
anchorPosition4D.w() = 1.0f;
auto anchorPosition2D =
renderData.projectionMatrix * renderData.viewMatrix * anchorPosition4D;
QPoint anchorScreen(
(anchorPosition2D.x() / anchorPosition2D.w() * 0.5f + 0.5f) *
gl->size.width(),
(anchorPosition2D.y() / anchorPosition2D.w() * -0.5f + 0.5f) *
gl->size.height());
painter.drawArc(QRect(anchorScreen, QSize(4, 4)), 0, 5760);
painter.drawPoint(anchorScreen);
painter.end();
}
<commit_msg>Render a mesh for the label anchor.<commit_after>#include "./label_node.h"
#include <QPainter>
#include <QPoint>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "./importer.h"
#include "./mesh.h"
LabelNode::LabelNode(Label label) : label(label)
{
Importer importer;
anchorMesh = importer.import("../assets/anchor.dae", 0);
}
LabelNode::~LabelNode()
{
}
void LabelNode::render(Gl *gl, RenderData renderData)
{
Eigen::Affine3f transform(Eigen::Translation3f(label.anchorPosition) *
Eigen::Scaling(0.005f));
renderData.modelMatrix = transform.matrix();
anchorMesh->render(gl, renderData);
QPainter painter;
painter.begin(gl->paintDevice);
painter.setPen(Qt::blue);
painter.setFont(QFont("Arial", 16));
painter.drawText(QRectF(10, 30, 300, 20), Qt::AlignLeft, "Label 1");
painter.end();
}
<|endoftext|> |
<commit_before>#ifdef PARTICLES
#include <unistd.h>
#include "../io.h"
#include "../grid3D.h"
#include"../random_functions.h"
#include "particles_3D.h"
#ifdef MPI_CHOLLA
#include"../mpi_routines.h"
#endif
#ifdef PARALLEL_OMP
#include "../parallel_omp.h"
#endif
Particles_3D::Particles_3D( void ){}
void Grid3D::Initialize_Particles( struct parameters *P ){
chprintf( "\nInitializing Particles...\n");
Particles.Initialize( P, Grav, H.xbound, H.ybound, H.zbound, H.xdglobal, H.ydglobal, H.zdglobal );
if (strcmp(P->init, "Uniform")==0) Initialize_Uniform_Particles();
#ifdef MPI_CHOLLA
MPI_Barrier( world );
#endif
chprintf( "Particles Initialized Successfully. \n\n");
}
void Particles_3D::Initialize( struct parameters *P, Grav3D &Grav, Real xbound, Real ybound, Real zbound, Real xdglobal, Real ydglobal, Real zdglobal){
n_local = 0;
n_total = 0;
n_total_initial = 0;
dt = 0.0;
t = 0.0;
max_dt = 1e-3;
C_cfl = 0.3;
#ifdef PARTICLES_CPU
real_vector_t pos_x;
real_vector_t pos_y;
real_vector_t pos_z;
real_vector_t vel_x;
real_vector_t vel_y;
real_vector_t vel_z;
real_vector_t grav_x;
real_vector_t grav_y;
real_vector_t grav_z;
#ifndef SINGLE_PARTICLE_MASS
real_vector_t mass;
#endif
#ifdef PARTICLE_IDS
int_vector_t partIDs;
#endif
#ifdef MPI_CHOLLA
int_vector_t out_indxs_vec_x0;
int_vector_t out_indxs_vec_x1;
int_vector_t out_indxs_vec_y0;
int_vector_t out_indxs_vec_y1;
int_vector_t out_indxs_vec_z0;
int_vector_t out_indxs_vec_z1;
#endif
#endif //PARTICLES_CPU
//Initialize Grid Values
G.nx_local = Grav.nx_local;
G.ny_local = Grav.ny_local;
G.nz_local = Grav.nz_local;
G.nx_total = Grav.nx_total;
G.ny_total = Grav.ny_total;
G.nz_total = Grav.nz_total;
G.dx = Grav.dx;
G.dy = Grav.dy;
G.dz = Grav.dz;
G.xMin = Grav.xMin;
G.yMin = Grav.yMin;
G.zMin = Grav.zMin;
G.xMax = G.xMin + G.nx_local*G.dx;
G.yMax = G.yMin + G.ny_local*G.dy;
G.zMax = G.zMin + G.nz_local*G.dz;
G.domainMin_x = xbound;
G.domainMax_x = xbound + xdglobal;
G.domainMin_y = ybound;
G.domainMax_y = ybound + ydglobal;
G.domainMin_z = zbound;
G.domainMax_z = zbound + zdglobal;
G.n_ghost_particles_grid = 1;
G.n_cells = (G.nx_local+2*G.n_ghost_particles_grid) * (G.ny_local+2*G.n_ghost_particles_grid) * (G.nz_local+2*G.n_ghost_particles_grid);
INITIAL = true;
TRANSFER_DENSITY_BOUNDARIES = false;
TRANSFER_PARTICLES_BOUNDARIES = false;
Allocate_Memory();
Initialize_Grid_Values();
// Initialize Particles
if (strcmp(P->init, "Spherical_Overdensity_3D")==0) Initialize_Sphere();
if (strcmp(P->init, "Zeldovich_Pancake")==0) Initialize_Zeldovich_Pancake( P );
if (strcmp(P->init, "Read_Grid")==0) Load_Particles_Data( P );
#ifdef MPI_CHOLLA
n_total_initial = ReducePartIntSum(n_local);
#else
n_total_initial = n_local;
#endif
chprintf("Particles Initialized: \n n_local: %lu \n", n_local );
chprintf(" n_total: %lu \n", n_total_initial );
chprintf(" xDomain_local: [%.4f %.4f ] [%.4f %.4f ] [%.4f %.4f ]\n", G.xMin, G.xMax, G.yMin, G.yMax, G.zMin, G.zMax );
chprintf(" xDomain_global: [%.4f %.4f ] [%.4f %.4f ] [%.4f %.4f ]\n", G.domainMin_x, G.domainMax_x, G.domainMin_y, G.domainMax_y, G.domainMin_z, G.domainMax_z);
chprintf(" dx: %f %f %f\n", G.dx, G.dy, G.dz );
#ifdef PARTICLE_IDS
chprintf(" Tracking particle IDs\n");
#endif
#ifdef PRINT_DOMAIN
for (int n=0; n<nproc; n++){
if (procID == n ) std::cout << procID << " x["<< G.xMin << "," << G.xMax << "] " << " y["<< G.yMin << "," << G.yMax << "] " << " z["<< G.zMin << "," << G.zMax << "] " << std::endl;
usleep( 100 );
}
#endif
#ifdef PARALLEL_OMP
chprintf(" Using OMP for particles calculations\n");
int n_omp_max = omp_get_max_threads();
chprintf(" MAX OMP Threads: %d\n", n_omp_max);
chprintf(" N OMP Threads per MPI process: %d\n", N_OMP_THREADS);
#ifdef PRINT_OMP_DOMAIN
// Print omp domain for each omp thread
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t omp_pIndx_start, omp_pIndx_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
#pragma omp barrier
Get_OMP_Particles_Indxs( n_local, n_omp_procs, omp_id, &omp_pIndx_start, &omp_pIndx_end );
for (int omp_indx = 0; omp_indx<n_omp_procs; omp_indx++){
if (omp_id == omp_indx) chprintf( " omp_id:%d p_start:%ld p_end:%ld \n", omp_id, omp_pIndx_start, omp_pIndx_end );
}
}
#endif//PRINT_OMP_DOMAIN
#endif//PARALLEL_OMP
#ifdef MPI_CHOLLA
chprintf( " N_Particles Boundaries Buffer Size: %d\n", N_PARTICLES_TRANSFER);
chprintf( " N_Data per Particle Transfer: %d\n", N_DATA_PER_PARTICLE_TRANSFER);
#endif
}
void Particles_3D::Allocate_Memory( void ){
G.density = (Real *) malloc(G.n_cells*sizeof(Real));
#ifdef PARTICLES_CPU
G.gravity_x = (Real *) malloc(G.n_cells*sizeof(Real));
G.gravity_y = (Real *) malloc(G.n_cells*sizeof(Real));
G.gravity_z = (Real *) malloc(G.n_cells*sizeof(Real));
#endif
}
void Particles_3D::Initialize_Grid_Values( void ){
int id;
for( id=0; id<G.n_cells; id++ ){
G.density[id] = 0;
#ifdef PARTICLES_CPU
G.gravity_x[id] = 0;
G.gravity_y[id] = 0;
G.gravity_z[id] = 0;
#endif
}
}
void Particles_3D::Initialize_Sphere( void ){
int i, j, k, id;
Real center_x, center_y, center_z, radius, sphereR;
center_x = 0.5;
center_y = 0.5;
center_z = 0.5;;
sphereR = 0.2;
part_int_t n_particles_local = G.nx_local*G.ny_local*G.nz_local;
part_int_t n_particles_total = G.nx_total*G.ny_total*G.nz_total;
Real rho_start = 1;
Real M_sphere = 4./3 * M_PI* rho_start * sphereR*sphereR*sphereR;
Real Mparticle = M_sphere / n_particles_total;
#ifdef SINGLE_PARTICLE_MASS
particle_mass = Mparticle;
#endif
part_int_t pID = 0;
Real pPos_x, pPos_y, pPos_z, r;
while ( pID < n_particles_local ){
pPos_x = Rand_Real( G.xMin, G.xMax );
pPos_y = Rand_Real( G.yMin, G.yMax );
pPos_z = Rand_Real( G.zMin, G.zMax );
r = sqrt( (pPos_x-center_x)*(pPos_x-center_x) + (pPos_y-center_y)*(pPos_y-center_y) + (pPos_z-center_z)*(pPos_z-center_z) );
if ( r > sphereR ) continue;
#ifdef PARTICLES_CPU
pos_x.push_back( pPos_x );
pos_y.push_back( pPos_y );
pos_z.push_back( pPos_z);
vel_x.push_back( 0.0 );
vel_y.push_back( 0.0 );
vel_z.push_back( 0.0 );
grav_x.push_back( 0.0 );
grav_y.push_back( 0.0 );
grav_z.push_back( 0.0 );
#ifdef PARTICLE_IDS
partIDs.push_back( pID );
#endif
#ifndef SINGLE_PARTICLE_MASS
mass.push_back( Mparticle );
#endif
#endif //PARTICLES_CPU
pID += 1;
}
n_local = pos_x.size();
chprintf( " Particles Uniform Sphere Initialized, n_local: %lu\n", n_local);
}
void Particles_3D::Initialize_Zeldovich_Pancake( struct parameters *P ){
chprintf("Setting Zeldovich Pancake initial conditions...\n");
// n_local = pos_x.size();
n_local = 0;
chprintf( " Particles Zeldovich Pancake Initialized, n_local: %lu\n", n_local);
}
void Grid3D::Initialize_Uniform_Particles(){
int i, j, k, id;
Real x_pos, y_pos, z_pos;
Real dVol, Mparticle;
dVol = H.dx * H.dy * H.dz;
Mparticle = dVol;
#ifdef SINGLE_PARTICLE_MASS
Particles.particle_mass = Mparticle;
#endif
part_int_t pID = 0;
for (k=H.n_ghost; k<H.nz-H.n_ghost; k++) {
for (j=H.n_ghost; j<H.ny-H.n_ghost; j++) {
for (i=H.n_ghost; i<H.nx-H.n_ghost; i++) {
id = i + j*H.nx + k*H.nx*H.ny;
// // get the centered cell positions at (i,j,k)
Get_Position(i, j, k, &x_pos, &y_pos, &z_pos);
#ifdef PARTICLES_CPU
Particles.pos_x.push_back( x_pos - 0.25*H.dx );
Particles.pos_y.push_back( y_pos - 0.25*H.dy );
Particles.pos_z.push_back( z_pos - 0.25*H.dz );
Particles.vel_x.push_back( 0.0 );
Particles.vel_y.push_back( 0.0 );
Particles.vel_z.push_back( 0.0 );
Particles.grav_x.push_back( 0.0 );
Particles.grav_y.push_back( 0.0 );
Particles.grav_z.push_back( 0.0 );
#ifdef PARTICLE_IDS
Particles.partIDs.push_back( pID );
#endif
#ifndef SINGLE_PARTICLE_MASS
Particles.mass.push_back( Mparticle );
#endif
#endif //PARTICLES_CPU
pID += 1;
}
}
}
#ifdef PARTICLES_CPU
Particles.n_local = Particles.pos_x.size();
#endif
#ifdef MPI_CHOLLA
Particles.n_total_initial = ReducePartIntSum(Particles.n_local);
#else
Particles.n_total_initial = Particles.n_local;
#endif
chprintf( " Particles Uniform Grid Initialized, n_local: %lu, n_total: %lu\n", Particles.n_local, Particles.n_total_initial );
}
void Particles_3D::Free_Memory(void){
free(G.density);
free(G.gravity_x);
free(G.gravity_y);
free(G.gravity_z);
pos_x.clear();
pos_y.clear();
pos_z.clear();
vel_x.clear();
vel_y.clear();
vel_z.clear();
grav_x.clear();
grav_y.clear();
grav_z.clear();
#ifdef PARTICLE_IDS
partIDs.clear();
#endif
#ifndef SINGLE_PARTICLE_MASS
mass.clear();
#endif
#ifdef MPI_CHOLLA
free(send_buffer_x0_particles);
free(send_buffer_x1_particles);
free(recv_buffer_x0_particles);
free(recv_buffer_x1_particles);
free(send_buffer_y0_particles);
free(send_buffer_y1_particles);
free(recv_buffer_y0_particles);
free(recv_buffer_y1_particles);
free(send_buffer_z0_particles);
free(send_buffer_z1_particles);
free(recv_buffer_z0_particles);
free(recv_buffer_z1_particles);
#endif
}
void Particles_3D::Reset( void ){
Free_Memory();
}
#endif//PARTICLES<commit_msg>added GPU to particles initialization<commit_after>#ifdef PARTICLES
#include <unistd.h>
#include "../io.h"
#include "../grid3D.h"
#include"../random_functions.h"
#include "particles_3D.h"
#ifdef MPI_CHOLLA
#include"../mpi_routines.h"
#endif
#ifdef PARALLEL_OMP
#include "../parallel_omp.h"
#endif
Particles_3D::Particles_3D( void ){}
void Grid3D::Initialize_Particles( struct parameters *P ){
chprintf( "\nInitializing Particles...\n");
Particles.Initialize( P, Grav, H.xbound, H.ybound, H.zbound, H.xdglobal, H.ydglobal, H.zdglobal );
if (strcmp(P->init, "Uniform")==0) Initialize_Uniform_Particles();
#ifdef MPI_CHOLLA
MPI_Barrier( world );
#endif
chprintf( "Particles Initialized Successfully. \n\n");
}
void Particles_3D::Initialize( struct parameters *P, Grav3D &Grav, Real xbound, Real ybound, Real zbound, Real xdglobal, Real ydglobal, Real zdglobal){
n_local = 0;
n_total = 0;
n_total_initial = 0;
dt = 0.0;
t = 0.0;
max_dt = 1e-3;
C_cfl = 0.3;
#ifdef PARTICLES_CPU
real_vector_t pos_x;
real_vector_t pos_y;
real_vector_t pos_z;
real_vector_t vel_x;
real_vector_t vel_y;
real_vector_t vel_z;
real_vector_t grav_x;
real_vector_t grav_y;
real_vector_t grav_z;
#ifndef SINGLE_PARTICLE_MASS
real_vector_t mass;
#endif
#ifdef PARTICLE_IDS
int_vector_t partIDs;
#endif
#ifdef MPI_CHOLLA
int_vector_t out_indxs_vec_x0;
int_vector_t out_indxs_vec_x1;
int_vector_t out_indxs_vec_y0;
int_vector_t out_indxs_vec_y1;
int_vector_t out_indxs_vec_z0;
int_vector_t out_indxs_vec_z1;
#endif
#endif //PARTICLES_CPU
//Initialize Grid Values
G.nx_local = Grav.nx_local;
G.ny_local = Grav.ny_local;
G.nz_local = Grav.nz_local;
G.nx_total = Grav.nx_total;
G.ny_total = Grav.ny_total;
G.nz_total = Grav.nz_total;
G.dx = Grav.dx;
G.dy = Grav.dy;
G.dz = Grav.dz;
G.xMin = Grav.xMin;
G.yMin = Grav.yMin;
G.zMin = Grav.zMin;
G.xMax = G.xMin + G.nx_local*G.dx;
G.yMax = G.yMin + G.ny_local*G.dy;
G.zMax = G.zMin + G.nz_local*G.dz;
G.domainMin_x = xbound;
G.domainMax_x = xbound + xdglobal;
G.domainMin_y = ybound;
G.domainMax_y = ybound + ydglobal;
G.domainMin_z = zbound;
G.domainMax_z = zbound + zdglobal;
G.n_ghost_particles_grid = 1;
G.n_cells = (G.nx_local+2*G.n_ghost_particles_grid) * (G.ny_local+2*G.n_ghost_particles_grid) * (G.nz_local+2*G.n_ghost_particles_grid);
#ifdef PARTICLES_GPU
G.size_dt_array = 1024*128;
G.n_cells_potential = ( G.nx_local + 2*N_GHOST_POTENTIAL ) * ( G.ny_local + 2*N_GHOST_POTENTIAL ) * ( G.nz_local + 2*N_GHOST_POTENTIAL );
#endif
INITIAL = true;
TRANSFER_DENSITY_BOUNDARIES = false;
TRANSFER_PARTICLES_BOUNDARIES = false;
Allocate_Memory();
Initialize_Grid_Values();
// Initialize Particles
if (strcmp(P->init, "Spherical_Overdensity_3D")==0) Initialize_Sphere();
if (strcmp(P->init, "Zeldovich_Pancake")==0) Initialize_Zeldovich_Pancake( P );
if (strcmp(P->init, "Read_Grid")==0) Load_Particles_Data( P );
#ifdef MPI_CHOLLA
n_total_initial = ReducePartIntSum(n_local);
#else
n_total_initial = n_local;
#endif
chprintf("Particles Initialized: \n n_local: %lu \n", n_local );
chprintf(" n_total: %lu \n", n_total_initial );
chprintf(" xDomain_local: [%.4f %.4f ] [%.4f %.4f ] [%.4f %.4f ]\n", G.xMin, G.xMax, G.yMin, G.yMax, G.zMin, G.zMax );
chprintf(" xDomain_global: [%.4f %.4f ] [%.4f %.4f ] [%.4f %.4f ]\n", G.domainMin_x, G.domainMax_x, G.domainMin_y, G.domainMax_y, G.domainMin_z, G.domainMax_z);
chprintf(" dx: %f %f %f\n", G.dx, G.dy, G.dz );
#ifdef PARTICLE_IDS
chprintf(" Tracking particle IDs\n");
#endif
#ifdef PRINT_DOMAIN
for (int n=0; n<nproc; n++){
if (procID == n ) std::cout << procID << " x["<< G.xMin << "," << G.xMax << "] " << " y["<< G.yMin << "," << G.yMax << "] " << " z["<< G.zMin << "," << G.zMax << "] " << std::endl;
usleep( 100 );
}
#endif
#if defined(PARALLEL_OMP) && defined(PARTICLES_CPU)
chprintf(" Using OMP for particles calculations\n");
int n_omp_max = omp_get_max_threads();
chprintf(" MAX OMP Threads: %d\n", n_omp_max);
chprintf(" N OMP Threads per MPI process: %d\n", N_OMP_THREADS);
#ifdef PRINT_OMP_DOMAIN
// Print omp domain for each omp thread
#pragma omp parallel num_threads( N_OMP_THREADS )
{
int omp_id, n_omp_procs;
part_int_t omp_pIndx_start, omp_pIndx_end;
omp_id = omp_get_thread_num();
n_omp_procs = omp_get_num_threads();
#pragma omp barrier
Get_OMP_Particles_Indxs( n_local, n_omp_procs, omp_id, &omp_pIndx_start, &omp_pIndx_end );
for (int omp_indx = 0; omp_indx<n_omp_procs; omp_indx++){
if (omp_id == omp_indx) chprintf( " omp_id:%d p_start:%ld p_end:%ld \n", omp_id, omp_pIndx_start, omp_pIndx_end );
}
}
#endif//PRINT_OMP_DOMAIN
#endif//PARALLEL_OMP
#ifdef MPI_CHOLLA
chprintf( " N_Particles Boundaries Buffer Size: %d\n", N_PARTICLES_TRANSFER);
chprintf( " N_Data per Particle Transfer: %d\n", N_DATA_PER_PARTICLE_TRANSFER);
#endif
}
void Particles_3D::Allocate_Memory( void ){
G.density = (Real *) malloc(G.n_cells*sizeof(Real));
#ifdef PARTICLES_CPU
G.gravity_x = (Real *) malloc(G.n_cells*sizeof(Real));
G.gravity_y = (Real *) malloc(G.n_cells*sizeof(Real));
G.gravity_z = (Real *) malloc(G.n_cells*sizeof(Real));
#endif
#ifdef PARTICLES_GPU
Allocate_Memory_GPU();
G.dti_array_host = (Real *) malloc(G.size_dt_array*sizeof(Real));
#endif
}
void Particles_3D::Initialize_Grid_Values( void ){
int id;
for( id=0; id<G.n_cells; id++ ){
G.density[id] = 0;
#ifdef PARTICLES_CPU
G.gravity_x[id] = 0;
G.gravity_y[id] = 0;
G.gravity_z[id] = 0;
#endif
}
}
void Particles_3D::Initialize_Sphere( void ){
int i, j, k, id;
Real center_x, center_y, center_z, radius, sphereR;
center_x = 0.5;
center_y = 0.5;
center_z = 0.5;;
sphereR = 0.2;
part_int_t n_particles_local = G.nx_local*G.ny_local*G.nz_local;
part_int_t n_particles_total = G.nx_total*G.ny_total*G.nz_total;
Real rho_start = 1;
Real M_sphere = 4./3 * M_PI* rho_start * sphereR*sphereR*sphereR;
Real Mparticle = M_sphere / n_particles_total;
#ifdef SINGLE_PARTICLE_MASS
particle_mass = Mparticle;
#endif
part_int_t pID = 0;
Real pPos_x, pPos_y, pPos_z, r;
while ( pID < n_particles_local ){
pPos_x = Rand_Real( G.xMin, G.xMax );
pPos_y = Rand_Real( G.yMin, G.yMax );
pPos_z = Rand_Real( G.zMin, G.zMax );
r = sqrt( (pPos_x-center_x)*(pPos_x-center_x) + (pPos_y-center_y)*(pPos_y-center_y) + (pPos_z-center_z)*(pPos_z-center_z) );
if ( r > sphereR ) continue;
#ifdef PARTICLES_CPU
pos_x.push_back( pPos_x );
pos_y.push_back( pPos_y );
pos_z.push_back( pPos_z);
vel_x.push_back( 0.0 );
vel_y.push_back( 0.0 );
vel_z.push_back( 0.0 );
grav_x.push_back( 0.0 );
grav_y.push_back( 0.0 );
grav_z.push_back( 0.0 );
#ifdef PARTICLE_IDS
partIDs.push_back( pID );
#endif
#ifndef SINGLE_PARTICLE_MASS
mass.push_back( Mparticle );
#endif
#endif //PARTICLES_CPU
pID += 1;
}
#ifdef PARTICLES_CPU
n_local = pos_x.size();
#endif
chprintf( " Particles Uniform Sphere Initialized, n_local: %lu\n", n_local);
}
void Particles_3D::Initialize_Zeldovich_Pancake( struct parameters *P ){
chprintf("Setting Zeldovich Pancake initial conditions...\n");
// n_local = pos_x.size();
n_local = 0;
chprintf( " Particles Zeldovich Pancake Initialized, n_local: %lu\n", n_local);
}
void Grid3D::Initialize_Uniform_Particles(){
int i, j, k, id;
Real x_pos, y_pos, z_pos;
Real dVol, Mparticle;
dVol = H.dx * H.dy * H.dz;
Mparticle = dVol;
#ifdef SINGLE_PARTICLE_MASS
Particles.particle_mass = Mparticle;
#endif
part_int_t pID = 0;
for (k=H.n_ghost; k<H.nz-H.n_ghost; k++) {
for (j=H.n_ghost; j<H.ny-H.n_ghost; j++) {
for (i=H.n_ghost; i<H.nx-H.n_ghost; i++) {
id = i + j*H.nx + k*H.nx*H.ny;
// // get the centered cell positions at (i,j,k)
Get_Position(i, j, k, &x_pos, &y_pos, &z_pos);
#ifdef PARTICLES_CPU
Particles.pos_x.push_back( x_pos - 0.25*H.dx );
Particles.pos_y.push_back( y_pos - 0.25*H.dy );
Particles.pos_z.push_back( z_pos - 0.25*H.dz );
Particles.vel_x.push_back( 0.0 );
Particles.vel_y.push_back( 0.0 );
Particles.vel_z.push_back( 0.0 );
Particles.grav_x.push_back( 0.0 );
Particles.grav_y.push_back( 0.0 );
Particles.grav_z.push_back( 0.0 );
#ifdef PARTICLE_IDS
Particles.partIDs.push_back( pID );
#endif
#ifndef SINGLE_PARTICLE_MASS
Particles.mass.push_back( Mparticle );
#endif
#endif //PARTICLES_CPU
pID += 1;
}
}
}
#ifdef PARTICLES_CPU
Particles.n_local = Particles.pos_x.size();
#endif
#ifdef MPI_CHOLLA
Particles.n_total_initial = ReducePartIntSum(Particles.n_local);
#else
Particles.n_total_initial = Particles.n_local;
#endif
chprintf( " Particles Uniform Grid Initialized, n_local: %lu, n_total: %lu\n", Particles.n_local, Particles.n_total_initial );
}
void Particles_3D::Free_Memory(void){
free(G.density);
#ifdef PARTICLES_CPU
free(G.gravity_x);
free(G.gravity_y);
free(G.gravity_z);
pos_x.clear();
pos_y.clear();
pos_z.clear();
vel_x.clear();
vel_y.clear();
vel_z.clear();
grav_x.clear();
grav_y.clear();
grav_z.clear();
#ifdef PARTICLE_IDS
partIDs.clear();
#endif
#ifndef SINGLE_PARTICLE_MASS
mass.clear();
#endif
#endif //PARTICLES_CPU
#ifdef MPI_CHOLLA
free(send_buffer_x0_particles);
free(send_buffer_x1_particles);
free(recv_buffer_x0_particles);
free(recv_buffer_x1_particles);
free(send_buffer_y0_particles);
free(send_buffer_y1_particles);
free(recv_buffer_y0_particles);
free(recv_buffer_y1_particles);
free(send_buffer_z0_particles);
free(send_buffer_z1_particles);
free(recv_buffer_z0_particles);
free(recv_buffer_z1_particles);
#endif
}
void Particles_3D::Reset( void ){
Free_Memory();
#ifdef PARTICLES_GPU
free(G.dti_array_host);
Free_Memory_GPU();
#endif
}
#endif//PARTICLES<|endoftext|> |
<commit_before>//
// Created by Martin Hansen on 18/04/16.
//
#include "KnowledgeBase.h"
void KnowledgeBase::aStar(int start, Clause goal) {
std::deque<Clause> queue; // Open set, frontier, to be visited
clauses[start].distanceFromStart = 0;
clauses[start].calcHeuristicDistance();
clauses[start].updateTotalDistance();
queue.push_back(clauses[start]);
double tempDistanceFromStart;
std::deque<Clause>::iterator iterator;
while (!queue.empty()) {
std::sort(queue.begin(), queue.end());
int currentIndex = getIndex(queue.front());
if (clauses[currentIndex] == goal) {
reconstructPath(start, currentIndex);
queue.clear();
break;
}
queue.pop_front();
clauses[currentIndex].visited = true;
clausalResolution(clauses[currentIndex]);
std::vector<std::pair<int, std::string>> neighbors = clauses[currentIndex].neighbors;
for (auto neighbor : neighbors) {
int index = neighbor.first;
if (clauses[index].visited) {
continue;
}
tempDistanceFromStart = clauses[currentIndex].distanceFromStart + 1;
iterator = std::find(queue.begin(), queue.end(), clauses[index]);
if (iterator == queue.end()) {
updateClause(index, tempDistanceFromStart, currentIndex);
queue.push_front(clauses[index]);
}
else if (tempDistanceFromStart >= clauses[index].distanceFromStart) {
continue;
}
else {
updateClause(index, tempDistanceFromStart, currentIndex);
iterator->cameFrom = clauses[index].cameFrom;
iterator->distanceFromStart = clauses[index].distanceFromStart;
iterator->heuristic_distance = clauses[index].heuristic_distance;
iterator->updateTotalDistance();
}
}
}
}
void KnowledgeBase::reconstructPath(int start, int goal) {
std::deque<std::string> path;
int currentIndex = goal;
int previousIndex;
std::vector<std::pair<int, std::string>>::iterator iterator;
while (currentIndex != start) {
previousIndex = clauses[currentIndex].cameFrom;
iterator = std::find_if(clauses[previousIndex].neighbors.begin(), clauses[previousIndex].neighbors.end(),
[currentIndex](const std::pair<int, std::string> element) {
return element.first == currentIndex;
});
currentIndex = previousIndex;
path.push_front(clauses[previousIndex].toString() + " && " + iterator -> second + " => " +
clauses[currentIndex].toString());
}
std::cout << "Resolution:\n";
for (auto s : path) {
std::cout << s << "\n";
}
}
void KnowledgeBase::updateClause(int clause, double tempDistanceFromStart, int current) {
clauses[clause].cameFrom = current;
clauses[clause].distanceFromStart = tempDistanceFromStart;
clauses[clause].calcHeuristicDistance();
clauses[clause].updateTotalDistance();
}
void KnowledgeBase::addClause(Clause &clause) {
clauses.push_back(clause);
}
void KnowledgeBase::clausalResolution(Clause &clause) {
for(auto c : clauses) {
std::deque<Literal> allSymbols;
std::deque<Literal> resolutedSymbols;
joinLiterals(allSymbols, clause.getSymbols());
joinLiterals(allSymbols, c.getSymbols());
eliminateDuplicateLiterals(allSymbols, resolutedSymbols);
Clause result(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
result.setSymbols(resolutedSymbols);
auto iterator = std::find(clauses.begin(), clauses.end(), result);
if(iterator == clauses.end()) {
clauses.push_back(result);
clause.addNeighbor(boost::lexical_cast<int>(clauses.size() - 1), c.toString());
} else if (clause == result) {
continue;
} else {
clause.addNeighbor(boost::lexical_cast<int>(std::distance(clauses.begin(), iterator)), c.toString());
}
std::cout << clause << " && " << c << " => " << result << "\n";
}
}
void KnowledgeBase::joinLiterals(std::deque<Literal> &to, std::deque<Literal> &symbols) {
std::deque<Literal>::const_iterator iterator;
for(iterator = symbols.begin(); iterator != symbols.end(); ++iterator) {
to.push_back(*iterator);
}
}
void KnowledgeBase::eliminateDuplicateLiterals(std::deque<Literal, std::allocator<Literal>> &allSymbols,
std::deque<Literal, std::allocator<Literal>> &resolutedSymbols) {
for(Literal& l : allSymbols) {
Literal inverse(l.toString());
inverse.negated = !inverse.negated;
if(std::find(allSymbols.begin(), allSymbols.end(), inverse) == allSymbols.end())
resolutedSymbols.push_back(l);
}
if(resolutedSymbols.size() == 0) {
Literal emptyLiteral("Ø");
resolutedSymbols.push_back(emptyLiteral);
}
}
int KnowledgeBase::getIndex(Clause &clause) {
auto iterator = std::find(clauses.begin(), clauses.end(), clause);
if(iterator != clauses.end()) {
return boost::lexical_cast<int>(std::distance(clauses.begin(), iterator));
}
return -1;
}<commit_msg>Fixed memory leak in code, but still there is a change of reference values which should not be happening<commit_after>//
// Created by Martin Hansen on 18/04/16.
//
#include "KnowledgeBase.h"
void KnowledgeBase::aStar(int start, Clause goal) {
std::deque<Clause> queue; // Open set, frontier, to be visited
clauses[start].distanceFromStart = 0;
clauses[start].calcHeuristicDistance();
clauses[start].updateTotalDistance();
queue.push_back(clauses[start]);
double tempDistanceFromStart;
std::deque<Clause>::iterator iterator;
while (!queue.empty()) {
std::sort(queue.begin(), queue.end());
int currentIndex = getIndex(queue.front());
if (clauses[currentIndex] == goal) {
reconstructPath(start, currentIndex);
queue.clear();
break;
}
queue.pop_front();
clauses[currentIndex].visited = true;
clausalResolution(clauses[currentIndex]);
std::vector<std::pair<int, std::string>> neighbors = clauses[currentIndex].neighbors;
for (auto neighbor : neighbors) {
int index = neighbor.first;
if (clauses[index].visited) {
continue;
}
tempDistanceFromStart = clauses[currentIndex].distanceFromStart + 1;
iterator = std::find(queue.begin(), queue.end(), clauses[index]);
if (iterator == queue.end()) {
updateClause(index, tempDistanceFromStart, currentIndex);
queue.push_front(clauses[index]);
}
else if (tempDistanceFromStart >= clauses[index].distanceFromStart) {
continue;
}
else {
updateClause(index, tempDistanceFromStart, currentIndex);
iterator->cameFrom = clauses[index].cameFrom;
iterator->distanceFromStart = clauses[index].distanceFromStart;
iterator->heuristic_distance = clauses[index].heuristic_distance;
iterator->updateTotalDistance();
}
}
}
}
void KnowledgeBase::reconstructPath(int start, int goal) {
std::deque<std::string> path;
int currentIndex = goal;
int previousIndex;
std::vector<std::pair<int, std::string>>::iterator iterator;
while (currentIndex != start) {
previousIndex = clauses[currentIndex].cameFrom;
iterator = std::find_if(clauses[previousIndex].neighbors.begin(), clauses[previousIndex].neighbors.end(),
[currentIndex](const std::pair<int, std::string> element) {
return element.first == currentIndex;
});
currentIndex = previousIndex;
path.push_front(clauses[previousIndex].toString() + " && " + iterator -> second + " => " +
clauses[currentIndex].toString());
}
std::cout << "Resolution:\n";
for (auto s : path) {
std::cout << s << "\n";
}
}
void KnowledgeBase::updateClause(int clause, double tempDistanceFromStart, int current) {
clauses[clause].cameFrom = current;
clauses[clause].distanceFromStart = tempDistanceFromStart;
clauses[clause].calcHeuristicDistance();
clauses[clause].updateTotalDistance();
}
void KnowledgeBase::addClause(Clause &clause) {
clauses.push_back(clause);
}
void KnowledgeBase::clausalResolution(Clause &clause) {
for(auto c : clauses) {
std::deque<Literal> allSymbols;
std::deque<Literal> resolutedSymbols;
joinLiterals(allSymbols, clause.getSymbols());
joinLiterals(allSymbols, c.getSymbols());
eliminateDuplicateLiterals(allSymbols, resolutedSymbols);
Clause result(std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
result.setSymbols(resolutedSymbols);
std::cout << clause << " && " << c << " => " << result << "\n";
std::vector<Clause>::const_iterator iterator = std::find(clauses.begin(), clauses.end(), result);
if(iterator == clauses.end()) {
clauses.push_back(result);
clause.addNeighbor(boost::lexical_cast<int>(clauses.size() - 1), c.toString());
} else if (*iterator == result) {
continue;
} else {
clause.addNeighbor(boost::lexical_cast<int>(std::distance(clauses.cbegin(), iterator)), c.toString());
}
}
}
void KnowledgeBase::joinLiterals(std::deque<Literal> &to, std::deque<Literal> &symbols) {
std::deque<Literal>::const_iterator iterator;
for(iterator = symbols.begin(); iterator != symbols.end(); ++iterator) {
to.push_back(*iterator);
}
}
void KnowledgeBase::eliminateDuplicateLiterals(std::deque<Literal, std::allocator<Literal>> &allSymbols,
std::deque<Literal, std::allocator<Literal>> &resolutedSymbols) {
for(Literal& l : allSymbols) {
Literal inverse(l.toString());
inverse.negated = !inverse.negated;
if(std::find(allSymbols.begin(), allSymbols.end(), inverse) == allSymbols.end())
resolutedSymbols.push_back(l);
}
if(resolutedSymbols.size() == 0) {
Literal emptyLiteral("Ø");
resolutedSymbols.push_back(emptyLiteral);
}
}
int KnowledgeBase::getIndex(Clause &clause) {
auto iterator = std::find(clauses.begin(), clauses.end(), clause);
if(iterator != clauses.end()) {
return boost::lexical_cast<int>(std::distance(clauses.begin(), iterator));
}
return -1;
}<|endoftext|> |
<commit_before>#include "websocketbroker.h"
#include "logger.h"
#include "errors/errorresponse.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QVector>
#include <QFile>
#include <QCoreApplication>
#include <QRegularExpression>
WebSocketBroker::WebSocketBroker(const QString& vssDir, const QString &vssName, const QString &brokerUrl, QObject *parent) :
QObject(parent), m_brokerUrl(brokerUrl)
{
loadJson(vssDir + "/" + vssName + ".json");
loadTempSignalList(vssDir + "/" + vssName + ".vsi");
connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketBroker::onConnected);
connect(this, &WebSocketBroker::sendMessageSignal, this, &WebSocketBroker::sendMessageSlot, Qt::QueuedConnection);
m_webSocket.open(QUrl(brokerUrl));
}
int WebSocketBroker::getSignalValue(const QString& path, QJsonArray& values)
{
// Check if path is single leaf.
// Check if path is single branch.
// Check if path contains asterisk.
// Check if path contains asterisk and leaf.
QJsonArray paths = parseGetPath(path);
DEBUG("WebSocketBroker",path);
QMutexLocker locker(&m_mutex);
if(!checkOpenDSConnection()) return ErrorReason::gateway_timeout;
// Check if signal exists.
if(!checkSignals(paths, true)) { return ErrorReason::invalid_path; }
DEBUG("WebSocketBroker","path exist");
// Create message to send
QJsonObject message;
message.insert("get", paths);
QJsonDocument jsonDoc(message);
// Lock and send message.
sendMessage(jsonDoc.toJson());
QEventLoop messageLoop;
connect(this, &WebSocketBroker::messageReceived, &messageLoop, &QEventLoop::quit);
QTimer::singleShot(m_timeout, &messageLoop, &QEventLoop::quit);
messageLoop.exec();
jsonDoc = QJsonDocument(m_receivedMessage);
// TODO Add check of Success in response.
// Could just return false, instead of array, if error?
if(jsonDoc.object()["get"].isArray())
{
values = jsonDoc.object()["get"].toArray();
DEBUG(" WebSocketBroker", "values are set");
return true;
}
DEBUG("WebSocketBroker", " there is no array in response ");
return false;
}
int WebSocketBroker::setSignalValue(const QString& path, const QVariant& values)
{
QJsonArray paths = parseSetPath(path, values.toJsonValue());
QMutexLocker locker(&m_mutex);
if(!checkOpenDSConnection()) return ErrorReason::gateway_timeout;
// Check if signal exists.
if(!checkSignals(paths, false)) {
return ErrorReason::invalid_path;
}
// Create message to send
QJsonObject message;
message.insert("set", paths);
QJsonDocument jsonDoc(message);
sendMessage(jsonDoc.toJson());
QEventLoop messageLoop;
connect(this, &WebSocketBroker::messageReceived, &messageLoop, &QEventLoop::quit);
QTimer::singleShot(m_timeout, &messageLoop, &QEventLoop::quit);
messageLoop.exec();
jsonDoc = QJsonDocument(m_receivedMessage);
qDebug() << jsonDoc;
// Should return false, or 0 if not bool. So should work without checking if bool
if (jsonDoc.object()["set"].toBool())
return 0;
else
return ErrorReason::bad_gateway;
}
QJsonObject WebSocketBroker::getVSSNode(const QString& path)
{
// clear old
m_vssTreeNode = QJsonObject();
if (m_vssTree.empty())
{
DEBUG("Server","Empty VSS tree. Returning empty node.");
return m_vssTreeNode;
}
else if (path == "")
{
DEBUG("Server","Empty path. Returning full tree.");
return m_vssTree;
}
else
{
QStringList tokens = path.split('.');
// Make a copy of the full tree
QJsonObject tree = m_vssTree;
QVector<JsonNode> nodes;
getTreeNodes(tree, tokens, nodes);
QJsonObject obj;
createJsonVssTree(nodes, obj);
return m_vssTreeNode;
}
}
QJsonObject WebSocketBroker::getVSSTree(const QString& path)
{
QString p = path;
QJsonObject tree;
return tree;
}
void WebSocketBroker::sendMessage(const QString message)
{
// Need to reset so that we dont accidentally use old message. Change to timeout errormsg?
m_receivedMessage = QJsonObject();
emit sendMessageSignal(message);
}
void WebSocketBroker::sendMessageSlot(const QString message)
{
m_webSocket.sendTextMessage(message);
m_webSocket.flush();
}
void WebSocketBroker::onConnected()
{
WARNING("","Connected to OpenDSAdapter");
connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketBroker::onTextMessageReceived);
}
void WebSocketBroker::onTextMessageReceived(QString message)
{
QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &parseError);
if(parseError.error != QJsonParseError::NoError)
{
m_receivedMessage = QJsonObject(); // Change to error.
}
else { m_receivedMessage = doc.object(); }
emit messageReceived();
}
void WebSocketBroker::getTreeNodes(QJsonObject& tree, QStringList& path, QVector<JsonNode>& nodes)
{
if (path.length() > 0)
{
QString key = path[0];
JsonNode node;
node.isBranch = path.length() > 1;
node.key = key;
if (node.isBranch)
{
removeAllKeysButOne(tree, key);
}
tree = tree.value(key).toObject();
QJsonObject treeCopy = tree;
if (node.isBranch)
{
removeOne(treeCopy, "children");
tree = tree.value("children").toObject();
}
node.json = treeCopy;
nodes.push_front(node);
path.removeFirst();
getTreeNodes(tree, path, nodes);
}
}
void WebSocketBroker::createJsonVssTree(QVector<JsonNode>& nodes, QJsonObject& json)
{
if (nodes.size() > 0)
{
JsonNode node = nodes.first();
QJsonObject obj;
if (node.isBranch)
{
node.json.insert("children", json);
obj.insert(node.key, node.json);
}
else
{
obj.insert(node.key, node.json);
}
nodes.removeFirst();
createJsonVssTree(nodes, obj);
}
else
{
m_vssTreeNode = json;
}
}
void WebSocketBroker::removeAllKeysButOne(QJsonObject& json, const QString& filter)
{
foreach (QString key, json.keys())
{
if (filter != key)
{
json.remove(key);
}
}
}
void WebSocketBroker::removeOne(QJsonObject& json, const QString& filter)
{
foreach (QString key, json.keys())
{
if (filter == key)
{
json.remove(key);
}
}
}
void WebSocketBroker::loadJson(const QString &fileName)
{
QFile jsonFile(fileName);
QJsonDocument doc;
if (jsonFile.exists())
{
jsonFile.open(QFile::ReadOnly);
doc = QJsonDocument().fromJson(jsonFile.readAll());
}
else
{
WARNING("Server",QString("VSS File %1 not found!").arg(fileName));
}
m_vssTree = doc.object();
}
void WebSocketBroker::loadTempSignalList(const QString &vssFile)
{
QRegularExpression regex(QString("^(\\S+) \\d+"));
QFile file(vssFile);
file.open(QFile::ReadOnly);
if(!file.exists())
{
WARNING("Server", "The flattened vsi signal file could not be found for the Signal Broker!");
file.close();
return;
}
while(!file.atEnd())
{
QRegularExpressionMatch match = regex.match(file.readLine());
if(match.hasMatch()) { m_tempSignalList.append(match.captured(1).trimmed()); }
}
}
bool WebSocketBroker::checkOpenDSConnection(){
if(m_webSocket.isValid()) return true;
WARNING("WebSocketBroker","No connection to OpenDS Adapter. Trying to reconnect.");
m_webSocket.open(QUrl(m_brokerUrl));
return false;
}
QJsonArray WebSocketBroker::parseGetPath(const QString& path)
{
QStringList sl = splitPath(path);
QJsonArray values;
if(sl.length() == 1)
foreach(auto const item, getPath(sl.first()))
{
QJsonObject value;
value.insert(item,"");
values.append(value);
}
else
foreach(auto const item, getPath(sl.first(), sl.last()))
{
QJsonObject value;
value.insert(item,"");
values.append(value);
}
return values;
}
QJsonArray WebSocketBroker::parseSetPath(const QString& path, const QJsonValue &setValues)
{
QStringList sl = splitPath(path);
QJsonArray values;
if(setValues.isArray())
{
foreach(QJsonValue const val, setValues.toArray())
{
QJsonObject value;
QJsonObject obj = val.toObject();
QString valuePath = sl.first() + "." + obj.keys().first();
QJsonValue tmp = obj.value(obj.keys().first());
if(tmp.isDouble())
{
value.insert(valuePath, tmp.toDouble());
}
else if(tmp.isBool())
{
value.insert(valuePath, tmp.toBool());
}
else
{
value.insert(valuePath, tmp.toString());
}
values.append(value);
}
}
else
{
QJsonObject value;
if(setValues.isDouble())
{
value.insert(path, setValues.toDouble());
}
else if(setValues.isBool())
{
value.insert(path, setValues.toBool());
}
else
{
value.insert(path, setValues.toString());
}
values .append(value);
}
return values;
}
bool WebSocketBroker::checkSignals(const QJsonArray &paths, bool getOrSet)
{
foreach (QJsonValue const &obj, paths)
{
foreach (QJsonValue key, obj.toObject().keys())
{
QJsonObject signal = getVSSNode(key.toString());
if(signal.isEmpty())
{
WARNING("Server", QString("Requested signal was not found : %1").arg(key.toString()));
return false;
}
if(getOrSet)
{
// TODO Check if the signal is ok to get
}
else
{
// TODO Check if the signal is ok to set
// Check if set is correct type
}
}
}
return true;
}
QStringList WebSocketBroker::getPath(QString startsWith)
{
return getPath(startsWith, "");
}
QStringList WebSocketBroker::getPath(QString startsWith, QString endsWith)
{
return m_tempSignalList.filter(QRegularExpression(QString("^%1.*%2$").arg(startsWith, endsWith)));
}
QStringList WebSocketBroker::splitPath(QString path)
{
QStringList sl;
int i = path.lastIndexOf("*");
if(i == -1) { sl << path; return sl; }
foreach(QString item, path.split("*"))
{
// Trim '.' from items.
if(item.startsWith(".")) { item = item.remove(0,1); }
if(item.endsWith(".")) { item = item.remove(item.length() -1, 1); }
sl << item;
}
return sl;
}
<commit_msg>Fixed so that get does not return true when it succeeds<commit_after>#include "websocketbroker.h"
#include "logger.h"
#include "errors/errorresponse.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QVector>
#include <QFile>
#include <QCoreApplication>
#include <QRegularExpression>
WebSocketBroker::WebSocketBroker(const QString& vssDir, const QString &vssName, const QString &brokerUrl, QObject *parent) :
QObject(parent), m_brokerUrl(brokerUrl)
{
loadJson(vssDir + "/" + vssName + ".json");
loadTempSignalList(vssDir + "/" + vssName + ".vsi");
connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketBroker::onConnected);
connect(this, &WebSocketBroker::sendMessageSignal, this, &WebSocketBroker::sendMessageSlot, Qt::QueuedConnection);
m_webSocket.open(QUrl(brokerUrl));
}
int WebSocketBroker::getSignalValue(const QString& path, QJsonArray& values)
{
// Check if path is single leaf.
// Check if path is single branch.
// Check if path contains asterisk.
// Check if path contains asterisk and leaf.
QJsonArray paths = parseGetPath(path);
DEBUG("WebSocketBroker",path);
QMutexLocker locker(&m_mutex);
if(!checkOpenDSConnection()) return ErrorReason::gateway_timeout;
// Check if signal exists.
if(!checkSignals(paths, true)) { return ErrorReason::invalid_path; }
DEBUG("WebSocketBroker","path exist");
// Create message to send
QJsonObject message;
message.insert("get", paths);
QJsonDocument jsonDoc(message);
// Lock and send message.
sendMessage(jsonDoc.toJson());
QEventLoop messageLoop;
connect(this, &WebSocketBroker::messageReceived, &messageLoop, &QEventLoop::quit);
QTimer::singleShot(m_timeout, &messageLoop, &QEventLoop::quit);
messageLoop.exec();
jsonDoc = QJsonDocument(m_receivedMessage);
// TODO Add check of Success in response.
// Could just return false, instead of array, if error?
if(jsonDoc.object()["get"].isArray())
{
values = jsonDoc.object()["get"].toArray();
DEBUG(" WebSocketBroker", "values are set");
return 0;
}
DEBUG("WebSocketBroker", " there is no array in response ");
return ErrorReason::bad_gateway;
}
int WebSocketBroker::setSignalValue(const QString& path, const QVariant& values)
{
QJsonArray paths = parseSetPath(path, values.toJsonValue());
QMutexLocker locker(&m_mutex);
if(!checkOpenDSConnection()) return ErrorReason::gateway_timeout;
// Check if signal exists.
if(!checkSignals(paths, false)) {
return ErrorReason::invalid_path;
}
// Create message to send
QJsonObject message;
message.insert("set", paths);
QJsonDocument jsonDoc(message);
sendMessage(jsonDoc.toJson());
QEventLoop messageLoop;
connect(this, &WebSocketBroker::messageReceived, &messageLoop, &QEventLoop::quit);
QTimer::singleShot(m_timeout, &messageLoop, &QEventLoop::quit);
messageLoop.exec();
jsonDoc = QJsonDocument(m_receivedMessage);
qDebug() << jsonDoc;
// Should return false, or 0 if not bool. So should work without checking if bool
if (jsonDoc.object()["set"].toBool())
return 0;
else
return ErrorReason::bad_gateway;
}
QJsonObject WebSocketBroker::getVSSNode(const QString& path)
{
// clear old
m_vssTreeNode = QJsonObject();
if (m_vssTree.empty())
{
DEBUG("Server","Empty VSS tree. Returning empty node.");
return m_vssTreeNode;
}
else if (path == "")
{
DEBUG("Server","Empty path. Returning full tree.");
return m_vssTree;
}
else
{
QStringList tokens = path.split('.');
// Make a copy of the full tree
QJsonObject tree = m_vssTree;
QVector<JsonNode> nodes;
getTreeNodes(tree, tokens, nodes);
QJsonObject obj;
createJsonVssTree(nodes, obj);
return m_vssTreeNode;
}
}
QJsonObject WebSocketBroker::getVSSTree(const QString& path)
{
QString p = path;
QJsonObject tree;
return tree;
}
void WebSocketBroker::sendMessage(const QString message)
{
// Need to reset so that we dont accidentally use old message. Change to timeout errormsg?
m_receivedMessage = QJsonObject();
emit sendMessageSignal(message);
}
void WebSocketBroker::sendMessageSlot(const QString message)
{
m_webSocket.sendTextMessage(message);
m_webSocket.flush();
}
void WebSocketBroker::onConnected()
{
WARNING("","Connected to OpenDSAdapter");
connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketBroker::onTextMessageReceived);
}
void WebSocketBroker::onTextMessageReceived(QString message)
{
QJsonParseError parseError;
QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &parseError);
if(parseError.error != QJsonParseError::NoError)
{
m_receivedMessage = QJsonObject(); // Change to error.
}
else { m_receivedMessage = doc.object(); }
emit messageReceived();
}
void WebSocketBroker::getTreeNodes(QJsonObject& tree, QStringList& path, QVector<JsonNode>& nodes)
{
if (path.length() > 0)
{
QString key = path[0];
JsonNode node;
node.isBranch = path.length() > 1;
node.key = key;
if (node.isBranch)
{
removeAllKeysButOne(tree, key);
}
tree = tree.value(key).toObject();
QJsonObject treeCopy = tree;
if (node.isBranch)
{
removeOne(treeCopy, "children");
tree = tree.value("children").toObject();
}
node.json = treeCopy;
nodes.push_front(node);
path.removeFirst();
getTreeNodes(tree, path, nodes);
}
}
void WebSocketBroker::createJsonVssTree(QVector<JsonNode>& nodes, QJsonObject& json)
{
if (nodes.size() > 0)
{
JsonNode node = nodes.first();
QJsonObject obj;
if (node.isBranch)
{
node.json.insert("children", json);
obj.insert(node.key, node.json);
}
else
{
obj.insert(node.key, node.json);
}
nodes.removeFirst();
createJsonVssTree(nodes, obj);
}
else
{
m_vssTreeNode = json;
}
}
void WebSocketBroker::removeAllKeysButOne(QJsonObject& json, const QString& filter)
{
foreach (QString key, json.keys())
{
if (filter != key)
{
json.remove(key);
}
}
}
void WebSocketBroker::removeOne(QJsonObject& json, const QString& filter)
{
foreach (QString key, json.keys())
{
if (filter == key)
{
json.remove(key);
}
}
}
void WebSocketBroker::loadJson(const QString &fileName)
{
QFile jsonFile(fileName);
QJsonDocument doc;
if (jsonFile.exists())
{
jsonFile.open(QFile::ReadOnly);
doc = QJsonDocument().fromJson(jsonFile.readAll());
}
else
{
WARNING("Server",QString("VSS File %1 not found!").arg(fileName));
}
m_vssTree = doc.object();
}
void WebSocketBroker::loadTempSignalList(const QString &vssFile)
{
QRegularExpression regex(QString("^(\\S+) \\d+"));
QFile file(vssFile);
file.open(QFile::ReadOnly);
if(!file.exists())
{
WARNING("Server", "The flattened vsi signal file could not be found for the Signal Broker!");
file.close();
return;
}
while(!file.atEnd())
{
QRegularExpressionMatch match = regex.match(file.readLine());
if(match.hasMatch()) { m_tempSignalList.append(match.captured(1).trimmed()); }
}
}
bool WebSocketBroker::checkOpenDSConnection(){
if(m_webSocket.isValid()) return true;
WARNING("WebSocketBroker","No connection to OpenDS Adapter. Trying to reconnect.");
m_webSocket.open(QUrl(m_brokerUrl));
return false;
}
QJsonArray WebSocketBroker::parseGetPath(const QString& path)
{
QStringList sl = splitPath(path);
QJsonArray values;
if(sl.length() == 1)
foreach(auto const item, getPath(sl.first()))
{
QJsonObject value;
value.insert(item,"");
values.append(value);
}
else
foreach(auto const item, getPath(sl.first(), sl.last()))
{
QJsonObject value;
value.insert(item,"");
values.append(value);
}
return values;
}
QJsonArray WebSocketBroker::parseSetPath(const QString& path, const QJsonValue &setValues)
{
QStringList sl = splitPath(path);
QJsonArray values;
if(setValues.isArray())
{
foreach(QJsonValue const val, setValues.toArray())
{
QJsonObject value;
QJsonObject obj = val.toObject();
QString valuePath = sl.first() + "." + obj.keys().first();
QJsonValue tmp = obj.value(obj.keys().first());
if(tmp.isDouble())
{
value.insert(valuePath, tmp.toDouble());
}
else if(tmp.isBool())
{
value.insert(valuePath, tmp.toBool());
}
else
{
value.insert(valuePath, tmp.toString());
}
values.append(value);
}
}
else
{
QJsonObject value;
if(setValues.isDouble())
{
value.insert(path, setValues.toDouble());
}
else if(setValues.isBool())
{
value.insert(path, setValues.toBool());
}
else
{
value.insert(path, setValues.toString());
}
values .append(value);
}
return values;
}
bool WebSocketBroker::checkSignals(const QJsonArray &paths, bool getOrSet)
{
foreach (QJsonValue const &obj, paths)
{
foreach (QJsonValue key, obj.toObject().keys())
{
QJsonObject signal = getVSSNode(key.toString());
if(signal.isEmpty())
{
WARNING("Server", QString("Requested signal was not found : %1").arg(key.toString()));
return false;
}
if(getOrSet)
{
// TODO Check if the signal is ok to get
}
else
{
// TODO Check if the signal is ok to set
// Check if set is correct type
}
}
}
return true;
}
QStringList WebSocketBroker::getPath(QString startsWith)
{
return getPath(startsWith, "");
}
QStringList WebSocketBroker::getPath(QString startsWith, QString endsWith)
{
return m_tempSignalList.filter(QRegularExpression(QString("^%1.*%2$").arg(startsWith, endsWith)));
}
QStringList WebSocketBroker::splitPath(QString path)
{
QStringList sl;
int i = path.lastIndexOf("*");
if(i == -1) { sl << path; return sl; }
foreach(QString item, path.split("*"))
{
// Trim '.' from items.
if(item.startsWith(".")) { item = item.remove(0,1); }
if(item.endsWith(".")) { item = item.remove(item.length() -1, 1); }
sl << item;
}
return sl;
}
<|endoftext|> |
<commit_before>/**********************************************************************************/
/* The MIT License(MIT) */
/* */
/* Copyright(c) 2016-2016 Matthieu Vendeville */
/* */
/* 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 "ImCpu.h"
#include "ImGpu.h"
#include "cuda_profiler_api.h"
#include <time.h>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <sstream>
using namespace std;
struct arg_struct {
std::string device_type;
std::string interpolation_type;
std::string in_file;
std::string out_file;
int iterations;
int new_width;
int new_height;
};
void *Resize( void *args)
{
Im *Im1,*Im2;
cudaError_t cudaStatus;
clock_t begin_time, end_time = 0;
int i;
struct arg_struct *parameters = (struct arg_struct *)args;
std::cout << "Using device: " << parameters->device_type <<'\n';
std::cout << "Nb iterations: " << parameters->iterations << '\n';
std::cout << "Interplation types: " << parameters->interpolation_type << '\n';
std::cout << "Input file: " << parameters->in_file << '\n';
std::cout << "Output file: " << parameters->out_file << '\n';
std::cout << "New width: " << parameters->new_width << '\n';
std::cout << "New height: " << parameters->new_height << '\n';
//
// Initialise GPU
//
cudaStatus = cudaSetDevice(0);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?");
}
//
// Init instance, depending on process happening on GPU or CPU
//
if ( parameters->device_type == "cpu" ){
Im1 = new ImCpu(parameters->in_file.c_str());
std::cout << "Creating Imcpu instance" << '\n';
}else{
Im1 = new ImGpu(parameters->in_file.c_str());
std::cout << "Creating Imgpu instance" << '\n';
}
// Perform and profile interpolation x times
for (i = 0; i < parameters->iterations; i++){
Im2 = Im1->clone();
if ( parameters->interpolation_type == "nn")
{
begin_time = clock();
Im2->InterpolateNN(parameters->new_width, parameters->new_height);
end_time += clock() - begin_time;
}
else
{
begin_time = clock();
Im2->InterpolateBilinear(parameters->new_width, parameters->new_height);
end_time += clock() - begin_time;
}
delete(Im2);
}
if ( parameters->iterations != 0)
{
std::cout << float(end_time) / CLOCKS_PER_SEC << '\n';
}else
{
std::cout << 0 << '\n';
}
//
// Save processed imaged
//
if ( parameters->interpolation_type == "nn")
{
Im1->InterpolateNN(parameters->new_width, parameters->new_height);
}
else
{
Im1->InterpolateBilinear(parameters->new_width, parameters->new_height);
}
Im1->Save2RawFile(parameters->out_file.c_str());
Im1->PrintRawFileName();
delete(Im1);
}
int main(int argc, char** argv)
{
cudaError_t cudaStatus;
int i;
int NbFiles = 10;
pthread_t threads[NbFiles];
struct arg_struct ThreadArguments[NbFiles];
cudaDeviceReset();
for (i=0; i<NbFiles; i++)
{
std::string filename_out = "lenaout" + std::to_string(i) + ".dat";
if (argc > 1 ){
NbFiles = 1;
ThreadArguments[i].device_type = std::string(argv[1]);
ThreadArguments[i].iterations = atoi(argv[2]);
ThreadArguments[i].interpolation_type = atoi(argv[3]);
ThreadArguments[i].in_file = std::string(argv[4]);
ThreadArguments[i].out_file = std::string(argv[5]);
ThreadArguments[i].new_width = atoi(argv[6]);
ThreadArguments[i].new_height = atoi(argv[7]);
}else{
ThreadArguments[i].device_type = std::string({"gpu"});
ThreadArguments[i].interpolation_type = std::string({"nn"});
ThreadArguments[i].in_file = std::string({"512x512x8x1_Lena.dat"});
ThreadArguments[i].out_file = filename_out;
ThreadArguments[i].iterations = 0;
ThreadArguments[i].new_width = 256;
ThreadArguments[i].new_height = 256;
}
}
for (i=0; i<NbFiles; i++)
{
if (pthread_create(&threads[i], NULL, &Resize, &ThreadArguments[i])) {
fprintf(stderr, "Error creating threadn");
return 1;
}
}
// Resize(device_type, interpolation_type, in_file, out_file, iterations, new_width, new_height);
for (i=0; i<NbFiles; i++)
{
if(pthread_join(threads[i], NULL)) {
fprintf(stderr, "Error joining threadn");
return 2;
}
}
for (i=0; i<NbFiles; i++)
{
ThreadArguments[i].device_type.erase();
ThreadArguments[i].in_file.erase();
ThreadArguments[i].interpolation_type.erase();
ThreadArguments[i].out_file.erase();
}
exit(0);
}
<commit_msg>using std thread<commit_after>/**********************************************************************************/
/* The MIT License(MIT) */
/* */
/* Copyright(c) 2016-2016 Matthieu Vendeville */
/* */
/* 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 "ImCpu.h"
#include "ImGpu.h"
#include "cuda_profiler_api.h"
#include <time.h>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <sstream>
#include <thread>
using namespace std;
struct arg_struct {
string device_type;
string interpolation_type;
string in_file;
string out_file;
int iterations;
int new_width;
int new_height;
};
void *Resize( void *args)
{
Im *Im1,*Im2;
cudaError_t cudaStatus;
clock_t begin_time, end_time = 0;
int i;
struct arg_struct *parameters = (struct arg_struct *)args;
cout << "Using device: " << parameters->device_type <<'\n';
cout << "Nb iterations: " << parameters->iterations << '\n';
cout << "Interplation types: " << parameters->interpolation_type << '\n';
cout << "Input file: " << parameters->in_file << '\n';
cout << "Output file: " << parameters->out_file << '\n';
cout << "New width: " << parameters->new_width << '\n';
cout << "New height: " << parameters->new_height << '\n';
//
// Initialise GPU
//
cudaStatus = cudaSetDevice(0);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?");
}
//
// Init instance, depending on process happening on GPU or CPU
//
if ( parameters->device_type == "cpu" ){
Im1 = new ImCpu(parameters->in_file.c_str());
cout << "Creating Imcpu instance" << '\n';
}else{
Im1 = new ImGpu(parameters->in_file.c_str());
cout << "Creating Imgpu instance" << '\n';
}
// Perform and profile interpolation parameters->iterations times
for (i = 0; i < parameters->iterations; i++){
Im2 = Im1->clone();
if ( parameters->interpolation_type == "nn")
{
begin_time = clock();
Im2->InterpolateNN(parameters->new_width, parameters->new_height);
end_time += clock() - begin_time;
}
else
{
begin_time = clock();
Im2->InterpolateBilinear(parameters->new_width, parameters->new_height);
end_time += clock() - begin_time;
}
delete(Im2);
}
if ( parameters->iterations != 0)
{
cout << float(end_time) / CLOCKS_PER_SEC << '\n';
}else
{
cout << 0 << '\n';
}
//
// Save processed imaged
//
if ( parameters->interpolation_type == "nn")
{
Im1->InterpolateNN(parameters->new_width, parameters->new_height);
}
else
{
Im1->InterpolateBilinear(parameters->new_width, parameters->new_height);
}
Im1->Save2RawFile(parameters->out_file.c_str());
Im1->PrintRawFileName();
delete(Im1);
}
int main(int argc, char** argv)
{
cudaError_t cudaStatus;
int i;
int NbFiles = 10;
std::thread threads[NbFiles];
struct arg_struct ThreadArguments[NbFiles];
/*
* Let's start
*/
// reset Gpu
cudaDeviceReset();
// For each thread, create an argument struct
for (i=0; i<NbFiles; i++)
{
std::string filename_out = "lenaout" + std::to_string(i) + ".dat";
if (argc > 1 ){
NbFiles = 1;
ThreadArguments[i].device_type = std::string(argv[1]);
ThreadArguments[i].iterations = atoi(argv[2]);
ThreadArguments[i].interpolation_type = atoi(argv[3]);
ThreadArguments[i].in_file = std::string(argv[4]);
ThreadArguments[i].out_file = std::string(argv[5]);
ThreadArguments[i].new_width = atoi(argv[6]);
ThreadArguments[i].new_height = atoi(argv[7]);
}else{
ThreadArguments[i].device_type = std::string({"gpu"});
ThreadArguments[i].interpolation_type = std::string({"nn"});
ThreadArguments[i].in_file = std::string({"512x512x8x1_Lena.dat"});
ThreadArguments[i].out_file = filename_out;
ThreadArguments[i].iterations = 0;
ThreadArguments[i].new_width = 256;
ThreadArguments[i].new_height = 256;
}
}
/*
* Create NbFiles threads to do parallel processing
*/
for (i=0; i<NbFiles; i++)
{
threads[i] = std::thread(Resize, &ThreadArguments[i]);
}
/*
* Wait for all threads to terminate properly
*/
for (i=0; i<NbFiles; i++)
{
threads[i].join();
}
/*
* Free all allocated resources and exit properly
*/
for (i=0; i<NbFiles; i++)
{
ThreadArguments[i].device_type.erase();
ThreadArguments[i].in_file.erase();
ThreadArguments[i].interpolation_type.erase();
ThreadArguments[i].out_file.erase();
}
exit(0);
}
<|endoftext|> |
<commit_before>// Authors: see AUTHORS.md at project root.
// CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root.
// URL: https://github.com/asrob-uc3m/robotDevastation
#include "MockRobotManager.hpp"
#include <ColorDebug.hpp>
const int rd::MockRobotManager::FORWARD = 1;
const int rd::MockRobotManager::BACKWARDS = 2;
const int rd::MockRobotManager::LEFT = 4;
const int rd::MockRobotManager::RIGHT = 8;
const int rd::MockRobotManager::NONE = 0;
const int rd::MockRobotManager::CAMERA_UP = 1;
const int rd::MockRobotManager::CAMERA_DOWN = 2;
const int rd::MockRobotManager::CAMERA_LEFT = 4;
const int rd::MockRobotManager::CAMERA_RIGHT = 8;
const int rd::MockRobotManager::CAMERA_NONE = 0;
rd::MockRobotManager::MockRobotManager(const std::string& robotName)
{
this->robotName = robotName;
movement_direction = NONE;
camera_movement_direction = CAMERA_NONE;
}
bool rd::MockRobotManager::moveForward(double value)
{
movement_direction = FORWARD;
return true;
}
bool rd::MockRobotManager::turnLeft(double value)
{
movement_direction = LEFT;
return true;
}
bool rd::MockRobotManager::stopMovement()
{
movement_direction = NONE;
return true;
}
bool rd::MockRobotManager::tiltDown(double value)
{
camera_movement_direction = CAMERA_DOWN;
return true;
}
bool rd::MockRobotManager::panLeft(double value)
{
camera_movement_direction = CAMERA_LEFT;
return true;
}
bool rd::MockRobotManager::stopCameraMovement()
{
camera_movement_direction = NONE;
return true;
}
bool rd::MockRobotManager::isMoving() const
{
return movement_direction!=NONE;
}
int rd::MockRobotManager::getMovementDirection()
{
return movement_direction;
}
bool rd::MockRobotManager::isCameraMoving()
{
return camera_movement_direction != NONE;
}
int rd::MockRobotManager::getCameraMovementDirection()
{
return camera_movement_direction;
}
<commit_msg>fix and improve testRobotDevastation<commit_after>// Authors: see AUTHORS.md at project root.
// CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root.
// URL: https://github.com/asrob-uc3m/robotDevastation
#include "MockRobotManager.hpp"
#include <ColorDebug.hpp>
const int rd::MockRobotManager::NONE = 0;
const int rd::MockRobotManager::FORWARD = 1;
const int rd::MockRobotManager::BACKWARDS = 2;
const int rd::MockRobotManager::LEFT = 3;
const int rd::MockRobotManager::RIGHT = 4;
const int rd::MockRobotManager::CAMERA_NONE = 5;
const int rd::MockRobotManager::CAMERA_DOWN = 6;
const int rd::MockRobotManager::CAMERA_UP = 7;
const int rd::MockRobotManager::CAMERA_LEFT = 8;
const int rd::MockRobotManager::CAMERA_RIGHT = 9;
rd::MockRobotManager::MockRobotManager(const std::string& robotName)
{
this->robotName = robotName;
movement_direction = NONE;
camera_movement_direction = CAMERA_NONE;
}
bool rd::MockRobotManager::moveForward(double value)
{
if(value > 0)
movement_direction = FORWARD;
else if(value < 0)
movement_direction = BACKWARDS;
else
movement_direction = NONE;
return true;
}
bool rd::MockRobotManager::turnLeft(double value)
{
if(value > 0)
movement_direction = LEFT;
else if(value < 0)
movement_direction = RIGHT;
else
movement_direction = NONE;
return true;
}
bool rd::MockRobotManager::stopMovement()
{
movement_direction = NONE;
return true;
}
bool rd::MockRobotManager::tiltDown(double value)
{
if(value > 0)
camera_movement_direction = CAMERA_DOWN;
else if(value < 0)
camera_movement_direction = CAMERA_UP;
else
camera_movement_direction = CAMERA_NONE;
return true;
}
bool rd::MockRobotManager::panLeft(double value)
{
if(value > 0)
movement_direction = CAMERA_LEFT;
else if(value < 0)
movement_direction = CAMERA_RIGHT;
else
movement_direction = CAMERA_NONE;
return true;
}
bool rd::MockRobotManager::stopCameraMovement()
{
camera_movement_direction = CAMERA_NONE;
return true;
}
bool rd::MockRobotManager::isMoving() const
{
return movement_direction!=NONE;
}
int rd::MockRobotManager::getMovementDirection()
{
return movement_direction;
}
bool rd::MockRobotManager::isCameraMoving()
{
return camera_movement_direction != CAMERA_NONE;
}
int rd::MockRobotManager::getCameraMovementDirection()
{
return camera_movement_direction;
}
<|endoftext|> |
<commit_before>#include "Object.h"
#include "Integer.h"
#include "Undefined.h"
#include "Function.h"
#include "Runtime.h"
namespace snot {
static Object* ObjectPrototype = NULL;
Object::~Object() {
if (m_Members.ref_count() == 1) {
for (auto iter = iterate(*m_Members); iter; ++iter) {
if (is_object(iter->second))
delete object(iter->second);
}
}
}
VALUE Object::call(VALUE self, uint64_t num_args, ...) {
va_list ap;
va_start(ap, num_args);
VALUE ret = va_call(self, num_args, ap);
va_end(ap);
return ret;
}
VALUE Object::va_call(VALUE self, uint64_t num_args, va_list& ap) {
VALUE call_handler = get("call");
if (is_object(call_handler))
return object(call_handler)->va_call(self, num_args, ap);
return value(this);
}
VALUE Object::set(const char* member, VALUE value) {
if (m_Members.ref_count() != 1) {
RefPtr<Members> new_members = new Members;
for (auto iter = iterate(*m_Members); iter; ++iter) {
VALUE val;
if (is_object(iter->second))
val = object(iter->second)->copy();
else
val = iter->second;
(*new_members)[iter->first] = val;
}
m_Members = new_members;
}
(*m_Members)[member] = value;
return value;
}
VALUE Object::get(const char* member) const {
auto iter = m_Members->find(member);
if (iter != m_Members->end())
return iter->second;
else {
if (this != ObjectPrototype)
return prototype()->get(member);
else
return undefined();
}
}
static VALUE object_id(VALUE self, uint64_t num_args, VALUE* args) {
assert(num_args == 0);
return value(reinterpret_cast<int64_t>(self));
}
static VALUE object_send(VALUE self, uint64_t num_args, VALUE* args) {
VALUE message = args[0];
// TODO: convert message to string, send it, return the result
return self;
}
static VALUE object_members(VALUE self, uint64_t num_args, VALUE* args) {
// TODO: construct array of member names
return self;
}
static VALUE object_get_prototype(VALUE self, uint64_t num_args, VALUE* args) {
if (is_object(self))
return value(object(self)->prototype());
return value(object_for(self));
}
static VALUE object_copy(VALUE self, uint64_t num_args, VALUE* args) {
return copy(self);
}
Object* object_prototype() {
if (!ObjectPrototype) {
ObjectPrototype = new Object;
ObjectPrototype->set("object_id", create_function(object_id));
VALUE send = create_function(object_send);
ObjectPrototype->set("send", send);
ObjectPrototype->set("__send__", send);
ObjectPrototype->set("members", create_function(object_members));
ObjectPrototype->set("prototype", create_function(object_get_prototype));
}
return ObjectPrototype;
}
}<commit_msg>use "__call__" for functors instead of the collision-prone "call".<commit_after>#include "Object.h"
#include "Integer.h"
#include "Undefined.h"
#include "Function.h"
#include "Runtime.h"
namespace snot {
static Object* ObjectPrototype = NULL;
Object::~Object() {
if (m_Members.ref_count() == 1) {
for (auto iter = iterate(*m_Members); iter; ++iter) {
if (is_object(iter->second))
delete object(iter->second);
}
}
}
VALUE Object::call(VALUE self, uint64_t num_args, ...) {
va_list ap;
va_start(ap, num_args);
VALUE ret = va_call(self, num_args, ap);
va_end(ap);
return ret;
}
VALUE Object::va_call(VALUE self, uint64_t num_args, va_list& ap) {
VALUE call_handler = get("__call__");
if (is_object(call_handler))
return object(call_handler)->va_call(self, num_args, ap);
// If there is no call handler, this is not a functor, so just return this
return value(this);
}
VALUE Object::set(const char* member, VALUE value) {
if (m_Members.ref_count() != 1) {
RefPtr<Members> new_members = new Members;
for (auto iter = iterate(*m_Members); iter; ++iter) {
VALUE val;
if (is_object(iter->second))
val = object(iter->second)->copy();
else
val = iter->second;
(*new_members)[iter->first] = val;
}
m_Members = new_members;
}
(*m_Members)[member] = value;
return value;
}
VALUE Object::get(const char* member) const {
auto iter = m_Members->find(member);
if (iter != m_Members->end())
return iter->second;
else {
if (this != ObjectPrototype)
return prototype()->get(member);
else
return undefined();
}
}
static VALUE object_id(VALUE self, uint64_t num_args, VALUE* args) {
assert(num_args == 0);
return value(reinterpret_cast<int64_t>(self));
}
static VALUE object_send(VALUE self, uint64_t num_args, VALUE* args) {
VALUE message = args[0];
// TODO: convert message to string, send it, return the result
return self;
}
static VALUE object_members(VALUE self, uint64_t num_args, VALUE* args) {
// TODO: construct array of member names
return self;
}
static VALUE object_get_prototype(VALUE self, uint64_t num_args, VALUE* args) {
if (is_object(self))
return value(object(self)->prototype());
return value(object_for(self));
}
static VALUE object_copy(VALUE self, uint64_t num_args, VALUE* args) {
return copy(self);
}
Object* object_prototype() {
if (!ObjectPrototype) {
ObjectPrototype = new Object;
ObjectPrototype->set("object_id", create_function(object_id));
VALUE send = create_function(object_send);
ObjectPrototype->set("send", send);
ObjectPrototype->set("__send__", send);
ObjectPrototype->set("members", create_function(object_members));
ObjectPrototype->set("prototype", create_function(object_get_prototype));
}
return ObjectPrototype;
}
}<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.6.212); FILE MERGED 2008/04/01 12:49:08 thb 1.6.212.2: #i85898# Stripping all external header guards 2008/03/31 14:22:21 rt 1.6.212.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: MNSInclude.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2002-10-17 09:27:55 $
*
* 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): Willem van Dorp, Darren Kenny
*
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
#define _CONNECTIVITY_MAB_NS_INCLUDE_HXX_ 1
//
// Only include Mozilla include files once and using this file...
//
#ifndef BOOL
# define MOZ_BOOL
# define BOOL mozBOOL
# define Bool mozBooL
#endif
// Turn off DEBUG Assertions
#ifdef _DEBUG
#define _DEBUG_WAS_DEFINED _DEBUG
#undef _DEBUG
#else
#undef _DEBUG_WAS_DEFINED _DEBUG
#endif
// and turn off the additional virtual methods which are part of some interfaces when compiled
// with debug
#ifdef DEBUG
#define DEBUG_WAS_DEFINED DEBUG
#undef DEBUG
#else
#undef DEBUG_WAS_DEFINED
#endif
#include <nsDebug.h>
#include <nsCOMPtr.h>
#include <nsISupportsArray.h>
#include <nsStr.h>
#include <nsString.h>
#include <nsString2.h>
#include <nsMemory.h>
#include <prtypes.h>
#include <nsRDFCID.h>
#include <nsXPIDLString.h>
#include <nsIRDFService.h>
#include <nsIRDFResource.h>
#include <nsReadableUtils.h>
#include <msgCore.h>
#include <nsIServiceManager.h>
#include <nsIAbCard.h>
#include <nsAbBaseCID.h>
#include <nsAbAddressCollecter.h>
#include <nsIPref.h>
#include <nsIAddrBookSession.h>
#include <nsIMsgHeaderParser.h>
#include <nsIAddrBookSession.h>
#include <nsIAbDirectory.h>
#include <nsAbDirectoryQuery.h>
#include <nsIAbDirectoryQuery.h>
#include <nsIAbDirectoryQueryProxy.h>
#include <nsIAbDirFactory.h>
#ifdef MOZ_BOOL
# undef BOOL
# undef Bool
#endif
#ifdef DEBUG_WAS_DEFINED
#define DEBUG DEBUG_WAS_DEFINED
#endif
#ifdef _DEBUG_WAS_DEFINED
#define _DEBUG _DEBUG_WAS_DEFINED
#endif
#endif // _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
<commit_msg>#100000# undef 1 param only<commit_after>/*************************************************************************
*
* $RCSfile: MNSInclude.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2002-10-18 08:51:22 $
*
* 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): Willem van Dorp, Darren Kenny
*
*
************************************************************************/
#ifndef _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
#define _CONNECTIVITY_MAB_NS_INCLUDE_HXX_ 1
//
// Only include Mozilla include files once and using this file...
//
#ifndef BOOL
# define MOZ_BOOL
# define BOOL mozBOOL
# define Bool mozBooL
#endif
// Turn off DEBUG Assertions
#ifdef _DEBUG
#define _DEBUG_WAS_DEFINED _DEBUG
#undef _DEBUG
#else
#undef _DEBUG_WAS_DEFINED
#endif
// and turn off the additional virtual methods which are part of some interfaces when compiled
// with debug
#ifdef DEBUG
#define DEBUG_WAS_DEFINED DEBUG
#undef DEBUG
#else
#undef DEBUG_WAS_DEFINED
#endif
#include <nsDebug.h>
#include <nsCOMPtr.h>
#include <nsISupportsArray.h>
#include <nsStr.h>
#include <nsString.h>
#include <nsString2.h>
#include <nsMemory.h>
#include <prtypes.h>
#include <nsRDFCID.h>
#include <nsXPIDLString.h>
#include <nsIRDFService.h>
#include <nsIRDFResource.h>
#include <nsReadableUtils.h>
#include <msgCore.h>
#include <nsIServiceManager.h>
#include <nsIAbCard.h>
#include <nsAbBaseCID.h>
#include <nsAbAddressCollecter.h>
#include <nsIPref.h>
#include <nsIAddrBookSession.h>
#include <nsIMsgHeaderParser.h>
#include <nsIAddrBookSession.h>
#include <nsIAbDirectory.h>
#include <nsAbDirectoryQuery.h>
#include <nsIAbDirectoryQuery.h>
#include <nsIAbDirectoryQueryProxy.h>
#include <nsIAbDirFactory.h>
#ifdef MOZ_BOOL
# undef BOOL
# undef Bool
#endif
#ifdef DEBUG_WAS_DEFINED
#define DEBUG DEBUG_WAS_DEFINED
#endif
#ifdef _DEBUG_WAS_DEFINED
#define _DEBUG _DEBUG_WAS_DEFINED
#endif
#endif // _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
<|endoftext|> |
<commit_before>/*
* ForwardChainer.cc
*
* Copyright (C) 2014,2015 OpenCog Foundation
*
* Author: Misgana Bayetta <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/util/random.h>
#include <opencog/atoms/pattern/BindLink.h>
#include <opencog/atoms/core/VariableList.h>
#include <opencog/atomutils/FindUtils.h>
#include <opencog/query/BindLinkAPI.h>
#include <opencog/rule-engine/Rule.h>
#include "ForwardChainer.h"
#include "FocusSetPMCB.h"
#include "../URELogger.h"
#include "../backwardchainer/ControlPolicy.h"
#include "../ThompsonSampling.h"
using namespace opencog;
ForwardChainer::ForwardChainer(AtomSpace& as, const Handle& rbs,
const Handle& source,
const Handle& vardecl,
const HandleSeq& focus_set,
source_selection_mode sm)
: _as(as), _config(as, rbs), _sources(_config, source, vardecl), _fcstat(as)
{
init(source, vardecl, focus_set);
}
ForwardChainer::~ForwardChainer()
{
}
void ForwardChainer::init(const Handle& source,
const Handle& vardecl,
const HandleSeq& focus_set)
{
validate(source);
_search_focus_set = not focus_set.empty();
// Add focus set atoms and sources to focus_set atomspace
if (_search_focus_set) {
_focus_set = focus_set;
for (const Handle& h : _focus_set)
_focus_set_as.add_atom(h);
for (const Source& src : _sources.sources)
_focus_set_as.add_atom(src.body);
}
// Set rules.
_rules = _config.get_rules();
// TODO: For now the FC follows the old standard. We may move to
// the new standard when all rules have been ported to the new one.
for (const Rule& rule : _rules)
rule.premises_as_clauses = true; // can be modify as mutable
// Reset the iteration count and max count
_iteration = 0;
}
UREConfig& ForwardChainer::get_config()
{
return _config;
}
const UREConfig& ForwardChainer::get_config() const
{
return _config;
}
void ForwardChainer::do_chain()
{
ure_logger().debug("Start Forward Chaining");
LAZY_URE_LOG_DEBUG << "With rule set:" << std::endl << oc_to_string(_rules);
// Relex2Logic uses this. TODO make a separate class to handle
// this robustly.
if(_sources.empty())
{
apply_all_rules();
return;
}
while (not termination())
{
do_step();
}
ure_logger().debug("Finished Forward Chaining");
}
void ForwardChainer::do_step()
{
_iteration++;
ure_logger().debug() << "Iteration " << _iteration
<< "/" << _config.get_maximum_iterations_str();
// Expand meta rules. This should probably be done on-the-fly in
// the select_rule method, but for now it's here
expand_meta_rules();
// Select source
Source* source = select_source();
if (source) {
LAZY_URE_LOG_DEBUG << "Selected source:" << std::endl
<< source->to_string();
} else {
LAZY_URE_LOG_DEBUG << "No source selected, abort iteration";
return;
}
// Select rule
RuleProbabilityPair rule_prob = select_rule(*source);
const Rule& rule = rule_prob.first;
double prob(rule_prob.second);
if (not rule.is_valid()) {
ure_logger().debug("No selected rule, abort iteration");
return;
} else {
LAZY_URE_LOG_DEBUG << "Selected rule, with probability " << prob
<< " of success:" << std::endl << rule.to_string();
}
// Apply rule on source
HandleSet products = apply_rule(rule, *source);
// Save trace (before inserting new sources because it will cause
// the source pointer to be invalid).
_fcstat.add_inference_record(_iteration - 1, source->body, rule, products);
// Insert the produced sources in the population of sources
_sources.insert(products, *source, prob);
}
bool ForwardChainer::termination()
{
bool terminate = false;
std::string msg;
// Terminate if all sources have been tried
if (_sources.exhausted) {
msg = "all sources have been exhausted";
terminate = true;
}
// Terminate if max iterations has been reached
else if (_config.get_maximum_iterations() == _iteration) {
msg = "reach maximum number of iterations";
terminate = true;
}
if (terminate)
ure_logger().debug() << "Terminate: " << msg;
return terminate;
}
/**
* Applies all rules in the rule base.
*
* @param search_focus_set flag for searching focus set.
*/
void ForwardChainer::apply_all_rules()
{
for (const Rule& rule : _rules) {
ure_logger().debug("Apply rule %s", rule.get_name().c_str());
HandleSet uhs = apply_rule(rule);
// Update
_fcstat.add_inference_record(_iteration,
_as.add_node(CONCEPT_NODE, "dummy-source"),
rule, uhs);
}
}
HandleSet ForwardChainer::get_chaining_result()
{
return _fcstat.get_all_products();
}
Source* ForwardChainer::select_source()
{
std::vector<double> weights = _sources.get_weights();
// Debug log
if (ure_logger().is_debug_enabled()) {
OC_ASSERT(weights.size() == _sources.size());
std::stringstream ss;
ss << "Weighted sources:";
for (size_t i = 0; i < weights.size(); i++) {
if (0 < weights[i]) {
ss << std::endl << weights[i] << " "
<< _sources.sources[i].body->id_to_string();
}
}
ure_logger().debug() << ss.str();
}
// Calculate the total weight to be sure it's greater than zero
double total = boost::accumulate(weights, 0.0);
if (total == 0.0) {
ure_logger().debug() << "All sources have been exhausted";
if (_config.get_retry_exhausted_sources()) {
ure_logger().debug() << "Reset all exhausted flags to retry them";
_sources.reset_exhausted();
// Try again
select_source();
} else {
_sources.exhausted = true;
return nullptr;
}
}
// Sample sources according to this distribution
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
return &rand_element(_sources.sources, dist);
}
RuleSet ForwardChainer::get_valid_rules(const Source& source)
{
// Generate all valid rules
RuleSet valid_rules;
for (const Rule& rule : _rules) {
// For now ignore meta rules as they are forwardly applied in
// expand_bit()
if (rule.is_meta())
continue;
const AtomSpace& ref_as(_search_focus_set ? _focus_set_as : _as);
RuleTypedSubstitutionMap urm =
rule.unify_source(source.body, source.vardecl, &ref_as);
RuleSet unified_rules = Rule::strip_typed_substitution(urm);
// Only insert unexplored rules for this source
RuleSet pos_rules;
for (const auto& rule : unified_rules)
if (not source.is_exhausted(rule))
pos_rules.insert(rule);
valid_rules.insert(pos_rules.begin(), pos_rules.end());
}
return valid_rules;
}
RuleProbabilityPair ForwardChainer::select_rule(const Handle& h)
{
Source src(h);
return select_rule(src);
}
RuleProbabilityPair ForwardChainer::select_rule(Source& source)
{
const RuleSet valid_rules = get_valid_rules(source);
// Log valid rules
if (ure_logger().is_debug_enabled()) {
std::stringstream ss;
ss << "The following rules are valid:" << std::endl
<< oc_to_string(valid_rules.aliases());
LAZY_URE_LOG_DEBUG << ss.str();
}
if (valid_rules.empty()) {
source.exhausted = true;
return {Rule(), 0.0};
}
return select_rule(valid_rules);
};
RuleProbabilityPair ForwardChainer::select_rule(const RuleSet& valid_rules)
{
// Build vector of all valid truth values
TruthValueSeq tvs;
for (const Rule& rule : valid_rules)
tvs.push_back(rule.get_tv());
// Build action selection distribution
std::vector<double> weights = ThompsonSampling(tvs).distribution();
// Log the distribution
if (ure_logger().is_debug_enabled()) {
std::stringstream ss;
ss << "Rule weights:" << std::endl;
size_t i = 0;
for (const Rule& rule : valid_rules) {
ss << weights[i] << " " << rule.get_name() << std::endl;
i++;
}
ure_logger().debug() << ss.str();
}
// Sample rules according to the weights
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
const Rule& selected_rule = rand_element(valid_rules, dist);
// Calculate the probability estimate of having this rule fulfill
// the objective (required to calculate its complexity)
double prob = BetaDistribution(selected_rule.get_tv()).mean();
return {selected_rule, prob};
}
HandleSet ForwardChainer::apply_rule(const Rule& rule, Source& source)
{
// Keep track of rule application to not do it again, and apply rule
source.rules.insert(rule);
return apply_rule(rule);
}
HandleSet ForwardChainer::apply_rule(const Rule& rule)
{
HandleSet results;
// Take the results from applying the rule, add them in the given
// AtomSpace and insert them in results
auto add_results = [&](AtomSpace& as, const HandleSeq& hs) {
for (const Handle& h : hs)
{
Type t = h->get_type();
// If it's a List or Set then add all the results. That
// kinda means that to infer List or Set themselves you
// need to Quote them.
if (t == LIST_LINK or t == SET_LINK)
for (const Handle& hc : h->getOutgoingSet())
results.insert(as.add_atom(hc));
else
results.insert(as.add_atom(h));
}
};
// Wrap in try/catch in case the pattern matcher can't handle it
try
{
AtomSpace& ref_as(_search_focus_set ? _focus_set_as : _as);
AtomSpace derived_rule_as(&ref_as);
Handle rhcpy = derived_rule_as.add_atom(rule.get_rule());
if (_search_focus_set) {
// rule.get_rule() may introduce a new atom that satisfies
// condition for the output. In order to prevent this
// undesirable effect, lets store rule.get_rule() in a
// child atomspace of parent focus_set_as so that PM will
// never be able to find this new undesired atom created
// from partial grounding.
BindLinkPtr bl = BindLinkCast(rhcpy);
FocusSetPMCB fs_pmcb(&derived_rule_as, &_as);
fs_pmcb.implicand = bl->get_implicand();
bl->imply(fs_pmcb, &_focus_set_as, false);
add_results(_focus_set_as, fs_pmcb.get_result_list());
}
// Search the whole atomspace.
else {
Handle h = bindlink(&_as, rhcpy);
add_results(_as, h->getOutgoingSet());
}
}
catch (...) {}
LAZY_URE_LOG_DEBUG << "Results:" << std::endl << oc_to_string(results);
return HandleSet(results.begin(), results.end());
}
void ForwardChainer::validate(const Handle& source)
{
if (source == Handle::UNDEFINED)
throw RuntimeException(TRACE_INFO, "ForwardChainer - Invalid source.");
}
void ForwardChainer::expand_meta_rules()
{
// This is kinda of hack before meta rules are fully supported by
// the Rule class.
size_t rules_size = _rules.size();
_rules.expand_meta_rules(_as);
if (rules_size != _rules.size()) {
ure_logger().debug() << "The rule set has gone from "
<< rules_size << " rules to " << _rules.size();
}
}
<commit_msg>Minor logging improvements<commit_after>/*
* ForwardChainer.cc
*
* Copyright (C) 2014,2015 OpenCog Foundation
*
* Author: Misgana Bayetta <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/util/random.h>
#include <opencog/atoms/pattern/BindLink.h>
#include <opencog/atoms/core/VariableList.h>
#include <opencog/atomutils/FindUtils.h>
#include <opencog/query/BindLinkAPI.h>
#include <opencog/rule-engine/Rule.h>
#include "ForwardChainer.h"
#include "FocusSetPMCB.h"
#include "../URELogger.h"
#include "../backwardchainer/ControlPolicy.h"
#include "../ThompsonSampling.h"
using namespace opencog;
ForwardChainer::ForwardChainer(AtomSpace& as, const Handle& rbs,
const Handle& source,
const Handle& vardecl,
const HandleSeq& focus_set,
source_selection_mode sm)
: _as(as), _config(as, rbs), _sources(_config, source, vardecl), _fcstat(as)
{
init(source, vardecl, focus_set);
}
ForwardChainer::~ForwardChainer()
{
}
void ForwardChainer::init(const Handle& source,
const Handle& vardecl,
const HandleSeq& focus_set)
{
validate(source);
_search_focus_set = not focus_set.empty();
// Add focus set atoms and sources to focus_set atomspace
if (_search_focus_set) {
_focus_set = focus_set;
for (const Handle& h : _focus_set)
_focus_set_as.add_atom(h);
for (const Source& src : _sources.sources)
_focus_set_as.add_atom(src.body);
}
// Set rules.
_rules = _config.get_rules();
// TODO: For now the FC follows the old standard. We may move to
// the new standard when all rules have been ported to the new one.
for (const Rule& rule : _rules)
rule.premises_as_clauses = true; // can be modify as mutable
// Reset the iteration count and max count
_iteration = 0;
}
UREConfig& ForwardChainer::get_config()
{
return _config;
}
const UREConfig& ForwardChainer::get_config() const
{
return _config;
}
void ForwardChainer::do_chain()
{
ure_logger().debug("Start Forward Chaining");
LAZY_URE_LOG_DEBUG << "With rule set:" << std::endl << oc_to_string(_rules);
// Relex2Logic uses this. TODO make a separate class to handle
// this robustly.
if(_sources.empty())
{
apply_all_rules();
return;
}
while (not termination())
{
do_step();
}
ure_logger().debug("Finished Forward Chaining");
}
void ForwardChainer::do_step()
{
_iteration++;
ure_logger().debug() << "Iteration " << _iteration
<< "/" << _config.get_maximum_iterations_str();
// Expand meta rules. This should probably be done on-the-fly in
// the select_rule method, but for now it's here
expand_meta_rules();
// Select source
Source* source = select_source();
if (source) {
LAZY_URE_LOG_DEBUG << "Selected source:" << std::endl
<< source->to_string();
} else {
LAZY_URE_LOG_DEBUG << "No source selected, abort iteration";
return;
}
// Select rule
RuleProbabilityPair rule_prob = select_rule(*source);
const Rule& rule = rule_prob.first;
double prob(rule_prob.second);
if (not rule.is_valid()) {
ure_logger().debug("No selected rule, abort iteration");
return;
} else {
LAZY_URE_LOG_DEBUG << "Selected rule, with probability " << prob
<< " of success:" << std::endl << rule.to_string();
}
// Apply rule on source
HandleSet products = apply_rule(rule, *source);
// Save trace (before inserting new sources because it will cause
// the source pointer to be invalid).
_fcstat.add_inference_record(_iteration - 1, source->body, rule, products);
// Insert the produced sources in the population of sources
_sources.insert(products, *source, prob);
}
bool ForwardChainer::termination()
{
bool terminate = false;
std::string msg;
// Terminate if all sources have been tried
if (_sources.exhausted) {
msg = "all sources have been exhausted";
terminate = true;
}
// Terminate if max iterations has been reached
else if (_config.get_maximum_iterations() == _iteration) {
msg = "reach maximum number of iterations";
terminate = true;
}
if (terminate)
ure_logger().debug() << "Terminate: " << msg;
return terminate;
}
/**
* Applies all rules in the rule base.
*
* @param search_focus_set flag for searching focus set.
*/
void ForwardChainer::apply_all_rules()
{
for (const Rule& rule : _rules) {
ure_logger().debug("Apply rule %s", rule.get_name().c_str());
HandleSet uhs = apply_rule(rule);
// Update
_fcstat.add_inference_record(_iteration,
_as.add_node(CONCEPT_NODE, "dummy-source"),
rule, uhs);
}
}
HandleSet ForwardChainer::get_chaining_result()
{
return _fcstat.get_all_products();
}
Source* ForwardChainer::select_source()
{
std::vector<double> weights = _sources.get_weights();
// Debug log
if (ure_logger().is_debug_enabled()) {
OC_ASSERT(weights.size() == _sources.size());
std::stringstream ss;
ss << "Weighted sources:" << std::endl << "size = " << weights.size();
for (size_t i = 0; i < weights.size(); i++) {
if (0 < weights[i]) {
ss << std::endl << weights[i] << " "
<< _sources.sources[i].body->id_to_string();
}
}
ure_logger().debug() << ss.str();
}
// Calculate the total weight to be sure it's greater than zero
double total = boost::accumulate(weights, 0.0);
if (total == 0.0) {
ure_logger().debug() << "All sources have been exhausted";
if (_config.get_retry_exhausted_sources()) {
ure_logger().debug() << "Reset all exhausted flags to retry them";
_sources.reset_exhausted();
// Try again
select_source();
} else {
_sources.exhausted = true;
return nullptr;
}
}
// Sample sources according to this distribution
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
return &rand_element(_sources.sources, dist);
}
RuleSet ForwardChainer::get_valid_rules(const Source& source)
{
// Generate all valid rules
RuleSet valid_rules;
for (const Rule& rule : _rules) {
// For now ignore meta rules as they are forwardly applied in
// expand_bit()
if (rule.is_meta())
continue;
const AtomSpace& ref_as(_search_focus_set ? _focus_set_as : _as);
RuleTypedSubstitutionMap urm =
rule.unify_source(source.body, source.vardecl, &ref_as);
RuleSet unified_rules = Rule::strip_typed_substitution(urm);
// Only insert unexplored rules for this source
RuleSet pos_rules;
for (const auto& rule : unified_rules)
if (not source.is_exhausted(rule))
pos_rules.insert(rule);
valid_rules.insert(pos_rules.begin(), pos_rules.end());
}
return valid_rules;
}
RuleProbabilityPair ForwardChainer::select_rule(const Handle& h)
{
Source src(h);
return select_rule(src);
}
RuleProbabilityPair ForwardChainer::select_rule(Source& source)
{
const RuleSet valid_rules = get_valid_rules(source);
// Log valid rules
if (ure_logger().is_debug_enabled()) {
std::stringstream ss;
ss << "The following rules are valid:" << std::endl
<< valid_rules.to_short_string();
LAZY_URE_LOG_DEBUG << ss.str();
}
if (valid_rules.empty()) {
source.exhausted = true;
return {Rule(), 0.0};
}
return select_rule(valid_rules);
};
RuleProbabilityPair ForwardChainer::select_rule(const RuleSet& valid_rules)
{
// Build vector of all valid truth values
TruthValueSeq tvs;
for (const Rule& rule : valid_rules)
tvs.push_back(rule.get_tv());
// Build action selection distribution
std::vector<double> weights = ThompsonSampling(tvs).distribution();
// Log the distribution
if (ure_logger().is_debug_enabled()) {
std::stringstream ss;
ss << "Rule weights:" << std::endl;
size_t i = 0;
for (const Rule& rule : valid_rules) {
ss << weights[i] << " " << rule.get_name() << std::endl;
i++;
}
ure_logger().debug() << ss.str();
}
// Sample rules according to the weights
std::discrete_distribution<size_t> dist(weights.begin(), weights.end());
const Rule& selected_rule = rand_element(valid_rules, dist);
// Calculate the probability estimate of having this rule fulfill
// the objective (required to calculate its complexity)
double prob = BetaDistribution(selected_rule.get_tv()).mean();
return {selected_rule, prob};
}
HandleSet ForwardChainer::apply_rule(const Rule& rule, Source& source)
{
// Keep track of rule application to not do it again, and apply rule
source.rules.insert(rule);
return apply_rule(rule);
}
HandleSet ForwardChainer::apply_rule(const Rule& rule)
{
HandleSet results;
// Take the results from applying the rule, add them in the given
// AtomSpace and insert them in results
auto add_results = [&](AtomSpace& as, const HandleSeq& hs) {
for (const Handle& h : hs)
{
Type t = h->get_type();
// If it's a List or Set then add all the results. That
// kinda means that to infer List or Set themselves you
// need to Quote them.
if (t == LIST_LINK or t == SET_LINK)
for (const Handle& hc : h->getOutgoingSet())
results.insert(as.add_atom(hc));
else
results.insert(as.add_atom(h));
}
};
// Wrap in try/catch in case the pattern matcher can't handle it
try
{
AtomSpace& ref_as(_search_focus_set ? _focus_set_as : _as);
AtomSpace derived_rule_as(&ref_as);
Handle rhcpy = derived_rule_as.add_atom(rule.get_rule());
if (_search_focus_set) {
// rule.get_rule() may introduce a new atom that satisfies
// condition for the output. In order to prevent this
// undesirable effect, lets store rule.get_rule() in a
// child atomspace of parent focus_set_as so that PM will
// never be able to find this new undesired atom created
// from partial grounding.
BindLinkPtr bl = BindLinkCast(rhcpy);
FocusSetPMCB fs_pmcb(&derived_rule_as, &_as);
fs_pmcb.implicand = bl->get_implicand();
bl->imply(fs_pmcb, &_focus_set_as, false);
add_results(_focus_set_as, fs_pmcb.get_result_list());
}
// Search the whole atomspace.
else {
Handle h = bindlink(&_as, rhcpy);
add_results(_as, h->getOutgoingSet());
}
}
catch (...) {}
LAZY_URE_LOG_DEBUG << "Results:" << std::endl << oc_to_string(results);
return HandleSet(results.begin(), results.end());
}
void ForwardChainer::validate(const Handle& source)
{
if (source == Handle::UNDEFINED)
throw RuntimeException(TRACE_INFO, "ForwardChainer - Invalid source.");
}
void ForwardChainer::expand_meta_rules()
{
// This is kinda of hack before meta rules are fully supported by
// the Rule class.
size_t rules_size = _rules.size();
_rules.expand_meta_rules(_as);
if (rules_size != _rules.size()) {
ure_logger().debug() << "The rule set has gone from "
<< rules_size << " rules to " << _rules.size();
}
}
<|endoftext|> |
<commit_before>#define DEFAULT_RU 1
#define DEFAULT_ACE_RU 0
#define DEFAULT_INS 0
#define DEFAULT_GUE 1
#define DEFAULT_BIS_TK 0
#define DEFAULT_BIS_TK_INS 0
#define DEFAULT_BIS_TK_GUE 0
#define DEFAULT_CWR2_US 0
#define DEFAULT_CWR2_RU 0
#define DEFAULT_CWR2_FIA 0
<commit_msg>[MISSIONS] - Removed old mso factions def from lingor mission<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "internaljobs.h"
#include "jobs.h"
#include <buildgraph/artifactcleaner.h>
#include <buildgraph/buildgraphloader.h>
#include <buildgraph/productbuilddata.h>
#include <buildgraph/projectbuilddata.h>
#include <buildgraph/executor.h>
#include <buildgraph/productinstaller.h>
#include <buildgraph/rulesevaluationcontext.h>
#include <language/language.h>
#include <language/loader.h>
#include <logging/logger.h>
#include <logging/translator.h>
#include <tools/error.h>
#include <tools/progressobserver.h>
#include <tools/preferences.h>
#include <tools/qbsassert.h>
#include <QEventLoop>
#include <QScopedPointer>
#include <QTimer>
namespace qbs {
namespace Internal {
class JobObserver : public ProgressObserver
{
public:
JobObserver(InternalJob *job) : m_canceled(false), m_job(job), m_timedLogger(0) { }
~JobObserver() { delete m_timedLogger; }
void cancel() { m_canceled = true; }
private:
void initialize(const QString &task, int maximum)
{
QBS_ASSERT(!m_timedLogger, delete m_timedLogger);
m_timedLogger = new TimedActivityLogger(m_job->logger(), task, QString(),
m_job->timed() ? LoggerInfo : LoggerDebug, m_job->timed());
m_value = 0;
m_maximum = maximum;
m_canceled = false;
emit m_job->newTaskStarted(task, maximum, m_job);
}
void setMaximum(int maximum)
{
m_maximum = maximum;
emit m_job->totalEffortChanged(maximum, m_job);
}
void setProgressValue(int value)
{
//QBS_ASSERT(value >= m_value, qDebug("old value = %d, new value = %d", m_value, value));
//QBS_ASSERT(value <= m_maximum, qDebug("value = %d, maximum = %d", value, m_maximum));
m_value = value;
if (value == m_maximum) {
delete m_timedLogger;
m_timedLogger = 0;
}
emit m_job->taskProgress(value, m_job);
}
int progressValue() { return m_value; }
int maximum() const { return m_maximum; }
bool canceled() const { return m_canceled; }
int m_value;
int m_maximum;
bool m_canceled;
InternalJob * const m_job;
TimedActivityLogger *m_timedLogger;
};
InternalJob::InternalJob(const Logger &logger, QObject *parent)
: QObject(parent)
, m_observer(new JobObserver(this))
, m_ownsObserver(true)
, m_logger(logger)
, m_timed(false)
{
}
InternalJob::~InternalJob()
{
if (m_ownsObserver)
delete m_observer;
}
void InternalJob::cancel()
{
m_observer->cancel();
}
void InternalJob::shareObserverWith(InternalJob *otherJob)
{
if (m_ownsObserver) {
delete m_observer;
m_ownsObserver = false;
}
m_observer = otherJob->m_observer;
}
void InternalJob::storeBuildGraph(const TopLevelProjectConstPtr &project)
{
try {
project->store(logger());
} catch (const ErrorInfo &error) {
logger().printWarning(error);
}
}
/**
* Construct a new thread wrapper for a synchronous job.
* This object takes over ownership of the synchronous job.
*/
InternalJobThreadWrapper::InternalJobThreadWrapper(InternalJob *synchronousJob, QObject *parent)
: InternalJob(synchronousJob->logger(), parent)
, m_job(synchronousJob)
, m_running(false)
{
synchronousJob->shareObserverWith(this);
m_job->moveToThread(&m_thread);
connect(m_job, SIGNAL(finished(Internal::InternalJob*)), SLOT(handleFinished()));
connect(m_job, SIGNAL(newTaskStarted(QString,int,Internal::InternalJob*)),
SIGNAL(newTaskStarted(QString,int,Internal::InternalJob*)));
connect(m_job, SIGNAL(taskProgress(int,Internal::InternalJob*)),
SIGNAL(taskProgress(int,Internal::InternalJob*)));
connect(m_job, SIGNAL(totalEffortChanged(int,Internal::InternalJob*)),
SIGNAL(totalEffortChanged(int,Internal::InternalJob*)));
m_job->connect(this, SIGNAL(startRequested()), SLOT(start()));
}
InternalJobThreadWrapper::~InternalJobThreadWrapper()
{
if (m_running) {
QEventLoop loop;
loop.connect(m_job, SIGNAL(finished(Internal::InternalJob*)), SLOT(quit));
loop.exec();
}
m_thread.quit();
m_thread.wait();
delete m_job;
}
void InternalJobThreadWrapper::start()
{
setTimed(m_job->timed());
m_thread.start();
m_running = true;
emit startRequested();
}
void InternalJobThreadWrapper::handleFinished()
{
m_running = false;
setError(m_job->error());
emit finished(this);
}
InternalSetupProjectJob::InternalSetupProjectJob(const Logger &logger)
: InternalJob(logger)
{
}
InternalSetupProjectJob::~InternalSetupProjectJob()
{
}
void InternalSetupProjectJob::init(const SetupProjectParameters ¶meters)
{
m_parameters = parameters;
setTimed(parameters.logElapsedTime());
}
void InternalSetupProjectJob::reportError(const ErrorInfo &error)
{
setError(error);
emit finished(this);
}
TopLevelProjectPtr InternalSetupProjectJob::project() const
{
return m_project;
}
void InternalSetupProjectJob::start()
{
try {
execute();
} catch (const ErrorInfo &error) {
setError(error);
}
emit finished(this);
}
void InternalSetupProjectJob::execute()
{
RulesEvaluationContextPtr evalContext(new RulesEvaluationContext(logger()));
evalContext->setObserver(observer());
switch (m_parameters.restoreBehavior()) {
case SetupProjectParameters::ResolveOnly:
resolveProjectFromScratch(evalContext->engine());
resolveBuildDataFromScratch(evalContext);
setupPlatformEnvironment();
break;
case SetupProjectParameters::RestoreOnly:
m_project = restoreProject(evalContext).loadedProject;
break;
case SetupProjectParameters::RestoreAndTrackChanges: {
const BuildGraphLoadResult loadResult = restoreProject(evalContext);
m_project = loadResult.newlyResolvedProject;
if (!m_project && !loadResult.discardLoadedProject)
m_project = loadResult.loadedProject;
if (!m_project)
resolveProjectFromScratch(evalContext->engine());
if (!m_project->buildData) {
resolveBuildDataFromScratch(evalContext);
if (loadResult.loadedProject)
BuildDataResolver::rescueBuildData(loadResult.loadedProject, m_project, logger());
}
setupPlatformEnvironment();
break;
}
}
if (!m_parameters.dryRun())
storeBuildGraph(m_project);
// The evalutation context cannot be re-used for building, which runs in a different thread.
m_project->buildData->evaluationContext.clear();
}
void InternalSetupProjectJob::resolveProjectFromScratch(ScriptEngine *engine)
{
Loader loader(engine, logger());
loader.setSearchPaths(m_parameters.searchPaths());
loader.setProgressObserver(observer());
m_project = loader.loadProject(m_parameters);
}
void InternalSetupProjectJob::resolveBuildDataFromScratch(const RulesEvaluationContextPtr &evalContext)
{
TimedActivityLogger resolveLogger(logger(), QLatin1String("Resolving build project"));
BuildDataResolver(logger()).resolveBuildData(m_project, evalContext);
}
void InternalSetupProjectJob::setupPlatformEnvironment()
{
const QVariantMap platformEnvironment
= m_parameters.buildConfiguration().value(QLatin1String("environment")).toMap();
m_project->platformEnvironment = platformEnvironment;
}
BuildGraphLoadResult InternalSetupProjectJob::restoreProject(const RulesEvaluationContextPtr &evalContext)
{
BuildGraphLoader bgLoader(m_parameters.environment(), logger());
const BuildGraphLoadResult loadResult = bgLoader.load(m_parameters, evalContext);
return loadResult;
}
BuildGraphTouchingJob::BuildGraphTouchingJob(const Logger &logger, QObject *parent)
: InternalJob(logger, parent), m_dryRun(false)
{
}
BuildGraphTouchingJob::~BuildGraphTouchingJob()
{
}
void BuildGraphTouchingJob::setup(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, bool dryRun)
{
m_project = project;
m_products = products;
m_dryRun = dryRun;
}
void BuildGraphTouchingJob::storeBuildGraph()
{
if (!m_dryRun)
InternalJob::storeBuildGraph(m_project);
}
InternalBuildJob::InternalBuildJob(const Logger &logger, QObject *parent)
: BuildGraphTouchingJob(logger, parent), m_executor(0)
{
}
void InternalBuildJob::build(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, const BuildOptions &buildOptions)
{
setup(project, products, buildOptions.dryRun());
setTimed(buildOptions.logElapsedTime());
m_executor = new Executor(logger());
m_executor->setProject(project);
m_executor->setProducts(products);
m_executor->setBuildOptions(buildOptions);
m_executor->setProgressObserver(observer());
QThread * const executorThread = new QThread(this);
m_executor->moveToThread(executorThread);
connect(m_executor, SIGNAL(reportCommandDescription(QString,QString)),
this, SIGNAL(reportCommandDescription(QString,QString)));
connect(m_executor, SIGNAL(reportProcessResult(qbs::ProcessResult)),
this, SIGNAL(reportProcessResult(qbs::ProcessResult)));
connect(executorThread, SIGNAL(started()), m_executor, SLOT(build()));
connect(m_executor, SIGNAL(finished()), SLOT(handleFinished()));
connect(m_executor, SIGNAL(destroyed()), executorThread, SLOT(quit()));
connect(executorThread, SIGNAL(finished()), this, SLOT(emitFinished()));
executorThread->start();
}
void InternalBuildJob::handleFinished()
{
setError(m_executor->error());
project()->buildData->evaluationContext.clear();
storeBuildGraph();
m_executor->deleteLater();
}
void InternalBuildJob::emitFinished()
{
emit finished(this);
}
InternalCleanJob::InternalCleanJob(const Logger &logger, QObject *parent)
: BuildGraphTouchingJob(logger, parent)
{
}
void InternalCleanJob::init(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, const CleanOptions &options)
{
setup(project, products, options.dryRun());
setTimed(options.logElapsedTime());
m_options = options;
}
void InternalCleanJob::start()
{
try {
ArtifactCleaner cleaner(logger(), observer());
cleaner.cleanup(project(), products(), m_options);
} catch (const ErrorInfo &error) {
setError(error);
}
storeBuildGraph();
emit finished(this);
}
InternalInstallJob::InternalInstallJob(const Logger &logger)
: InternalJob(logger)
{
}
InternalInstallJob::~InternalInstallJob()
{
}
void InternalInstallJob::init(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, const InstallOptions &options)
{
m_project = project;
m_products = products;
m_options = options;
setTimed(options.logElapsedTime());
}
void InternalInstallJob::start()
{
try {
ProductInstaller(m_project, m_products, m_options, observer(), logger()).install();
} catch (const ErrorInfo &error) {
setError(error);
}
emit finished(this);
}
} // namespace Internal
} // namespace qbs
<commit_msg>Fix connect<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "internaljobs.h"
#include "jobs.h"
#include <buildgraph/artifactcleaner.h>
#include <buildgraph/buildgraphloader.h>
#include <buildgraph/productbuilddata.h>
#include <buildgraph/projectbuilddata.h>
#include <buildgraph/executor.h>
#include <buildgraph/productinstaller.h>
#include <buildgraph/rulesevaluationcontext.h>
#include <language/language.h>
#include <language/loader.h>
#include <logging/logger.h>
#include <logging/translator.h>
#include <tools/error.h>
#include <tools/progressobserver.h>
#include <tools/preferences.h>
#include <tools/qbsassert.h>
#include <QEventLoop>
#include <QScopedPointer>
#include <QTimer>
namespace qbs {
namespace Internal {
class JobObserver : public ProgressObserver
{
public:
JobObserver(InternalJob *job) : m_canceled(false), m_job(job), m_timedLogger(0) { }
~JobObserver() { delete m_timedLogger; }
void cancel() { m_canceled = true; }
private:
void initialize(const QString &task, int maximum)
{
QBS_ASSERT(!m_timedLogger, delete m_timedLogger);
m_timedLogger = new TimedActivityLogger(m_job->logger(), task, QString(),
m_job->timed() ? LoggerInfo : LoggerDebug, m_job->timed());
m_value = 0;
m_maximum = maximum;
m_canceled = false;
emit m_job->newTaskStarted(task, maximum, m_job);
}
void setMaximum(int maximum)
{
m_maximum = maximum;
emit m_job->totalEffortChanged(maximum, m_job);
}
void setProgressValue(int value)
{
//QBS_ASSERT(value >= m_value, qDebug("old value = %d, new value = %d", m_value, value));
//QBS_ASSERT(value <= m_maximum, qDebug("value = %d, maximum = %d", value, m_maximum));
m_value = value;
if (value == m_maximum) {
delete m_timedLogger;
m_timedLogger = 0;
}
emit m_job->taskProgress(value, m_job);
}
int progressValue() { return m_value; }
int maximum() const { return m_maximum; }
bool canceled() const { return m_canceled; }
int m_value;
int m_maximum;
bool m_canceled;
InternalJob * const m_job;
TimedActivityLogger *m_timedLogger;
};
InternalJob::InternalJob(const Logger &logger, QObject *parent)
: QObject(parent)
, m_observer(new JobObserver(this))
, m_ownsObserver(true)
, m_logger(logger)
, m_timed(false)
{
}
InternalJob::~InternalJob()
{
if (m_ownsObserver)
delete m_observer;
}
void InternalJob::cancel()
{
m_observer->cancel();
}
void InternalJob::shareObserverWith(InternalJob *otherJob)
{
if (m_ownsObserver) {
delete m_observer;
m_ownsObserver = false;
}
m_observer = otherJob->m_observer;
}
void InternalJob::storeBuildGraph(const TopLevelProjectConstPtr &project)
{
try {
project->store(logger());
} catch (const ErrorInfo &error) {
logger().printWarning(error);
}
}
/**
* Construct a new thread wrapper for a synchronous job.
* This object takes over ownership of the synchronous job.
*/
InternalJobThreadWrapper::InternalJobThreadWrapper(InternalJob *synchronousJob, QObject *parent)
: InternalJob(synchronousJob->logger(), parent)
, m_job(synchronousJob)
, m_running(false)
{
synchronousJob->shareObserverWith(this);
m_job->moveToThread(&m_thread);
connect(m_job, SIGNAL(finished(Internal::InternalJob*)), SLOT(handleFinished()));
connect(m_job, SIGNAL(newTaskStarted(QString,int,Internal::InternalJob*)),
SIGNAL(newTaskStarted(QString,int,Internal::InternalJob*)));
connect(m_job, SIGNAL(taskProgress(int,Internal::InternalJob*)),
SIGNAL(taskProgress(int,Internal::InternalJob*)));
connect(m_job, SIGNAL(totalEffortChanged(int,Internal::InternalJob*)),
SIGNAL(totalEffortChanged(int,Internal::InternalJob*)));
m_job->connect(this, SIGNAL(startRequested()), SLOT(start()));
}
InternalJobThreadWrapper::~InternalJobThreadWrapper()
{
if (m_running) {
QEventLoop loop;
loop.connect(m_job, SIGNAL(finished(Internal::InternalJob*)), SLOT(quit()));
loop.exec();
}
m_thread.quit();
m_thread.wait();
delete m_job;
}
void InternalJobThreadWrapper::start()
{
setTimed(m_job->timed());
m_thread.start();
m_running = true;
emit startRequested();
}
void InternalJobThreadWrapper::handleFinished()
{
m_running = false;
setError(m_job->error());
emit finished(this);
}
InternalSetupProjectJob::InternalSetupProjectJob(const Logger &logger)
: InternalJob(logger)
{
}
InternalSetupProjectJob::~InternalSetupProjectJob()
{
}
void InternalSetupProjectJob::init(const SetupProjectParameters ¶meters)
{
m_parameters = parameters;
setTimed(parameters.logElapsedTime());
}
void InternalSetupProjectJob::reportError(const ErrorInfo &error)
{
setError(error);
emit finished(this);
}
TopLevelProjectPtr InternalSetupProjectJob::project() const
{
return m_project;
}
void InternalSetupProjectJob::start()
{
try {
execute();
} catch (const ErrorInfo &error) {
setError(error);
}
emit finished(this);
}
void InternalSetupProjectJob::execute()
{
RulesEvaluationContextPtr evalContext(new RulesEvaluationContext(logger()));
evalContext->setObserver(observer());
switch (m_parameters.restoreBehavior()) {
case SetupProjectParameters::ResolveOnly:
resolveProjectFromScratch(evalContext->engine());
resolveBuildDataFromScratch(evalContext);
setupPlatformEnvironment();
break;
case SetupProjectParameters::RestoreOnly:
m_project = restoreProject(evalContext).loadedProject;
break;
case SetupProjectParameters::RestoreAndTrackChanges: {
const BuildGraphLoadResult loadResult = restoreProject(evalContext);
m_project = loadResult.newlyResolvedProject;
if (!m_project && !loadResult.discardLoadedProject)
m_project = loadResult.loadedProject;
if (!m_project)
resolveProjectFromScratch(evalContext->engine());
if (!m_project->buildData) {
resolveBuildDataFromScratch(evalContext);
if (loadResult.loadedProject)
BuildDataResolver::rescueBuildData(loadResult.loadedProject, m_project, logger());
}
setupPlatformEnvironment();
break;
}
}
if (!m_parameters.dryRun())
storeBuildGraph(m_project);
// The evalutation context cannot be re-used for building, which runs in a different thread.
m_project->buildData->evaluationContext.clear();
}
void InternalSetupProjectJob::resolveProjectFromScratch(ScriptEngine *engine)
{
Loader loader(engine, logger());
loader.setSearchPaths(m_parameters.searchPaths());
loader.setProgressObserver(observer());
m_project = loader.loadProject(m_parameters);
}
void InternalSetupProjectJob::resolveBuildDataFromScratch(const RulesEvaluationContextPtr &evalContext)
{
TimedActivityLogger resolveLogger(logger(), QLatin1String("Resolving build project"));
BuildDataResolver(logger()).resolveBuildData(m_project, evalContext);
}
void InternalSetupProjectJob::setupPlatformEnvironment()
{
const QVariantMap platformEnvironment
= m_parameters.buildConfiguration().value(QLatin1String("environment")).toMap();
m_project->platformEnvironment = platformEnvironment;
}
BuildGraphLoadResult InternalSetupProjectJob::restoreProject(const RulesEvaluationContextPtr &evalContext)
{
BuildGraphLoader bgLoader(m_parameters.environment(), logger());
const BuildGraphLoadResult loadResult = bgLoader.load(m_parameters, evalContext);
return loadResult;
}
BuildGraphTouchingJob::BuildGraphTouchingJob(const Logger &logger, QObject *parent)
: InternalJob(logger, parent), m_dryRun(false)
{
}
BuildGraphTouchingJob::~BuildGraphTouchingJob()
{
}
void BuildGraphTouchingJob::setup(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, bool dryRun)
{
m_project = project;
m_products = products;
m_dryRun = dryRun;
}
void BuildGraphTouchingJob::storeBuildGraph()
{
if (!m_dryRun)
InternalJob::storeBuildGraph(m_project);
}
InternalBuildJob::InternalBuildJob(const Logger &logger, QObject *parent)
: BuildGraphTouchingJob(logger, parent), m_executor(0)
{
}
void InternalBuildJob::build(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, const BuildOptions &buildOptions)
{
setup(project, products, buildOptions.dryRun());
setTimed(buildOptions.logElapsedTime());
m_executor = new Executor(logger());
m_executor->setProject(project);
m_executor->setProducts(products);
m_executor->setBuildOptions(buildOptions);
m_executor->setProgressObserver(observer());
QThread * const executorThread = new QThread(this);
m_executor->moveToThread(executorThread);
connect(m_executor, SIGNAL(reportCommandDescription(QString,QString)),
this, SIGNAL(reportCommandDescription(QString,QString)));
connect(m_executor, SIGNAL(reportProcessResult(qbs::ProcessResult)),
this, SIGNAL(reportProcessResult(qbs::ProcessResult)));
connect(executorThread, SIGNAL(started()), m_executor, SLOT(build()));
connect(m_executor, SIGNAL(finished()), SLOT(handleFinished()));
connect(m_executor, SIGNAL(destroyed()), executorThread, SLOT(quit()));
connect(executorThread, SIGNAL(finished()), this, SLOT(emitFinished()));
executorThread->start();
}
void InternalBuildJob::handleFinished()
{
setError(m_executor->error());
project()->buildData->evaluationContext.clear();
storeBuildGraph();
m_executor->deleteLater();
}
void InternalBuildJob::emitFinished()
{
emit finished(this);
}
InternalCleanJob::InternalCleanJob(const Logger &logger, QObject *parent)
: BuildGraphTouchingJob(logger, parent)
{
}
void InternalCleanJob::init(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, const CleanOptions &options)
{
setup(project, products, options.dryRun());
setTimed(options.logElapsedTime());
m_options = options;
}
void InternalCleanJob::start()
{
try {
ArtifactCleaner cleaner(logger(), observer());
cleaner.cleanup(project(), products(), m_options);
} catch (const ErrorInfo &error) {
setError(error);
}
storeBuildGraph();
emit finished(this);
}
InternalInstallJob::InternalInstallJob(const Logger &logger)
: InternalJob(logger)
{
}
InternalInstallJob::~InternalInstallJob()
{
}
void InternalInstallJob::init(const TopLevelProjectPtr &project,
const QList<ResolvedProductPtr> &products, const InstallOptions &options)
{
m_project = project;
m_products = products;
m_options = options;
setTimed(options.logElapsedTime());
}
void InternalInstallJob::start()
{
try {
ProductInstaller(m_project, m_products, m_options, observer(), logger()).install();
} catch (const ErrorInfo &error) {
setError(error);
}
emit finished(this);
}
} // namespace Internal
} // namespace qbs
<|endoftext|> |
<commit_before>#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Notify>
#include <set>
#include <iostream>
using namespace osg;
ArgumentParser::ArgumentParser(int* argc,char **argv):
_argc(argc),
_argv(argv),
_usage(ApplicationUsage::instance())
{
}
std::string ArgumentParser::getApplicationName() const
{
if (_argc>0) return std::string(_argv[0]);
return "";
}
int ArgumentParser::find(const std::string& str) const
{
for(int pos=1;pos<*_argc;++pos)
{
if (str==_argv[pos])
{
return pos;
}
}
return 0;
}
bool ArgumentParser::match(int pos, const std::string& str) const
{
return pos<*_argc && str==_argv[pos];
}
bool ArgumentParser::isOption(int pos) const
{
return (pos<*_argc && _argv[pos][0]=='-');
}
bool ArgumentParser::isString(int pos) const
{
return pos<*_argc && !isOption(pos);
}
bool ArgumentParser::isNumber(int pos) const
{
if (pos>=*_argc) return false;
bool hadPlusMinus = false;
bool hadDecimalPlace = false;
bool hadExponent = false;
bool couldBeInt = true;
bool couldBeFloat = true;
int noZeroToNine = 0;
const char* ptr = _argv[pos];
// check if could be a hex number.
if (strncmp(ptr,"0x",2)==0)
{
// skip over leading 0x, and then go through rest of string
// checking to make sure all values are 0...9 or a..f.
ptr+=2;
while (
*ptr!=0 &&
((*ptr>='0' && *ptr<='9') ||
(*ptr>='a' && *ptr<='f') ||
(*ptr>='A' && *ptr<='F'))
)
{
++ptr;
}
// got to end of string without failure, therefore must be a hex integer.
if (*ptr==0) return true;
}
ptr = _argv[pos];
// check if a float or an int.
while (*ptr!=0 && couldBeFloat)
{
if (*ptr=='+' || *ptr=='-')
{
if (hadPlusMinus)
{
couldBeInt = false;
couldBeFloat = false;
} else hadPlusMinus = true;
}
else if (*ptr>='0' && *ptr<='9')
{
noZeroToNine++;
}
else if (*ptr=='.')
{
if (hadDecimalPlace)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadDecimalPlace = true;
couldBeInt = false;
}
}
else if (*ptr=='e' || *ptr=='E')
{
if (hadExponent || noZeroToNine==0)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadExponent = true;
couldBeInt = false;
hadDecimalPlace = false;
hadPlusMinus = false;
noZeroToNine=0;
}
}
else
{
couldBeInt = false;
couldBeFloat = false;
}
++ptr;
}
if (couldBeInt && noZeroToNine>0) return true;
if (couldBeFloat && noZeroToNine>0) return true;
return false;
}
bool ArgumentParser::containsOptions() const
{
for(int pos=1;pos<*_argc;++pos)
{
if (isOption(pos)) return true;
}
return false;
}
void ArgumentParser::remove(int pos,int num)
{
if (num==0) return;
for(;pos+num<*_argc;++pos)
{
_argv[pos]=_argv[pos+num];
}
for(;pos<*_argc;++pos)
{
_argv[pos]=0;
}
*_argc-=num;
}
bool ArgumentParser::read(const std::string& str)
{
int pos=find(str);
if (pos<=0) return false;
remove(pos);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2,std::string& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) || !isString(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
value3 = _argv[pos+3];
remove(pos,4);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2,float& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) || !isNumber(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
value3 = atof(_argv[pos+3]);
remove(pos,4);
return true;
}
bool ArgumentParser::errors(ErrorSeverity severity) const
{
for(ErrorMessageMap::const_iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity) return true;
}
return false;
}
void ArgumentParser::reportError(const std::string& message,ErrorSeverity severity)
{
_errorMessageMap[message]=severity;
}
void ArgumentParser::reportRemainingOptionsAsUnrecognized(ErrorSeverity severity)
{
std::set<std::string> options;
if (_usage)
{
// parse the usage options to get all the option that the application can potential handle.
for(ApplicationUsage::UsageMap::const_iterator itr=_usage->getCommandLineOptions().begin();
itr!=_usage->getCommandLineOptions().end();
++itr)
{
const std::string& option = itr->first;
std::string::size_type prevpos = 0, pos = 0;
while ((pos=option.find(' ',prevpos))!=std::string::npos)
{
if (option[prevpos]=='-')
{
options.insert(std::string(option,prevpos,pos-prevpos));
}
prevpos=pos+1;
}
if (option[prevpos]=='-')
{
options.insert(std::string(option,prevpos,std::string::npos));
}
}
}
for(int pos=1;pos<argc();++pos)
{
// if an option and havn't been previous querried for report as unrecognized.
if (isOption(pos) && options.find(_argv[pos])==options.end())
{
reportError(getApplicationName() +": unrceognized option "+_argv[pos],severity);
}
}
}
void ArgumentParser::writeErrorMessages(std::ostream& output,ErrorSeverity severity)
{
for(ErrorMessageMap::iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity)
{
output<< getApplicationName() << ": " << itr->first << std::endl;
}
}
}
<commit_msg>From Jason Ballenger, fix for ArgumentParser::getApplicationName()<commit_after>#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Notify>
#include <set>
#include <iostream>
using namespace osg;
ArgumentParser::ArgumentParser(int* argc,char **argv):
_argc(argc),
_argv(argv),
_usage(ApplicationUsage::instance())
{
}
std::string ArgumentParser::getApplicationName() const
{
if (_argc && *_argc>0 ) return std::string(_argv[0]);
return "";
}
int ArgumentParser::find(const std::string& str) const
{
for(int pos=1;pos<*_argc;++pos)
{
if (str==_argv[pos])
{
return pos;
}
}
return 0;
}
bool ArgumentParser::match(int pos, const std::string& str) const
{
return pos<*_argc && str==_argv[pos];
}
bool ArgumentParser::isOption(int pos) const
{
return (pos<*_argc && _argv[pos][0]=='-');
}
bool ArgumentParser::isString(int pos) const
{
return pos<*_argc && !isOption(pos);
}
bool ArgumentParser::isNumber(int pos) const
{
if (pos>=*_argc) return false;
bool hadPlusMinus = false;
bool hadDecimalPlace = false;
bool hadExponent = false;
bool couldBeInt = true;
bool couldBeFloat = true;
int noZeroToNine = 0;
const char* ptr = _argv[pos];
// check if could be a hex number.
if (strncmp(ptr,"0x",2)==0)
{
// skip over leading 0x, and then go through rest of string
// checking to make sure all values are 0...9 or a..f.
ptr+=2;
while (
*ptr!=0 &&
((*ptr>='0' && *ptr<='9') ||
(*ptr>='a' && *ptr<='f') ||
(*ptr>='A' && *ptr<='F'))
)
{
++ptr;
}
// got to end of string without failure, therefore must be a hex integer.
if (*ptr==0) return true;
}
ptr = _argv[pos];
// check if a float or an int.
while (*ptr!=0 && couldBeFloat)
{
if (*ptr=='+' || *ptr=='-')
{
if (hadPlusMinus)
{
couldBeInt = false;
couldBeFloat = false;
} else hadPlusMinus = true;
}
else if (*ptr>='0' && *ptr<='9')
{
noZeroToNine++;
}
else if (*ptr=='.')
{
if (hadDecimalPlace)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadDecimalPlace = true;
couldBeInt = false;
}
}
else if (*ptr=='e' || *ptr=='E')
{
if (hadExponent || noZeroToNine==0)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadExponent = true;
couldBeInt = false;
hadDecimalPlace = false;
hadPlusMinus = false;
noZeroToNine=0;
}
}
else
{
couldBeInt = false;
couldBeFloat = false;
}
++ptr;
}
if (couldBeInt && noZeroToNine>0) return true;
if (couldBeFloat && noZeroToNine>0) return true;
return false;
}
bool ArgumentParser::containsOptions() const
{
for(int pos=1;pos<*_argc;++pos)
{
if (isOption(pos)) return true;
}
return false;
}
void ArgumentParser::remove(int pos,int num)
{
if (num==0) return;
for(;pos+num<*_argc;++pos)
{
_argv[pos]=_argv[pos+num];
}
for(;pos<*_argc;++pos)
{
_argv[pos]=0;
}
*_argc-=num;
}
bool ArgumentParser::read(const std::string& str)
{
int pos=find(str);
if (pos<=0) return false;
remove(pos);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2,std::string& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) || !isString(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
value3 = _argv[pos+3];
remove(pos,4);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2,float& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) || !isNumber(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
value3 = atof(_argv[pos+3]);
remove(pos,4);
return true;
}
bool ArgumentParser::errors(ErrorSeverity severity) const
{
for(ErrorMessageMap::const_iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity) return true;
}
return false;
}
void ArgumentParser::reportError(const std::string& message,ErrorSeverity severity)
{
_errorMessageMap[message]=severity;
}
void ArgumentParser::reportRemainingOptionsAsUnrecognized(ErrorSeverity severity)
{
std::set<std::string> options;
if (_usage)
{
// parse the usage options to get all the option that the application can potential handle.
for(ApplicationUsage::UsageMap::const_iterator itr=_usage->getCommandLineOptions().begin();
itr!=_usage->getCommandLineOptions().end();
++itr)
{
const std::string& option = itr->first;
std::string::size_type prevpos = 0, pos = 0;
while ((pos=option.find(' ',prevpos))!=std::string::npos)
{
if (option[prevpos]=='-')
{
options.insert(std::string(option,prevpos,pos-prevpos));
}
prevpos=pos+1;
}
if (option[prevpos]=='-')
{
options.insert(std::string(option,prevpos,std::string::npos));
}
}
}
for(int pos=1;pos<argc();++pos)
{
// if an option and havn't been previous querried for report as unrecognized.
if (isOption(pos) && options.find(_argv[pos])==options.end())
{
reportError(getApplicationName() +": unrceognized option "+_argv[pos],severity);
}
}
}
void ArgumentParser::writeErrorMessages(std::ostream& output,ErrorSeverity severity)
{
for(ErrorMessageMap::iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity)
{
output<< getApplicationName() << ": " << itr->first << std::endl;
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <set>
using namespace osg;
ArgumentParser::ArgumentParser(int* argc,char **argv):
_argc(argc),
_argv(argv),
_usage(ApplicationUsage::instance())
{
}
std::string ArgumentParser::getProgramName() const
{
if (_argc>0) return std::string(_argv[0]);
return "";
}
int ArgumentParser::find(const std::string& str) const
{
for(int pos=1;pos<*_argc;++pos)
{
if (str==_argv[pos])
{
return pos;
}
}
return 0;
}
bool ArgumentParser::match(int pos, const std::string& str) const
{
return pos<*_argc && str==_argv[pos];
}
bool ArgumentParser::isOption(int pos) const
{
return (pos<*_argc && _argv[pos][0]=='-');
}
bool ArgumentParser::isString(int pos) const
{
return pos<*_argc && !isOption(pos);
}
bool ArgumentParser::isNumber(int pos) const
{
if (pos>=*_argc) return false;
bool hadPlusMinus = false;
bool hadDecimalPlace = false;
bool hadExponent = false;
bool couldBeInt = true;
bool couldBeFloat = true;
int noZeroToNine = 0;
const char* ptr = _argv[pos];
// check if could be a hex number.
if (strncmp(ptr,"0x",2)==0)
{
// skip over leading 0x, and then go through rest of string
// checking to make sure all values are 0...9 or a..f.
ptr+=2;
while (
*ptr!=0 &&
((*ptr>='0' && *ptr<='9') ||
(*ptr>='a' && *ptr<='f') ||
(*ptr>='A' && *ptr<='F'))
)
{
++ptr;
}
// got to end of string without failure, therefore must be a hex integer.
if (*ptr==0) return true;
}
ptr = _argv[pos];
// check if a float or an int.
while (*ptr!=0 && couldBeFloat)
{
if (*ptr=='+' || *ptr=='-')
{
if (hadPlusMinus)
{
couldBeInt = false;
couldBeFloat = false;
} else hadPlusMinus = true;
}
else if (*ptr>='0' && *ptr<='9')
{
noZeroToNine++;
}
else if (*ptr=='.')
{
if (hadDecimalPlace)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadDecimalPlace = true;
couldBeInt = false;
}
}
else if (*ptr=='e' || *ptr=='E')
{
if (hadExponent || noZeroToNine==0)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadExponent = true;
couldBeInt = false;
hadDecimalPlace = false;
hadPlusMinus = false;
noZeroToNine=0;
}
}
else
{
couldBeInt = false;
couldBeFloat = false;
}
++ptr;
}
if (couldBeInt && noZeroToNine>0) return true;
if (couldBeFloat && noZeroToNine>0) return true;
return false;
}
bool ArgumentParser::containsOptions() const
{
for(int pos=1;pos<*_argc;++pos)
{
if (isOption(pos)) return true;
}
return false;
}
void ArgumentParser::remove(int pos,int num)
{
if (num==0) return;
for(;pos+num<*_argc;++pos)
{
_argv[pos]=_argv[pos+num];
}
for(;pos<*_argc;++pos)
{
_argv[pos]=0;
}
*_argc-=num;
}
bool ArgumentParser::read(const std::string& str)
{
int pos=find(str);
if (pos<=0) return false;
remove(pos);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2,std::string& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) || !isString(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
value3 = _argv[pos+3];
remove(pos,4);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2,float& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) || !isNumber(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
value3 = atof(_argv[pos+3]);
remove(pos,4);
return true;
}
bool ArgumentParser::errors(ErrorSeverity severity) const
{
for(ErrorMessageMap::const_iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity) return true;
}
return false;
}
void ArgumentParser::reportError(const std::string& message,ErrorSeverity severity)
{
_errorMessageMap[message]=severity;
}
void ArgumentParser::reportRemainingOptionsAsUnrecognized(ErrorSeverity severity)
{
std::set<std::string> options;
if (_usage)
{
// parse the usage options to get all the option that the application can potential handle.
for(ApplicationUsage::UsageMap::const_iterator itr=_usage->getCommandLineOptions().begin();
itr!=_usage->getCommandLineOptions().end();
++itr)
{
const std::string& option = itr->first;
unsigned int prevpos = 0, pos = 0;
while ((pos=option.find(' ',prevpos))!=std::string::npos)
{
if (option[prevpos]=='-') options.insert(std::string(option,prevpos,pos-prevpos));
prevpos=pos+1;
}
if (option[prevpos]=='-') options.insert(std::string(option,prevpos,std::string::npos));
}
}
for(int pos=1;pos<argc();++pos)
{
// if an option and havn't been previous querried for report as unrecognized.
if (isOption(pos) && options.find(_argv[pos])==options.end())
{
reportError(getProgramName() +": unrceognized option "+_argv[pos],severity);
}
}
}
void ArgumentParser::writeErrorMessages(std::ostream& output,ErrorSeverity severity)
{
for(ErrorMessageMap::iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity)
{
output<< getProgramName() << ": " << itr->first << std::endl;
}
}
}
<commit_msg>Added extra debugging messages into the ArgumentParser::reportRemainingOptionsAsUnrecognized(ErrorSeverity severity) method to help track down a crash under x86-64.<commit_after>#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Notify>
#include <set>
#include <iostream>
using namespace osg;
ArgumentParser::ArgumentParser(int* argc,char **argv):
_argc(argc),
_argv(argv),
_usage(ApplicationUsage::instance())
{
}
std::string ArgumentParser::getProgramName() const
{
if (_argc>0) return std::string(_argv[0]);
return "";
}
int ArgumentParser::find(const std::string& str) const
{
for(int pos=1;pos<*_argc;++pos)
{
if (str==_argv[pos])
{
return pos;
}
}
return 0;
}
bool ArgumentParser::match(int pos, const std::string& str) const
{
return pos<*_argc && str==_argv[pos];
}
bool ArgumentParser::isOption(int pos) const
{
return (pos<*_argc && _argv[pos][0]=='-');
}
bool ArgumentParser::isString(int pos) const
{
return pos<*_argc && !isOption(pos);
}
bool ArgumentParser::isNumber(int pos) const
{
if (pos>=*_argc) return false;
bool hadPlusMinus = false;
bool hadDecimalPlace = false;
bool hadExponent = false;
bool couldBeInt = true;
bool couldBeFloat = true;
int noZeroToNine = 0;
const char* ptr = _argv[pos];
// check if could be a hex number.
if (strncmp(ptr,"0x",2)==0)
{
// skip over leading 0x, and then go through rest of string
// checking to make sure all values are 0...9 or a..f.
ptr+=2;
while (
*ptr!=0 &&
((*ptr>='0' && *ptr<='9') ||
(*ptr>='a' && *ptr<='f') ||
(*ptr>='A' && *ptr<='F'))
)
{
++ptr;
}
// got to end of string without failure, therefore must be a hex integer.
if (*ptr==0) return true;
}
ptr = _argv[pos];
// check if a float or an int.
while (*ptr!=0 && couldBeFloat)
{
if (*ptr=='+' || *ptr=='-')
{
if (hadPlusMinus)
{
couldBeInt = false;
couldBeFloat = false;
} else hadPlusMinus = true;
}
else if (*ptr>='0' && *ptr<='9')
{
noZeroToNine++;
}
else if (*ptr=='.')
{
if (hadDecimalPlace)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadDecimalPlace = true;
couldBeInt = false;
}
}
else if (*ptr=='e' || *ptr=='E')
{
if (hadExponent || noZeroToNine==0)
{
couldBeInt = false;
couldBeFloat = false;
}
else
{
hadExponent = true;
couldBeInt = false;
hadDecimalPlace = false;
hadPlusMinus = false;
noZeroToNine=0;
}
}
else
{
couldBeInt = false;
couldBeFloat = false;
}
++ptr;
}
if (couldBeInt && noZeroToNine>0) return true;
if (couldBeFloat && noZeroToNine>0) return true;
return false;
}
bool ArgumentParser::containsOptions() const
{
for(int pos=1;pos<*_argc;++pos)
{
if (isOption(pos)) return true;
}
return false;
}
void ArgumentParser::remove(int pos,int num)
{
if (num==0) return;
for(;pos+num<*_argc;++pos)
{
_argv[pos]=_argv[pos+num];
}
for(;pos<*_argc;++pos)
{
_argv[pos]=0;
}
*_argc-=num;
}
bool ArgumentParser::read(const std::string& str)
{
int pos=find(str);
if (pos<=0) return false;
remove(pos);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,std::string& value1,std::string& value2,std::string& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isString(pos+1) || !isString(pos+2) || !isString(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = _argv[pos+1];
value2 = _argv[pos+2];
value3 = _argv[pos+3];
remove(pos,4);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
remove(pos,2);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) )
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
remove(pos,3);
return true;
}
bool ArgumentParser::read(const std::string& str,float& value1,float& value2,float& value3)
{
int pos=find(str);
if (pos<=0) return false;
if (!isNumber(pos+1) || !isNumber(pos+2) || !isNumber(pos+3))
{
reportError("argument to `"+str+"` is missing");
return false;
}
value1 = atof(_argv[pos+1]);
value2 = atof(_argv[pos+2]);
value3 = atof(_argv[pos+3]);
remove(pos,4);
return true;
}
bool ArgumentParser::errors(ErrorSeverity severity) const
{
for(ErrorMessageMap::const_iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity) return true;
}
return false;
}
void ArgumentParser::reportError(const std::string& message,ErrorSeverity severity)
{
_errorMessageMap[message]=severity;
}
void ArgumentParser::reportRemainingOptionsAsUnrecognized(ErrorSeverity severity)
{
std::set<std::string> options;
if (_usage)
{
// parse the usage options to get all the option that the application can potential handle.
for(ApplicationUsage::UsageMap::const_iterator itr=_usage->getCommandLineOptions().begin();
itr!=_usage->getCommandLineOptions().end();
++itr)
{
const std::string& option = itr->first;
unsigned int prevpos = 0, pos = 0;
while ((pos=option.find(' ',prevpos))!=std::string::npos)
{
if (option[prevpos]=='-')
{
// verbose approach implemented for debugging string(const string&,unsigned int,unsigned int) operation on x86-64
notify(INFO)<<"option=\""<<option<<"\" \tprevpos="<<prevpos<<" \tn="<<pos-prevpos;
std::string str(option,prevpos,pos-prevpos);
notify(INFO)<<" \tstr=\""<<str<<"\"";
options.insert(str);
notify(INFO)<<" \tinserted into options set"<<std::endl;
// original op which causes a crash under x86-64
//options.insert(std::string(option,prevpos,pos-prevpos));
}
prevpos=pos+1;
}
if (option[prevpos]=='-')
{
// verbose approach implemented for debugging string(const string&,unsigned int,unsigned int) operation on x86-64
notify(INFO)<<"option=\""<<option<<"\" \tprevpos="<<prevpos<<" \tn=npos";
std::string str(option,prevpos,pos-prevpos);
notify(INFO)<<" \tstr=\""<<str<<"\"";
options.insert(str);
notify(INFO)<<" \tinserted into options set"<<std::endl;
// original op
//options.insert(std::string(option,prevpos,std::string::npos));
}
}
}
for(int pos=1;pos<argc();++pos)
{
// if an option and havn't been previous querried for report as unrecognized.
if (isOption(pos) && options.find(_argv[pos])==options.end())
{
reportError(getProgramName() +": unrceognized option "+_argv[pos],severity);
}
}
}
void ArgumentParser::writeErrorMessages(std::ostream& output,ErrorSeverity severity)
{
for(ErrorMessageMap::iterator itr=_errorMessageMap.begin();
itr!=_errorMessageMap.end();
++itr)
{
if (itr->second>=severity)
{
output<< getProgramName() << ": " << itr->first << std::endl;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Remove deprecated text attribute from <body> in calc export to html<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: htmlimp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hjs $ $Date: 2003-08-19 11:37:18 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD
#include <svx/lrspitem.hxx>
#include <svx/paperinf.hxx>
#include <svx/sizeitem.hxx>
#include <svx/ulspitem.hxx>
#include <svx/boxitem.hxx>
#include <vcl/svapp.hxx>
#include "htmlimp.hxx"
#include "htmlpars.hxx"
#include "filter.hxx"
#include "global.hxx"
#include "document.hxx"
#include "editutil.hxx"
#include "stlpool.hxx"
#include "stlsheet.hxx"
#include "compiler.hxx"
#include "rangenam.hxx"
#include "attrib.hxx"
#include "ftools.hxx"
//------------------------------------------------------------------------
FltError ScImportHTML( SvStream &rStream, ScDocument *pDoc,
ScRange& rRange, double nOutputFactor, BOOL bCalcWidthHeight )
{
ScHTMLImport aImp( pDoc, rRange, bCalcWidthHeight );
FltError nErr = (FltError) aImp.Read( rStream );
ScRange aR = aImp.GetRange();
rRange.aEnd = aR.aEnd;
aImp.WriteToDocument( TRUE, nOutputFactor );
return nErr;
}
ScHTMLImport::ScHTMLImport( ScDocument* pDocP, const ScRange& rRange, BOOL bCalcWidthHeight ) :
ScEEImport( pDocP, rRange )
{
Size aPageSize;
OutputDevice* pDefaultDev = Application::GetDefaultDevice();
const String& aPageStyle = pDoc->GetPageStyle( rRange.aStart.Tab() );
ScStyleSheet* pStyleSheet = (ScStyleSheet*)pDoc->
GetStyleSheetPool()->Find( aPageStyle, SFX_STYLE_FAMILY_PAGE );
if ( pStyleSheet )
{
const SfxItemSet& rSet = pStyleSheet->GetItemSet();
const SvxLRSpaceItem* pLRItem = (const SvxLRSpaceItem*) &rSet.Get( ATTR_LRSPACE );
long nLeftMargin = pLRItem->GetLeft();
long nRightMargin = pLRItem->GetRight();
const SvxULSpaceItem* pULItem = (const SvxULSpaceItem*) &rSet.Get( ATTR_ULSPACE );
long nTopMargin = pULItem->GetUpper();
long nBottomMargin = pULItem->GetLower();
aPageSize = ((const SvxSizeItem&) rSet.Get(ATTR_PAGE_SIZE)).GetSize();
if ( !aPageSize.Width() || !aPageSize.Height() )
{
DBG_ERRORFILE("PageSize Null ?!?!?");
aPageSize = SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 );
}
aPageSize.Width() -= nLeftMargin + nRightMargin;
aPageSize.Height() -= nTopMargin + nBottomMargin;
aPageSize = pDefaultDev->LogicToPixel( aPageSize, MapMode( MAP_TWIP ) );
}
else
{
DBG_ERRORFILE("kein StyleSheet?!?");
aPageSize = pDefaultDev->LogicToPixel(
SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 ), MapMode( MAP_TWIP ) );
}
if( bCalcWidthHeight )
pParser = new ScHTMLLayoutParser( pEngine, aPageSize, pDocP );
else
pParser = new ScHTMLQueryParser( pEngine, pDocP );
}
ScHTMLImport::~ScHTMLImport()
{
// Reihenfolge wichtig, sonst knallt's irgendwann irgendwo in irgendeinem Dtor!
// Ist gewaehrleistet, da ScEEImport Basisklasse ist
delete (ScHTMLParser*) pParser; // vor EditEngine!
}
void ScHTMLImport::InsertRangeName( ScDocument* pDoc, const String& rName, const ScRange& rRange )
{
ComplRefData aRefData;
aRefData.InitRange( rRange );
ScTokenArray aTokArray;
aTokArray.AddDoubleReference( aRefData );
ScRangeData* pRangeData = new ScRangeData( pDoc, rName, aTokArray );
if( !pDoc->GetRangeName()->Insert( pRangeData ) )
delete pRangeData;
}
void ScHTMLImport::WriteToDocument( BOOL bSizeColsRows, double nOutputFactor )
{
ScEEImport::WriteToDocument( bSizeColsRows, nOutputFactor );
const ScHTMLParser* pParser = GetParser();
const ScHTMLTable* pGlobTable = pParser->GetGlobalTable();
if( !pGlobTable )
return;
// set cell borders for HTML table cells
pGlobTable->ApplyCellBorders( pDoc, aRange.aStart );
// correct cell borders for merged cells
for ( ScEEParseEntry* pEntry = pParser->First(); pEntry; pEntry = pParser->Next() )
{
if( (pEntry->nColOverlap > 1) || (pEntry->nRowOverlap > 1) )
{
USHORT nTab = aRange.aStart.Tab();
const ScMergeAttr* pItem = (ScMergeAttr*) pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_MERGE );
if( pItem->IsMerged() )
{
USHORT nColMerge = pItem->GetColMerge();
USHORT nRowMerge = pItem->GetRowMerge();
const SvxBoxItem* pToItem = (const SvxBoxItem*)
pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_BORDER );
SvxBoxItem aNewItem( *pToItem );
if( nColMerge > 1 )
{
const SvxBoxItem* pFromItem = (const SvxBoxItem*)
pDoc->GetAttr( pEntry->nCol + nColMerge - 1, pEntry->nRow, nTab, ATTR_BORDER );
aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_RIGHT ), BOX_LINE_RIGHT );
}
if( nRowMerge > 1 )
{
const SvxBoxItem* pFromItem = (const SvxBoxItem*)
pDoc->GetAttr( pEntry->nCol, pEntry->nRow + nRowMerge - 1, nTab, ATTR_BORDER );
aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_BOTTOM ), BOX_LINE_BOTTOM );
}
pDoc->ApplyAttr( pEntry->nCol, pEntry->nRow, nTab, aNewItem );
}
}
}
// create ranges for HTML tables
// 1 - entire document
ScRange aNewRange( aRange.aStart );
aNewRange.aEnd.IncCol( pGlobTable->GetDocSize( tdCol ) - 1 );
aNewRange.aEnd.IncRow( pGlobTable->GetDocSize( tdRow ) - 1 );
InsertRangeName( pDoc, ScfTools::GetHTMLDocName(), aNewRange );
// 2 - all tables
InsertRangeName( pDoc, ScfTools::GetHTMLTablesName(), ScRange( aRange.aStart ) );
// 3 - single tables
short nColDiff = (short)aRange.aStart.Col();
short nRowDiff = (short)aRange.aStart.Row();
short nTabDiff = (short)aRange.aStart.Tab();
ScHTMLTable* pTable = NULL;
ScHTMLTableId nTableId = SC_HTML_GLOBAL_TABLE;
while( pTable = pGlobTable->FindNestedTable( ++nTableId ) )
{
pTable->GetDocRange( aNewRange );
aNewRange.Move( nColDiff, nRowDiff, nTabDiff );
// insert table number as name
InsertRangeName( pDoc, ScfTools::GetNameFromHTMLIndex( nTableId ), aNewRange );
// insert table id as name
if( pTable->GetTableName().Len() )
{
String aName( ScfTools::GetNameFromHTMLName( pTable->GetTableName() ) );
USHORT nPos;
if( !pDoc->GetRangeName()->SearchName( aName, nPos ) )
InsertRangeName( pDoc, aName, aNewRange );
}
}
}
String ScHTMLImport::GetHTMLRangeNameList( ScDocument* pDoc, const String& rOrigName )
{
DBG_ASSERT( pDoc, "ScHTMLImport::GetHTMLRangeNameList - missing document" );
String aNewName;
ScRangeName* pRangeNames = pDoc->GetRangeName();
ScRangeList aRangeList;
xub_StrLen nTokenCnt = rOrigName.GetTokenCount( ';' );
xub_StrLen nStringIx = 0;
for( xub_StrLen nToken = 0; nToken < nTokenCnt; nToken++ )
{
String aToken( rOrigName.GetToken( 0, ';', nStringIx ) );
if( pRangeNames && ScfTools::IsHTMLTablesName( aToken ) )
{ // build list with all HTML tables
ULONG nIndex = 1;
USHORT nPos;
BOOL bLoop = TRUE;
while( bLoop )
{
aToken = ScfTools::GetNameFromHTMLIndex( nIndex++ );
bLoop = pRangeNames->SearchName( aToken, nPos );
if( bLoop )
{
const ScRangeData* pRangeData = (*pRangeNames)[ nPos ];
ScRange aRange;
if( pRangeData && pRangeData->IsReference( aRange ) && !aRangeList.In( aRange ) )
{
ScGlobal::AddToken( aNewName, aToken, ';' );
aRangeList.Append( aRange );
}
}
}
}
else
ScGlobal::AddToken( aNewName, aToken, ';' );
}
return aNewName;
}
<commit_msg>INTEGRATION: CWS rowlimit (1.11.74); FILE MERGED 2004/03/01 16:04:31 jmarmion 1.11.74.2: #i1967# step 5 changes. 2004/01/19 15:52:35 jmarmion 1.11.74.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short.<commit_after>/*************************************************************************
*
* $RCSfile: htmlimp.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2004-06-04 10:49:39 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------------
#include "scitems.hxx"
#include <svx/eeitem.hxx>
#define ITEMID_FIELD EE_FEATURE_FIELD
#include <svx/lrspitem.hxx>
#include <svx/paperinf.hxx>
#include <svx/sizeitem.hxx>
#include <svx/ulspitem.hxx>
#include <svx/boxitem.hxx>
#include <vcl/svapp.hxx>
#include "htmlimp.hxx"
#include "htmlpars.hxx"
#include "filter.hxx"
#include "global.hxx"
#include "document.hxx"
#include "editutil.hxx"
#include "stlpool.hxx"
#include "stlsheet.hxx"
#include "compiler.hxx"
#include "rangenam.hxx"
#include "attrib.hxx"
#include "ftools.hxx"
//------------------------------------------------------------------------
FltError ScImportHTML( SvStream &rStream, ScDocument *pDoc,
ScRange& rRange, double nOutputFactor, BOOL bCalcWidthHeight )
{
ScHTMLImport aImp( pDoc, rRange, bCalcWidthHeight );
FltError nErr = (FltError) aImp.Read( rStream );
ScRange aR = aImp.GetRange();
rRange.aEnd = aR.aEnd;
aImp.WriteToDocument( TRUE, nOutputFactor );
return nErr;
}
ScHTMLImport::ScHTMLImport( ScDocument* pDocP, const ScRange& rRange, BOOL bCalcWidthHeight ) :
ScEEImport( pDocP, rRange )
{
Size aPageSize;
OutputDevice* pDefaultDev = Application::GetDefaultDevice();
const String& aPageStyle = pDoc->GetPageStyle( rRange.aStart.Tab() );
ScStyleSheet* pStyleSheet = (ScStyleSheet*)pDoc->
GetStyleSheetPool()->Find( aPageStyle, SFX_STYLE_FAMILY_PAGE );
if ( pStyleSheet )
{
const SfxItemSet& rSet = pStyleSheet->GetItemSet();
const SvxLRSpaceItem* pLRItem = (const SvxLRSpaceItem*) &rSet.Get( ATTR_LRSPACE );
long nLeftMargin = pLRItem->GetLeft();
long nRightMargin = pLRItem->GetRight();
const SvxULSpaceItem* pULItem = (const SvxULSpaceItem*) &rSet.Get( ATTR_ULSPACE );
long nTopMargin = pULItem->GetUpper();
long nBottomMargin = pULItem->GetLower();
aPageSize = ((const SvxSizeItem&) rSet.Get(ATTR_PAGE_SIZE)).GetSize();
if ( !aPageSize.Width() || !aPageSize.Height() )
{
DBG_ERRORFILE("PageSize Null ?!?!?");
aPageSize = SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 );
}
aPageSize.Width() -= nLeftMargin + nRightMargin;
aPageSize.Height() -= nTopMargin + nBottomMargin;
aPageSize = pDefaultDev->LogicToPixel( aPageSize, MapMode( MAP_TWIP ) );
}
else
{
DBG_ERRORFILE("kein StyleSheet?!?");
aPageSize = pDefaultDev->LogicToPixel(
SvxPaperInfo::GetPaperSize( SVX_PAPER_A4 ), MapMode( MAP_TWIP ) );
}
if( bCalcWidthHeight )
pParser = new ScHTMLLayoutParser( pEngine, aPageSize, pDocP );
else
pParser = new ScHTMLQueryParser( pEngine, pDocP );
}
ScHTMLImport::~ScHTMLImport()
{
// Reihenfolge wichtig, sonst knallt's irgendwann irgendwo in irgendeinem Dtor!
// Ist gewaehrleistet, da ScEEImport Basisklasse ist
delete (ScHTMLParser*) pParser; // vor EditEngine!
}
void ScHTMLImport::InsertRangeName( ScDocument* pDoc, const String& rName, const ScRange& rRange )
{
ComplRefData aRefData;
aRefData.InitRange( rRange );
ScTokenArray aTokArray;
aTokArray.AddDoubleReference( aRefData );
ScRangeData* pRangeData = new ScRangeData( pDoc, rName, aTokArray );
if( !pDoc->GetRangeName()->Insert( pRangeData ) )
delete pRangeData;
}
void ScHTMLImport::WriteToDocument( BOOL bSizeColsRows, double nOutputFactor )
{
ScEEImport::WriteToDocument( bSizeColsRows, nOutputFactor );
const ScHTMLParser* pParser = GetParser();
const ScHTMLTable* pGlobTable = pParser->GetGlobalTable();
if( !pGlobTable )
return;
// set cell borders for HTML table cells
pGlobTable->ApplyCellBorders( pDoc, aRange.aStart );
// correct cell borders for merged cells
for ( ScEEParseEntry* pEntry = pParser->First(); pEntry; pEntry = pParser->Next() )
{
if( (pEntry->nColOverlap > 1) || (pEntry->nRowOverlap > 1) )
{
SCTAB nTab = aRange.aStart.Tab();
const ScMergeAttr* pItem = (ScMergeAttr*) pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_MERGE );
if( pItem->IsMerged() )
{
SCCOL nColMerge = pItem->GetColMerge();
SCROW nRowMerge = pItem->GetRowMerge();
const SvxBoxItem* pToItem = (const SvxBoxItem*)
pDoc->GetAttr( pEntry->nCol, pEntry->nRow, nTab, ATTR_BORDER );
SvxBoxItem aNewItem( *pToItem );
if( nColMerge > 1 )
{
const SvxBoxItem* pFromItem = (const SvxBoxItem*)
pDoc->GetAttr( pEntry->nCol + nColMerge - 1, pEntry->nRow, nTab, ATTR_BORDER );
aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_RIGHT ), BOX_LINE_RIGHT );
}
if( nRowMerge > 1 )
{
const SvxBoxItem* pFromItem = (const SvxBoxItem*)
pDoc->GetAttr( pEntry->nCol, pEntry->nRow + nRowMerge - 1, nTab, ATTR_BORDER );
aNewItem.SetLine( pFromItem->GetLine( BOX_LINE_BOTTOM ), BOX_LINE_BOTTOM );
}
pDoc->ApplyAttr( pEntry->nCol, pEntry->nRow, nTab, aNewItem );
}
}
}
// create ranges for HTML tables
// 1 - entire document
ScRange aNewRange( aRange.aStart );
aNewRange.aEnd.IncCol( static_cast<SCsCOL>(pGlobTable->GetDocSize( tdCol )) - 1 );
aNewRange.aEnd.IncRow( pGlobTable->GetDocSize( tdRow ) - 1 );
InsertRangeName( pDoc, ScfTools::GetHTMLDocName(), aNewRange );
// 2 - all tables
InsertRangeName( pDoc, ScfTools::GetHTMLTablesName(), ScRange( aRange.aStart ) );
// 3 - single tables
SCsCOL nColDiff = (SCsCOL)aRange.aStart.Col();
SCsROW nRowDiff = (SCsROW)aRange.aStart.Row();
SCsTAB nTabDiff = (SCsTAB)aRange.aStart.Tab();
ScHTMLTable* pTable = NULL;
ScHTMLTableId nTableId = SC_HTML_GLOBAL_TABLE;
while( pTable = pGlobTable->FindNestedTable( ++nTableId ) )
{
pTable->GetDocRange( aNewRange );
aNewRange.Move( nColDiff, nRowDiff, nTabDiff );
// insert table number as name
InsertRangeName( pDoc, ScfTools::GetNameFromHTMLIndex( nTableId ), aNewRange );
// insert table id as name
if( pTable->GetTableName().Len() )
{
String aName( ScfTools::GetNameFromHTMLName( pTable->GetTableName() ) );
USHORT nPos;
if( !pDoc->GetRangeName()->SearchName( aName, nPos ) )
InsertRangeName( pDoc, aName, aNewRange );
}
}
}
String ScHTMLImport::GetHTMLRangeNameList( ScDocument* pDoc, const String& rOrigName )
{
DBG_ASSERT( pDoc, "ScHTMLImport::GetHTMLRangeNameList - missing document" );
String aNewName;
ScRangeName* pRangeNames = pDoc->GetRangeName();
ScRangeList aRangeList;
xub_StrLen nTokenCnt = rOrigName.GetTokenCount( ';' );
xub_StrLen nStringIx = 0;
for( xub_StrLen nToken = 0; nToken < nTokenCnt; nToken++ )
{
String aToken( rOrigName.GetToken( 0, ';', nStringIx ) );
if( pRangeNames && ScfTools::IsHTMLTablesName( aToken ) )
{ // build list with all HTML tables
ULONG nIndex = 1;
USHORT nPos;
BOOL bLoop = TRUE;
while( bLoop )
{
aToken = ScfTools::GetNameFromHTMLIndex( nIndex++ );
bLoop = pRangeNames->SearchName( aToken, nPos );
if( bLoop )
{
const ScRangeData* pRangeData = (*pRangeNames)[ nPos ];
ScRange aRange;
if( pRangeData && pRangeData->IsReference( aRange ) && !aRangeList.In( aRange ) )
{
ScGlobal::AddToken( aNewName, aToken, ';' );
aRangeList.Append( aRange );
}
}
}
}
else
ScGlobal::AddToken( aNewName, aToken, ';' );
}
return aNewName;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filter.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-07-21 12:27:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// Das geht: Versionserkennung WKS, WK1 und WK3
// ...Rest steht in op.cpp
//------------------------------------------------------------------------
#include <tools/solar.h>
#include <string.h>
#include <map>
#include "filter.hxx"
#include "document.hxx"
#include "compiler.hxx"
#include "scerrors.hxx"
#include "root.hxx"
#include "lotrange.hxx"
#include "optab.h"
#include "scmem.h"
#include "decl.h"
#include "tool.h"
#ifndef SC_FPROGRESSBAR_HXX
#include "fprogressbar.hxx"
#endif
#include "op.h"
// Konstanten ------------------------------------------------------------
const UINT16 nBOF = 0x0000;
// externe Variablen -----------------------------------------------------
extern WKTYP eTyp; // Typ der gerade in bearbeitung befindlichen Datei
WKTYP eTyp;
extern BOOL bEOF; // zeigt Ende der Datei
BOOL bEOF;
extern CharSet eCharNach; // Zeichenkonvertierung von->nach
CharSet eCharNach;
extern CharSet eCharVon;
CharSet eCharVon;
extern ScDocument* pDoc; // Aufhaenger zum Dokumentzugriff
ScDocument* pDoc;
extern sal_Char* pPuffer; // -> memory.cxx
extern sal_Char* pDummy1; // -> memory.cxx
extern OPCODE_FKT pOpFkt[ FKT_LIMIT ];
// -> optab.cxx, Tabelle moeglicher Opcodes
extern OPCODE_FKT pOpFkt123[ FKT_LIMIT123 ];
// -> optab.cxx, Table of possible Opcodes
extern long nDateiLaenge; // -> datei.cpp, ...der gerade offenen Datei
LOTUS_ROOT* pLotusRoot = NULL;
std::map<UINT16, ScPatternAttr> aLotusPatternPool;
static FltError
generate_Opcodes( SvStream& aStream, ScDocument* pDoc,
ScfStreamProgressBar& aPrgrsBar, WKTYP eTyp )
{
OPCODE_FKT *pOps;
int nOps;
switch(eTyp)
{
case eWK_1:
case eWK_2:
pOps = pOpFkt;
nOps = FKT_LIMIT;
break;
case eWK123:
pOps = pOpFkt123;
nOps = FKT_LIMIT123;
break;
case eWK3: return eERR_NI;
case eWK_Error: return eERR_FORMAT;
default: return eERR_UNKN_WK;
}
aStream.Seek( 0UL );
while( !bEOF && !aStream.IsEof() )
{
UINT16 nOpcode, nLength;
aStream >> nOpcode >> nLength;
#ifdef DEBUG
fprintf( stderr, "nOpcode=%x nLength=%x\n", nOpcode, nLength);
#endif
aPrgrsBar.Progress();
if( nOpcode == LOTUS_EOF )
bEOF = TRUE;
else if( nOpcode == LOTUS_FILEPASSWD )
return eERR_FILEPASSWD;
else if( nOpcode < nOps )
pOps[ nOpcode ] ( aStream, nLength );
else if( eTyp == eWK123 &&
nOpcode == LOTUS_PATTERN )
{
// This is really ugly - needs re-factoring ...
aStream.SeekRel(nLength);
aStream >> nOpcode >> nLength;
if ( nOpcode == 0x29a)
{
aStream.SeekRel(nLength);
aStream >> nOpcode >> nLength;
if ( nOpcode == 0x804 )
{
aStream.SeekRel(nLength);
OP_ApplyPatternArea123(aStream);
}
else
aStream.SeekRel(nLength);
}
else
aStream.SeekRel(nLength);
}
else
aStream.SeekRel( nLength );
}
MemDelete();
pDoc->CalcAfterLoad();
return eERR_OK;
}
WKTYP ScanVersion( SvStream& aStream )
{
// PREC: pWKDatei: Zeiger auf offene Datei
// POST: return: Typ der Datei
UINT16 nOpcode, nVersNr, nRecLen;
// erstes Byte muss wegen BOF zwingend 0 sein!
aStream >> nOpcode;
if( nOpcode != nBOF )
return eWK_UNKNOWN;
aStream >> nRecLen >> nVersNr;
if( aStream.IsEof() )
return eWK_Error;
switch( nVersNr )
{
case 0x0404:
if( nRecLen == 2 )
return eWK_1;
else
return eWK_UNKNOWN;
break;
case 0x0406:
if( nRecLen == 2 )
return eWK_2;
else
return eWK_UNKNOWN;
break;
case 0x1000:
aStream >> nVersNr;
if( aStream.IsEof() ) return eWK_Error;
if( nVersNr == 0x0004 && nRecLen == 26 )
{ // 4 Bytes von 26 gelesen->22 ueberlesen
aStream.Read( pDummy1, 22 );
return eWK3;
}
break;
case 0x1003:
if( nRecLen == 0x1a )
return eWK123;
else
return eWK_UNKNOWN;
break;
case 0x1005:
if( nRecLen == 0x1a )
return eWK123;
else
return eWK_UNKNOWN;
break;
}
return eWK_UNKNOWN;
}
FltError ScImportLotus123old( SvStream& aStream, ScDocument* pDocument, CharSet eSrc )
{
aStream.Seek( 0UL );
// Zeiger auf Dokument global machen
pDoc = pDocument;
bEOF = FALSE;
eCharVon = eSrc;
// Speicher besorgen
if( !MemNew() )
return eERR_NOMEM;
InitPage(); // Seitenformat initialisieren (nur Tab 0!)
// Progressbar starten
ScfStreamProgressBar aPrgrsBar( aStream, pDocument->GetDocumentShell() );
// Datei-Typ ermitteln
eTyp = ScanVersion( aStream );
aLotusPatternPool.clear();
return generate_Opcodes( aStream, pDoc, aPrgrsBar, eTyp );
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.7.110); FILE MERGED 2006/12/14 14:01:21 dr 1.7.110.2: #i69284# remove compiler warnings for unxsols4 2006/12/12 16:42:50 dr 1.7.110.1: #i69284# remove compiler warnings for unxlngi6<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filter.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:38:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// Das geht: Versionserkennung WKS, WK1 und WK3
// ...Rest steht in op.cpp
//------------------------------------------------------------------------
#include <tools/solar.h>
#include <string.h>
#include <map>
#include "filter.hxx"
#include "document.hxx"
#include "compiler.hxx"
#include "scerrors.hxx"
#include "root.hxx"
#include "lotrange.hxx"
#include "optab.h"
#include "scmem.h"
#include "decl.h"
#include "tool.h"
#ifndef SC_FPROGRESSBAR_HXX
#include "fprogressbar.hxx"
#endif
#include "op.h"
// Konstanten ------------------------------------------------------------
const UINT16 nBOF = 0x0000;
// externe Variablen -----------------------------------------------------
extern WKTYP eTyp; // Typ der gerade in bearbeitung befindlichen Datei
WKTYP eTyp;
extern BOOL bEOF; // zeigt Ende der Datei
BOOL bEOF;
extern CharSet eCharNach; // Zeichenkonvertierung von->nach
CharSet eCharNach;
extern CharSet eCharVon;
CharSet eCharVon;
extern ScDocument* pDoc; // Aufhaenger zum Dokumentzugriff
ScDocument* pDoc;
extern sal_Char* pPuffer; // -> memory.cxx
extern sal_Char* pDummy1; // -> memory.cxx
extern OPCODE_FKT pOpFkt[ FKT_LIMIT ];
// -> optab.cxx, Tabelle moeglicher Opcodes
extern OPCODE_FKT pOpFkt123[ FKT_LIMIT123 ];
// -> optab.cxx, Table of possible Opcodes
extern long nDateiLaenge; // -> datei.cpp, ...der gerade offenen Datei
LOTUS_ROOT* pLotusRoot = NULL;
std::map<UINT16, ScPatternAttr> aLotusPatternPool;
static FltError
generate_Opcodes( SvStream& aStream, ScDocument& rDoc,
ScfStreamProgressBar& aPrgrsBar, WKTYP eType )
{
OPCODE_FKT *pOps;
int nOps;
switch(eType)
{
case eWK_1:
case eWK_2:
pOps = pOpFkt;
nOps = FKT_LIMIT;
break;
case eWK123:
pOps = pOpFkt123;
nOps = FKT_LIMIT123;
break;
case eWK3: return eERR_NI;
case eWK_Error: return eERR_FORMAT;
default: return eERR_UNKN_WK;
}
aStream.Seek( 0UL );
while( !bEOF && !aStream.IsEof() )
{
UINT16 nOpcode, nLength;
aStream >> nOpcode >> nLength;
#ifdef DEBUG
fprintf( stderr, "nOpcode=%x nLength=%x\n", nOpcode, nLength);
#endif
aPrgrsBar.Progress();
if( nOpcode == LOTUS_EOF )
bEOF = TRUE;
else if( nOpcode == LOTUS_FILEPASSWD )
return eERR_FILEPASSWD;
else if( nOpcode < nOps )
pOps[ nOpcode ] ( aStream, nLength );
else if( eType == eWK123 &&
nOpcode == LOTUS_PATTERN )
{
// This is really ugly - needs re-factoring ...
aStream.SeekRel(nLength);
aStream >> nOpcode >> nLength;
if ( nOpcode == 0x29a)
{
aStream.SeekRel(nLength);
aStream >> nOpcode >> nLength;
if ( nOpcode == 0x804 )
{
aStream.SeekRel(nLength);
OP_ApplyPatternArea123(aStream);
}
else
aStream.SeekRel(nLength);
}
else
aStream.SeekRel(nLength);
}
else
aStream.SeekRel( nLength );
}
MemDelete();
rDoc.CalcAfterLoad();
return eERR_OK;
}
WKTYP ScanVersion( SvStream& aStream )
{
// PREC: pWKDatei: Zeiger auf offene Datei
// POST: return: Typ der Datei
UINT16 nOpcode, nVersNr, nRecLen;
// erstes Byte muss wegen BOF zwingend 0 sein!
aStream >> nOpcode;
if( nOpcode != nBOF )
return eWK_UNKNOWN;
aStream >> nRecLen >> nVersNr;
if( aStream.IsEof() )
return eWK_Error;
switch( nVersNr )
{
case 0x0404:
if( nRecLen == 2 )
return eWK_1;
else
return eWK_UNKNOWN;
case 0x0406:
if( nRecLen == 2 )
return eWK_2;
else
return eWK_UNKNOWN;
case 0x1000:
aStream >> nVersNr;
if( aStream.IsEof() ) return eWK_Error;
if( nVersNr == 0x0004 && nRecLen == 26 )
{ // 4 Bytes von 26 gelesen->22 ueberlesen
aStream.Read( pDummy1, 22 );
return eWK3;
}
break;
case 0x1003:
if( nRecLen == 0x1a )
return eWK123;
else
return eWK_UNKNOWN;
case 0x1005:
if( nRecLen == 0x1a )
return eWK123;
else
return eWK_UNKNOWN;
}
return eWK_UNKNOWN;
}
FltError ScImportLotus123old( SvStream& aStream, ScDocument* pDocument, CharSet eSrc )
{
aStream.Seek( 0UL );
// Zeiger auf Dokument global machen
pDoc = pDocument;
bEOF = FALSE;
eCharVon = eSrc;
// Speicher besorgen
if( !MemNew() )
return eERR_NOMEM;
InitPage(); // Seitenformat initialisieren (nur Tab 0!)
// Progressbar starten
ScfStreamProgressBar aPrgrsBar( aStream, pDocument->GetDocumentShell() );
// Datei-Typ ermitteln
eTyp = ScanVersion( aStream );
aLotusPatternPool.clear();
return generate_Opcodes( aStream, *pDoc, aPrgrsBar, eTyp );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlbodyi.cxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: sab $ $Date: 2002-09-26 12:08:41 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#include "xmlbodyi.hxx"
#include "xmltabi.hxx"
#include "xmlnexpi.hxx"
#include "xmldrani.hxx"
#include "xmlimprt.hxx"
#include "xmldpimp.hxx"
#include "xmlcvali.hxx"
#include "xmlstyli.hxx"
#ifndef SC_XMLLABRI_HXX
#include "xmllabri.hxx"
#endif
#ifndef _SC_XMLCONSOLIDATIONCONTEXT_HXX
#include "XMLConsolidationContext.hxx"
#endif
#ifndef _SC_XMLDDELINKSCONTEXT_HXX
#include "XMLDDELinksContext.hxx"
#endif
#ifndef _SC_XMLCALCULATIONSETTINGSCONTEXT_HXX
#include "XMLCalculationSettingsContext.hxx"
#endif
#ifndef _SC_XMLTRACKEDCHANGESCONTEXT_HXX
#include "XMLTrackedChangesContext.hxx"
#endif
#ifndef SC_XMLEMPTYCONTEXT_HXX
#include "XMLEmptyContext.hxx"
#endif
#ifndef _SCERRORS_HXX
#include "scerrors.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLBodyContext::ScXMLBodyContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>& xAttrList ) :
SvXMLImportContext( rImport, nPrfx, rLName ),
pChangeTrackingImportHelper(NULL),
bProtected(sal_False),
sPassword()
{
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
if (nPrefix == XML_NAMESPACE_TABLE)
{
if (IsXMLToken(aLocalName, XML_STRUCTURE_PROTECTED))
bProtected = IsXMLToken(sValue, XML_TRUE);
else if (IsXMLToken(aLocalName, XML_PROTECTION_KEY))
sPassword = sValue;
}
}
}
ScXMLBodyContext::~ScXMLBodyContext()
{
}
SvXMLImportContext *ScXMLBodyContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetScImport().GetBodyElemTokenMap();
sal_Bool bOrdered = sal_False;
sal_Bool bHeading = sal_False;
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
// case XML_TOK_TEXT_H:
// bHeading = TRUE;
// case XML_TOK_TEXT_P:
// pContext = new SwXMLParaContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bHeading );
// break;
// case XML_TOK_TEXT_ORDERED_LIST:
// bOrdered = TRUE;
// case XML_TOK_TEXT_UNORDERED_LIST:
// pContext = new SwXMLListBlockContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bOrdered );
// break;
case XML_TOK_BODY_TRACKED_CHANGES :
{
pChangeTrackingImportHelper = GetScImport().GetChangeTrackingImportHelper();
if (pChangeTrackingImportHelper)
pContext = new ScXMLTrackedChangesContext( GetScImport(), nPrefix, rLocalName, xAttrList, pChangeTrackingImportHelper);
}
break;
case XML_TOK_BODY_CALCULATION_SETTINGS :
pContext = new ScXMLCalculationSettingsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_CONTENT_VALIDATIONS :
pContext = new ScXMLContentValidationsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_LABEL_RANGES:
pContext = new ScXMLLabelRangesContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_TABLE:
{
if (GetScImport().GetTables().GetCurrentSheet() >= MAXTAB)
{
GetScImport().SetRangeOverflowType(SCWARN_IMPORT_SHEET_OVERFLOW);
pContext = new ScXMLEmptyContext(GetScImport(), nPrefix, rLocalName);
}
else
{
pContext = new ScXMLTableContext( GetScImport(),nPrefix, rLocalName,
xAttrList );
}
}
break;
case XML_TOK_BODY_NAMED_EXPRESSIONS:
pContext = new ScXMLNamedExpressionsContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGES:
pContext = new ScXMLDatabaseRangesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGE:
pContext = new ScXMLDatabaseRangeContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATA_PILOT_TABLES:
pContext = new ScXMLDataPilotTablesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_CONSOLIDATION:
pContext = new ScXMLConsolidationContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DDE_LINKS:
pContext = new ScXMLDDELinksContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
void ScXMLBodyContext::EndElement()
{
GetScImport().LockSolarMutex();
ScMyImpDetectiveOpArray* pDetOpArray = GetScImport().GetDetectiveOpArray();
ScDocument* pDoc = GetScImport().GetDocument();
ScMyImpDetectiveOp aDetOp;
if (pDoc && GetScImport().GetModel().is())
{
if (pDetOpArray)
{
pDetOpArray->Sort();
while( pDetOpArray->GetFirstOp( aDetOp ) )
{
ScDetOpData aOpData( aDetOp.aPosition, aDetOp.eOpType );
pDoc->AddDetectiveOperation( aOpData );
}
}
if (pChangeTrackingImportHelper)
pChangeTrackingImportHelper->CreateChangeTrack(GetScImport().GetDocument());
if (bProtected)
{
uno::Sequence<sal_Int8> aPass;
if (sPassword.getLength())
SvXMLUnitConverter::decodeBase64(aPass, sPassword);
pDoc->SetDocProtection(bProtected, aPass);
}
uno::Reference <sheet::XSpreadsheetDocument> xSpreadDoc( GetScImport().GetModel(), uno::UNO_QUERY );
if ( xSpreadDoc.is() )
{
uno::Reference<sheet::XSpreadsheets> xSheets = xSpreadDoc->getSheets();
uno::Reference <container::XIndexAccess> xIndex( xSheets, uno::UNO_QUERY );
if ( xIndex.is() )
{
uno::Any aSheet = xIndex->getByIndex(0);
uno::Reference< sheet::XSpreadsheet > xSheet;
if ( aSheet >>= xSheet )
{
uno::Reference <beans::XPropertySet> xProperties(xSheet, uno::UNO_QUERY);
if (xProperties.is())
{
XMLTableStylesContext *pStyles = (XMLTableStylesContext *)GetScImport().GetAutoStyles();
rtl::OUString sTableStyleName(GetScImport().GetFirstTableStyle());
if (sTableStyleName.getLength())
{
XMLTableStyleContext* pStyle = (XMLTableStyleContext *)pStyles->FindStyleChildContext(
XML_STYLE_FAMILY_TABLE_TABLE, sTableStyleName, sal_True);
if (pStyle)
pStyle->FillPropertySet(xProperties);
}
}
}
}
}
}
GetScImport().UnlockSolarMutex();
}
<commit_msg>INTEGRATION: CWS calcrtl (1.20.84); FILE MERGED 2003/10/30 13:29:29 sab 1.20.84.1: #106948#; rtl load/save of shapes<commit_after>/*************************************************************************
*
* $RCSfile: xmlbodyi.cxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: hr $ $Date: 2004-02-03 12:31:00 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#include "xmlbodyi.hxx"
#include "xmltabi.hxx"
#include "xmlnexpi.hxx"
#include "xmldrani.hxx"
#include "xmlimprt.hxx"
#include "xmldpimp.hxx"
#include "xmlcvali.hxx"
#include "xmlstyli.hxx"
#ifndef SC_XMLLABRI_HXX
#include "xmllabri.hxx"
#endif
#ifndef _SC_XMLCONSOLIDATIONCONTEXT_HXX
#include "XMLConsolidationContext.hxx"
#endif
#ifndef _SC_XMLDDELINKSCONTEXT_HXX
#include "XMLDDELinksContext.hxx"
#endif
#ifndef _SC_XMLCALCULATIONSETTINGSCONTEXT_HXX
#include "XMLCalculationSettingsContext.hxx"
#endif
#ifndef _SC_XMLTRACKEDCHANGESCONTEXT_HXX
#include "XMLTrackedChangesContext.hxx"
#endif
#ifndef SC_XMLEMPTYCONTEXT_HXX
#include "XMLEmptyContext.hxx"
#endif
#ifndef _SCERRORS_HXX
#include "scerrors.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLBodyContext::ScXMLBodyContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>& xAttrList ) :
SvXMLImportContext( rImport, nPrfx, rLName ),
pChangeTrackingImportHelper(NULL),
bProtected(sal_False),
sPassword()
{
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
if (nPrefix == XML_NAMESPACE_TABLE)
{
if (IsXMLToken(aLocalName, XML_STRUCTURE_PROTECTED))
bProtected = IsXMLToken(sValue, XML_TRUE);
else if (IsXMLToken(aLocalName, XML_PROTECTION_KEY))
sPassword = sValue;
}
}
}
ScXMLBodyContext::~ScXMLBodyContext()
{
}
SvXMLImportContext *ScXMLBodyContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetScImport().GetBodyElemTokenMap();
sal_Bool bOrdered = sal_False;
sal_Bool bHeading = sal_False;
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
// case XML_TOK_TEXT_H:
// bHeading = TRUE;
// case XML_TOK_TEXT_P:
// pContext = new SwXMLParaContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bHeading );
// break;
// case XML_TOK_TEXT_ORDERED_LIST:
// bOrdered = TRUE;
// case XML_TOK_TEXT_UNORDERED_LIST:
// pContext = new SwXMLListBlockContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bOrdered );
// break;
case XML_TOK_BODY_TRACKED_CHANGES :
{
pChangeTrackingImportHelper = GetScImport().GetChangeTrackingImportHelper();
if (pChangeTrackingImportHelper)
pContext = new ScXMLTrackedChangesContext( GetScImport(), nPrefix, rLocalName, xAttrList, pChangeTrackingImportHelper);
}
break;
case XML_TOK_BODY_CALCULATION_SETTINGS :
pContext = new ScXMLCalculationSettingsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_CONTENT_VALIDATIONS :
pContext = new ScXMLContentValidationsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_LABEL_RANGES:
pContext = new ScXMLLabelRangesContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_TABLE:
{
if (GetScImport().GetTables().GetCurrentSheet() >= MAXTAB)
{
GetScImport().SetRangeOverflowType(SCWARN_IMPORT_SHEET_OVERFLOW);
pContext = new ScXMLEmptyContext(GetScImport(), nPrefix, rLocalName);
}
else
{
pContext = new ScXMLTableContext( GetScImport(),nPrefix, rLocalName,
xAttrList );
}
}
break;
case XML_TOK_BODY_NAMED_EXPRESSIONS:
pContext = new ScXMLNamedExpressionsContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGES:
pContext = new ScXMLDatabaseRangesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGE:
pContext = new ScXMLDatabaseRangeContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATA_PILOT_TABLES:
pContext = new ScXMLDataPilotTablesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_CONSOLIDATION:
pContext = new ScXMLConsolidationContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DDE_LINKS:
pContext = new ScXMLDDELinksContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
void ScXMLBodyContext::EndElement()
{
GetScImport().LockSolarMutex();
ScMyImpDetectiveOpArray* pDetOpArray = GetScImport().GetDetectiveOpArray();
ScDocument* pDoc = GetScImport().GetDocument();
ScMyImpDetectiveOp aDetOp;
if (pDoc && GetScImport().GetModel().is())
{
if (pDetOpArray)
{
pDetOpArray->Sort();
while( pDetOpArray->GetFirstOp( aDetOp ) )
{
ScDetOpData aOpData( aDetOp.aPosition, aDetOp.eOpType );
pDoc->AddDetectiveOperation( aOpData );
}
}
if (pChangeTrackingImportHelper)
pChangeTrackingImportHelper->CreateChangeTrack(GetScImport().GetDocument());
if (bProtected)
{
uno::Sequence<sal_Int8> aPass;
if (sPassword.getLength())
SvXMLUnitConverter::decodeBase64(aPass, sPassword);
pDoc->SetDocProtection(bProtected, aPass);
}
std::vector<rtl::OUString> aTableStyleNames(GetScImport().GetTableStyle());
uno::Reference <sheet::XSpreadsheetDocument> xSpreadDoc( GetScImport().GetModel(), uno::UNO_QUERY );
if ( xSpreadDoc.is() && !aTableStyleNames.empty())
{
uno::Reference <container::XIndexAccess> xIndex( xSpreadDoc->getSheets(), uno::UNO_QUERY );
if ( xIndex.is() )
{
sal_Int32 nTableCount = xIndex->getCount();
sal_Int32 nSize(aTableStyleNames.size());
DBG_ASSERT(nTableCount == nSize, "every table should have a style name");
for(sal_uInt32 i = 0; i < nTableCount; i++)
{
if (i < nSize)
{
uno::Reference <beans::XPropertySet> xProperties(xIndex->getByIndex(i), uno::UNO_QUERY);
if (xProperties.is())
{
rtl::OUString sTableStyleName(aTableStyleNames[i]);
XMLTableStylesContext *pStyles = (XMLTableStylesContext *)GetScImport().GetAutoStyles();
if (sTableStyleName.getLength())
{
XMLTableStyleContext* pStyle = (XMLTableStyleContext *)pStyles->FindStyleChildContext(
XML_STYLE_FAMILY_TABLE_TABLE, sTableStyleName, sal_True);
if (pStyle)
pStyle->FillPropertySet(xProperties);
}
}
}
}
}
}
}
GetScImport().UnlockSolarMutex();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: xmlbodyi.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: sab $ $Date: 2001-09-25 10:37:31 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#include "xmlbodyi.hxx"
#include "xmltabi.hxx"
#include "xmlnexpi.hxx"
#include "xmldrani.hxx"
#include "xmlimprt.hxx"
#include "xmldpimp.hxx"
#include "xmlcvali.hxx"
#include "xmlstyli.hxx"
#ifndef SC_XMLLABRI_HXX
#include "xmllabri.hxx"
#endif
#ifndef _SC_XMLCONSOLIDATIONCONTEXT_HXX
#include "XMLConsolidationContext.hxx"
#endif
#ifndef _SC_XMLDDELINKSCONTEXT_HXX
#include "XMLDDELinksContext.hxx"
#endif
#ifndef _SC_XMLCALCULATIONSETTINGSCONTEXT_HXX
#include "XMLCalculationSettingsContext.hxx"
#endif
#ifndef _SC_XMLTRACKEDCHANGESCONTEXT_HXX
#include "XMLTrackedChangesContext.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLBodyContext::ScXMLBodyContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>& xAttrList ) :
SvXMLImportContext( rImport, nPrfx, rLName ),
pChangeTrackingImportHelper(NULL),
bProtected(sal_False),
sPassword()
{
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
if (nPrefix == XML_NAMESPACE_TABLE)
{
if (IsXMLToken(aLocalName, XML_STRUCTURE_PROTECTED))
bProtected = IsXMLToken(sValue, XML_TRUE);
else if (IsXMLToken(aLocalName, XML_PROTECTION_KEY))
sPassword = sValue;
}
}
}
ScXMLBodyContext::~ScXMLBodyContext()
{
}
SvXMLImportContext *ScXMLBodyContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetScImport().GetBodyElemTokenMap();
sal_Bool bOrdered = sal_False;
sal_Bool bHeading = sal_False;
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
// case XML_TOK_TEXT_H:
// bHeading = TRUE;
// case XML_TOK_TEXT_P:
// pContext = new SwXMLParaContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bHeading );
// break;
// case XML_TOK_TEXT_ORDERED_LIST:
// bOrdered = TRUE;
// case XML_TOK_TEXT_UNORDERED_LIST:
// pContext = new SwXMLListBlockContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bOrdered );
// break;
case XML_TOK_BODY_TRACKED_CHANGES :
{
pChangeTrackingImportHelper = GetScImport().GetChangeTrackingImportHelper();
if (pChangeTrackingImportHelper)
pContext = new ScXMLTrackedChangesContext( GetScImport(), nPrefix, rLocalName, xAttrList, pChangeTrackingImportHelper);
}
break;
case XML_TOK_BODY_CALCULATION_SETTINGS :
pContext = new ScXMLCalculationSettingsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_CONTENT_VALIDATIONS :
pContext = new ScXMLContentValidationsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_LABEL_RANGES:
pContext = new ScXMLLabelRangesContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_TABLE:
// if( !GetScImport().GetPaM().GetNode()->FindTableNode() )
pContext = new ScXMLTableContext( GetScImport(),nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_NAMED_EXPRESSIONS:
pContext = new ScXMLNamedExpressionsContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGES:
pContext = new ScXMLDatabaseRangesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGE:
pContext = new ScXMLDatabaseRangeContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATA_PILOT_TABLES:
pContext = new ScXMLDataPilotTablesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_CONSOLIDATION:
pContext = new ScXMLConsolidationContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DDE_LINKS:
pContext = new ScXMLDDELinksContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
void ScXMLBodyContext::EndElement()
{
GetScImport().LockSolarMutex();
ScMyImpDetectiveOpArray* pDetOpArray = GetScImport().GetDetectiveOpArray();
ScDocument* pDoc = GetScImport().GetDocument();
ScMyImpDetectiveOp aDetOp;
if (pDoc && GetScImport().GetModel().is())
{
if (pDetOpArray)
{
pDetOpArray->Sort();
while( pDetOpArray->GetFirstOp( aDetOp ) )
{
ScDetOpData aOpData( aDetOp.aPosition, aDetOp.eOpType );
pDoc->AddDetectiveOperation( aOpData );
}
}
if (pChangeTrackingImportHelper)
pChangeTrackingImportHelper->CreateChangeTrack(GetScImport().GetDocument());
if (bProtected)
{
uno::Sequence<sal_Int8> aPass;
if (sPassword.getLength())
SvXMLUnitConverter::decodeBase64(aPass, sPassword);
pDoc->SetDocProtection(bProtected, aPass);
}
uno::Reference <sheet::XSpreadsheetDocument> xSpreadDoc( GetScImport().GetModel(), uno::UNO_QUERY );
if ( xSpreadDoc.is() )
{
uno::Reference<sheet::XSpreadsheets> xSheets = xSpreadDoc->getSheets();
uno::Reference <container::XIndexAccess> xIndex( xSheets, uno::UNO_QUERY );
if ( xIndex.is() )
{
uno::Any aSheet = xIndex->getByIndex(0);
uno::Reference< sheet::XSpreadsheet > xSheet;
if ( aSheet >>= xSheet )
{
uno::Reference <beans::XPropertySet> xProperties(xSheet, uno::UNO_QUERY);
if (xProperties.is())
{
XMLTableStylesContext *pStyles = (XMLTableStylesContext *)GetScImport().GetAutoStyles();
rtl::OUString sTableStyleName(GetScImport().GetFirstTableStyle());
if (sTableStyleName.getLength())
{
XMLTableStyleContext* pStyle = (XMLTableStyleContext *)pStyles->FindStyleChildContext(
XML_STYLE_FAMILY_TABLE_TABLE, sTableStyleName, sal_True);
if (pStyle)
pStyle->FillPropertySet(xProperties);
}
}
}
}
}
}
GetScImport().UnlockSolarMutex();
}
<commit_msg>#103502#; create empty context if to much sheets<commit_after>/*************************************************************************
*
* $RCSfile: xmlbodyi.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: sab $ $Date: 2002-09-24 16:05:36 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#include "xmlbodyi.hxx"
#include "xmltabi.hxx"
#include "xmlnexpi.hxx"
#include "xmldrani.hxx"
#include "xmlimprt.hxx"
#include "xmldpimp.hxx"
#include "xmlcvali.hxx"
#include "xmlstyli.hxx"
#ifndef SC_XMLLABRI_HXX
#include "xmllabri.hxx"
#endif
#ifndef _SC_XMLCONSOLIDATIONCONTEXT_HXX
#include "XMLConsolidationContext.hxx"
#endif
#ifndef _SC_XMLDDELINKSCONTEXT_HXX
#include "XMLDDELinksContext.hxx"
#endif
#ifndef _SC_XMLCALCULATIONSETTINGSCONTEXT_HXX
#include "XMLCalculationSettingsContext.hxx"
#endif
#ifndef _SC_XMLTRACKEDCHANGESCONTEXT_HXX
#include "XMLTrackedChangesContext.hxx"
#endif
#ifndef SC_XMLEMPTYCONTEXT_HXX
#include "XMLEmptyContext.hxx"
#endif
#include <xmloff/xmltkmap.hxx>
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLBodyContext::ScXMLBodyContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const uno::Reference<xml::sax::XAttributeList>& xAttrList ) :
SvXMLImportContext( rImport, nPrfx, rLName ),
pChangeTrackingImportHelper(NULL),
bProtected(sal_False),
sPassword()
{
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for( sal_Int16 i=0; i < nAttrCount; i++ )
{
rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
rtl::OUString aLocalName;
USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName );
rtl::OUString sValue = xAttrList->getValueByIndex( i );
if (nPrefix == XML_NAMESPACE_TABLE)
{
if (IsXMLToken(aLocalName, XML_STRUCTURE_PROTECTED))
bProtected = IsXMLToken(sValue, XML_TRUE);
else if (IsXMLToken(aLocalName, XML_PROTECTION_KEY))
sPassword = sValue;
}
}
}
ScXMLBodyContext::~ScXMLBodyContext()
{
}
SvXMLImportContext *ScXMLBodyContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLocalName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
SvXMLImportContext *pContext = 0;
const SvXMLTokenMap& rTokenMap = GetScImport().GetBodyElemTokenMap();
sal_Bool bOrdered = sal_False;
sal_Bool bHeading = sal_False;
switch( rTokenMap.Get( nPrefix, rLocalName ) )
{
// case XML_TOK_TEXT_H:
// bHeading = TRUE;
// case XML_TOK_TEXT_P:
// pContext = new SwXMLParaContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bHeading );
// break;
// case XML_TOK_TEXT_ORDERED_LIST:
// bOrdered = TRUE;
// case XML_TOK_TEXT_UNORDERED_LIST:
// pContext = new SwXMLListBlockContext( GetSwImport(),nPrefix, rLocalName,
// xAttrList, bOrdered );
// break;
case XML_TOK_BODY_TRACKED_CHANGES :
{
pChangeTrackingImportHelper = GetScImport().GetChangeTrackingImportHelper();
if (pChangeTrackingImportHelper)
pContext = new ScXMLTrackedChangesContext( GetScImport(), nPrefix, rLocalName, xAttrList, pChangeTrackingImportHelper);
}
break;
case XML_TOK_BODY_CALCULATION_SETTINGS :
pContext = new ScXMLCalculationSettingsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_CONTENT_VALIDATIONS :
pContext = new ScXMLContentValidationsContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_LABEL_RANGES:
pContext = new ScXMLLabelRangesContext( GetScImport(), nPrefix, rLocalName, xAttrList );
break;
case XML_TOK_BODY_TABLE:
{
if (GetScImport().GetTables().GetCurrentSheet() >= MAXTAB)
{
GetScImport().SetHasRangeOverflow();
pContext = new ScXMLEmptyContext(GetScImport(), nPrefix, rLocalName);
}
else
{
pContext = new ScXMLTableContext( GetScImport(),nPrefix, rLocalName,
xAttrList );
}
}
break;
case XML_TOK_BODY_NAMED_EXPRESSIONS:
pContext = new ScXMLNamedExpressionsContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGES:
pContext = new ScXMLDatabaseRangesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATABASE_RANGE:
pContext = new ScXMLDatabaseRangeContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DATA_PILOT_TABLES:
pContext = new ScXMLDataPilotTablesContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_CONSOLIDATION:
pContext = new ScXMLConsolidationContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
case XML_TOK_BODY_DDE_LINKS:
pContext = new ScXMLDDELinksContext ( GetScImport(), nPrefix, rLocalName,
xAttrList );
break;
}
if( !pContext )
pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );
return pContext;
}
void ScXMLBodyContext::EndElement()
{
GetScImport().LockSolarMutex();
ScMyImpDetectiveOpArray* pDetOpArray = GetScImport().GetDetectiveOpArray();
ScDocument* pDoc = GetScImport().GetDocument();
ScMyImpDetectiveOp aDetOp;
if (pDoc && GetScImport().GetModel().is())
{
if (pDetOpArray)
{
pDetOpArray->Sort();
while( pDetOpArray->GetFirstOp( aDetOp ) )
{
ScDetOpData aOpData( aDetOp.aPosition, aDetOp.eOpType );
pDoc->AddDetectiveOperation( aOpData );
}
}
if (pChangeTrackingImportHelper)
pChangeTrackingImportHelper->CreateChangeTrack(GetScImport().GetDocument());
if (bProtected)
{
uno::Sequence<sal_Int8> aPass;
if (sPassword.getLength())
SvXMLUnitConverter::decodeBase64(aPass, sPassword);
pDoc->SetDocProtection(bProtected, aPass);
}
uno::Reference <sheet::XSpreadsheetDocument> xSpreadDoc( GetScImport().GetModel(), uno::UNO_QUERY );
if ( xSpreadDoc.is() )
{
uno::Reference<sheet::XSpreadsheets> xSheets = xSpreadDoc->getSheets();
uno::Reference <container::XIndexAccess> xIndex( xSheets, uno::UNO_QUERY );
if ( xIndex.is() )
{
uno::Any aSheet = xIndex->getByIndex(0);
uno::Reference< sheet::XSpreadsheet > xSheet;
if ( aSheet >>= xSheet )
{
uno::Reference <beans::XPropertySet> xProperties(xSheet, uno::UNO_QUERY);
if (xProperties.is())
{
XMLTableStylesContext *pStyles = (XMLTableStylesContext *)GetScImport().GetAutoStyles();
rtl::OUString sTableStyleName(GetScImport().GetFirstTableStyle());
if (sTableStyleName.getLength())
{
XMLTableStyleContext* pStyle = (XMLTableStyleContext *)pStyles->FindStyleChildContext(
XML_STYLE_FAMILY_TABLE_TABLE, sTableStyleName, sal_True);
if (pStyle)
pStyle->FillPropertySet(xProperties);
}
}
}
}
}
}
GetScImport().UnlockSolarMutex();
}
<|endoftext|> |
<commit_before>/*
$Id$
*/
// This class runs the test TOF preprocessor
// It uses AliTestShuttle to simulate a full Shuttle process
// The input data is created in the functions
// CreateDCSAliasMap() creates input that would in the same way come from DCS
// ReadDCSAliasMap() reads from a file
// CreateInputFilesMap() creates a list of local files, that can be accessed by the shuttle
void TOFPreprocessor()
{
gSystem->Load("$ALICE/SHUTTLE/TestShuttle/libTestShuttle.so");
// initialize location of CDB
AliTestShuttle::SetMainCDB("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");
AliTestShuttle::SetMainRefStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestReference");
// create AliTestShuttle instance
AliTestShuttle* shuttle = new AliTestShuttle(0, 0, 1000);
// Generation of "fake" input DCS data
TMap* dcsAliasMap = CreateDCSAliasMap();
// now give the alias map to the shuttle
shuttle->SetDCSInput(dcsAliasMap);
// processing files. for the time being, the files are local.
shuttle->AddInputFile(AliTestShuttle::kDAQ, "TOF", "DELAYS", "MON", "$ALICE_ROOT/TOF/ShuttleInput/Total.root");
shuttle->AddInputFile(AliTestShuttle::kDAQ, "TOF", "RUNLevel", "MON", "$ALICE_ROOT/TOF/ShuttleInput/Partial.root");
// instantiation of the preprocessor
AliPreprocessor* pp = new AliTOFPreprocessor(shuttle);
// preprocessing
shuttle->Process();
// checking the file which should have been created
AliCDBEntry* entry = AliCDBManager::Instance()->Get("TOF/Calib/OnlineDelay", 0);
if (!entry)
{
printf("The file is not there. Something went wrong.\n");
return;
}
AliTOFDataDCS* output = dynamic_cast<AliTOFDataDCS*> (entry->GetObject());
// If everything went fine, draw the result
if (output)
output->Draw();
}
TMap* CreateDCSAliasMap()
{
// Creates a DCS structure
// The structure is the following:
// TMap (key --> value)
// <DCSAlias> --> <valueList>
// <DCSAlias> is a string
// <valueList> is a TObjArray of AliDCSValue
TMap* aliasMap = new TMap;
aliasMap->SetOwner(1);
TRandom random;
TDatime *datime = new TDatime();
Int_t time = datime->GetTime();
Int_t date = datime->GetDate();
Int_t pid = gSystem->GetPid();
delete datime;
Int_t iseed = TMath::Abs(10000 * pid + time - date);
Float_t tentHVv=6500, tentHVi=80, tentLVv=2.7, tentLVi=4.5,
tentLVv33=3.3, tentLVv50=5.0, tentLVv48=48,
tentLVi33=100, tentLVi50=3.0, tentLVi48=10,
tentFEEthr=1.0, tentFEEtfeac=25, tentFEEttrm=45,
tentTemp=25, tentPress=900;
Float_t sigmaHVv=10, sigmaHVi=10, sigmaLVv=0.2, sigmaLVi=1.0,
sigmaLVv33=0.1, sigmaLVv50=0.1, sigmaLVv48=1,
sigmaLVi33=10, sigmaLVi50=0.5, sigmaLVi48=2,
sigmaFEEthr=0.1, sigmaFEEtfeac=10, sigmaFEEttrm=4,
sigmaTemp=1, sigmaPress=10;
Float_t tent=0, sigma=0, thr=0;
Int_t NAliases=10514, NHV=90, NLV=576, NLV33=72, NLV50=72, NLV48=72, NFEEthr=1152, NFEEtfeac=576, NFEEttrm=6840, NT=1, NP=1;
for(int nAlias=0;nAlias<NAliases;nAlias++) {
TObjArray* valueSet = new TObjArray;
valueSet->SetOwner(1);
TString sindex;
TString aliasName;
if (nAlias<NHV){
aliasName = "tof_hv_vp_";
sindex.Form("%02i",nAlias);
aliasName += sindex;
//aliasName += nAlias;
tent=tentHVv;
sigma=sigmaHVv;
// thr=thrHVv;
}
else if (nAlias<NHV*2){
// aliasName = "HVvneg";
//aliasName += nAlias-NHV;
aliasName = "tof_hv_vn_";
sindex.Form("%02i",nAlias-NHV);
aliasName += sindex;
tent=-tentHVv;
sigma=-sigmaHVv;
//thr=-thrHVv;
}
else if (nAlias<NHV*3){
// aliasName = "HVcpos";
//aliasName += nAlias-2*NHV;
aliasName = "tof_hv_ip_";
sindex.Form("%02i",nAlias-2*NHV);
aliasName += sindex;
tent=tentHVi;
sigma=sigmaHVi;
//thr=thrHVc;
}
else if (nAlias<NHV*4){
// aliasName = "HVcneg";
//aliasName += nAlias-3*NHV;
aliasName = "tof_hv_in_";
sindex.Form("%02i",nAlias-3*NHV);
aliasName += sindex;
tent=-tentHVi;
sigma=-sigmaHVi;
//thr=-thrHVc;
}
else if (nAlias<NHV*4+NLV){
// aliasName = "LVv";
//aliasName += nAlias-4*NHV;
aliasName = "tof_lv_vfea_";
sindex.Form("%03i",nAlias-4*NHV);
aliasName += sindex;
tent=tentLVv;
sigma=sigmaLVv;
//thr=thrLVv;
}
else if (nAlias<NHV*4+2*NLV){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_ifea_";
sindex.Form("%03i",nAlias-(4*NHV+NLV));
aliasName += sindex;
tent=tentLVi;
sigma=sigmaLVi;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+NLV33){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_v33_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV));
aliasName += sindex;
tent=tentLVv33;
sigma=sigmaLVv33;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_i33_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+NLV33));
aliasName += sindex;
tent=tentLVi33;
sigma=sigmaLVi33;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+NLV50){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_v50_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33));
aliasName += sindex;
tent=tentLVv50;
sigma=sigmaLVv50;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_i50_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33+NLV50));
aliasName += sindex;
tent=tentLVi50;
sigma=sigmaLVi50;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+NLV48){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_v48_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50));
aliasName += sindex;
tent=tentLVv48;
sigma=sigmaLVv48;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_i48_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+NLV48));
aliasName += sindex;
tent=tentLVi48;
sigma=sigmaLVi48;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr){
// aliasName = "FEEthr";
//aliasName += nAlias-(4*NHV+2*NLV-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48));
aliasName = "tof_fee_th_";
sindex.Form("%04i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48));
aliasName += sindex;
tent=tentFEEthr;
sigma=sigmaFEEthr;
//thr=thrFEEthr;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac){
//cout << " nalias fee temp = " << nAlias << endl;
// aliasName = "FEEt";
//aliasName += nAlias-(4*NHV+2*NLV+NFEEthr);
aliasName = "tof_fee_tfeac_";
sindex.Form("%03i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr));
aliasName += sindex;
//cout << " nalias fee temp name = " << aliasName << endl;
tent=tentFEEtfeac;
sigma=sigmaFEEtfeac;
//thr=thrFEEthr;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac+NFEEttrm){
//cout << " nalias fee temp = " << nAlias << endl;
// aliasName = "FEEt";
//aliasName += nAlias-(4*NHV+2*NLV+NFEEthr);
aliasName = "tof_fee_ttrm_";
sindex.Form("%04i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac));
aliasName += sindex;
//cout << " nalias fee temp name = " << aliasName << endl;
tent=tentFEEttrm;
sigma=sigmaFEEttrm;
//thr=thrFEEthr;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac+NFEEttrm+1){
cout << " putting temperature" << endl;
aliasName = "temperature";
tent=tentTemp;
sigma=sigmaTemp;
//thr=thrTemp;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac+NFEEttrm+2){
cout << " putting pressure" << endl;
aliasName = "pressure";
tent=tentPress;
sigma=sigmaPress;
//thr=thrPress;
}
// gauss generation of values
for (int timeStamp=0;timeStamp<1000;timeStamp+=10){
Float_t gaussvalue = (Float_t) (random.Gaus(tent,sigma));
if (TMath::Abs(gaussvalue-tent)>sigma){
AliDCSValue* dcsVal = new AliDCSValue(gaussvalue, timeStamp);
valueSet->Add(dcsVal);
}
}
aliasMap->Add(new TObjString(aliasName), valueSet);
}
return aliasMap;
}
TMap* ReadDCSAliasMap()
{
// Open a file that contains DCS input data
// The CDB framework is used to open the file, this means the file is located
// in $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB/<detector>/DCS/Data
// The file contains an AliCDBEntry that contains a TMap with the DCS structure.
// An explanation of the structure can be found in CreateDCSAliasMap()
AliCDBEntry *entry = AliCDBManager::Instance()->Get("TOF/DCS/Data", 0);
return dynamic_cast<TMap*> (entry->GetObject());
}
void WriteDCSAliasMap()
{
// This writes the output from CreateDCSAliasMap to a CDB file
TMap* dcsAliasMap = CreateDCSAliasMap();
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Chiara");
metaData.SetComment("Test object for TOFPreprocessor.C");
AliCDBId id("TOF/DCS/Data", 0, 0);
// initialize location of CDB
AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");
AliCDBManager::Instance()->Put(dcsAliasMap, id, &metaData);
}
<commit_msg>Updated setting of the storages<commit_after>/*
$Id$
*/
// This class runs the test TOF preprocessor
// It uses AliTestShuttle to simulate a full Shuttle process
// The input data is created in the functions
// CreateDCSAliasMap() creates input that would in the same way come from DCS
// ReadDCSAliasMap() reads from a file
// CreateInputFilesMap() creates a list of local files, that can be accessed by the shuttle
extern TBenchmark *gBenchmark;
void TOFPreprocessor()
{
gSystem->Load("$ALICE/SHUTTLE/TestShuttle/libTestShuttle.so");
// initialize location of CDB
AliTestShuttle::SetMainCDB("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");
AliTestShuttle::SetMainRefStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestReference");
// create AliTestShuttle instance
AliTestShuttle* shuttle = new AliTestShuttle(0, 0, 1000);
// Generation of "fake" input DCS data
TMap* dcsAliasMap = CreateDCSAliasMap();
// now give the alias map to the shuttle
shuttle->SetDCSInput(dcsAliasMap);
// processing files. for the time being, the files are local.
shuttle->AddInputFile(AliTestShuttle::kDAQ, "TOF", "DELAYS", "MON", "$ALICE_ROOT/TOF/ShuttleInput/Total.root");
shuttle->AddInputFile(AliTestShuttle::kDAQ, "TOF", "RUNLevel", "MON", "$ALICE_ROOT/TOF/ShuttleInput/Partial.root");
// instantiation of the preprocessor
AliPreprocessor* pp = new AliTOFPreprocessor(shuttle);
// preprocessing
gBenchmark->Start("process");
shuttle->Process();
gBenchmark->Stop("process");
gBenchmark->Print("process");
// checking the file which should have been created
AliCDBEntry* chkEntry = AliCDBManager::Instance()->GetStorage(AliShuttleInterface::GetMainCDB())
->Get("TOF/Calib/OnlineDelay", 0);
if (!chkEntry)
{
printf("The file is not there. Something went wrong.\n");
return;
}
AliTOFDataDCS* output = dynamic_cast<AliTOFDataDCS*> (chkEntry->GetObject());
// If everything went fine, draw the result
if (output)
output->Draw();
}
TMap* CreateDCSAliasMap()
{
// Creates a DCS structure
// The structure is the following:
// TMap (key --> value)
// <DCSAlias> --> <valueList>
// <DCSAlias> is a string
// <valueList> is a TObjArray of AliDCSValue
// An AliDCSValue consists of timestamp and a value in form of a AliSimpleValue
// In this example 6 aliases exists: DCSAlias1 ... DCSAlias6
// Each contains 1000 values randomly generated by TRandom::Gaus + 5*nAlias
TMap* aliasMap = new TMap;
aliasMap->SetOwner(1);
TRandom random;
TDatime *datime = new TDatime();
Int_t time = datime->GetTime();
Int_t date = datime->GetDate();
Int_t pid = gSystem->GetPid();
delete datime;
Int_t iseed = TMath::Abs(10000 * pid + time - date);
//Float_t thrHVv=7.75, thrHVc=3, thrLVv=2.75, thrLVc=2.5,
//thrFEEthr=1.5, thrFEEt=10, thrTemp=35, thrPress=1000;
//Float_t tentHVv=6.75, tentHVc=2, tentLVv=1.75, tentLVc=1.5,
// tentFEEthr=0.5, te result=0;
//ntFEEt=20, tentTemp=25, tentPress=900;
//Float_t sigmaHVv=1, sigmaHVc=0.25, sigmaLVv=0.25, sigmaLVc=0.25,
// sigmaFEEthr=0.05, sigmaFEEt=5, sigmaTemp=1, sigmaPress=10;
Float_t tentHVv=6500, tentHVi=80, tentLVv=2.7, tentLVi=4.5,
tentLVv33=3.3, tentLVv50=5.0, tentLVv48=48,
tentLVi33=100, tentLVi50=3.0, tentLVi48=10,
tentFEEthr=1.0, tentFEEtfeac=25, tentFEEttrm=45,
tentTemp=25, tentPress=900;
Float_t sigmaHVv=10, sigmaHVi=10, sigmaLVv=0.2, sigmaLVi=1.0,
sigmaLVv33=0.1, sigmaLVv50=0.1, sigmaLVv48=1,
sigmaLVi33=10, sigmaLVi50=0.5, sigmaLVi48=2,
sigmaFEEthr=0.1, sigmaFEEtfeac=10, sigmaFEEttrm=4,
sigmaTemp=1, sigmaPress=10;
Float_t tent=0, sigma=0, thr=0;
Int_t NAliases=10514, NHV=90, NLV=576, NLV33=72, NLV50=72, NLV48=72, NFEEthr=1152, NFEEtfeac=576, NFEEttrm=6840, NT=1, NP=1;
for(int nAlias=0;nAlias<NAliases;nAlias++) {
TObjArray* valueSet = new TObjArray;
valueSet->SetOwner(1);
TString sindex;
TString aliasName;
if (nAlias<NHV){
aliasName = "tof_hv_vp_";
sindex.Form("%02i",nAlias);
aliasName += sindex;
//aliasName += nAlias;
tent=tentHVv;
sigma=sigmaHVv;
// thr=thrHVv;
}
else if (nAlias<NHV*2){
// aliasName = "HVvneg";
//aliasName += nAlias-NHV;
aliasName = "tof_hv_vn_";
sindex.Form("%02i",nAlias-NHV);
aliasName += sindex;
tent=-tentHVv;
sigma=-sigmaHVv;
//thr=-thrHVv;
}
else if (nAlias<NHV*3){
// aliasName = "HVcpos";
//aliasName += nAlias-2*NHV;
aliasName = "tof_hv_ip_";
sindex.Form("%02i",nAlias-2*NHV);
aliasName += sindex;
tent=tentHVi;
sigma=sigmaHVi;
//thr=thrHVc;
}
else if (nAlias<NHV*4){
// aliasName = "HVcneg";
//aliasName += nAlias-3*NHV;
aliasName = "tof_hv_in_";
sindex.Form("%02i",nAlias-3*NHV);
aliasName += sindex;
tent=-tentHVi;
sigma=-sigmaHVi;
//thr=-thrHVc;
}
else if (nAlias<NHV*4+NLV){
// aliasName = "LVv";
//aliasName += nAlias-4*NHV;
aliasName = "tof_lv_vfea_";
sindex.Form("%03i",nAlias-4*NHV);
aliasName += sindex;
tent=tentLVv;
sigma=sigmaLVv;
//thr=thrLVv;
}
else if (nAlias<NHV*4+2*NLV){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_ifea_";
sindex.Form("%03i",nAlias-(4*NHV+NLV));
aliasName += sindex;
tent=tentLVi;
sigma=sigmaLVi;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+NLV33){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_v33_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV));
aliasName += sindex;
tent=tentLVv33;
sigma=sigmaLVv33;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_i33_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+NLV33));
aliasName += sindex;
tent=tentLVi33;
sigma=sigmaLVi33;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+NLV50){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_v50_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33));
aliasName += sindex;
tent=tentLVv50;
sigma=sigmaLVv50;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_i50_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33+NLV50));
aliasName += sindex;
tent=tentLVi50;
sigma=sigmaLVi50;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+NLV48){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_v48_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50));
aliasName += sindex;
tent=tentLVv48;
sigma=sigmaLVv48;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48){
// aliasName = "LVc";
//aliasName += nAlias-(4*NHV+NLV);
aliasName = "tof_lv_i48_";
sindex.Form("%02i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+NLV48));
aliasName += sindex;
tent=tentLVi48;
sigma=sigmaLVi48;
//thr=thrLVc;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr){
// aliasName = "FEEthr";
//aliasName += nAlias-(4*NHV+2*NLV-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48));
aliasName = "tof_fee_th_";
sindex.Form("%04i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48));
aliasName += sindex;
tent=tentFEEthr;
sigma=sigmaFEEthr;
//thr=thrFEEthr;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac){
//cout << " nalias fee temp = " << nAlias << endl;
// aliasName = "FEEt";
//aliasName += nAlias-(4*NHV+2*NLV+NFEEthr);
aliasName = "tof_fee_tfeac_";
sindex.Form("%03i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr));
aliasName += sindex;
//cout << " nalias fee temp name = " << aliasName << endl;
tent=tentFEEtfeac;
sigma=sigmaFEEtfeac;
//thr=thrFEEthr;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac+NFEEttrm){
//cout << " nalias fee temp = " << nAlias << endl;
// aliasName = "FEEt";
//aliasName += nAlias-(4*NHV+2*NLV+NFEEthr);
aliasName = "tof_fee_ttrm_";
sindex.Form("%04i",nAlias-(4*NHV+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac));
aliasName += sindex;
//cout << " nalias fee temp name = " << aliasName << endl;
tent=tentFEEttrm;
sigma=sigmaFEEttrm;
//thr=thrFEEthr;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac+NFEEttrm+1){
cout << " putting temperature" << endl;
aliasName = "temperature";
tent=tentTemp;
sigma=sigmaTemp;
//thr=thrTemp;
}
else if (nAlias<NHV*4+2*NLV+2*NLV33+2*NLV50+2*NLV48+NFEEthr+NFEEtfeac+NFEEttrm+2){
cout << " putting pressure" << endl;
aliasName = "pressure";
tent=tentPress;
sigma=sigmaPress;
//thr=thrPress;
}
// gauss generation of values
for (int timeStamp=0;timeStamp<1000;timeStamp+=10){
Float_t gaussvalue = (Float_t) (random.Gaus(tent,sigma));
if (TMath::Abs(gaussvalue-tent)>sigma){
AliDCSValue* dcsVal = new AliDCSValue(gaussvalue, timeStamp);
valueSet->Add(dcsVal);
}
}
aliasMap->Add(new TObjString(aliasName), valueSet);
}
return aliasMap;
}
TMap* ReadDCSAliasMap()
{
// Open a file that contains DCS input data
// The CDB framework is used to open the file, this means the file is located
// in $ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB/<detector>/DCS/Data
// The file contains an AliCDBEntry that contains a TMap with the DCS structure.
// An explanation of the structure can be found in CreateDCSAliasMap()
AliCDBEntry *entry = AliCDBManager::Instance()->Get("TOF/DCS/Data", 0);
return dynamic_cast<TMap*> (entry->GetObject());
}
void WriteDCSAliasMap()
{
// This writes the output from CreateDCSAliasMap to a CDB file
TMap* dcsAliasMap = CreateDCSAliasMap();
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Chiara");
metaData.SetComment("Test object for TOFPreprocessor.C");
AliCDBId id("TOF/DCS/Data", 0, 0);
// initialize location of CDB
AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/SHUTTLE/TestShuttle/TestCDB");
AliCDBManager::Instance()->Put(dcsAliasMap, id, &metaData);
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS dialogdiet (1.26.74); FILE MERGED 2003/12/10 15:02:33 mba 1.26.74.1: #i22972#: offmgr removed<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix CompoundPredicate::CodegenComputeFn<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* 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 "game.h"
#include "localplayer.h"
#include "map.h"
#include "tile.h"
#include <otclient/net/protocolgame.h>
#include <framework/core/eventdispatcher.h>
#include <framework/ui/uimanager.h>
Game g_game;
void Game::loginWorld(const std::string& account, const std::string& password, const std::string& worldHost, int worldPort, const std::string& characterName)
{
m_protocolGame = ProtocolGamePtr(new ProtocolGame);
m_protocolGame->login(account, password, worldHost, (uint16)worldPort, characterName);
}
void Game::cancelLogin()
{
processLogout();
}
void Game::logout(bool force)
{
if(!m_protocolGame || !m_online)
return;
m_protocolGame->sendLogout();
if(force)
processLogout();
}
void Game::processLoginError(const std::string& error)
{
g_lua.callGlobalField("Game", "onLoginError", error);
}
void Game::processConnectionError(const boost::system::error_code& error)
{
// connection errors only have meaning if we still have a protocol
if(m_protocolGame) {
if(error != asio::error::eof)
g_lua.callGlobalField("Game", "onConnectionError", error.message());
processLogout();
}
}
void Game::processLogin(const LocalPlayerPtr& localPlayer)
{
m_localPlayer = localPlayer;
m_online = true;
g_lua.callGlobalField("Game", "onLogin", m_localPlayer);
}
void Game::processLogout()
{
if(m_online) {
g_lua.callGlobalField("Game", "onLogout", m_localPlayer);
m_localPlayer.reset();
m_online = false;
}
if(m_protocolGame) {
m_protocolGame->disconnect();
m_protocolGame.reset();
}
}
void Game::processTextMessage(int type, const std::string& message)
{
g_lua.callGlobalField("Game","onTextMessage", type, message);
}
void Game::processInventoryChange(int slot, const ItemPtr& item)
{
if(item)
item->setPos(Position(65535, slot, 0));
g_lua.callGlobalField("Game","onInventoryChange", slot, item);
}
void Game::walk(Otc::Direction direction)
{
if(!m_online || !m_localPlayer->canWalk(direction) || !checkBotProtection())
return;
cancelFollow();
m_localPlayer->clientWalk(direction);
switch(direction) {
case Otc::North:
m_protocolGame->sendWalkNorth();
break;
case Otc::East:
m_protocolGame->sendWalkEast();
break;
case Otc::South:
m_protocolGame->sendWalkSouth();
break;
case Otc::West:
m_protocolGame->sendWalkWest();
break;
case Otc::NorthEast:
m_protocolGame->sendWalkNorthEast();
break;
case Otc::SouthEast:
m_protocolGame->sendWalkSouthEast();
break;
case Otc::SouthWest:
m_protocolGame->sendWalkSouthWest();
break;
case Otc::NorthWest:
m_protocolGame->sendWalkNorthWest();
break;
}
}
void Game::turn(Otc::Direction direction)
{
if(!m_online)
return;
switch(direction) {
case Otc::North:
m_protocolGame->sendTurnNorth();
break;
case Otc::East:
m_protocolGame->sendTurnEast();
break;
case Otc::South:
m_protocolGame->sendTurnSouth();
break;
case Otc::West:
m_protocolGame->sendTurnWest();
break;
}
}
void Game::look(const ThingPtr& thing)
{
if(!m_online || !thing || !checkBotProtection())
return;
int stackpos = getThingStackpos(thing);
if(stackpos != -1)
m_protocolGame->sendLookAt(thing->getPos(), thing->getId(), stackpos);
}
void Game::use(const ThingPtr& thing)
{
if(!m_online || !thing || !checkBotProtection())
return;
int stackpos = getThingStackpos(thing);
if(stackpos != -1)
m_protocolGame->sendUseItem(thing->getPos(), thing->getId(), stackpos, 0);// last 0 has something to do with container
}
void Game::attack(const CreaturePtr& creature)
{
if(!m_online || !creature || !checkBotProtection())
return;
if(m_attackingCreature)
m_attackingCreature->hideStaticSquare();
creature->showStaticSquare(Fw::red);
m_attackingCreature = creature;
m_protocolGame->sendAttack(creature->getId());
}
void Game::cancelAttack()
{
if(m_attackingCreature) {
m_protocolGame->sendAttack(0);
m_attackingCreature->hideStaticSquare();
m_attackingCreature = nullptr;
}
}
void Game::onAttackCancelled()
{
if(m_attackingCreature) {
m_attackingCreature->hideStaticSquare();
m_attackingCreature = nullptr;
}
}
void Game::follow(const CreaturePtr& creature)
{
if(!m_online || !creature || !checkBotProtection())
return;
if(m_followingCreature)
m_followingCreature->hideStaticSquare();
creature->showStaticSquare(Fw::green);
m_followingCreature = creature;
m_protocolGame->sendFollow(creature->getId());
}
void Game::cancelFollow()
{
if(m_followingCreature) {
m_protocolGame->sendFollow(0);
m_followingCreature->hideStaticSquare();
m_followingCreature = nullptr;
}
}
void Game::rotate(const ThingPtr& thing)
{
if(!m_online || !thing || !checkBotProtection())
return;
int stackpos = getThingStackpos(thing);
if(stackpos != -1)
m_protocolGame->sendRotateItem(thing->getPos(), thing->getId(), stackpos);
}
int Game::getThingStackpos(const ThingPtr& thing)
{
// thing is at map
if(thing->getPos().x != 65535) {
TilePtr tile = g_map.getTile(thing->getPos());
return tile->getThingStackpos(thing);
}
// thing is at container or inventory
return 0;
}
void Game::talkChannel(int channelType, int channelId, const std::string& message)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendTalk(channelType, channelId, "", message);
}
void Game::talkPrivate(int channelType, const std::string& receiver, const std::string& message)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendTalk(channelType, 0, receiver, message);
}
void Game::inviteToParty(int creatureId)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendInviteToParty(creatureId);
}
void Game::openOutfitWindow()
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendGetOutfit();
}
void Game::setOutfit(const Outfit& outfit)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendSetOutfit(outfit);
}
void Game::addVip(const std::string& name)
{
if(!m_online || name.empty() || !checkBotProtection())
return;
m_protocolGame->sendAddVip(name);
}
void Game::removeVip(int playerId)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendRemoveVip(playerId);
}
bool Game::checkBotProtection()
{
#ifndef DISABLE_BOT_PROTECTION
if(g_lua.isInCppCallback() && !g_ui.isOnInputEvent()) {
logError("cought a lua call to a bot protected game function, the call was canceled");
return false;
}
#endif
return true;
}
<commit_msg>fix walk again<commit_after>/*
* Copyright (c) 2010-2012 OTClient <https://github.com/edubart/otclient>
*
* 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 "game.h"
#include "localplayer.h"
#include "map.h"
#include "tile.h"
#include <otclient/net/protocolgame.h>
#include <framework/core/eventdispatcher.h>
#include <framework/ui/uimanager.h>
Game g_game;
void Game::loginWorld(const std::string& account, const std::string& password, const std::string& worldHost, int worldPort, const std::string& characterName)
{
m_protocolGame = ProtocolGamePtr(new ProtocolGame);
m_protocolGame->login(account, password, worldHost, (uint16)worldPort, characterName);
}
void Game::cancelLogin()
{
processLogout();
}
void Game::logout(bool force)
{
if(!m_protocolGame || !m_online)
return;
m_protocolGame->sendLogout();
if(force)
processLogout();
}
void Game::processLoginError(const std::string& error)
{
g_lua.callGlobalField("Game", "onLoginError", error);
}
void Game::processConnectionError(const boost::system::error_code& error)
{
// connection errors only have meaning if we still have a protocol
if(m_protocolGame) {
if(error != asio::error::eof)
g_lua.callGlobalField("Game", "onConnectionError", error.message());
processLogout();
}
}
void Game::processLogin(const LocalPlayerPtr& localPlayer)
{
m_localPlayer = localPlayer;
m_online = true;
g_lua.callGlobalField("Game", "onLogin", m_localPlayer);
}
void Game::processLogout()
{
if(m_online) {
g_lua.callGlobalField("Game", "onLogout", m_localPlayer);
m_localPlayer.reset();
m_online = false;
}
if(m_protocolGame) {
m_protocolGame->disconnect();
m_protocolGame.reset();
}
}
void Game::processTextMessage(int type, const std::string& message)
{
g_lua.callGlobalField("Game","onTextMessage", type, message);
}
void Game::processInventoryChange(int slot, const ItemPtr& item)
{
if(item)
item->setPos(Position(65535, slot, 0));
g_lua.callGlobalField("Game","onInventoryChange", slot, item);
}
void Game::walk(Otc::Direction direction)
{
if(!m_online || !m_localPlayer->canWalk(direction) || (!checkBotProtection() && m_localPlayer->getNextWalkDirection() == Otc::InvalidDirection))
return;
cancelFollow();
m_localPlayer->clientWalk(direction);
switch(direction) {
case Otc::North:
m_protocolGame->sendWalkNorth();
break;
case Otc::East:
m_protocolGame->sendWalkEast();
break;
case Otc::South:
m_protocolGame->sendWalkSouth();
break;
case Otc::West:
m_protocolGame->sendWalkWest();
break;
case Otc::NorthEast:
m_protocolGame->sendWalkNorthEast();
break;
case Otc::SouthEast:
m_protocolGame->sendWalkSouthEast();
break;
case Otc::SouthWest:
m_protocolGame->sendWalkSouthWest();
break;
case Otc::NorthWest:
m_protocolGame->sendWalkNorthWest();
break;
}
}
void Game::turn(Otc::Direction direction)
{
if(!m_online)
return;
switch(direction) {
case Otc::North:
m_protocolGame->sendTurnNorth();
break;
case Otc::East:
m_protocolGame->sendTurnEast();
break;
case Otc::South:
m_protocolGame->sendTurnSouth();
break;
case Otc::West:
m_protocolGame->sendTurnWest();
break;
}
}
void Game::look(const ThingPtr& thing)
{
if(!m_online || !thing || !checkBotProtection())
return;
int stackpos = getThingStackpos(thing);
if(stackpos != -1)
m_protocolGame->sendLookAt(thing->getPos(), thing->getId(), stackpos);
}
void Game::use(const ThingPtr& thing)
{
if(!m_online || !thing || !checkBotProtection())
return;
int stackpos = getThingStackpos(thing);
if(stackpos != -1)
m_protocolGame->sendUseItem(thing->getPos(), thing->getId(), stackpos, 0);// last 0 has something to do with container
}
void Game::attack(const CreaturePtr& creature)
{
if(!m_online || !creature || !checkBotProtection())
return;
if(m_attackingCreature)
m_attackingCreature->hideStaticSquare();
creature->showStaticSquare(Fw::red);
m_attackingCreature = creature;
m_protocolGame->sendAttack(creature->getId());
}
void Game::cancelAttack()
{
if(m_attackingCreature) {
m_protocolGame->sendAttack(0);
m_attackingCreature->hideStaticSquare();
m_attackingCreature = nullptr;
}
}
void Game::onAttackCancelled()
{
if(m_attackingCreature) {
m_attackingCreature->hideStaticSquare();
m_attackingCreature = nullptr;
}
}
void Game::follow(const CreaturePtr& creature)
{
if(!m_online || !creature || !checkBotProtection())
return;
if(m_followingCreature)
m_followingCreature->hideStaticSquare();
creature->showStaticSquare(Fw::green);
m_followingCreature = creature;
m_protocolGame->sendFollow(creature->getId());
}
void Game::cancelFollow()
{
if(m_followingCreature) {
m_protocolGame->sendFollow(0);
m_followingCreature->hideStaticSquare();
m_followingCreature = nullptr;
}
}
void Game::rotate(const ThingPtr& thing)
{
if(!m_online || !thing || !checkBotProtection())
return;
int stackpos = getThingStackpos(thing);
if(stackpos != -1)
m_protocolGame->sendRotateItem(thing->getPos(), thing->getId(), stackpos);
}
int Game::getThingStackpos(const ThingPtr& thing)
{
// thing is at map
if(thing->getPos().x != 65535) {
TilePtr tile = g_map.getTile(thing->getPos());
return tile->getThingStackpos(thing);
}
// thing is at container or inventory
return 0;
}
void Game::talkChannel(int channelType, int channelId, const std::string& message)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendTalk(channelType, channelId, "", message);
}
void Game::talkPrivate(int channelType, const std::string& receiver, const std::string& message)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendTalk(channelType, 0, receiver, message);
}
void Game::inviteToParty(int creatureId)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendInviteToParty(creatureId);
}
void Game::openOutfitWindow()
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendGetOutfit();
}
void Game::setOutfit(const Outfit& outfit)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendSetOutfit(outfit);
}
void Game::addVip(const std::string& name)
{
if(!m_online || name.empty() || !checkBotProtection())
return;
m_protocolGame->sendAddVip(name);
}
void Game::removeVip(int playerId)
{
if(!m_online || !checkBotProtection())
return;
m_protocolGame->sendRemoveVip(playerId);
}
bool Game::checkBotProtection()
{
#ifndef DISABLE_BOT_PROTECTION
if(g_lua.isInCppCallback() && !g_ui.isOnInputEvent()) {
logError("cought a lua call to a bot protected game function, the call was canceled");
return false;
}
#endif
return true;
}
<|endoftext|> |
<commit_before><commit_msg>Fix a build issue on ZETA.<commit_after><|endoftext|> |
<commit_before><commit_msg>Set entries correctly visible, fdo#47102<commit_after><|endoftext|> |
<commit_before>/*
* 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
* Kohei Yoshida <[email protected]>
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* 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.
*/
#ifndef __SC_DPUIGLOBAL_HXX__
#define __SC_DPUIGLOBAL_HXX__
#define OUTER_MARGIN_HOR 4
#define OUTER_MARGIN_VER 4
#define DATA_FIELD_BTN_GAP 2 // must be an even number
#define ROW_FIELD_BTN_GAP 2 // must be an even number
#define FIELD_BTN_WIDTH 81
#define FIELD_BTN_HEIGHT 23
#define SELECT_FIELD_BTN_SPACE 2
#define FIELD_AREA_GAP 3 // gap between row/column/data/page areas
#endif
<commit_msg>Added mode lines for the new file.<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
* Kohei Yoshida <[email protected]>
* Portions created by the Initial Developer are Copyright (C) 2010 the
* Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* 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.
*/
#ifndef __SC_DPUIGLOBAL_HXX__
#define __SC_DPUIGLOBAL_HXX__
#define OUTER_MARGIN_HOR 4
#define OUTER_MARGIN_VER 4
#define DATA_FIELD_BTN_GAP 2 // must be an even number
#define ROW_FIELD_BTN_GAP 2 // must be an even number
#define FIELD_BTN_WIDTH 81
#define FIELD_BTN_HEIGHT 23
#define SELECT_FIELD_BTN_SPACE 2
#define FIELD_AREA_GAP 3 // gap between row/column/data/page areas
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: chartsh.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-02-03 20:30:59 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include <svx/eeitem.hxx>
#include <svx/fontwork.hxx>
//CHINA001 #include <svx/labdlg.hxx>
#include <svx/srchitem.hxx>
#include <svx/tabarea.hxx>
#include <svx/tabline.hxx>
//CHINA001 #include <svx/transfrm.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/request.hxx>
#include <svtools/whiter.hxx>
#include <vcl/msgbox.hxx>
#include "chartsh.hxx"
#include "drwlayer.hxx"
#include "sc.hrc"
#include "viewdata.hxx"
#include "document.hxx"
#include "docpool.hxx"
#include "drawview.hxx"
#include "scresid.hxx"
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#define ScChartShell
#include "scslots.hxx"
SFX_IMPL_INTERFACE(ScChartShell, ScDrawShell, ScResId(SCSTR_CHARTSHELL) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,
ScResId(RID_DRAW_OBJECTBAR) );
SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_CHART) );
SFX_OBJECTMENU_REGISTRATION( SID_OBJECTMENU0, ScResId(RID_OBJECTMENU_DRAW) );
}
TYPEINIT1( ScChartShell, ScDrawShell );
ScChartShell::ScChartShell(ScViewData* pData) :
ScDrawShell(pData)
{
SetHelpId(HID_SCSHELL_CHARTSH);
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("ChartObject")));
}
ScChartShell::~ScChartShell()
{
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.536); FILE MERGED 2005/09/05 15:04:37 rt 1.3.536.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: chartsh.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 20:51:54 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
//------------------------------------------------------------------
#include <svx/eeitem.hxx>
#include <svx/fontwork.hxx>
//CHINA001 #include <svx/labdlg.hxx>
#include <svx/srchitem.hxx>
#include <svx/tabarea.hxx>
#include <svx/tabline.hxx>
//CHINA001 #include <svx/transfrm.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/request.hxx>
#include <svtools/whiter.hxx>
#include <vcl/msgbox.hxx>
#include "chartsh.hxx"
#include "drwlayer.hxx"
#include "sc.hrc"
#include "viewdata.hxx"
#include "document.hxx"
#include "docpool.hxx"
#include "drawview.hxx"
#include "scresid.hxx"
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#define ScChartShell
#include "scslots.hxx"
SFX_IMPL_INTERFACE(ScChartShell, ScDrawShell, ScResId(SCSTR_CHARTSHELL) )
{
SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,
ScResId(RID_DRAW_OBJECTBAR) );
SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_CHART) );
SFX_OBJECTMENU_REGISTRATION( SID_OBJECTMENU0, ScResId(RID_OBJECTMENU_DRAW) );
}
TYPEINIT1( ScChartShell, ScDrawShell );
ScChartShell::ScChartShell(ScViewData* pData) :
ScDrawShell(pData)
{
SetHelpId(HID_SCSHELL_CHARTSH);
SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("ChartObject")));
}
ScChartShell::~ScChartShell()
{
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: spelldialog.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "spelldialog.hxx"
#include <sfx2/app.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/svxids.hrc>
#include <svx/editstat.hxx>
#include <svx/editview.hxx>
#include <svx/unolingu.hxx>
#include "selectionstate.hxx"
#include "spelleng.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "scmod.hxx"
#include "editable.hxx"
#include "undoblk.hxx"
// ============================================================================
SFX_IMPL_CHILDWINDOW( ScSpellDialogChildWindow, SID_SPELL_DIALOG )
ScSpellDialogChildWindow::ScSpellDialogChildWindow( Window* pParentP, USHORT nId,
SfxBindings* pBindings, SfxChildWinInfo* pInfo ) :
::svx::SpellDialogChildWindow( pParentP, nId, pBindings, pInfo ),
mpViewShell( 0 ),
mpViewData( 0 ),
mpDocShell( 0 ),
mpDoc( 0 ),
mbNeedNextObj( false ),
mbOldIdleDisabled( false )
{
Init();
}
ScSpellDialogChildWindow::~ScSpellDialogChildWindow()
{
Reset();
}
SfxChildWinInfo ScSpellDialogChildWindow::GetInfo() const
{
return ::svx::SpellDialogChildWindow::GetInfo();
}
void ScSpellDialogChildWindow::InvalidateSpellDialog()
{
::svx::SpellDialogChildWindow::InvalidateSpellDialog();
}
// protected ------------------------------------------------------------------
::svx::SpellPortions ScSpellDialogChildWindow::GetNextWrongSentence()
{
::svx::SpellPortions aPortions;
if( mxEngine.get() && mpViewData )
{
if( EditView* pEditView = mpViewData->GetSpellingView() )
{
// edit engine handles cell iteration internally
do
{
if( mbNeedNextObj )
mxEngine->SpellNextDocument();
mbNeedNextObj = !mxEngine->IsFinished() && !mxEngine->SpellSentence( *pEditView, aPortions );
}
while( mbNeedNextObj );
}
// finished? - close the spelling dialog
if( mxEngine->IsFinished() )
GetBindings().GetDispatcher()->Execute( SID_SPELL_DIALOG, SFX_CALLMODE_ASYNCHRON );
}
return aPortions;
}
void ScSpellDialogChildWindow::ApplyChangedSentence( const ::svx::SpellPortions& rChanged )
{
if( mxEngine.get() && mpViewData )
if( EditView* pEditView = mpViewData->GetSpellingView() )
mxEngine->ApplyChangedSentence( *pEditView, rChanged );
}
void ScSpellDialogChildWindow::GetFocus()
{
if( IsSelectionChanged() )
{
Reset();
InvalidateSpellDialog();
Init();
}
}
void ScSpellDialogChildWindow::LoseFocus()
{
}
// private --------------------------------------------------------------------
void ScSpellDialogChildWindow::Reset()
{
if( mpViewShell && (mpViewShell == PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
{
if( mxEngine.get() && mxEngine->IsAnyModified() )
{
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCTAB nTab = rCursor.Tab();
SCCOL nOldCol = rCursor.Col();
SCROW nOldRow = rCursor.Row();
SCCOL nNewCol = mpViewData->GetCurX();
SCROW nNewRow = mpViewData->GetCurY();
mpDocShell->GetUndoManager()->AddUndoAction( new ScUndoConversion(
mpDocShell, mpViewData->GetMarkData(),
nOldCol, nOldRow, nTab, mxUndoDoc.release(),
nNewCol, nNewRow, nTab, mxRedoDoc.release(),
ScConversionParam( SC_CONVERSION_SPELLCHECK ) ) );
mpDoc->SetDirty();
mpDocShell->SetDocumentModified();
}
mpViewData->SetSpellingView( 0 );
mpViewShell->KillEditView( TRUE );
mpDocShell->PostPaintGridAll();
mpViewShell->UpdateInputHandler();
mpDoc->DisableIdle( mbOldIdleDisabled );
}
mxEngine.reset();
mxUndoDoc.reset();
mxRedoDoc.reset();
mxOldSel.reset();
mpViewShell = 0;
mpViewData = 0;
mpDocShell = 0;
mpDoc = 0;
mbNeedNextObj = false;
mbOldIdleDisabled = false;
}
void ScSpellDialogChildWindow::Init()
{
if( mpViewShell )
return;
if( (mpViewShell = PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) == 0 )
return;
mpViewData = mpViewShell->GetViewData();
// exit edit mode - TODO support spelling in edit mode
if( mpViewData->HasEditView( mpViewData->GetActivePart() ) )
SC_MOD()->InputEnterHandler();
mxOldSel.reset( new ScSelectionState( *mpViewData ) );
mpDocShell = mpViewData->GetDocShell();
mpDoc = mpDocShell->GetDocument();
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCCOL nCol = rCursor.Col();
SCROW nRow = rCursor.Row();
SCTAB nTab = rCursor.Tab();
ScMarkData& rMarkData = mpViewData->GetMarkData();
rMarkData.MarkToMulti();
switch( mxOldSel->GetSelectionType() )
{
case SC_SELECTTYPE_NONE:
case SC_SELECTTYPE_SHEET:
{
// test if there is something editable
ScEditableTester aTester( mpDoc, rMarkData );
if( !aTester.IsEditable() )
{
mpViewShell->ErrorMessage( aTester.GetMessageId() );
return;
}
}
break;
// edit mode exited, see TODO above
// case SC_SELECTTYPE_EDITCELL:
// break;
default:
DBG_ERRORFILE( "ScSpellDialogChildWindow::Init - unknown selection type" );
}
mbOldIdleDisabled = mpDoc->IsIdleDisabled();
mpDoc->DisableIdle( TRUE ); // #42726# stop online spelling
// *** create Undo/Redo documents *** -------------------------------------
mxUndoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxUndoDoc->InitUndo( mpDoc, nTab, nTab );
mxRedoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxRedoDoc->InitUndo( mpDoc, nTab, nTab );
if ( rMarkData.GetSelectCount() > 1 )
{
SCTAB nTabCount = mpDoc->GetTableCount();
for( SCTAB nOtherTab = 0; nOtherTab < nTabCount; ++nOtherTab )
{
if( rMarkData.GetTableSelect( nOtherTab ) && (nOtherTab != nTab) )
{
mxUndoDoc->AddUndoTab( nOtherTab, nOtherTab );
mxRedoDoc->AddUndoTab( nOtherTab, nOtherTab );
}
}
}
// *** create and init the edit engine *** --------------------------------
mxEngine.reset( new ScSpellingEngine(
mpDoc->GetEnginePool(), *mpViewData, mxUndoDoc.get(), mxRedoDoc.get(), LinguMgr::GetSpellChecker() ) );
mxEngine->SetRefDevice( mpViewData->GetActiveWin() );
mpViewShell->MakeEditView( mxEngine.get(), nCol, nRow );
EditView* pEditView = mpViewData->GetEditView( mpViewData->GetActivePart() );
mpViewData->SetSpellingView( pEditView );
Rectangle aRect( Point( 0, 0 ), Point( 0, 0 ) );
pEditView->SetOutputArea( aRect );
mxEngine->SetControlWord( EE_CNTRL_USECHARATTRIBS );
mxEngine->EnableUndo( FALSE );
mxEngine->SetPaperSize( aRect.GetSize() );
mxEngine->SetText( EMPTY_STRING );
mxEngine->ClearModifyFlag();
mbNeedNextObj = true;
}
bool ScSpellDialogChildWindow::IsSelectionChanged()
{
if( !mxOldSel.get() || !mpViewShell || (mpViewShell != PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
return true;
if( EditView* pEditView = mpViewData->GetSpellingView() )
if( pEditView->GetEditEngine() != mxEngine.get() )
return true;
ScSelectionState aNewSel( *mpViewData );
return mxOldSel->GetSheetSelection() != aNewSel.GetSheetSelection();
}
// ============================================================================
<commit_msg>INTEGRATION: CWS tl55 (1.7.84); FILE MERGED 2008/06/24 08:35:05 os 1.7.84.1: #i85999# grammar checking<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: spelldialog.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "spelldialog.hxx"
#include <sfx2/app.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
#include <svx/svxids.hrc>
#include <svx/editstat.hxx>
#include <svx/editview.hxx>
#include <svx/unolingu.hxx>
#include "selectionstate.hxx"
#include "spelleng.hxx"
#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "scmod.hxx"
#include "editable.hxx"
#include "undoblk.hxx"
// ============================================================================
SFX_IMPL_CHILDWINDOW( ScSpellDialogChildWindow, SID_SPELL_DIALOG )
ScSpellDialogChildWindow::ScSpellDialogChildWindow( Window* pParentP, USHORT nId,
SfxBindings* pBindings, SfxChildWinInfo* pInfo ) :
::svx::SpellDialogChildWindow( pParentP, nId, pBindings, pInfo ),
mpViewShell( 0 ),
mpViewData( 0 ),
mpDocShell( 0 ),
mpDoc( 0 ),
mbNeedNextObj( false ),
mbOldIdleDisabled( false )
{
Init();
}
ScSpellDialogChildWindow::~ScSpellDialogChildWindow()
{
Reset();
}
SfxChildWinInfo ScSpellDialogChildWindow::GetInfo() const
{
return ::svx::SpellDialogChildWindow::GetInfo();
}
void ScSpellDialogChildWindow::InvalidateSpellDialog()
{
::svx::SpellDialogChildWindow::InvalidateSpellDialog();
}
// protected ------------------------------------------------------------------
::svx::SpellPortions ScSpellDialogChildWindow::GetNextWrongSentence()
{
::svx::SpellPortions aPortions;
if( mxEngine.get() && mpViewData )
{
if( EditView* pEditView = mpViewData->GetSpellingView() )
{
// edit engine handles cell iteration internally
do
{
if( mbNeedNextObj )
mxEngine->SpellNextDocument();
mbNeedNextObj = !mxEngine->IsFinished() && !mxEngine->SpellSentence( *pEditView, aPortions, false );
}
while( mbNeedNextObj );
}
// finished? - close the spelling dialog
if( mxEngine->IsFinished() )
GetBindings().GetDispatcher()->Execute( SID_SPELL_DIALOG, SFX_CALLMODE_ASYNCHRON );
}
return aPortions;
}
void ScSpellDialogChildWindow::ApplyChangedSentence( const ::svx::SpellPortions& rChanged )
{
if( mxEngine.get() && mpViewData )
if( EditView* pEditView = mpViewData->GetSpellingView() )
mxEngine->ApplyChangedSentence( *pEditView, rChanged, false );
}
void ScSpellDialogChildWindow::GetFocus()
{
if( IsSelectionChanged() )
{
Reset();
InvalidateSpellDialog();
Init();
}
}
void ScSpellDialogChildWindow::LoseFocus()
{
}
// private --------------------------------------------------------------------
void ScSpellDialogChildWindow::Reset()
{
if( mpViewShell && (mpViewShell == PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
{
if( mxEngine.get() && mxEngine->IsAnyModified() )
{
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCTAB nTab = rCursor.Tab();
SCCOL nOldCol = rCursor.Col();
SCROW nOldRow = rCursor.Row();
SCCOL nNewCol = mpViewData->GetCurX();
SCROW nNewRow = mpViewData->GetCurY();
mpDocShell->GetUndoManager()->AddUndoAction( new ScUndoConversion(
mpDocShell, mpViewData->GetMarkData(),
nOldCol, nOldRow, nTab, mxUndoDoc.release(),
nNewCol, nNewRow, nTab, mxRedoDoc.release(),
ScConversionParam( SC_CONVERSION_SPELLCHECK ) ) );
mpDoc->SetDirty();
mpDocShell->SetDocumentModified();
}
mpViewData->SetSpellingView( 0 );
mpViewShell->KillEditView( TRUE );
mpDocShell->PostPaintGridAll();
mpViewShell->UpdateInputHandler();
mpDoc->DisableIdle( mbOldIdleDisabled );
}
mxEngine.reset();
mxUndoDoc.reset();
mxRedoDoc.reset();
mxOldSel.reset();
mpViewShell = 0;
mpViewData = 0;
mpDocShell = 0;
mpDoc = 0;
mbNeedNextObj = false;
mbOldIdleDisabled = false;
}
void ScSpellDialogChildWindow::Init()
{
if( mpViewShell )
return;
if( (mpViewShell = PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) == 0 )
return;
mpViewData = mpViewShell->GetViewData();
// exit edit mode - TODO support spelling in edit mode
if( mpViewData->HasEditView( mpViewData->GetActivePart() ) )
SC_MOD()->InputEnterHandler();
mxOldSel.reset( new ScSelectionState( *mpViewData ) );
mpDocShell = mpViewData->GetDocShell();
mpDoc = mpDocShell->GetDocument();
const ScAddress& rCursor = mxOldSel->GetCellCursor();
SCCOL nCol = rCursor.Col();
SCROW nRow = rCursor.Row();
SCTAB nTab = rCursor.Tab();
ScMarkData& rMarkData = mpViewData->GetMarkData();
rMarkData.MarkToMulti();
switch( mxOldSel->GetSelectionType() )
{
case SC_SELECTTYPE_NONE:
case SC_SELECTTYPE_SHEET:
{
// test if there is something editable
ScEditableTester aTester( mpDoc, rMarkData );
if( !aTester.IsEditable() )
{
mpViewShell->ErrorMessage( aTester.GetMessageId() );
return;
}
}
break;
// edit mode exited, see TODO above
// case SC_SELECTTYPE_EDITCELL:
// break;
default:
DBG_ERRORFILE( "ScSpellDialogChildWindow::Init - unknown selection type" );
}
mbOldIdleDisabled = mpDoc->IsIdleDisabled();
mpDoc->DisableIdle( TRUE ); // #42726# stop online spelling
// *** create Undo/Redo documents *** -------------------------------------
mxUndoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxUndoDoc->InitUndo( mpDoc, nTab, nTab );
mxRedoDoc.reset( new ScDocument( SCDOCMODE_UNDO ) );
mxRedoDoc->InitUndo( mpDoc, nTab, nTab );
if ( rMarkData.GetSelectCount() > 1 )
{
SCTAB nTabCount = mpDoc->GetTableCount();
for( SCTAB nOtherTab = 0; nOtherTab < nTabCount; ++nOtherTab )
{
if( rMarkData.GetTableSelect( nOtherTab ) && (nOtherTab != nTab) )
{
mxUndoDoc->AddUndoTab( nOtherTab, nOtherTab );
mxRedoDoc->AddUndoTab( nOtherTab, nOtherTab );
}
}
}
// *** create and init the edit engine *** --------------------------------
mxEngine.reset( new ScSpellingEngine(
mpDoc->GetEnginePool(), *mpViewData, mxUndoDoc.get(), mxRedoDoc.get(), LinguMgr::GetSpellChecker() ) );
mxEngine->SetRefDevice( mpViewData->GetActiveWin() );
mpViewShell->MakeEditView( mxEngine.get(), nCol, nRow );
EditView* pEditView = mpViewData->GetEditView( mpViewData->GetActivePart() );
mpViewData->SetSpellingView( pEditView );
Rectangle aRect( Point( 0, 0 ), Point( 0, 0 ) );
pEditView->SetOutputArea( aRect );
mxEngine->SetControlWord( EE_CNTRL_USECHARATTRIBS );
mxEngine->EnableUndo( FALSE );
mxEngine->SetPaperSize( aRect.GetSize() );
mxEngine->SetText( EMPTY_STRING );
mxEngine->ClearModifyFlag();
mbNeedNextObj = true;
}
bool ScSpellDialogChildWindow::IsSelectionChanged()
{
if( !mxOldSel.get() || !mpViewShell || (mpViewShell != PTR_CAST( ScTabViewShell, SfxViewShell::Current() )) )
return true;
if( EditView* pEditView = mpViewData->GetSpellingView() )
if( pEditView->GetEditEngine() != mxEngine.get() )
return true;
ScSelectionState aNewSel( *mpViewData );
return mxOldSel->GetSheetSelection() != aNewSel.GetSheetSelection();
}
// ============================================================================
<|endoftext|> |
<commit_before>#include <iostream>
#include <conio.h>
#include <vector>
#include <Windows.h>
#include "..\include\Common.h"
#include "..\include\Gambling.h"
#include "..\include\Player.h"
using namespace std;
using namespace Common;
// Contains the functions needed to simulate a gamble for items.
void Gambling::Gamble(Player *_Player){
// A gambling arena, in which the die you roll must be equal or higher than requirement
// Uses the Player object passed in to give won items to player.
/// Maybe check Coins? If too low then can't gamble.
// Generates random values for the local variables declared in the class.
GenerateValues();
// check if the player has enough money to play
if (_Player->GetCoins() < CoinsDeduction) {
// the player does not have enough money
cout << "You need at least " << CoinsDeduction << " coins to gamble." << endl << "0 - 9) Understood" << endl;
Sleep(SLEEP_MS);
return;
}
// Player's die. Equal to a random number between 1 and 9.
int Die=ReturnShakenDie();
// Initialized to analyze user input.
int choice = 0;
// Loops until player chooses to reveal die.
while (choice!=1){
/// Since the ClearScreen() method is in class Game, system("CLS") is used instead.
/// Must fix.
ClearScreen();
// Prints required die number to win gamble.
/// Currently says 'REQUIREMENT: 9 and over' when DieRequirement==9, when dies cannot go over 9.
cout << endl << "REQUIREMENT: " << DieRequirement << " and over" << endl;
// Prints the amount of items received if gamble is won.
cout << "PRIZE: [" << ItemNumber << "] ";
// Prints the item name according to the char Item.
switch(Item){
case 0:
cout << "arrows" << endl;
break;
case 1:
cout << "bombs" << endl;
break;
case 2:
cout << "potions" << endl;
break;
case 3:
cout << "whetstones" << endl;
break;
default:
// No default, since ReturnItem(), which GenerateValue() calls, already has one.
// Technically impossible for char Item to be other than b, p, w, a.
break;
}
// Prints Coins deduction if you lose the gamble.
cout << "PENALTY: [" << CoinsDeduction << "] coins" << endl << endl;
cout << "1) Reveal Die" << endl;
cout << "2) Shake Die" << endl;
cout << "3) Pass" << endl << "\n";
choice = input();
switch (choice){
case 1:
// Only breaks because the loop stops since choice==1.
break;
case 2:
cout << "You shake the die." << endl;
Sleep(SLEEP_MS);
// Generates another random number for the die, simulating the real life die shake.
Die=ReturnShakenDie();
break;
case 3:
// Returns to Intermission().
return;
default:
break;
}
}
// Prints what you rolled.
cout << "You rolled a " << Die << "." << endl;
Sleep(SLEEP_MS);
// Evaluates whether or not you won the bet.
if (Die>=DieRequirement)
// Passes in Player object to give player the items won.
WinGamble(_Player);
else
// Passes in Player object to deduct experience from the player for losing the gamble.
LoseGamble(_Player);
}
void Gambling::GenerateValues(){
// Generates values for the variables used in the gamble.
// Generates a number between 1 and 9, the number that the player's die must be equal to or greater than.
DieRequirement=1+rand()%9;
// The amount of items won if the player win the gamble.
ItemNumber=1+rand()%4;
// The amount of experience lost if the player loses the gamble.
CoinsDeduction=100;
// Initializes Item equal to a random char to indicate the item won.
Item=ReturnItem();
}
int Gambling::ReturnShakenDie(){
// Returns a random integer between 1 and 9.
return 1+rand()%9;
}
char Gambling::ReturnItem(){
// Generates a random char with a random integer selector, indicating the item won in the gamble.
int selector=rand()%4;
switch(selector){
case 0:
// Arrows are the item.
return 0;
case 1:
// Bombs are the item.
return 1;
case 2:
// Potions are the item.
return 2;
case 3:
// Whetstones are the item.
return 3;
default:
// By default, arrows are the item if the random integer does not equal any of the above cases.
return 0;
}
}
void Gambling::WinGamble(Player *_Player){
// Executes the events when the gamble is won.
// Uses the Player object to give player items won.
cout << "You win the bet!" << endl;
vector<int> drops;
for (int i = 0; i < NUM_ITEMS; i++) {
drops.push_back((Item == i) ? ItemNumber : 0);
}
// Evaluates local class variable Item to see what item was won.
// ItemNumber is passed in to AddToInventory() to provide the number of items won.
// The place of ItemNumber in the arguments is to specify which item was won.
// More clarification and information in the _Player->AddToInventory(int, int, int ,int) function.
_Player->AddToInventory(drops);
// Used to pause the console to let the player see what they won.
/// Must use something more efficient.
system("PAUSE");
}
void Gambling::LoseGamble(Player *_Player){
// Executes the events when gamble is lost.
// Uses the Player object passed in to deduct experience.
cout << "You lost the bet! You lose " << CoinsDeduction << " coins!" << endl;
// Deducts the player's experience.
_Player->LoseCoins(CoinsDeduction);
system("PAUSE");
}
<commit_msg>Remove input message<commit_after>#include <iostream>
#include <conio.h>
#include <vector>
#include <Windows.h>
#include "..\include\Common.h"
#include "..\include\Gambling.h"
#include "..\include\Player.h"
using namespace std;
using namespace Common;
// Contains the functions needed to simulate a gamble for items.
void Gambling::Gamble(Player *_Player){
// A gambling arena, in which the die you roll must be equal or higher than requirement
// Uses the Player object passed in to give won items to player.
/// Maybe check Coins? If too low then can't gamble.
// Generates random values for the local variables declared in the class.
GenerateValues();
// check if the player has enough money to play
if (_Player->GetCoins() < CoinsDeduction) {
// the player does not have enough money
cout << "You need at least " << CoinsDeduction << " coins to gamble." << endl;
Sleep(SLEEP_MS);
return;
}
// Player's die. Equal to a random number between 1 and 9.
int Die=ReturnShakenDie();
// Initialized to analyze user input.
int choice = 0;
// Loops until player chooses to reveal die.
while (choice!=1){
/// Since the ClearScreen() method is in class Game, system("CLS") is used instead.
/// Must fix.
ClearScreen();
// Prints required die number to win gamble.
/// Currently says 'REQUIREMENT: 9 and over' when DieRequirement==9, when dies cannot go over 9.
cout << endl << "REQUIREMENT: " << DieRequirement << " and over" << endl;
// Prints the amount of items received if gamble is won.
cout << "PRIZE: [" << ItemNumber << "] ";
// Prints the item name according to the char Item.
switch(Item){
case 0:
cout << "arrows" << endl;
break;
case 1:
cout << "bombs" << endl;
break;
case 2:
cout << "potions" << endl;
break;
case 3:
cout << "whetstones" << endl;
break;
default:
// No default, since ReturnItem(), which GenerateValue() calls, already has one.
// Technically impossible for char Item to be other than b, p, w, a.
break;
}
// Prints Coins deduction if you lose the gamble.
cout << "PENALTY: [" << CoinsDeduction << "] coins" << endl << endl;
cout << "1) Reveal Die" << endl;
cout << "2) Shake Die" << endl;
cout << "3) Pass" << endl << "\n";
choice = input();
switch (choice){
case 1:
// Only breaks because the loop stops since choice==1.
break;
case 2:
cout << "You shake the die." << endl;
Sleep(SLEEP_MS);
// Generates another random number for the die, simulating the real life die shake.
Die=ReturnShakenDie();
break;
case 3:
// Returns to Intermission().
return;
default:
break;
}
}
// Prints what you rolled.
cout << "You rolled a " << Die << "." << endl;
Sleep(SLEEP_MS);
// Evaluates whether or not you won the bet.
if (Die>=DieRequirement)
// Passes in Player object to give player the items won.
WinGamble(_Player);
else
// Passes in Player object to deduct experience from the player for losing the gamble.
LoseGamble(_Player);
}
void Gambling::GenerateValues(){
// Generates values for the variables used in the gamble.
// Generates a number between 1 and 9, the number that the player's die must be equal to or greater than.
DieRequirement=1+rand()%9;
// The amount of items won if the player win the gamble.
ItemNumber=1+rand()%4;
// The amount of experience lost if the player loses the gamble.
CoinsDeduction=100;
// Initializes Item equal to a random char to indicate the item won.
Item=ReturnItem();
}
int Gambling::ReturnShakenDie(){
// Returns a random integer between 1 and 9.
return 1+rand()%9;
}
char Gambling::ReturnItem(){
// Generates a random char with a random integer selector, indicating the item won in the gamble.
int selector=rand()%4;
switch(selector){
case 0:
// Arrows are the item.
return 0;
case 1:
// Bombs are the item.
return 1;
case 2:
// Potions are the item.
return 2;
case 3:
// Whetstones are the item.
return 3;
default:
// By default, arrows are the item if the random integer does not equal any of the above cases.
return 0;
}
}
void Gambling::WinGamble(Player *_Player){
// Executes the events when the gamble is won.
// Uses the Player object to give player items won.
cout << "You win the bet!" << endl;
vector<int> drops;
for (int i = 0; i < NUM_ITEMS; i++) {
drops.push_back((Item == i) ? ItemNumber : 0);
}
// Evaluates local class variable Item to see what item was won.
// ItemNumber is passed in to AddToInventory() to provide the number of items won.
// The place of ItemNumber in the arguments is to specify which item was won.
// More clarification and information in the _Player->AddToInventory(int, int, int ,int) function.
_Player->AddToInventory(drops);
// Used to pause the console to let the player see what they won.
/// Must use something more efficient.
system("PAUSE");
}
void Gambling::LoseGamble(Player *_Player){
// Executes the events when gamble is lost.
// Uses the Player object passed in to deduct experience.
cout << "You lost the bet! You lose " << CoinsDeduction << " coins!" << endl;
// Deducts the player's experience.
_Player->LoseCoins(CoinsDeduction);
system("PAUSE");
}
<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "array.h"
#include "benchmark.h"
#include <random>
#include <iostream>
using namespace nda;
// The standard matrix notation is to refer to elements by 'row,
// column'. To make this efficient for typical programs, we're going
// to make the second dimension the dense dim. This shape has the
// option of making the size of the matrix compile-time constant via
// the template parameters.
template <index_t Rows = UNK, index_t Cols = UNK>
using matrix_shape = shape<dim<UNK, Rows>, dense_dim<UNK, Cols>>;
// A matrix or matrix_ref is an array or array_ref with Shape =
// matrix_shape.
template <typename T, index_t Rows = UNK, index_t Cols = UNK,
typename Alloc = std::allocator<T>>
using matrix = array<T, matrix_shape<Rows, Cols>, Alloc>;
template <typename T, index_t Rows = UNK, index_t Cols = UNK>
using matrix_ref = array_ref<T, matrix_shape<Rows, Cols>>;
// A textbook implementation of matrix multiplication. This is very simple,
// but it is slow, primarily because of poor locality of the loads of b. The
// reduction loop is innermost.
template <typename TAB, typename TC, index_t Rows, index_t Cols>
__attribute__((noinline))
void multiply_reduce_cols(const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC, Rows, Cols>& c) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) = 0;
for (index_t k : a.j()) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// This implementation moves the reduction loop between the rows and columns
// loops. This avoids the locality problem for the loads from b. This also is
// an easier loop to vectorize (it does not vectorize a reduction variable).
template <typename TAB, typename TC, index_t Rows, index_t Cols>
__attribute__((noinline))
void multiply_reduce_rows(const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC, Rows, Cols>& c) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) = 0;
}
for (index_t k : a.j()) {
for (index_t j : c.j()) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// This implementation reorders the reduction loop innermost. This vectorizes
// well, but has poor locality. However, this will be a useful helper function
// for the tiled implementation below.
template <typename TAB, typename TC, index_t Rows, index_t Cols>
__attribute__((always_inline))
void multiply_reduce_matrices(const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC, Rows, Cols>& c) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) = 0;
}
}
for (index_t k : a.j()) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// This implementation of matrix multiplication splits the loops over
// the output matrix into chunks, and reorders the small loops
// innermost to form tiles. This implementation should allow the compiler
// to keep all of the accumulators for the output in registers.
// For the matrix size benchmarked in main, this runs in ~0.44ms.
// This appears to achieve ~70% of the peak theoretical throughput
// of my machine.
template <typename TAB, typename TC>
__attribute__((noinline))
void multiply_reduce_tiles(const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC>& c) {
// Adjust this depending on the target architecture. For AVX2,
// vectors are 256-bit.
constexpr index_t vector_size = 32 / sizeof(TC);
// We want the tiles to be as big as possible without spilling any
// of the accumulator registers to the stack.
constexpr index_t tile_rows = 3;
constexpr index_t tile_cols = vector_size * 4;
for (auto io : split<tile_rows>(c.i())) {
for (auto jo : split<tile_cols>(c.j())) {
// Make a reference to this tile of the output.
auto c_tile = c(io, jo);
#if 0
// TODO: This should work, but it's slow, probably due to potential
// aliasing that we can't fix due to https://bugs.llvm.org/show_bug.cgi?id=45863
multiply_reduce_matrices(a, b, c_tile);
#elif 0
// TODO: This should work, but it's slow, probably due to potential
// aliasing that we can't fix due to https://bugs.llvm.org/show_bug.cgi?id=45863
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
c_tile(i, j) = 0;
}
}
for (index_t k : a.j()) {
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
c_tile(i, j) += a(i, k) * b(k, j);
}
}
}
#else
TC buffer[tile_rows * tile_cols] = { 0.0f };
auto accumulator = make_array_ref(buffer, make_compact(c_tile.shape()));
for (index_t k : a.j()) {
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
accumulator(i, j) += a(i, k) * b(k, j);
}
}
}
#if 0
// TODO: This should work, but it's slow, it appears to
// blow up the nice in-register accumulation of the loop
// above.
copy(accumulator, c_tile);
#else
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
c_tile(i, j) = accumulator(i, j);
}
}
#endif
#endif
}
}
}
int main(int, const char**) {
// Define two input matrices.
constexpr index_t M = 24;
constexpr index_t K = 10000;
constexpr index_t N = 64;
matrix<float> a({M, K});
matrix<float> b({K, N});
// 'for_each_value' calls the given function with a reference to
// each value in the array. Use this to randomly initialize the
// matrices with random values.
std::mt19937_64 rng;
std::uniform_real_distribution<float> uniform(0, 1);
a.for_each_value([&](float& x) { x = uniform(rng); });
b.for_each_value([&](float& x) { x = uniform(rng); });
// Compute the result using all matrix multiply methods.
matrix<float> c_reduce_cols({M, N});
double reduce_cols_time = benchmark([&]() {
multiply_reduce_cols(a.ref(), b.ref(), c_reduce_cols.ref());
});
std::cout << "reduce_cols time: " << reduce_cols_time * 1e3 << " ms" << std::endl;
matrix<float> c_reduce_rows({M, N});
double reduce_rows_time = benchmark([&]() {
multiply_reduce_rows(a.ref(), b.ref(), c_reduce_rows.ref());
});
std::cout << "reduce_rows time: " << reduce_rows_time * 1e3 << " ms" << std::endl;
matrix<float> c_reduce_tiles({M, N});
double reduce_tiles_time = benchmark([&]() {
multiply_reduce_tiles(a.ref(), b.ref(), c_reduce_tiles.ref());
});
std::cout << "reduce_tiles time: " << reduce_tiles_time * 1e3 << " ms" << std::endl;
// Verify the results from all methods are equal.
const float epsilon = 1e-4f;
for (index_t i = 0; i < M; i++) {
for (index_t j = 0; j < N; j++) {
if (std::abs(c_reduce_rows(i, j) - c_reduce_cols(i, j)) > epsilon) {
std::cout
<< "c_reduce_rows(" << i << ", " << j << ") = " << c_reduce_rows(i, j)
<< " != c_reduce_cols(" << i << ", " << j << ") = " << c_reduce_cols(i, j) << std::endl;
return -1;
}
if (std::abs(c_reduce_tiles(i, j) - c_reduce_cols(i, j)) > epsilon) {
std::cout
<< "c_reduce_tiles(" << i << ", " << j << ") = " << c_reduce_tiles(i, j)
<< " != c_reduce_cols(" << i << ", " << j << ") = " << c_reduce_cols(i, j) << std::endl;
return -1;
}
}
}
return 0;
}
<commit_msg>Add C version of multiply_reduce_cols.<commit_after>// Copyright 2019 Google LLC
//
// 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
//
// https://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 "array.h"
#include "benchmark.h"
#include <random>
#include <iostream>
using namespace nda;
// The standard matrix notation is to refer to elements by 'row,
// column'. To make this efficient for typical programs, we're going
// to make the second dimension the dense dim. This shape has the
// option of making the size of the matrix compile-time constant via
// the template parameters.
template <index_t Rows = UNK, index_t Cols = UNK>
using matrix_shape = shape<dim<UNK, Rows>, dense_dim<UNK, Cols>>;
// A matrix or matrix_ref is an array or array_ref with Shape =
// matrix_shape.
template <typename T, index_t Rows = UNK, index_t Cols = UNK,
typename Alloc = std::allocator<T>>
using matrix = array<T, matrix_shape<Rows, Cols>, Alloc>;
template <typename T, index_t Rows = UNK, index_t Cols = UNK>
using matrix_ref = array_ref<T, matrix_shape<Rows, Cols>>;
// A textbook implementation of matrix multiplication. This is very simple,
// but it is slow, primarily because of poor locality of the loads of b. The
// reduction loop is innermost.
template <typename TAB, typename TC, index_t Rows, index_t Cols>
__attribute__((noinline))
void multiply_reduce_cols(
const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC, Rows, Cols>& c) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) = 0;
for (index_t k : a.j()) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// Similar to the above, but written in plain C. The timing of this version
// indicates the performance overhead (if any) of the array helpers.
template <typename TAB, typename TC>
__attribute__((noinline))
void multiply_reduce_cols_native(
const TAB* a, const TAB* b, TC* c, int M, int K, int N) {
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
TC sum = 0;
for (int k = 0; k < K; k++) {
sum += a[i * K + k] * b[k * N + j];
}
c[i * N + j] = sum;
}
}
}
// This implementation moves the reduction loop between the rows and columns
// loops. This avoids the locality problem for the loads from b. This also is
// an easier loop to vectorize (it does not vectorize a reduction variable).
template <typename TAB, typename TC, index_t Rows, index_t Cols>
__attribute__((noinline))
void multiply_reduce_rows(
const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC, Rows, Cols>& c) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) = 0;
}
for (index_t k : a.j()) {
for (index_t j : c.j()) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// This implementation reorders the reduction loop innermost. This vectorizes
// well, but has poor locality. However, this will be a useful helper function
// for the tiled implementation below.
template <typename TAB, typename TC, index_t Rows, index_t Cols>
__attribute__((always_inline))
void multiply_reduce_matrices(
const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC, Rows, Cols>& c) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) = 0;
}
}
for (index_t k : a.j()) {
for (index_t i : c.i()) {
for (index_t j : c.j()) {
c(i, j) += a(i, k) * b(k, j);
}
}
}
}
// This implementation of matrix multiplication splits the loops over
// the output matrix into chunks, and reorders the small loops
// innermost to form tiles. This implementation should allow the compiler
// to keep all of the accumulators for the output in registers.
// For the matrix size benchmarked in main, this runs in ~0.44ms.
// This appears to achieve ~70% of the peak theoretical throughput
// of my machine.
template <typename TAB, typename TC>
__attribute__((noinline))
void multiply_reduce_tiles(
const matrix_ref<TAB>& a, const matrix_ref<TAB>& b,
const matrix_ref<TC>& c) {
// Adjust this depending on the target architecture. For AVX2,
// vectors are 256-bit.
constexpr index_t vector_size = 32 / sizeof(TC);
// We want the tiles to be as big as possible without spilling any
// of the accumulator registers to the stack.
constexpr index_t tile_rows = 3;
constexpr index_t tile_cols = vector_size * 4;
for (auto io : split<tile_rows>(c.i())) {
for (auto jo : split<tile_cols>(c.j())) {
// Make a reference to this tile of the output.
auto c_tile = c(io, jo);
#if 0
// TODO: This should work, but it's slow, probably due to potential
// aliasing that we can't fix due to https://bugs.llvm.org/show_bug.cgi?id=45863
multiply_reduce_matrices(a, b, c_tile);
#elif 0
// TODO: This should work, but it's slow, probably due to potential
// aliasing that we can't fix due to https://bugs.llvm.org/show_bug.cgi?id=45863
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
c_tile(i, j) = 0;
}
}
for (index_t k : a.j()) {
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
c_tile(i, j) += a(i, k) * b(k, j);
}
}
}
#else
TC buffer[tile_rows * tile_cols] = { 0.0f };
auto accumulator = make_array_ref(buffer, make_compact(c_tile.shape()));
for (index_t k : a.j()) {
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
accumulator(i, j) += a(i, k) * b(k, j);
}
}
}
#if 0
// TODO: This should work, but it's slow, it appears to
// blow up the nice in-register accumulation of the loop
// above.
copy(accumulator, c_tile);
#else
for (index_t i : c_tile.i()) {
for (index_t j : c_tile.j()) {
c_tile(i, j) = accumulator(i, j);
}
}
#endif
#endif
}
}
}
float relative_error(float a, float b) {
return std::abs(a - b) / std::max(a, b);
}
int main(int, const char**) {
// Define two input matrices.
constexpr index_t M = 24;
constexpr index_t K = 10000;
constexpr index_t N = 64;
matrix<float> a({M, K});
matrix<float> b({K, N});
// 'for_each_value' calls the given function with a reference to
// each value in the array. Use this to randomly initialize the
// matrices with random values.
std::mt19937_64 rng;
std::uniform_real_distribution<float> uniform(0, 1);
a.for_each_value([&](float& x) { x = uniform(rng); });
b.for_each_value([&](float& x) { x = uniform(rng); });
// Compute the result using all matrix multiply methods.
matrix<float> c_reduce_cols({M, N});
double reduce_cols_time = benchmark([&]() {
multiply_reduce_cols(a.ref(), b.ref(), c_reduce_cols.ref());
});
std::cout << "reduce_cols time: " << reduce_cols_time * 1e3 << " ms" << std::endl;
matrix<float> c_reduce_cols_native({M, N});
double reduce_cols_native_time = benchmark([&]() {
multiply_reduce_cols_native(a.data(), b.data(), c_reduce_cols_native.data(), M, K, N);
});
std::cout << "reduce_cols_native time: " << reduce_cols_native_time * 1e3 << " ms" << std::endl;
matrix<float> c_reduce_rows({M, N});
double reduce_rows_time = benchmark([&]() {
multiply_reduce_rows(a.ref(), b.ref(), c_reduce_rows.ref());
});
std::cout << "reduce_rows time: " << reduce_rows_time * 1e3 << " ms" << std::endl;
matrix<float> c_reduce_tiles({M, N});
double reduce_tiles_time = benchmark([&]() {
multiply_reduce_tiles(a.ref(), b.ref(), c_reduce_tiles.ref());
});
std::cout << "reduce_tiles time: " << reduce_tiles_time * 1e3 << " ms" << std::endl;
// Verify the results from all methods are equal.
const float tolerance = 1e-4f;
for (index_t i = 0; i < M; i++) {
for (index_t j = 0; j < N; j++) {
if (relative_error(c_reduce_cols_native(i, j), c_reduce_cols(i, j)) > tolerance) {
std::cout
<< "c_reduce_cols_native(" << i << ", " << j << ") = " << c_reduce_cols_native(i, j)
<< " != c_reduce_cols(" << i << ", " << j << ") = " << c_reduce_cols(i, j) << std::endl;
return -1;
}
if (relative_error(c_reduce_rows(i, j), c_reduce_cols(i, j)) > tolerance) {
std::cout
<< "c_reduce_rows(" << i << ", " << j << ") = " << c_reduce_rows(i, j)
<< " != c_reduce_cols(" << i << ", " << j << ") = " << c_reduce_cols(i, j) << std::endl;
return -1;
}
if (relative_error(c_reduce_tiles(i, j), c_reduce_cols(i, j)) > tolerance) {
std::cout
<< "c_reduce_tiles(" << i << ", " << j << ") = " << c_reduce_tiles(i, j)
<< " != c_reduce_cols(" << i << ", " << j << ") = " << c_reduce_cols(i, j) << std::endl;
return -1;
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* AliFemtoPPbpbLamZVtxMultContainer.cxx
*
* Created on: Aug 30, 2017
* Author: gu74req
*/
//#include "AliLog.h"
#include <iostream>
#include "AliFemtoDreamZVtxMultContainer.h"
#include "TLorentzVector.h"
#include "TDatabasePDG.h"
#include "TVector2.h"
ClassImp(AliFemtoDreamPartContainer)
AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer()
: fPartContainer(0),
fPDGParticleSpecies(0),
fWhichPairs(){
}
AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer(
AliFemtoDreamCollConfig *conf)
: fPartContainer(conf->GetNParticles(),
AliFemtoDreamPartContainer(conf->GetMixingDepth())),
fPDGParticleSpecies(conf->GetPDGCodes()),
fWhichPairs(conf->GetWhichPairs()){
TDatabasePDG::Instance()->AddParticle("deuteron", "deuteron", 1.8756134,
kTRUE, 0.0, 1, "Nucleus", 1000010020);
TDatabasePDG::Instance()->AddAntiParticle("anti-deuteron", -1000010020);
}
AliFemtoDreamZVtxMultContainer::~AliFemtoDreamZVtxMultContainer() {
// TODO Auto-generated destructor stub
}
void AliFemtoDreamZVtxMultContainer::SetEvent(
std::vector<std::vector<AliFemtoDreamBasePart>> &Particles) {
//This method sets the particles of an event only in the case, that
//more than one particle was identified, to avoid empty events.
// if (Particles->size()!=fParticleSpecies){
// TString errMessage = Form("Number of Input Particlese (%d) doese not"
// "correspond to the Number of particles Set (%d)",Particles->size(),
// fParticleSpecies);
// AliFatal(errMessage.Data());
// } else {
std::vector<std::vector<AliFemtoDreamBasePart>>::iterator itInput = Particles
.begin();
std::vector<AliFemtoDreamPartContainer>::iterator itContainer = fPartContainer
.begin();
while (itContainer != fPartContainer.end()) {
if (itInput->size() > 0) {
itContainer->SetEvent(*itInput);
}
++itInput;
++itContainer;
}
// }
}
void AliFemtoDreamZVtxMultContainer::PairParticlesSE(
std::vector<std::vector<AliFemtoDreamBasePart>> &Particles,
AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) {
float RelativeK = 0;
int HistCounter = 0;
//First loop over all the different Species
auto itPDGPar1 = fPDGParticleSpecies.begin();
for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end();
++itSpec1) {
auto itPDGPar2 = fPDGParticleSpecies.begin();
itPDGPar2 += itSpec1 - Particles.begin();
for (auto itSpec2 = itSpec1; itSpec2 != Particles.end(); ++itSpec2) {
HigherMath->FillPairCounterSE(HistCounter, itSpec1->size(),
itSpec2->size());
//Now loop over the actual Particles and correlate them
for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end();
++itPart1) {
AliFemtoDreamBasePart part1 = *itPart1;
std::vector<AliFemtoDreamBasePart>::iterator itPart2;
if (itSpec1 == itSpec2) {
itPart2 = itPart1 + 1;
} else {
itPart2 = itSpec2->begin();
}
while (itPart2 != itSpec2->end()) {
AliFemtoDreamBasePart part2 = *itPart2;
// Delta eta - Delta phi* cut
if (fDoDeltaEtaDeltaPhiCut && CPR) {
if (!HigherMath->PassesPairSelection(*itPart1, *itPart2, false)) {
++itPart2;
continue;
}
}
RelativeK = HigherMath->FillSameEvent(HistCounter, iMult, cent,
itPart1->GetMomentum(),
*itPDGPar1,
itPart2->GetMomentum(),
*itPDGPar2);
HigherMath->MassQA(HistCounter, RelativeK, *itPart1, *itPart2);
HigherMath->SEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1,
*itPart2, *itPDGPar2, RelativeK, false);
HigherMath->SEMomentumResolution(HistCounter, &(*itPart1), *itPDGPar1,
&(*itPart2), *itPDGPar2, RelativeK);
++itPart2;
}
}
++HistCounter;
itPDGPar2++;
}
itPDGPar1++;
}
}
void AliFemtoDreamZVtxMultContainer::PairParticlesME(
std::vector<std::vector<AliFemtoDreamBasePart>> &Particles,
AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) {
float RelativeK = 0;
int HistCounter = 0;
auto itPDGPar1 = fPDGParticleSpecies.begin();
//First loop over all the different Species
for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end();
++itSpec1) {
//We dont want to correlate the particles twice. Mixed Event Dist. of
//Particle1 + Particle2 == Particle2 + Particle 1
int SkipPart = itSpec1 - Particles.begin();
auto itPDGPar2 = fPDGParticleSpecies.begin() + SkipPart;
for (auto itSpec2 = fPartContainer.begin() + SkipPart;
itSpec2 != fPartContainer.end(); ++itSpec2) {
if (itSpec1->size() > 0) {
HigherMath->FillEffectiveMixingDepth(HistCounter,
(int) itSpec2->GetMixingDepth());
}
for (int iDepth = 0; iDepth < (int) itSpec2->GetMixingDepth(); ++iDepth) {
std::vector<AliFemtoDreamBasePart> ParticlesOfEvent = itSpec2->GetEvent(
iDepth);
HigherMath->FillPairCounterME(HistCounter, itSpec1->size(),
ParticlesOfEvent.size());
for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end();
++itPart1) {
for (auto itPart2 = ParticlesOfEvent.begin();
itPart2 != ParticlesOfEvent.end(); ++itPart2) {
if (fDoDeltaEtaDeltaPhiCut && CPR) {
if (!HigherMath->PassesPairSelection(*itPart1, *itPart2, false)) {
continue;
}
}
RelativeK = HigherMath->FillMixedEvent(
HistCounter, iMult, cent, itPart1->GetMomentum(), *itPDGPar1,
itPart2->GetMomentum(), *itPDGPar2,
AliFemtoDreamCollConfig::kNone);
HigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1,
*itPart2, *itPDGPar2, RelativeK, false);
HigherMath->MEMomentumResolution(HistCounter, &(*itPart1),
*itPDGPar1, &(*itPart2),
*itPDGPar2, RelativeK);
}
}
}
++HistCounter;
++itPDGPar2;
}
++itPDGPar1;
}
}
<commit_msg>Applies changes for new cpr and phi at rad plots<commit_after>/*
* AliFemtoPPbpbLamZVtxMultContainer.cxx
*
* Created on: Aug 30, 2017
* Author: gu74req
*/
//#include "AliLog.h"
#include <iostream>
#include "AliFemtoDreamZVtxMultContainer.h"
#include "TLorentzVector.h"
#include "TDatabasePDG.h"
#include "TVector2.h"
ClassImp(AliFemtoDreamPartContainer)
AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer()
: fPartContainer(0),
fPDGParticleSpecies(0),
fWhichPairs(){
}
AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer(
AliFemtoDreamCollConfig *conf)
: fPartContainer(conf->GetNParticles(),
AliFemtoDreamPartContainer(conf->GetMixingDepth())),
fPDGParticleSpecies(conf->GetPDGCodes()),
fWhichPairs(conf->GetWhichPairs()){
TDatabasePDG::Instance()->AddParticle("deuteron", "deuteron", 1.8756134,
kTRUE, 0.0, 1, "Nucleus", 1000010020);
TDatabasePDG::Instance()->AddAntiParticle("anti-deuteron", -1000010020);
}
AliFemtoDreamZVtxMultContainer::~AliFemtoDreamZVtxMultContainer() {
// TODO Auto-generated destructor stub
}
void AliFemtoDreamZVtxMultContainer::SetEvent(
std::vector<std::vector<AliFemtoDreamBasePart>> &Particles) {
//This method sets the particles of an event only in the case, that
//more than one particle was identified, to avoid empty events.
// if (Particles->size()!=fParticleSpecies){
// TString errMessage = Form("Number of Input Particlese (%d) doese not"
// "correspond to the Number of particles Set (%d)",Particles->size(),
// fParticleSpecies);
// AliFatal(errMessage.Data());
// } else {
std::vector<std::vector<AliFemtoDreamBasePart>>::iterator itInput = Particles
.begin();
std::vector<AliFemtoDreamPartContainer>::iterator itContainer = fPartContainer
.begin();
while (itContainer != fPartContainer.end()) {
if (itInput->size() > 0) {
itContainer->SetEvent(*itInput);
}
++itInput;
++itContainer;
}
// }
}
void AliFemtoDreamZVtxMultContainer::PairParticlesSE(
std::vector<std::vector<AliFemtoDreamBasePart>> &Particles,
AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) {
float RelativeK = 0;
int HistCounter = 0;
//First loop over all the different Species
auto itPDGPar1 = fPDGParticleSpecies.begin();
for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end();
++itSpec1) {
auto itPDGPar2 = fPDGParticleSpecies.begin();
itPDGPar2 += itSpec1 - Particles.begin();
for (auto itSpec2 = itSpec1; itSpec2 != Particles.end(); ++itSpec2) {
HigherMath->FillPairCounterSE(HistCounter, itSpec1->size(),
itSpec2->size());
//Now loop over the actual Particles and correlate them
for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end();
++itPart1) {
AliFemtoDreamBasePart part1 = *itPart1;
std::vector<AliFemtoDreamBasePart>::iterator itPart2;
if (itSpec1 == itSpec2) {
itPart2 = itPart1 + 1;
} else {
itPart2 = itSpec2->begin();
}
while (itPart2 != itSpec2->end()) {
AliFemtoDreamBasePart part2 = *itPart2;
TLorentzVector PartOne, PartTwo;
PartOne.SetXYZM(
itPart1->GetMomentum().X(), itPart1->GetMomentum().Y(),
itPart1->GetMomentum().Z(),
TDatabasePDG::Instance()->GetParticle(*itPDGPar1)->Mass());
PartTwo.SetXYZM(
itPart2->GetMomentum().X(), itPart2->GetMomentum().Y(),
itPart2->GetMomentum().Z(),
TDatabasePDG::Instance()->GetParticle(*itPDGPar2)->Mass());
float RelativeK = HigherMath->RelativePairMomentum(PartOne, PartTwo);
if (!HigherMath->PassesPairSelection(HistCounter, *itPart1, *itPart2,
RelativeK, true, false)) {
++itPart2;
continue;
}
RelativeK = HigherMath->FillSameEvent(HistCounter, iMult, cent,
itPart1->GetMomentum(),
*itPDGPar1,
itPart2->GetMomentum(),
*itPDGPar2);
HigherMath->MassQA(HistCounter, RelativeK, *itPart1, *itPart2);
HigherMath->SEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1,
*itPart2, *itPDGPar2, RelativeK, false);
HigherMath->SEMomentumResolution(HistCounter, &(*itPart1), *itPDGPar1,
&(*itPart2), *itPDGPar2, RelativeK);
++itPart2;
}
}
++HistCounter;
itPDGPar2++;
}
itPDGPar1++;
}
}
void AliFemtoDreamZVtxMultContainer::PairParticlesME(
std::vector<std::vector<AliFemtoDreamBasePart>> &Particles,
AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) {
float RelativeK = 0;
int HistCounter = 0;
auto itPDGPar1 = fPDGParticleSpecies.begin();
//First loop over all the different Species
for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end();
++itSpec1) {
//We dont want to correlate the particles twice. Mixed Event Dist. of
//Particle1 + Particle2 == Particle2 + Particle 1
int SkipPart = itSpec1 - Particles.begin();
auto itPDGPar2 = fPDGParticleSpecies.begin() + SkipPart;
for (auto itSpec2 = fPartContainer.begin() + SkipPart;
itSpec2 != fPartContainer.end(); ++itSpec2) {
if (itSpec1->size() > 0) {
HigherMath->FillEffectiveMixingDepth(HistCounter,
(int) itSpec2->GetMixingDepth());
}
for (int iDepth = 0; iDepth < (int) itSpec2->GetMixingDepth(); ++iDepth) {
std::vector<AliFemtoDreamBasePart> ParticlesOfEvent = itSpec2->GetEvent(
iDepth);
HigherMath->FillPairCounterME(HistCounter, itSpec1->size(),
ParticlesOfEvent.size());
for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end();
++itPart1) {
for (auto itPart2 = ParticlesOfEvent.begin();
itPart2 != ParticlesOfEvent.end(); ++itPart2) {
TLorentzVector PartOne, PartTwo;
PartOne.SetXYZM(
itPart1->GetMomentum().X(), itPart1->GetMomentum().Y(),
itPart1->GetMomentum().Z(),
TDatabasePDG::Instance()->GetParticle(*itPDGPar1)->Mass());
PartTwo.SetXYZM(
itPart2->GetMomentum().X(), itPart2->GetMomentum().Y(),
itPart2->GetMomentum().Z(),
TDatabasePDG::Instance()->GetParticle(*itPDGPar2)->Mass());
float RelativeK = HigherMath->RelativePairMomentum(PartOne, PartTwo);
if (!HigherMath->PassesPairSelection(HistCounter, *itPart1, *itPart2,
RelativeK, false, false)) {
continue;
}
RelativeK = HigherMath->FillMixedEvent(
HistCounter, iMult, cent, itPart1->GetMomentum(), *itPDGPar1,
itPart2->GetMomentum(), *itPDGPar2,
AliFemtoDreamCollConfig::kNone);
HigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1,
*itPart2, *itPDGPar2, RelativeK, false);
HigherMath->MEMomentumResolution(HistCounter, &(*itPart1),
*itPDGPar1, &(*itPart2),
*itPDGPar2, RelativeK);
}
}
}
++HistCounter;
++itPDGPar2;
}
++itPDGPar1;
}
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreD3D11HardwareVertexBuffer.h"
#include "OgreD3D11HardwareBuffer.h"
#include "OgreD3D11Device.h"
namespace Ogre {
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize,
size_t numVertices, HardwareBuffer::Usage usage, D3D11Device & device,
bool useSystemMemory, bool useShadowBuffer)
: HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, useSystemMemory, useShadowBuffer),
mBufferImpl(0)
{
// everything is done via internal generalisation
mBufferImpl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER,
mSizeInBytes, mUsage, device, useSystemMemory, useShadowBuffer);
}
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::~D3D11HardwareVertexBuffer()
{
SAFE_DELETE(mBufferImpl);
}
//---------------------------------------------------------------------
void* D3D11HardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options)
{
return mBufferImpl->lock(offset, length, options);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::unlock(void)
{
mBufferImpl->unlock();
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest)
{
mBufferImpl->readData(offset, length, pDest);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource,
bool discardWholeBuffer)
{
mBufferImpl->writeData(offset, length, pSource, discardWholeBuffer);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset,
size_t dstOffset, size_t length, bool discardWholeBuffer)
{
// check if the other buffer is also a D3D11HardwareVertexBuffer
if (srcBuffer.isSystemMemory())
{
// src is not not a D3D11HardwareVertexBuffer - use default copy
HardwareBuffer::copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer);
}
else
{
// src is a D3D11HardwareVertexBuffer use d3d11 optimized copy
D3D11HardwareVertexBuffer& d3dBuf = static_cast<D3D11HardwareVertexBuffer&>(srcBuffer);
mBufferImpl->copyData(*(d3dBuf.mBufferImpl), srcOffset, dstOffset, length, discardWholeBuffer);
}
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::isLocked(void) const
{
return mBufferImpl->isLocked();
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::releaseIfDefaultPool(void)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
SAFE_RELEASE(mlpD3DBuffer);
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::recreateIfDefaultPool(D3D11Device & device)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
// Create the Index buffer
HRESULT hr = device->CreateIndexBuffer(
static_cast<UINT>(mSizeInBytes),
D3D11Mappings::get(mUsage),
D3D11Mappings::get(mIndexType),
mD3DPool,
&mlpD3DBuffer,
NULL
);
if (FAILED(hr))
{
String msg = DXGetErrorDescription(hr);
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Cannot create D3D11 Index buffer: " + msg,
"D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer");
}
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
ID3D11Buffer * D3D11HardwareVertexBuffer::getD3DVertexBuffer( void ) const
{
return mBufferImpl->getD3DBuffer();
}
//---------------------------------------------------------------------
}
<commit_msg>D3D11 render system: Fixed a comment typo.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreD3D11HardwareVertexBuffer.h"
#include "OgreD3D11HardwareBuffer.h"
#include "OgreD3D11Device.h"
namespace Ogre {
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize,
size_t numVertices, HardwareBuffer::Usage usage, D3D11Device & device,
bool useSystemMemory, bool useShadowBuffer)
: HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, useSystemMemory, useShadowBuffer),
mBufferImpl(0)
{
// everything is done via internal generalisation
mBufferImpl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER,
mSizeInBytes, mUsage, device, useSystemMemory, useShadowBuffer);
}
//---------------------------------------------------------------------
D3D11HardwareVertexBuffer::~D3D11HardwareVertexBuffer()
{
SAFE_DELETE(mBufferImpl);
}
//---------------------------------------------------------------------
void* D3D11HardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options)
{
return mBufferImpl->lock(offset, length, options);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::unlock(void)
{
mBufferImpl->unlock();
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest)
{
mBufferImpl->readData(offset, length, pDest);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource,
bool discardWholeBuffer)
{
mBufferImpl->writeData(offset, length, pSource, discardWholeBuffer);
}
//---------------------------------------------------------------------
void D3D11HardwareVertexBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset,
size_t dstOffset, size_t length, bool discardWholeBuffer)
{
// check if the other buffer is also a D3D11HardwareVertexBuffer
if (srcBuffer.isSystemMemory())
{
// src is not a D3D11HardwareVertexBuffer - use default copy
HardwareBuffer::copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer);
}
else
{
// src is a D3D11HardwareVertexBuffer use d3d11 optimized copy
D3D11HardwareVertexBuffer& d3dBuf = static_cast<D3D11HardwareVertexBuffer&>(srcBuffer);
mBufferImpl->copyData(*(d3dBuf.mBufferImpl), srcOffset, dstOffset, length, discardWholeBuffer);
}
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::isLocked(void) const
{
return mBufferImpl->isLocked();
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::releaseIfDefaultPool(void)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
SAFE_RELEASE(mlpD3DBuffer);
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
bool D3D11HardwareVertexBuffer::recreateIfDefaultPool(D3D11Device & device)
{
/* if (mD3DPool == D3DPOOL_DEFAULT)
{
// Create the Index buffer
HRESULT hr = device->CreateIndexBuffer(
static_cast<UINT>(mSizeInBytes),
D3D11Mappings::get(mUsage),
D3D11Mappings::get(mIndexType),
mD3DPool,
&mlpD3DBuffer,
NULL
);
if (FAILED(hr))
{
String msg = DXGetErrorDescription(hr);
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"Cannot create D3D11 Index buffer: " + msg,
"D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer");
}
return true;
}
return false;
*/
return true;
}
//---------------------------------------------------------------------
ID3D11Buffer * D3D11HardwareVertexBuffer::getD3DVertexBuffer( void ) const
{
return mBufferImpl->getD3DBuffer();
}
//---------------------------------------------------------------------
}
<|endoftext|> |
<commit_before>#include "main_action_planner_node.hpp"
int main(int argc, char** argv) {
ros::init(argc, argv, "test_action_planner_node");
ros::NodeHandle nh {"~"};
StateChecker status {nh};
while (ros::ok()) {
auto posture_key = status.getPostureKey();
RequestPosture* rp_p = RequestPostureFactory::get(posture_key[0], nh);
if (!rp_p) {
ROS_INFO("Error: get nullptr by RP Factory: arg is [%s]", posture_key[0].c_str());
return -1;
}
SendPosture* sp_p = SendPostureFactory::get(posture_key[1], nh);
if (!sp_p) {
ROS_INFO("Error: get nullptr by SP Factory: arg is [%s]", posture_key[1].c_str());
return -1;
}
std::vector<double> angles;
rp_p->requestPosture(angles);
sp_p->sendPosture(angles);
ros::spinOnce();
}
return 0;
}
<commit_msg>Use relational node handle for topic communicate<commit_after>#include "main_action_planner_node.hpp"
int main(int argc, char** argv) {
ros::init(argc, argv, "test_action_planner_node");
ros::NodeHandle nh {};
StateChecker status {nh};
while (ros::ok()) {
auto posture_key = status.getPostureKey();
RequestPosture* rp_p = RequestPostureFactory::get(posture_key[0], nh);
if (!rp_p) {
ROS_INFO("Error: get nullptr by RP Factory: arg is [%s]", posture_key[0].c_str());
return -1;
}
SendPosture* sp_p = SendPostureFactory::get(posture_key[1], nh);
if (!sp_p) {
ROS_INFO("Error: get nullptr by SP Factory: arg is [%s]", posture_key[1].c_str());
return -1;
}
std::vector<double> angles;
rp_p->requestPosture(angles);
sp_p->sendPosture(angles);
ros::spinOnce();
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>send brightness to websocket using json<commit_after><|endoftext|> |
<commit_before>#include "maemodeploystepwidget.h"
#include "ui_maemodeploystepwidget.h"
#include "maemodeploystep.h"
#include "maemodeployablelistmodel.h"
#include "maemodeployablelistwidget.h"
#include "maemodeployables.h"
#include "maemodeviceconfiglistmodel.h"
#include "maemorunconfiguration.h"
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/target.h>
namespace Qt4ProjectManager {
namespace Internal {
MaemoDeployStepWidget::MaemoDeployStepWidget(MaemoDeployStep *step) :
ProjectExplorer::BuildStepConfigWidget(),
ui(new Ui::MaemoDeployStepWidget),
m_step(step)
{
ui->setupUi(this);
connect(m_step->deployables(), SIGNAL(modelsCreated()), this,
SLOT(handleModelsCreated()));
handleModelsCreated();
}
MaemoDeployStepWidget::~MaemoDeployStepWidget()
{
delete ui;
}
void MaemoDeployStepWidget::init()
{
#ifdef DEPLOY_VIA_MOUNT
ui->mountPortSpinBox->setValue(m_step->mountPort());
connect(ui->mountPortSpinBox, SIGNAL(valueChanged(int)), this,
SLOT(handleMountPortEdited(int)));
#else
ui->mountPortLabel->hide();
ui->mountPortSpinBox->hide();
#endif
handleDeviceConfigModelChanged();
connect(m_step->buildConfiguration()->target(),
SIGNAL(activeRunConfigurationChanged(ProjectExplorer::RunConfiguration*)),
this, SLOT(handleDeviceConfigModelChanged()));
connect(ui->deviceConfigComboBox, SIGNAL(activated(int)), this,
SLOT(setCurrentDeviceConfig(int)));
}
void MaemoDeployStepWidget::handleDeviceConfigModelChanged()
{
const MaemoDeviceConfigListModel * const oldModel
= qobject_cast<MaemoDeviceConfigListModel *>(ui->deviceConfigComboBox->model());
if (oldModel)
disconnect(oldModel, 0, this, 0);
MaemoDeviceConfigListModel * const devModel = m_step->deviceConfigModel();
ui->deviceConfigComboBox->setModel(devModel);
connect(devModel, SIGNAL(currentChanged()), this,
SLOT(handleDeviceUpdate()));
connect(devModel, SIGNAL(modelReset()), this,
SLOT(handleDeviceUpdate()));
handleDeviceUpdate();
}
void MaemoDeployStepWidget::handleDeviceUpdate()
{
ui->deviceConfigComboBox->setCurrentIndex(m_step->deviceConfigModel()
->currentIndex());
emit updateSummary();
}
QString MaemoDeployStepWidget::summaryText() const
{
return tr("<b>Deploy to device</b>: ") + m_step->deviceConfig().name;
}
QString MaemoDeployStepWidget::displayName() const
{
return QString();
}
void MaemoDeployStepWidget::handleModelsCreated()
{
ui->tabWidget->clear();
for (int i = 0; i < m_step->deployables()->modelCount(); ++i) {
MaemoDeployableListModel * const model
= m_step->deployables()->modelAt(i);
ui->tabWidget->addTab(new MaemoDeployableListWidget(this, model),
model->projectName());
}
}
void MaemoDeployStepWidget::setCurrentDeviceConfig(int index)
{
m_step->deviceConfigModel()->setCurrentIndex(index);
}
void MaemoDeployStepWidget::handleMountPortEdited(int newPort)
{
#ifdef DEPLOY_VIA_MOUNT
m_step->setMountPort(newPort);
#endif
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Fix gcc warning<commit_after>#include "maemodeploystepwidget.h"
#include "ui_maemodeploystepwidget.h"
#include "maemodeploystep.h"
#include "maemodeployablelistmodel.h"
#include "maemodeployablelistwidget.h"
#include "maemodeployables.h"
#include "maemodeviceconfiglistmodel.h"
#include "maemorunconfiguration.h"
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/target.h>
namespace Qt4ProjectManager {
namespace Internal {
MaemoDeployStepWidget::MaemoDeployStepWidget(MaemoDeployStep *step) :
ProjectExplorer::BuildStepConfigWidget(),
ui(new Ui::MaemoDeployStepWidget),
m_step(step)
{
ui->setupUi(this);
connect(m_step->deployables(), SIGNAL(modelsCreated()), this,
SLOT(handleModelsCreated()));
handleModelsCreated();
}
MaemoDeployStepWidget::~MaemoDeployStepWidget()
{
delete ui;
}
void MaemoDeployStepWidget::init()
{
#ifdef DEPLOY_VIA_MOUNT
ui->mountPortSpinBox->setValue(m_step->mountPort());
connect(ui->mountPortSpinBox, SIGNAL(valueChanged(int)), this,
SLOT(handleMountPortEdited(int)));
#else
ui->mountPortLabel->hide();
ui->mountPortSpinBox->hide();
#endif
handleDeviceConfigModelChanged();
connect(m_step->buildConfiguration()->target(),
SIGNAL(activeRunConfigurationChanged(ProjectExplorer::RunConfiguration*)),
this, SLOT(handleDeviceConfigModelChanged()));
connect(ui->deviceConfigComboBox, SIGNAL(activated(int)), this,
SLOT(setCurrentDeviceConfig(int)));
}
void MaemoDeployStepWidget::handleDeviceConfigModelChanged()
{
const MaemoDeviceConfigListModel * const oldModel
= qobject_cast<MaemoDeviceConfigListModel *>(ui->deviceConfigComboBox->model());
if (oldModel)
disconnect(oldModel, 0, this, 0);
MaemoDeviceConfigListModel * const devModel = m_step->deviceConfigModel();
ui->deviceConfigComboBox->setModel(devModel);
connect(devModel, SIGNAL(currentChanged()), this,
SLOT(handleDeviceUpdate()));
connect(devModel, SIGNAL(modelReset()), this,
SLOT(handleDeviceUpdate()));
handleDeviceUpdate();
}
void MaemoDeployStepWidget::handleDeviceUpdate()
{
ui->deviceConfigComboBox->setCurrentIndex(m_step->deviceConfigModel()
->currentIndex());
emit updateSummary();
}
QString MaemoDeployStepWidget::summaryText() const
{
return tr("<b>Deploy to device</b>: ") + m_step->deviceConfig().name;
}
QString MaemoDeployStepWidget::displayName() const
{
return QString();
}
void MaemoDeployStepWidget::handleModelsCreated()
{
ui->tabWidget->clear();
for (int i = 0; i < m_step->deployables()->modelCount(); ++i) {
MaemoDeployableListModel * const model
= m_step->deployables()->modelAt(i);
ui->tabWidget->addTab(new MaemoDeployableListWidget(this, model),
model->projectName());
}
}
void MaemoDeployStepWidget::setCurrentDeviceConfig(int index)
{
m_step->deviceConfigModel()->setCurrentIndex(index);
}
void MaemoDeployStepWidget::handleMountPortEdited(int newPort)
{
#ifdef DEPLOY_VIA_MOUNT
m_step->setMountPort(newPort);
#else
Q_UNUSED(newPort);
#endif
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>#include "painterapplication.hpp"
#include <fea/ui/sdl2windowbackend.hpp>
#include <fea/ui/sdl2inputbackend.hpp>
PainterApplication::PainterApplication() :
mWindow(new fea::SDL2WindowBackend()),
mInputHandler(new fea::SDL2InputBackend())
{
}
void PainterApplication::setup(const std::vector<std::string>& args)
{
mWindow.create(fea::VideoMode(800, 600), "painter");
}
void PainterApplication::loop()
{
fea::Event event;
while(mInputHandler.pollEvent(event))
{
if(event.type == fea::Event::KEYPRESSED)
{
if(event.key.code == fea::Keyboard::ESCAPE)
quit();
}
}
}
void PainterApplication::destroy()
{
mWindow.close();
}
<commit_msg>made window display<commit_after>#include "painterapplication.hpp"
#include <fea/ui/sdl2windowbackend.hpp>
#include <fea/ui/sdl2inputbackend.hpp>
PainterApplication::PainterApplication() :
mWindow(new fea::SDL2WindowBackend()),
mInputHandler(new fea::SDL2InputBackend())
{
}
void PainterApplication::setup(const std::vector<std::string>& args)
{
mWindow.create(fea::VideoMode(800, 600), "painter");
}
void PainterApplication::loop()
{
fea::Event event;
while(mInputHandler.pollEvent(event))
{
if(event.type == fea::Event::KEYPRESSED)
{
if(event.key.code == fea::Keyboard::ESCAPE)
quit();
}
}
mWindow.swapBuffers();
}
void PainterApplication::destroy()
{
mWindow.close();
}
<|endoftext|> |
<commit_before>// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2011, Roboterclub Aachen e.V.
* 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 Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*
* $Id$
*/
// ----------------------------------------------------------------------------
#ifndef XPCC_STM32__SYSTICK_TIMER_HPP
#define XPCC_STM32__SYSTICK_TIMER_HPP
#include <stdint.h>
#include "core.hpp"
namespace xpcc
{
namespace stm32
{
/**
* @brief SysTick Timer
* @ingroup stm32
*/
class SysTickTimer
{
public:
static void
enable(uint32_t reload = ((F_CPU / 1000) - 1));
static void
disable();
static void
attachInterrupt(InterruptHandler handler);
static void
detachInterrupt();
};
}
}
#endif // XPCC_STM32__SYSTICK_TIMER_HPP
<commit_msg>some documentation<commit_after>// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2011, Roboterclub Aachen e.V.
* 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 Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*
* $Id$
*/
// ----------------------------------------------------------------------------
#ifndef XPCC_STM32__SYSTICK_TIMER_HPP
#define XPCC_STM32__SYSTICK_TIMER_HPP
#include <stdint.h>
#include "core.hpp"
namespace xpcc
{
namespace stm32
{
/**
* @brief SysTick Timer
* @ingroup stm32
*/
class SysTickTimer
{
public:
/**
* Enables the SysTick Timer generating periodically events.
* Warning: if SysTick Timer is enabled the xpcc::Clock, which
* is bounded to xpcc::Timeout and other similar workflow
* classes, is incremented on each event.
* You must not increment the xpcc::Clock
* additionally somewhere else.
*
*/
static void
enable(uint32_t reload = ((F_CPU / 1000) - 1));
/**
* Disables SysTick Timer.
* Warning: If SysTick Timer is disabled xpcc::Clock is not
* incremented automatically. Workflow classes which
* depend on xpcc::Clock will not work if xpcc::Clock
* is not incremented.
*/
static void
disable();
/**
* Passed method will be called periodically on each event.
* Previously passed interrupt handler will be detached.
*/
static void
attachInterrupt(InterruptHandler handler);
/**
* Detaches previously attached interrupt handler.
*/
static void
detachInterrupt();
};
}
}
#endif // XPCC_STM32__SYSTICK_TIMER_HPP
<|endoftext|> |
<commit_before>/*
Persons Model Item
Represents one person in the model
Copyright (C) 2012 Martin Klapetek <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License 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
*/
#include "persons-model-item.h"
#include "persons-model-contact-item.h"
#include <Nepomuk2/Vocabulary/PIMO>
#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Resource>
#include <Nepomuk2/Variant>
#include <Soprano/Vocabulary/NAO>
#include <KDebug>
PersonsModelItem::PersonsModelItem(const QUrl &personUri)
{
setData(personUri, PersonsModel::UriRole);
}
PersonsModelItem::PersonsModelItem(const Nepomuk2::Resource& person)
{
setData(person.uri(), PersonsModel::UriRole);
setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList());
qDebug() << "new person" << text() << rowCount();
}
QVariant PersonsModelItem::queryChildrenForRole(int role) const
{
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (!value.isNull()) {
return value;
}
}
return QVariant();
}
QVariantList PersonsModelItem::queryChildrenForRoleList(int role) const
{
QVariantList ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (!value.isNull()) {
ret += value;
}
}
return ret;
}
QVariant PersonsModelItem::data(int role) const
{
switch(role) {
case PersonsModel::NameRole:
case Qt::DisplayRole: {
QVariant value = queryChildrenForRole(Qt::DisplayRole);
if(value.isNull())
value = queryChildrenForRole(PersonsModel::ContactIdRole);
if(value.isNull())
return QString("PIMO:Person - %1").arg(data(PersonsModel::UriRole).toString());
else
return value;
}
case PersonsModel::StatusRole: //TODO: use a better algorithm for finding the actual status
case PersonsModel::NickRole:
return queryChildrenForRole(role);
case PersonsModel::LabelRole:
case PersonsModel::IMRole:
case PersonsModel::PhoneRole:
case PersonsModel::EmailRole:
case PersonsModel::PhotoRole:
case PersonsModel::ContactIdRole:
return queryChildrenForRoleList(role);
case PersonsModel::ContactsCountRole:
return rowCount();
case PersonsModel::ResourceTypeRole:
return PersonsModel::Person;
}
return QStandardItem::data(role);
}
void PersonsModelItem::removeContacts(const QList<QUrl>& contacts)
{
kDebug() << "remove contacts" << contacts;
for(int i=0; i<rowCount(); ) {
QStandardItem* item = child(i);
if(contacts.contains(item->data(PersonsModel::UriRole).toUrl()))
removeRow(i);
else
++i;
}
emitDataChanged();
}
void PersonsModelItem::addContacts(const QList<QUrl>& _contacts)
{
QList<QUrl> contacts(_contacts);
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach(const QVariant& uri, uris) {
contacts.removeOne(uri.toUrl());
}
//query the model for the contacts, if they are present, then need to be just moved
QList<QStandardItem*> toplevelContacts;
foreach(const QUrl &uri, contacts) {
QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri);
if (contactIndex.isValid()) {
toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row()));
}
}
//append the moved contacts to this person and remove them from 'contacts'
//so they are not added twice
foreach(QStandardItem *contactItem, toplevelContacts) {
PersonsModelContactItem *contact = dynamic_cast<PersonsModelContactItem*>(contactItem);
appendRow(contact);
contacts.removeOne(contact->uri());
}
kDebug() << "add contacts" << contacts;
QList<PersonsModelContactItem*> rows;
foreach(const QUrl& uri, contacts) {
appendRow(new PersonsModelContactItem(Nepomuk2::Resource(uri)));
}
emitDataChanged();
}
void PersonsModelItem::setContacts(const QList<QUrl>& contacts)
{
kDebug() << "set contacts" << contacts;
if (contacts.isEmpty()) {
//nothing to do here
return;
}
if(hasChildren()) {
QList<QUrl> toRemove;
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach(const QVariant& contact, uris) {
if(!contacts.contains(contact.toUrl()))
toRemove += contact.toUrl();
}
removeContacts(toRemove);
}
QList<QUrl> toAdd;
foreach(const QUrl& contact, contacts) {
toAdd += contact;
}
addContacts(toAdd);
Q_ASSERT(hasChildren());
}
<commit_msg>qDebug -> kDebug<commit_after>/*
Persons Model Item
Represents one person in the model
Copyright (C) 2012 Martin Klapetek <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License 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
*/
#include "persons-model-item.h"
#include "persons-model-contact-item.h"
#include <Nepomuk2/Vocabulary/PIMO>
#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Resource>
#include <Nepomuk2/Variant>
#include <Soprano/Vocabulary/NAO>
#include <KDebug>
PersonsModelItem::PersonsModelItem(const QUrl &personUri)
{
setData(personUri, PersonsModel::UriRole);
}
PersonsModelItem::PersonsModelItem(const Nepomuk2::Resource& person)
{
setData(person.uri(), PersonsModel::UriRole);
setContacts(person.property(Nepomuk2::Vocabulary::PIMO::groundingOccurrence()).toUrlList());
kDebug() << "new person" << text() << rowCount();
}
QVariant PersonsModelItem::queryChildrenForRole(int role) const
{
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (!value.isNull()) {
return value;
}
}
return QVariant();
}
QVariantList PersonsModelItem::queryChildrenForRoleList(int role) const
{
QVariantList ret;
for (int i = 0; i < rowCount(); i++) {
QVariant value = child(i)->data(role);
if (!value.isNull()) {
ret += value;
}
}
return ret;
}
QVariant PersonsModelItem::data(int role) const
{
switch(role) {
case PersonsModel::NameRole:
case Qt::DisplayRole: {
QVariant value = queryChildrenForRole(Qt::DisplayRole);
if(value.isNull())
value = queryChildrenForRole(PersonsModel::ContactIdRole);
if(value.isNull())
return QString("PIMO:Person - %1").arg(data(PersonsModel::UriRole).toString());
else
return value;
}
case PersonsModel::StatusRole: //TODO: use a better algorithm for finding the actual status
case PersonsModel::NickRole:
return queryChildrenForRole(role);
case PersonsModel::LabelRole:
case PersonsModel::IMRole:
case PersonsModel::PhoneRole:
case PersonsModel::EmailRole:
case PersonsModel::PhotoRole:
case PersonsModel::ContactIdRole:
return queryChildrenForRoleList(role);
case PersonsModel::ContactsCountRole:
return rowCount();
case PersonsModel::ResourceTypeRole:
return PersonsModel::Person;
}
return QStandardItem::data(role);
}
void PersonsModelItem::removeContacts(const QList<QUrl>& contacts)
{
kDebug() << "remove contacts" << contacts;
for(int i=0; i<rowCount(); ) {
QStandardItem* item = child(i);
if(contacts.contains(item->data(PersonsModel::UriRole).toUrl()))
removeRow(i);
else
++i;
}
emitDataChanged();
}
void PersonsModelItem::addContacts(const QList<QUrl>& _contacts)
{
QList<QUrl> contacts(_contacts);
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach(const QVariant& uri, uris) {
contacts.removeOne(uri.toUrl());
}
//query the model for the contacts, if they are present, then need to be just moved
QList<QStandardItem*> toplevelContacts;
foreach(const QUrl &uri, contacts) {
QModelIndex contactIndex = qobject_cast<PersonsModel*>(model())->indexForUri(uri);
if (contactIndex.isValid()) {
toplevelContacts.append(qobject_cast<PersonsModel*>(model())->takeRow(contactIndex.row()));
}
}
//append the moved contacts to this person and remove them from 'contacts'
//so they are not added twice
foreach(QStandardItem *contactItem, toplevelContacts) {
PersonsModelContactItem *contact = dynamic_cast<PersonsModelContactItem*>(contactItem);
appendRow(contact);
contacts.removeOne(contact->uri());
}
kDebug() << "add contacts" << contacts;
QList<PersonsModelContactItem*> rows;
foreach(const QUrl& uri, contacts) {
appendRow(new PersonsModelContactItem(Nepomuk2::Resource(uri)));
}
emitDataChanged();
}
void PersonsModelItem::setContacts(const QList<QUrl>& contacts)
{
kDebug() << "set contacts" << contacts;
if (contacts.isEmpty()) {
//nothing to do here
return;
}
if(hasChildren()) {
QList<QUrl> toRemove;
QVariantList uris = queryChildrenForRoleList(PersonsModel::UriRole);
foreach(const QVariant& contact, uris) {
if(!contacts.contains(contact.toUrl()))
toRemove += contact.toUrl();
}
removeContacts(toRemove);
}
QList<QUrl> toAdd;
foreach(const QUrl& contact, contacts) {
toAdd += contact;
}
addContacts(toAdd);
Q_ASSERT(hasChildren());
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/filesystem/path.hpp>
namespace fs = boost::filesystem;
#include <vw/Image.h>
#include <vw/FileIO.h>
#include <vw/Cartography/FileIO.h>
#include <vw/Cartography/GeoReference.h>
using namespace vw;
// Functors
template <class Arg1T, class Arg2T>
struct ReplaceChannelFunc: public ReturnFixedType<Arg1T> {
private:
int m_channel;
public:
ReplaceChannelFunc( int const& channel ) : m_channel(channel) {}
inline Arg1T operator()( Arg1T const& arg1,
Arg2T const& arg2 ) const {
Arg1T t( arg1 );
t[m_channel] = arg2;
return t;
}
};
template <class Image1T, class Image2T>
inline BinaryPerPixelView<Image1T, Image2T, ReplaceChannelFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> >
replace_channel( ImageViewBase<Image1T> const& image1,
int const& channel,
ImageViewBase<Image2T> const& image2 ) {
typedef ReplaceChannelFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> func_type;
return BinaryPerPixelView<Image1T, Image2T, func_type >( image1.impl(), image2.impl(), func_type(channel));
}
// Standard Arguments
struct Options {
std::string input_rgb, input_gray;
std::string output_file;
};
// Image Operations
template <class ChannelT>
void do_merge(Options const& opt) {
DiskImageView<PixelGray<ChannelT> > shaded_image( opt.input_gray );
DiskImageView<PixelRGB<ChannelT> > rgb_image( opt.input_rgb );
cartography::GeoReference georef;
cartography::read_georeference(georef, opt.input_rgb);
ImageViewRef<PixelRGB<ChannelT> > result = pixel_cast<PixelRGB<ChannelT> >(replace_channel(pixel_cast<PixelHSV<ChannelT> >(rgb_image),2,shaded_image));
cartography::write_georeferenced_image( opt.output_file, result, georef,
TerminalProgressCallback("tools.hsv_merge","Writing:") );
}
// Handle input
int main( int argc, char *argv[] ) {
Options opt;
po::options_description desc("Description: Mimicks hsv_merge.py by Frank Warmerdam and Trent Hare. Use it to combine results from gdaldem.");
desc.add_options()
("input-rgb", po::value<std::string>(&opt.input_rgb), "Explicitly specify the input rgb image.")
("input-gray", po::value<std::string>(&opt.input_gray), "Explicitly specify the input gray image.")
("output-file,o", po::value<std::string>(&opt.output_file), "Specify the output file.")
("help,h", "Display this help message");
po::positional_options_description p;
p.add("input-rgb", 1 );
p.add("input-gray", 1 );
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );
po::notify( vm );
} catch ( po::error & e ) {
std::cout << "An error occured while parsing command line arguments.\n";
std::cout << "\t" << e.what() << "\n\n";
std::cout << desc << std::endl;
return 1;
}
if( vm.count("help") ||
(opt.input_rgb == "" && opt.input_gray == "" ) ) {
std::cout << desc << std::endl;
return 1;
}
try {
// Get the input RGB's type
DiskImageResource *rsrc = DiskImageResource::open(opt.input_rgb);
ChannelTypeEnum channel_type = rsrc->channel_type();
delete rsrc;
switch( channel_type ) {
case VW_CHANNEL_UINT8: do_merge<uint8>( opt ); break;
case VW_CHANNEL_INT16: do_merge<int16>( opt ); break;
case VW_CHANNEL_UINT16: do_merge<uint16>( opt ); break;
default: do_merge<float32>( opt );
}
} catch ( Exception& e ) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
<commit_msg>FileIO.h doesn't exist<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/filesystem/path.hpp>
namespace fs = boost::filesystem;
#include <vw/Image.h>
#include <vw/FileIO.h>
#include <vw/Cartography/GeoReference.h>
using namespace vw;
// Functors
template <class Arg1T, class Arg2T>
struct ReplaceChannelFunc: public ReturnFixedType<Arg1T> {
private:
int m_channel;
public:
ReplaceChannelFunc( int const& channel ) : m_channel(channel) {}
inline Arg1T operator()( Arg1T const& arg1,
Arg2T const& arg2 ) const {
Arg1T t( arg1 );
t[m_channel] = arg2;
return t;
}
};
template <class Image1T, class Image2T>
inline BinaryPerPixelView<Image1T, Image2T, ReplaceChannelFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> >
replace_channel( ImageViewBase<Image1T> const& image1,
int const& channel,
ImageViewBase<Image2T> const& image2 ) {
typedef ReplaceChannelFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> func_type;
return BinaryPerPixelView<Image1T, Image2T, func_type >( image1.impl(), image2.impl(), func_type(channel));
}
// Standard Arguments
struct Options {
std::string input_rgb, input_gray;
std::string output_file;
};
// Image Operations
template <class ChannelT>
void do_merge(Options const& opt) {
DiskImageView<PixelGray<ChannelT> > shaded_image( opt.input_gray );
DiskImageView<PixelRGB<ChannelT> > rgb_image( opt.input_rgb );
cartography::GeoReference georef;
cartography::read_georeference(georef, opt.input_rgb);
ImageViewRef<PixelRGB<ChannelT> > result = pixel_cast<PixelRGB<ChannelT> >(replace_channel(pixel_cast<PixelHSV<ChannelT> >(rgb_image),2,shaded_image));
cartography::write_georeferenced_image( opt.output_file, result, georef,
TerminalProgressCallback("tools.hsv_merge","Writing:") );
}
// Handle input
int main( int argc, char *argv[] ) {
Options opt;
po::options_description desc("Description: Mimicks hsv_merge.py by Frank Warmerdam and Trent Hare. Use it to combine results from gdaldem.");
desc.add_options()
("input-rgb", po::value<std::string>(&opt.input_rgb), "Explicitly specify the input rgb image.")
("input-gray", po::value<std::string>(&opt.input_gray), "Explicitly specify the input gray image.")
("output-file,o", po::value<std::string>(&opt.output_file), "Specify the output file.")
("help,h", "Display this help message");
po::positional_options_description p;
p.add("input-rgb", 1 );
p.add("input-gray", 1 );
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );
po::notify( vm );
} catch ( po::error & e ) {
std::cout << "An error occured while parsing command line arguments.\n";
std::cout << "\t" << e.what() << "\n\n";
std::cout << desc << std::endl;
return 1;
}
if( vm.count("help") ||
(opt.input_rgb == "" && opt.input_gray == "" ) ) {
std::cout << desc << std::endl;
return 1;
}
try {
// Get the input RGB's type
DiskImageResource *rsrc = DiskImageResource::open(opt.input_rgb);
ChannelTypeEnum channel_type = rsrc->channel_type();
delete rsrc;
switch( channel_type ) {
case VW_CHANNEL_UINT8: do_merge<uint8>( opt ); break;
case VW_CHANNEL_INT16: do_merge<int16>( opt ); break;
case VW_CHANNEL_UINT16: do_merge<uint16>( opt ); break;
default: do_merge<float32>( opt );
}
} catch ( Exception& e ) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_training.C
/// @brief Train dram
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include "p9_mss_draminit_training.H"
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Train dram
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint16_t i_special_training )
{
fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;
FAPI_INF("Start draminit training");
uint8_t l_reset_disable = 0;
FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) );
// Configure the CCS engine.
{
fapi2::buffer<uint64_t> l_ccs_config;
FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );
// It's unclear if we want to run with this true or false. Right now (10/15) this
// has to be false. Shelton was unclear if this should be on or off in general BRS
mss::ccs::stop_on_err(i_target, l_ccs_config, false);
mss::ccs::ue_disable(i_target, l_ccs_config, false);
mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true);
// Hm. Centaur sets this up for the longest duration possible. Can we do better?
mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);
#ifndef JIM_SAYS_TURN_OFF_ECC
mss::ccs::disable_ecc(i_target, l_ccs_config);
#endif
FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
}
// Clean out any previous calibration results, set bad-bits and configure the ranks.
FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size());
for( auto p : i_target.getChildren<TARGET_TYPE_MCA>())
{
mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;
// Setup a series of register probes which we'll see during the polling loop
l_program.iv_probes =
{
// One block for each DP16
{p, "wr_cntr_status0 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0},
{p, "wr_cntr_status1 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0},
{p, "wr_cntr_status2 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0},
{p, "wr_lvl_status (dp16 0)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0},
{p, "wr_cntr_status0 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1},
{p, "wr_cntr_status1 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1},
{p, "wr_cntr_status2 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1},
{p, "wr_lvl_status (dp16 1)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1},
{p, "wr_cntr_status0 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2},
{p, "wr_cntr_status1 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2},
{p, "wr_cntr_status2 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2},
{p, "wr_lvl_status (dp16 2)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2},
{p, "wr_cntr_status0 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3},
{p, "wr_cntr_status1 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3},
{p, "wr_cntr_status2 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3},
{p, "wr_lvl_status (dp16 3)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3},
{p, "wr_cntr_status0 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4},
{p, "wr_cntr_status1 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4},
{p, "wr_cntr_status2 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4},
{p, "wr_lvl_status (dp16 4)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4},
};
// Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,
// and we're supposed to poll for the done or timeout bit. But we don't want
// to wait 0xFFFF cycles before we start polling - that's too long. So we put
// in a best-guess of how long to wait. This, in a perfect world, would be the
// time it takes one rank to train one training algorithm times the number of
// ranks we're going to train. We fail-safe as worst-case we simply poll the
// register too much - so we can tune this as we learn more.
l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;
l_program.iv_poll.iv_initial_sim_delay = 200;
l_program.iv_poll.iv_poll_count = 0xFFFF;
// Returned from set_rank_pairs, it tells us how many rank pairs
// we configured on this port.
std::vector<uint64_t> l_pairs;
#ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE
// This isn't correct - shouldn't be setting
static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000;
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) );
#endif
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );
// The following registers must be configured to the correct operating environment:
// Unclear, can probably be 0's for sim BRS
// • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422
FAPI_TRY( mss::reset_seq_config0(p) );
FAPI_TRY( mss::reset_seq_rd_wr_data(p) );
FAPI_TRY( mss::reset_odt_config(p) );
// These are reset in phy_scominit
// • Section 5.2.6.1 WC Configuration 0 Register on page 434
// • Section 5.2.6.2 WC Configuration 1 Register on page 436
// • Section 5.2.6.3 WC Configuration 2 Register on page 438
// Get our rank pairs.
FAPI_TRY( mss::get_rank_pairs(p, l_pairs) );
// Setup the config register
//
// Grab the attribute which contains the information on what cal steps we should run
// if the i_specal_training bits have not been specified.
if (i_special_training == 0)
{
FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );
}
FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training);
// Check to see if we're supposed to reset the delay values before starting training
// don't reset if we're running special training - assumes there's a checkpoint which has valid state.
if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0))
{
FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) );
}
FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size());
// For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.
// NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE
// THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.
for (auto rp : l_pairs)
{
auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);
FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1);
l_program.iv_instructions.push_back(l_inst);
// We need to figure out how long to wait before we start polling. Each cal step has an expected
// duration, so for each cal step which was enabled, we update the CCS program.
FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );
FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );
// In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a
// timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)
// for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register
// should be polled to determine which calibration step failed.
// If we got a cal timeout, or another CCS error just leave now. If we got success, check the error
// bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.
FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );
FAPI_TRY( mss::process_initial_cal_errors(p) );
}
}
fapi_try_exit:
FAPI_INF("End draminit training");
return fapi2::current_err;
}
}
<commit_msg>Add ability to disable port fails for training<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_draminit_training.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_draminit_training.C
/// @brief Train dram
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include "p9_mss_draminit_training.H"
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
extern "C"
{
///
/// @brief Train dram
/// @param[in] i_target, the McBIST of the ports of the dram you're training
/// @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
const uint16_t i_special_training )
{
fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;
FAPI_INF("Start draminit training");
uint8_t l_reset_disable = 0;
FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) );
// Configure the CCS engine.
{
fapi2::buffer<uint64_t> l_ccs_config;
FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );
// It's unclear if we want to run with this true or false. Right now (10/15) this
// has to be false. Shelton was unclear if this should be on or off in general BRS
mss::ccs::stop_on_err(i_target, l_ccs_config, false);
mss::ccs::ue_disable(i_target, l_ccs_config, false);
mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true);
// Hm. Centaur sets this up for the longest duration possible. Can we do better?
mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);
#ifndef JIM_SAYS_TURN_OFF_ECC
mss::ccs::disable_ecc(i_target, l_ccs_config);
#endif
FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );
}
// Clean out any previous calibration results, set bad-bits and configure the ranks.
FAPI_DBG("MCA's on this McBIST: %d", i_target.getChildren<TARGET_TYPE_MCA>().size());
for( auto p : i_target.getChildren<TARGET_TYPE_MCA>())
{
mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;
// Setup a series of register probes which we'll see during the polling loop
l_program.iv_probes =
{
// One block for each DP16
{p, "wr_cntr_status0 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0},
{p, "wr_cntr_status1 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0},
{p, "wr_cntr_status2 (dp16 0)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0},
{p, "wr_lvl_status (dp16 0)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0},
{p, "wr_cntr_status0 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1},
{p, "wr_cntr_status1 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1},
{p, "wr_cntr_status2 (dp16 1)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1},
{p, "wr_lvl_status (dp16 1)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1},
{p, "wr_cntr_status0 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2},
{p, "wr_cntr_status1 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2},
{p, "wr_cntr_status2 (dp16 2)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2},
{p, "wr_lvl_status (dp16 2)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2},
{p, "wr_cntr_status0 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3},
{p, "wr_cntr_status1 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3},
{p, "wr_cntr_status2 (dp16 3)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3},
{p, "wr_lvl_status (dp16 3)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3},
{p, "wr_cntr_status0 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4},
{p, "wr_cntr_status1 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4},
{p, "wr_cntr_status2 (dp16 4)", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4},
{p, "wr_lvl_status (dp16 4)", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4},
};
// Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,
// and we're supposed to poll for the done or timeout bit. But we don't want
// to wait 0xFFFF cycles before we start polling - that's too long. So we put
// in a best-guess of how long to wait. This, in a perfect world, would be the
// time it takes one rank to train one training algorithm times the number of
// ranks we're going to train. We fail-safe as worst-case we simply poll the
// register too much - so we can tune this as we learn more.
l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;
l_program.iv_poll.iv_initial_sim_delay = 200;
l_program.iv_poll.iv_poll_count = 0xFFFF;
// Returned from set_rank_pairs, it tells us how many rank pairs
// we configured on this port.
std::vector<uint64_t> l_pairs;
#ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE
// This isn't correct - shouldn't be setting
static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000;
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) );
#endif
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );
FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );
// Disable port fails as it doesn't appear the MC handles initial cal timeouts
// correctly (cal_length.) BRS, see conversation with Brad Michael
FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) );
// The following registers must be configured to the correct operating environment:
// Unclear, can probably be 0's for sim BRS
// • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422
FAPI_TRY( mss::reset_seq_config0(p) );
FAPI_TRY( mss::reset_seq_rd_wr_data(p) );
FAPI_TRY( mss::reset_odt_config(p) );
// These are reset in phy_scominit
// • Section 5.2.6.1 WC Configuration 0 Register on page 434
// • Section 5.2.6.2 WC Configuration 1 Register on page 436
// • Section 5.2.6.3 WC Configuration 2 Register on page 438
// Get our rank pairs.
FAPI_TRY( mss::get_rank_pairs(p, l_pairs) );
// Setup the config register
//
// Grab the attribute which contains the information on what cal steps we should run
// if the i_specal_training bits have not been specified.
if (i_special_training == 0)
{
FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );
}
FAPI_DBG("cal steps enabled: 0x%x special training: 0x%x", l_cal_steps_enabled, i_special_training);
// Check to see if we're supposed to reset the delay values before starting training
// don't reset if we're running special training - assumes there's a checkpoint which has valid state.
if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0))
{
FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) );
}
FAPI_DBG("generating calibration CCS instructions: %d rank-pairs", l_pairs.size());
// For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.
// NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE
// THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.
for (auto rp : l_pairs)
{
auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);
FAPI_DBG("exeecuting training CCS instruction: 0x%llx, 0x%llx", l_inst.arr0, l_inst.arr1);
l_program.iv_instructions.push_back(l_inst);
// We need to figure out how long to wait before we start polling. Each cal step has an expected
// duration, so for each cal step which was enabled, we update the CCS program.
FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );
FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );
// In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a
// timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)
// for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register
// should be polled to determine which calibration step failed.
// If we got a cal timeout, or another CCS error just leave now. If we got success, check the error
// bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.
FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );
FAPI_TRY( mss::process_initial_cal_errors(p) );
}
}
fapi_try_exit:
FAPI_INF("End draminit training");
return fapi2::current_err;
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_utils_to_throttle.C
/// @brief Sets throttles
/// TMGT will call this procedure to set the N address operations (commands)
/// allowed within a window of M DRAM clocks given the minimum dram data bus utilization.
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <p9_mss_utils_to_throttle.H>
// fapi2
#include <fapi2.H>
// mss lib
#include <lib/power_thermal/throttle.H>
#include <lib/utils/index.H>
#include <lib/utils/find.H>
#include <lib/utils/conversions.H>
#include <lib/mss_attribute_accessors.H>
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;
extern "C"
{
///
/// @brief Sets number commands allowed within a given data bus utilization.
/// @param[in] i_target the controller target
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_utils_to_throttle( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
{
std::vector<uint8_t> l_databus_util(mss::PORTS_PER_MCS, 0);
std::vector<uint32_t> l_throttled_cmds(mss::PORTS_PER_MCS, 0);
uint32_t l_dram_clocks = 0;
FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );
// TK - Who sets this attribute? OCC? Not set in eff_config for p8 - AAM
// If set by OCC can they just pass in value as a parameter? - AAM
FAPI_TRY( mss::databus_util( i_target, l_databus_util.data()) );
for( const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target) )
{
const auto l_port_num = mss::index( l_mca );
FAPI_INF( "MRW dram clock window: %d, databus utilization[%d]: %d",
l_dram_clocks,
l_port_num,
l_databus_util[l_port_num] );
// Calculate programmable N address operations within M dram clock window
l_throttled_cmds[l_port_num] = mss::throttled_cmds( l_databus_util[l_port_num], l_dram_clocks );
FAPI_INF( "Calculated N commands per port [%d] = %d",
l_port_num,
l_throttled_cmds[l_port_num]);
}// end for
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_OCC_THROTTLED_N_CMDS,
i_target,
UINT32_VECTOR_TO_1D_ARRAY(l_throttled_cmds, mss::PORTS_PER_MCS)) );
fapi_try_exit:
return fapi2::current_err;
}
}// extern C
<commit_msg>Implement MRW attributes; dram_clks, db_util, 2n_mode<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2016 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_utils_to_throttle.C
/// @brief Sets throttles
/// TMGT will call this procedure to set the N address operations (commands)
/// allowed within a window of M DRAM clocks given the minimum dram data bus utilization.
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <p9_mss_utils_to_throttle.H>
// fapi2
#include <fapi2.H>
// mss lib
#include <lib/power_thermal/throttle.H>
#include <lib/utils/index.H>
#include <lib/utils/find.H>
#include <lib/utils/conversions.H>
#include <lib/mss_attribute_accessors.H>
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_DIMM;
extern "C"
{
///
/// @brief Sets number commands allowed within a given data bus utilization.
/// @param[in] i_target the controller target
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_utils_to_throttle( const fapi2::Target<TARGET_TYPE_MCS>& i_target )
{
uint32_t l_databus_util = 0;
std::vector<uint32_t> l_throttled_cmds(mss::PORTS_PER_MCS, 0);
uint32_t l_dram_clocks = 0;
FAPI_TRY( mss::mrw_mem_m_dram_clocks(l_dram_clocks) );
FAPI_TRY( mss::mrw_max_dram_databus_util(l_databus_util) );
for( const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target) )
{
const auto l_port_num = mss::index( l_mca );
FAPI_INF( "MRW dram clock window: %d, databus utilization: %d",
l_dram_clocks,
l_databus_util );
// Calculate programmable N address operations within M dram clock window
l_throttled_cmds[l_port_num] = mss::throttled_cmds( l_databus_util, l_dram_clocks );
FAPI_INF( "Calculated N commands per port [%d] = %d",
l_port_num,
l_throttled_cmds[l_port_num]);
}// end for
FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_OCC_THROTTLED_N_CMDS,
i_target,
UINT32_VECTOR_TO_1D_ARRAY(l_throttled_cmds, mss::PORTS_PER_MCS)) );
fapi_try_exit:
return fapi2::current_err;
}
}// extern C
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket_attr.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_pm_get_poundv_bucket_attr.C
/// @brief Grab PM data from certain bucket in #V keyword in LRPX record
///
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket_attr.H>
#include <p9_pm_get_poundv_bucket.H>
#include <mvpd_access_defs.H>
#include <attribute_ids.H>
fapi2::ReturnCode p9_pm_get_poundv_bucket_attr(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
uint8_t* o_data)
{
FAPI_DBG("Entering p9_pm_get_poundv_bucket_attr ....");
uint8_t* l_prDataPtr = NULL;
uint8_t* l_fullVpdData = NULL;
uint8_t l_overridePresent = 0;
uint32_t l_tempVpdSize = 0;
uint32_t l_vpdSize = 0;
uint8_t l_eqChipUnitPos = 0;
uint8_t l_bucketId;
uint8_t l_bucketSize = 0;
uint32_t l_sysNestFreq = 0;
fapi2::voltageBucketData_t* l_currentBucket = NULL;
uint8_t l_numMatches = 0;
fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;
//To read MVPD we will need the proc parent of the inputted EQ target
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =
i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
//Need to determine which LRP record to read from depending on which
//bucket we are getting the power management data from. FapiPos will
//tell us which LRP record to use.
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,
i_target,
l_eqChipUnitPos));
FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,
fapi2::INVALID_EQ_CHIP_POS().
set_EQ_POSITION( l_eqChipUnitPos ),
"Invalid EQ chip unit position = 0x%X",
l_eqChipUnitPos);
//The enumeration for the LRPx records are just 3 more
//than the EQ chip unit pos. See mvpd_access_defs.H
lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +
fapi2::MVPD_RECORD_LRP0 );
//check if bucket num has been overriden
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,
i_target,
l_overridePresent));
if(l_overridePresent != 0)
{
//If it has been overriden then get the override
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,
i_target,
l_bucketId));
}
else
{
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
NULL,
l_tempVpdSize) );
//save off the actual vpd size
l_vpdSize = l_tempVpdSize;
//Allocate memory for vpd data
l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
l_fullVpdData,
l_tempVpdSize) );
//Version 2:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x33 byte
//bucket b: 0x33 byte
//bucket c: 0x33 byte
//bucket d: 0x33 byte
//bucket e: 0x33 byte
//bucket f: 0x33 byte
if( *l_fullVpdData == POUNDV_VERSION_2)
{
//Set the size of the bucket
l_bucketSize = VERSION_2_BUCKET_SIZE;
//Reset VPD size because we want to find size of another VPD record
l_tempVpdSize = 0;
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
NULL,
l_tempVpdSize) );
l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
l_prDataPtr,
l_tempVpdSize) );
//Bucket ID is byte[4] of the PR keyword
memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));
}
//Version 3:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x3D byte
//bucket b: 0x3D byte
//bucket c: 0x3D byte
//bucket d: 0x3D byte
//bucket e: 0x3D byte
//bucket f: 0x3D byte
else if( *l_fullVpdData == POUNDV_VERSION_3 )
{
// Set the size of the bucket
l_bucketSize = VERSION_3_BUCKET_SIZE;
// Version 3 uses the nest frequency to choose the bucket Id
// get the system target to find the NEST_FREQ_MHZ
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,
l_sysParent,
l_sysNestFreq));
//cast the voltage data into an array of buckets
fapi2::voltageBucketData_t* l_buckets = reinterpret_cast
<fapi2::voltageBucketData_t*>
(l_fullVpdData + POUNDV_BUCKET_OFFSET);
for(int i = 0; i < NUM_BUCKETS; i++)
{
if(l_buckets[i].pbFreq == l_sysNestFreq)
{
l_numMatches++;
if(l_numMatches > 1)
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::"
" Multiple buckets (%d) reporting the same nest frequency"
" Bucket Nest = %d Bucket ID = %d",
l_numMatches,
l_buckets[i].pbFreq,
(i + 1));
}
else
{
l_currentBucket = &l_buckets[i];
}
}
}
if(l_numMatches == 1)
{
l_bucketId = l_currentBucket->bucketId;
}
else
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching nest freqs found. Matches found = %d",
l_numMatches );
FAPI_ASSERT(false,
fapi2::INVALID_MATCHING_FREQ_NUMBER().
set_MATCHES_FOUND(l_numMatches),
"Matches found is NOT 1" );
}
}
else
{
FAPI_ASSERT( false,
fapi2::INVALID_POUNDV_VERSION()
.set_POUNDV_VERSION(*l_fullVpdData),
"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x",
*l_fullVpdData);
}
// This assert ensures the size of the calculated data is correct
FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *
l_bucketSize) >= l_bucketSize,
fapi2::BAD_VPD_READ().set_EXPECTED_SIZE(sizeof(l_bucketSize))
.set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -
((l_bucketId - 1) * l_bucketSize)),
"#V data read was too small!" );
}// else no override
// Ensure we got a valid bucket id
// NOTE: Bucket IDs range from 1-6
FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),
fapi2::INVALID_BUCKET_ID()
.set_TARGET(i_target)
.set_BUCKET_ID(l_bucketId),
"Invalid Bucket Id = %d",
l_bucketId );
// Use the selected bucket id to populate the output data
memcpy(o_data,
l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,
l_bucketSize);
fapi_try_exit:
if(l_fullVpdData != NULL)
{
free(l_fullVpdData);
l_fullVpdData = NULL;
}
if(l_prDataPtr != NULL)
{
free(l_prDataPtr);
l_prDataPtr = NULL;
}
FAPI_DBG("Exiting p9_pm_get_poundv_bucket_attr ....");
return fapi2::current_err;
}
<commit_msg>Improve error data for frequency mismatch from #V<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket_attr.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_pm_get_poundv_bucket_attr.C
/// @brief Grab PM data from certain bucket in #V keyword in LRPX record
///
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket_attr.H>
#include <p9_pm_get_poundv_bucket.H>
#include <mvpd_access_defs.H>
#include <attribute_ids.H>
fapi2::ReturnCode p9_pm_get_poundv_bucket_attr(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
uint8_t* o_data)
{
FAPI_DBG("Entering p9_pm_get_poundv_bucket_attr ....");
uint8_t* l_prDataPtr = NULL;
uint8_t* l_fullVpdData = NULL;
uint8_t l_overridePresent = 0;
uint32_t l_tempVpdSize = 0;
uint32_t l_vpdSize = 0;
uint8_t l_eqChipUnitPos = 0;
uint8_t l_bucketId;
uint8_t l_bucketSize = 0;
uint32_t l_sysNestFreq = 0;
fapi2::voltageBucketData_t* l_currentBucket = NULL;
uint8_t l_numMatches = 0;
fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;
//To read MVPD we will need the proc parent of the inputted EQ target
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =
i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
//Need to determine which LRP record to read from depending on which
//bucket we are getting the power management data from. FapiPos will
//tell us which LRP record to use.
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,
i_target,
l_eqChipUnitPos));
FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,
fapi2::INVALID_EQ_CHIP_POS().
set_EQ_POSITION( l_eqChipUnitPos ),
"Invalid EQ chip unit position = 0x%X",
l_eqChipUnitPos);
//The enumeration for the LRPx records are just 3 more
//than the EQ chip unit pos. See mvpd_access_defs.H
lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +
fapi2::MVPD_RECORD_LRP0 );
//check if bucket num has been overriden
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,
i_target,
l_overridePresent));
if(l_overridePresent != 0)
{
//If it has been overriden then get the override
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,
i_target,
l_bucketId));
}
else
{
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
NULL,
l_tempVpdSize) );
//save off the actual vpd size
l_vpdSize = l_tempVpdSize;
//Allocate memory for vpd data
l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
l_fullVpdData,
l_tempVpdSize) );
//Version 2:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x33 byte
//bucket b: 0x33 byte
//bucket c: 0x33 byte
//bucket d: 0x33 byte
//bucket e: 0x33 byte
//bucket f: 0x33 byte
if( *l_fullVpdData == POUNDV_VERSION_2)
{
//Set the size of the bucket
l_bucketSize = VERSION_2_BUCKET_SIZE;
//Reset VPD size because we want to find size of another VPD record
l_tempVpdSize = 0;
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
NULL,
l_tempVpdSize) );
l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
l_prDataPtr,
l_tempVpdSize) );
//Bucket ID is byte[4] of the PR keyword
memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));
}
//Version 3:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x3D byte
//bucket b: 0x3D byte
//bucket c: 0x3D byte
//bucket d: 0x3D byte
//bucket e: 0x3D byte
//bucket f: 0x3D byte
else if( *l_fullVpdData == POUNDV_VERSION_3 )
{
// Set the size of the bucket
l_bucketSize = VERSION_3_BUCKET_SIZE;
//Save off some FFDC data about the #V data itself
uint16_t l_bucketNestFreqs[NUM_BUCKETS] = { 0, 0, 0, 0, 0, 0 };
// Version 3 uses the nest frequency to choose the bucket Id
// get the system target to find the NEST_FREQ_MHZ
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,
l_sysParent,
l_sysNestFreq));
//cast the voltage data into an array of buckets
fapi2::voltageBucketData_t* l_buckets = reinterpret_cast
<fapi2::voltageBucketData_t*>
(l_fullVpdData + POUNDV_BUCKET_OFFSET);
for(int i = 0; i < NUM_BUCKETS; i++)
{
if(l_buckets[i].pbFreq == l_sysNestFreq)
{
l_numMatches++;
if(l_numMatches > 1)
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::"
" Multiple buckets (%d) reporting the same nest frequency"
" Bucket Nest = %d Bucket ID = %d, First Bucket = %d",
l_numMatches,
l_buckets[i].pbFreq,
(i + 1),
l_currentBucket);
}
else
{
l_currentBucket = &l_buckets[i];
}
}
//save FFDC in case we fail
l_bucketNestFreqs[i] = l_buckets[i].pbFreq;
}
if(l_numMatches == 1)
{
l_bucketId = l_currentBucket->bucketId;
}
else
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching nest freqs found for PBFreq=%d. Matches found = %d",
l_sysNestFreq, l_numMatches );
FAPI_ASSERT(false,
fapi2::INVALID_MATCHING_FREQ_NUMBER().
set_MATCHES_FOUND(l_numMatches).
set_DESIRED_FREQPB(l_sysNestFreq).
set_LRPREC(lrpRecord).
set_BUCKETA_FREQPB(l_bucketNestFreqs[0]).
set_BUCKETB_FREQPB(l_bucketNestFreqs[1]).
set_BUCKETC_FREQPB(l_bucketNestFreqs[2]).
set_BUCKETD_FREQPB(l_bucketNestFreqs[3]).
set_BUCKETE_FREQPB(l_bucketNestFreqs[4]).
set_BUCKETF_FREQPB(l_bucketNestFreqs[5]).
set_EQ(i_target),
"Matches found is NOT 1" );
}
}
else
{
FAPI_ASSERT( false,
fapi2::INVALID_POUNDV_VERSION()
.set_POUNDV_VERSION(*l_fullVpdData),
"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x",
*l_fullVpdData);
}
// This assert ensures the size of the calculated data is correct
FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *
l_bucketSize) >= l_bucketSize,
fapi2::BAD_VPD_READ().set_EXPECTED_SIZE(sizeof(l_bucketSize))
.set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -
((l_bucketId - 1) * l_bucketSize)),
"#V data read was too small!" );
}// else no override
// Ensure we got a valid bucket id
// NOTE: Bucket IDs range from 1-6
FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),
fapi2::INVALID_BUCKET_ID()
.set_TARGET(i_target)
.set_BUCKET_ID(l_bucketId),
"Invalid Bucket Id = %d",
l_bucketId );
// Use the selected bucket id to populate the output data
memcpy(o_data,
l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,
l_bucketSize);
fapi_try_exit:
if(l_fullVpdData != NULL)
{
free(l_fullVpdData);
l_fullVpdData = NULL;
}
if(l_prDataPtr != NULL)
{
free(l_prDataPtr);
l_prDataPtr = NULL;
}
FAPI_DBG("Exiting p9_pm_get_poundv_bucket_attr ....");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DrawDocShell.hxx,v $
* $Revision: 1.17 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SD_DRAW_DOC_SHELL_HXX
#define SD_DRAW_DOC_SHELL_HXX
#include <sfx2/docfac.hxx>
#include <sfx2/objsh.hxx>
#include <vcl/jobset.hxx>
#include "glob.hxx"
#include "sdmod.hxx"
#include "pres.hxx"
#include "sddllapi.h"
#include "fupoor.hxx"
class SfxStyleSheetBasePool;
class SfxStatusBarManager;
class SdStyleSheetPool;
class FontList;
class SdDrawDocument;
class SvxItemFactory;
class SdPage;
class SfxPrinter;
struct SdrDocumentStreamInfo;
struct SpellCallbackInfo;
class AbstractSvxNameDialog;
class SdFormatClipboard;
namespace sd {
class FrameView;
class View;
class ViewShell;
// ------------------
// - DrawDocShell -
// ------------------
class SD_DLLPUBLIC DrawDocShell : public SfxObjectShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDDRAWDOCSHELL)
SFX_DECL_OBJECTFACTORY();
DrawDocShell (
SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
BOOL bSdDataObj=FALSE,
DocumentType=DOCUMENT_TYPE_IMPRESS,
BOOL bScriptSupport=TRUE);
DrawDocShell (
SdDrawDocument* pDoc,
SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
BOOL bSdDataObj=FALSE,
DocumentType=DOCUMENT_TYPE_IMPRESS);
virtual ~DrawDocShell();
void UpdateRefDevice();
virtual void Activate( BOOL bMDI );
virtual void Deactivate( BOOL bMDI );
virtual BOOL InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL ConvertFrom( SfxMedium &rMedium );
virtual BOOL Save();
virtual BOOL SaveAsOwnFormat( SfxMedium& rMedium );
virtual BOOL ConvertTo( SfxMedium &rMedium );
virtual BOOL SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual sal_Bool Load( SfxMedium &rMedium );
virtual sal_Bool LoadFrom( SfxMedium& rMedium );
virtual sal_Bool SaveAs( SfxMedium &rMedium );
virtual Rectangle GetVisArea(USHORT nAspect) const;
virtual void Draw(OutputDevice*, const JobSetup& rSetup, USHORT nAspect = ASPECT_CONTENT);
virtual SfxUndoManager* GetUndoManager();
virtual Printer* GetDocumentPrinter();
virtual void OnDocumentPrinterChanged(Printer* pNewPrinter);
virtual SfxStyleSheetBasePool* GetStyleSheetPool();
virtual void SetOrganizerSearchMask(SfxStyleSheetBasePool* pBasePool) const;
virtual Size GetFirstPageSize();
virtual void FillClass(SvGlobalName* pClassName, sal_uInt32* pFormat, String* pAppName, String* pFullTypeName, String* pShortTypeName, sal_Int32 nFileFormat ) const;
virtual void SetModified( BOOL = TRUE );
using SotObject::GetInterface;
using SfxObjectShell::GetVisArea;
using SfxShell::GetViewShell;
sd::ViewShell* GetViewShell() { return mpViewShell; }
::sd::FrameView* GetFrameView();
::Window* GetWindow() const;
::sd::FunctionReference GetDocShellFunction() const { return mxDocShellFunction; }
void SetDocShellFunction( const ::sd::FunctionReference& xFunction );
SdDrawDocument* GetDoc();
DocumentType GetDocumentType() const { return meDocType; }
SfxPrinter* GetPrinter(BOOL bCreate);
void SetPrinter(SfxPrinter *pNewPrinter);
void UpdateFontList();
BOOL IsInDestruction() const { return mbInDestruction; }
void CancelSearching();
void Execute( SfxRequest& rReq );
void GetState(SfxItemSet&);
void Connect(sd::ViewShell* pViewSh);
void Disconnect(sd::ViewShell* pViewSh);
void UpdateTablePointers();
BOOL GotoBookmark(const String& rBookmark);
Bitmap GetPagePreviewBitmap(SdPage* pPage, USHORT nMaxEdgePixel);
/** checks, if the given name is a valid new name for a slide
<p>If the name is invalid, an <type>SvxNameDialog</type> pops up that
queries again for a new name until it is ok or the user chose
Cancel.</p>
@param pWin is necessary to pass to the <type>SvxNameDialog</type> in
case an invalid name was entered.
@param rName the new name that is to be set for a slide. This string
may be set to an empty string (see below).
@return TRUE, if the new name is unique. Note that if the user entered
a default name of a not-yet-existing slide (e.g. 'Slide 17'),
TRUE is returned, but rName is set to an empty string.
*/
BOOL CheckPageName(::Window* pWin, String& rName );
void SetSlotFilter(BOOL bEnable = FALSE, USHORT nCount = 0, const USHORT* pSIDs = NULL) { mbFilterEnable = bEnable; mnFilterCount = nCount; mpFilterSIDs = pSIDs; }
void ApplySlotFilter() const;
UINT16 GetStyleFamily() const { return mnStyleFamily; }
void SetStyleFamily( UINT16 nSF ) { mnStyleFamily = nSF; }
BOOL HasSpecialProgress() const { return ( mpSpecialProgress != NULL && mpSpecialProgressHdl != NULL ); }
void ReleaseSpecialProgress() { mpSpecialProgress = NULL; mpSpecialProgressHdl = NULL; }
void SetSpecialProgress( SfxProgress* _pProgress, Link* pLink ) { mpSpecialProgress = _pProgress; mpSpecialProgressHdl = pLink; }
SfxProgress* GetSpecialProgress() { return( HasSpecialProgress() ? mpSpecialProgress : NULL ); }
sal_Bool IsNewDocument() const;
/** executes the SID_OPENDOC slot to let the framework open a document
with the given URL and this document as a referer */
void OpenBookmark( const String& rBookmarkURL );
/** checks, if the given name is a valid new name for a slide
<p>This method does not pop up any dialog (like CheckPageName).</p>
@param rInOutPageName the new name for a slide that is to be renamed.
This string will be set to an empty string if
bResetStringIfStandardName is true and the name is of the
form of any, possibly not-yet existing, standard slide
(e.g. 'Slide 17')
@param bResetStringIfStandardName if true allows setting rInOutPageName
to an empty string, which returns true and implies that the
slide will later on get a new standard name (with a free
slide number).
@return true, if the new name is unique. If bResetStringIfStandardName
is true, the return value is also true, if the slide name is
a standard name (see above)
*/
bool IsNewPageNameValid( String & rInOutPageName, bool bResetStringIfStandardName = false );
/** Return the reference device for the current document. When the
inherited implementation returns a device then this is passed to the
caller. Otherwise the returned value depends on the printer
independent layout mode and will usually be either a printer or a
virtual device used for screen rendering.
@return
Returns NULL when the current document has no reference device.
*/
virtual OutputDevice* GetDocumentRefDev (void);
DECL_LINK( RenameSlideHdl, AbstractSvxNameDialog* );
// #91457# ExecuteSpellPopup now handled by DrawDocShell
DECL_LINK( OnlineSpellCallback, SpellCallbackInfo* );
void ClearUndoBuffer();
public:
SdFormatClipboard* mpFormatClipboard;
protected:
SdDrawDocument* mpDoc;
SfxUndoManager* mpUndoManager;
SfxPrinter* mpPrinter;
::sd::ViewShell* mpViewShell;
FontList* mpFontList;
::sd::FunctionReference mxDocShellFunction;
DocumentType meDocType;
UINT16 mnStyleFamily;
const USHORT* mpFilterSIDs;
USHORT mnFilterCount;
BOOL mbFilterEnable;
BOOL mbSdDataObj;
BOOL mbInDestruction;
BOOL mbOwnPrinter;
BOOL mbNewDocument;
static SfxProgress* mpSpecialProgress;
static Link* mpSpecialProgressHdl;
bool mbOwnDocument; // if true, we own mpDoc and will delete it in our d'tor
void Construct();
virtual void InPlaceActivate( BOOL bActive );
};
#ifndef SV_DECL_DRAW_DOC_SHELL_DEFINED
#define SV_DECL_DRAW_DOC_SHELL_DEFINED
SV_DECL_REF(DrawDocShell)
#endif
SV_IMPL_REF (DrawDocShell)
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS impress145 (1.17.50); FILE MERGED 2008/06/12 10:59:54 cl 1.17.50.1: #i73436# use only models with correct persist for clipboard<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DrawDocShell.hxx,v $
* $Revision: 1.18 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SD_DRAW_DOC_SHELL_HXX
#define SD_DRAW_DOC_SHELL_HXX
#include <sfx2/docfac.hxx>
#include <sfx2/objsh.hxx>
#include <vcl/jobset.hxx>
#include "glob.hxx"
#include "sdmod.hxx"
#include "pres.hxx"
#include "sddllapi.h"
#include "fupoor.hxx"
class SfxStyleSheetBasePool;
class SfxStatusBarManager;
class SdStyleSheetPool;
class FontList;
class SdDrawDocument;
class SvxItemFactory;
class SdPage;
class SfxPrinter;
struct SdrDocumentStreamInfo;
struct SpellCallbackInfo;
class AbstractSvxNameDialog;
class SdFormatClipboard;
namespace sd {
class FrameView;
class View;
class ViewShell;
// ------------------
// - DrawDocShell -
// ------------------
class SD_DLLPUBLIC DrawDocShell : public SfxObjectShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SD_IF_SDDRAWDOCSHELL)
SFX_DECL_OBJECTFACTORY();
DrawDocShell (
SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
BOOL bSdDataObj=FALSE,
DocumentType=DOCUMENT_TYPE_IMPRESS,
BOOL bScriptSupport=TRUE);
DrawDocShell (
SdDrawDocument* pDoc,
SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED,
BOOL bSdDataObj=FALSE,
DocumentType=DOCUMENT_TYPE_IMPRESS);
virtual ~DrawDocShell();
void UpdateRefDevice();
virtual void Activate( BOOL bMDI );
virtual void Deactivate( BOOL bMDI );
virtual BOOL InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL ConvertFrom( SfxMedium &rMedium );
virtual BOOL Save();
virtual BOOL SaveAsOwnFormat( SfxMedium& rMedium );
virtual BOOL ConvertTo( SfxMedium &rMedium );
virtual BOOL SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual sal_Bool Load( SfxMedium &rMedium );
virtual sal_Bool LoadFrom( SfxMedium& rMedium );
virtual sal_Bool SaveAs( SfxMedium &rMedium );
virtual Rectangle GetVisArea(USHORT nAspect) const;
virtual void Draw(OutputDevice*, const JobSetup& rSetup, USHORT nAspect = ASPECT_CONTENT);
virtual SfxUndoManager* GetUndoManager();
virtual Printer* GetDocumentPrinter();
virtual void OnDocumentPrinterChanged(Printer* pNewPrinter);
virtual SfxStyleSheetBasePool* GetStyleSheetPool();
virtual void SetOrganizerSearchMask(SfxStyleSheetBasePool* pBasePool) const;
virtual Size GetFirstPageSize();
virtual void FillClass(SvGlobalName* pClassName, sal_uInt32* pFormat, String* pAppName, String* pFullTypeName, String* pShortTypeName, sal_Int32 nFileFormat ) const;
virtual void SetModified( BOOL = TRUE );
using SotObject::GetInterface;
using SfxObjectShell::GetVisArea;
using SfxShell::GetViewShell;
sd::ViewShell* GetViewShell() { return mpViewShell; }
::sd::FrameView* GetFrameView();
::Window* GetWindow() const;
::sd::FunctionReference GetDocShellFunction() const { return mxDocShellFunction; }
void SetDocShellFunction( const ::sd::FunctionReference& xFunction );
SdDrawDocument* GetDoc();
DocumentType GetDocumentType() const { return meDocType; }
SfxPrinter* GetPrinter(BOOL bCreate);
void SetPrinter(SfxPrinter *pNewPrinter);
void UpdateFontList();
BOOL IsInDestruction() const { return mbInDestruction; }
void CancelSearching();
void Execute( SfxRequest& rReq );
void GetState(SfxItemSet&);
void Connect(sd::ViewShell* pViewSh);
void Disconnect(sd::ViewShell* pViewSh);
void UpdateTablePointers();
BOOL GotoBookmark(const String& rBookmark);
Bitmap GetPagePreviewBitmap(SdPage* pPage, USHORT nMaxEdgePixel);
/** checks, if the given name is a valid new name for a slide
<p>If the name is invalid, an <type>SvxNameDialog</type> pops up that
queries again for a new name until it is ok or the user chose
Cancel.</p>
@param pWin is necessary to pass to the <type>SvxNameDialog</type> in
case an invalid name was entered.
@param rName the new name that is to be set for a slide. This string
may be set to an empty string (see below).
@return TRUE, if the new name is unique. Note that if the user entered
a default name of a not-yet-existing slide (e.g. 'Slide 17'),
TRUE is returned, but rName is set to an empty string.
*/
BOOL CheckPageName(::Window* pWin, String& rName );
void SetSlotFilter(BOOL bEnable = FALSE, USHORT nCount = 0, const USHORT* pSIDs = NULL) { mbFilterEnable = bEnable; mnFilterCount = nCount; mpFilterSIDs = pSIDs; }
void ApplySlotFilter() const;
UINT16 GetStyleFamily() const { return mnStyleFamily; }
void SetStyleFamily( UINT16 nSF ) { mnStyleFamily = nSF; }
BOOL HasSpecialProgress() const { return ( mpSpecialProgress != NULL && mpSpecialProgressHdl != NULL ); }
void ReleaseSpecialProgress() { mpSpecialProgress = NULL; mpSpecialProgressHdl = NULL; }
void SetSpecialProgress( SfxProgress* _pProgress, Link* pLink ) { mpSpecialProgress = _pProgress; mpSpecialProgressHdl = pLink; }
SfxProgress* GetSpecialProgress() { return( HasSpecialProgress() ? mpSpecialProgress : NULL ); }
sal_Bool IsNewDocument() const;
/** executes the SID_OPENDOC slot to let the framework open a document
with the given URL and this document as a referer */
void OpenBookmark( const String& rBookmarkURL );
/** checks, if the given name is a valid new name for a slide
<p>This method does not pop up any dialog (like CheckPageName).</p>
@param rInOutPageName the new name for a slide that is to be renamed.
This string will be set to an empty string if
bResetStringIfStandardName is true and the name is of the
form of any, possibly not-yet existing, standard slide
(e.g. 'Slide 17')
@param bResetStringIfStandardName if true allows setting rInOutPageName
to an empty string, which returns true and implies that the
slide will later on get a new standard name (with a free
slide number).
@return true, if the new name is unique. If bResetStringIfStandardName
is true, the return value is also true, if the slide name is
a standard name (see above)
*/
bool IsNewPageNameValid( String & rInOutPageName, bool bResetStringIfStandardName = false );
/** Return the reference device for the current document. When the
inherited implementation returns a device then this is passed to the
caller. Otherwise the returned value depends on the printer
independent layout mode and will usually be either a printer or a
virtual device used for screen rendering.
@return
Returns NULL when the current document has no reference device.
*/
virtual OutputDevice* GetDocumentRefDev (void);
DECL_LINK( RenameSlideHdl, AbstractSvxNameDialog* );
// #91457# ExecuteSpellPopup now handled by DrawDocShell
DECL_LINK( OnlineSpellCallback, SpellCallbackInfo* );
void ClearUndoBuffer();
public:
SdFormatClipboard* mpFormatClipboard;
protected:
SdDrawDocument* mpDoc;
SfxUndoManager* mpUndoManager;
SfxPrinter* mpPrinter;
::sd::ViewShell* mpViewShell;
FontList* mpFontList;
::sd::FunctionReference mxDocShellFunction;
DocumentType meDocType;
UINT16 mnStyleFamily;
const USHORT* mpFilterSIDs;
USHORT mnFilterCount;
BOOL mbFilterEnable;
BOOL mbSdDataObj;
BOOL mbInDestruction;
BOOL mbOwnPrinter;
BOOL mbNewDocument;
static SfxProgress* mpSpecialProgress;
static Link* mpSpecialProgressHdl;
bool mbOwnDocument; // if true, we own mpDoc and will delete it in our d'tor
void Construct(bool bClipboard);
virtual void InPlaceActivate( BOOL bActive );
};
#ifndef SV_DECL_DRAW_DOC_SHELL_DEFINED
#define SV_DECL_DRAW_DOC_SHELL_DEFINED
SV_DECL_REF(DrawDocShell)
#endif
SV_IMPL_REF (DrawDocShell)
} // end of namespace sd
#endif
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.