<commit_before>//************************************************************/
//
//	Ratio Implementation
//
//	Implements the SPXRatio class, which validates the ratio
//  type string, and then grabs the required TGraphs and
//  performs the necessary divisions, returning a fully
//  configured and ready-to-draw TGraph.
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		25.09.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/

#include <iostream>
#include <sstream>

#include "SPXRatio.h"
#include "SPXUtilities.h"
#include "SPXException.h"

//Class name for debug statements
const std::string cn = "SPXRatio::";

//Must define the static debug variable in the implementation
bool SPXRatio::debug;

//Takes a string argument in the following form:
//
//	(numerator) / (denominator) 							<-- MUST have the parenthesis!
//
// 	Where the options for numerator and denominator are:
//
//		[grid_steering_file.txt, pdf_steering_file.txt]		<-- Convolute
//		data_steering file									<-- Data
//		grid_steering file 									<-- Reference
//
//	And the numerator/denominator pair options are:
//
//		data / convolute
//		convolute / data
//		data / data
//		convolute / reference
//
void SPXRatio::Parse(std::string &s) {
    std::string mn = "Parse: ";

	std::string numBlob;
	std::string denBlob;

    if(debug) std::cout << cn << mn << "Parsing ratio string: " << s << std::endl;

    //Parse the string into numerator and denominator (delimit with '/')
    std::vector<std::string> v = SPXStringUtilities::ParseString(s, '/');

    //Make sure vector is EXACTLY 2 strings long
    if(v.size() != 2) {
    	throw SPXParseException(cn + mn + "Ratio string: " + s + " is NOT in the form (numerator) / (denominator)");
    }

    //Obtain the numerator and denominator blobs from parsed list
	numBlob = v.at(0);
	denBlob = v.at(1);

	if(numBlob.empty()) {
		throw SPXParseException(cn + mn + "Numerator blob is empty");
	} else {
		numeratorBlob = numBlob;
	}

	if(denBlob.empty()) {
		throw SPXParseException(cn + mn + "Denominator blob is empty");
	} else {
		denominatorBlob = denBlob;
	}

	if(debug) {
		std::cout << cn << mn << "Numerator blob parsed as: " << numeratorBlob << std::endl;
		std::cout << cn << mn << "Denominator blob parsed as: " << denominatorBlob << std::endl;
	}

    if(debug) std::cout << cn << mn << "Ratio style is: " << ratioStyle.ToString() << "(" << ratioStyle.GetStyle() << ")" << std::endl;

    //Check the RatioStyle:
    if(ratioStyle.IsDataOverConvolute()) {
        if(debug) std::cout << cn << mn << "Data over Convolute" << std::endl;

        //Error if numBlob matches a convolute string
        if(MatchesConvoluteString(numBlob)) {
            throw SPXParseException(cn + mn + "Numerator blob should have a \"data\" style, but has \"convolute\" style");
        }

        //Error if denBlob does NOT match a convolute string
        if(!MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Denominator blob should have a \"convolute\" style, but does not");
        }

        //Get the data steering file from the numerator
        numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");

        //Get the grid/pdf steering files from the denominator
        SPXStringUtilities::RemoveCharacters(denBlob, "()");
        SPXStringUtilities::RemoveCharacters(denBlob, "[]");
        std::vector<std::string> v_den = SPXStringUtilities::CommaSeparatedListToVector(denBlob);
        if(v_den.size() != 2) {
            throw SPXParseException(cn + mn + "Denominator blob is NOT of the form \"[grid_file, pdf_file]\"");
        }
        denominatorConvoluteGridFile = v_den.at(0);
        denominatorConvolutePDFFile = v_den.at(1);

        if(debug) {
            std::cout << cn << mn << "Successfully parsed data / convolute string: " << std::endl;

            std::ostringstream oss;
            oss << numeratorDataFile << " / " << "[" << denominatorConvoluteGridFile << ", " << denominatorConvolutePDFFile << "]";
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    else if(ratioStyle.IsConvoluteOverData()) {
        if(debug) std::cout << cn << mn << "Convolute over Data" << std::endl;

        //Error if numBlob does NOT match a convolute string
        if(!MatchesConvoluteString(numBlob)) {
            throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
        }

        //Error if denBlob matches a convolute string
        if(MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Denominator blob should have a \"data\" style, but has \"convolute\" style");
        }

        //Get the grid/pdf steering files from the numerator
        SPXStringUtilities::RemoveCharacters(numBlob, "()");
        SPXStringUtilities::RemoveCharacters(numBlob, "[]");
        std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
        if(v_num.size() != 2) {
            throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
        }
        numeratorConvoluteGridFile = v_num.at(0);
        numeratorConvolutePDFFile = v_num.at(1);

        //Get the data steering file from the denominator
        denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");

        if(debug) {
            std::cout << cn << mn << "Successfully parsed convolute / data string: " << std::endl;
            std::ostringstream oss;
            oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorDataFile;
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    else if(ratioStyle.IsConvoluteOverReference()) {
        if(debug) std::cout << cn << mn << "Convolute over reference" << std::endl;

        //Error if numBlob does NOT match a convolute string
        if(!MatchesConvoluteString(numBlob)) {
            throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
        }

        //Error if denBlob matches a convolute string
        if(MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Denominator blob should have a \"reference\" style, but has \"convolute\" style");
        }

        //Get the grid/pdf steering files from the numerator
        SPXStringUtilities::RemoveCharacters(numBlob, "()");
        SPXStringUtilities::RemoveCharacters(numBlob, "[]");
        std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
        if(v_num.size() != 2) {
            throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
        }
        numeratorConvoluteGridFile = v_num.at(0);
        numeratorConvolutePDFFile = v_num.at(1);

        //Get the reference grid steering file from the denominator
        denominatorReferenceGridFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");

        //Error if reference grid steering file does NOT match the convolute grid file
        if(numeratorConvoluteGridFile.compare(denominatorReferenceGridFile) != 0) {
            throw SPXParseException(cn + mn + "Numerator's convolute grid file \"" + numeratorConvoluteGridFile + \
                "\" MUST match the denominator's refererence grid file: \"" + denominatorReferenceGridFile + "\"");
        }

        if(debug) {
            std::cout << cn << mn << "Successfully parsed convolute / reference string: " << std::endl;
            std::ostringstream oss;
            oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorReferenceGridFile;
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    else if(ratioStyle.IsDataOverData()) {
        if(debug) std::cout << cn << mn << "Data Over Data" << std::endl;

        //Error if numerator or denominator matches convolute string
        if(MatchesConvoluteString(numBlob) || MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Numerator AND denominator blob should have a \"data\" style, but at least one has \"convolute\" style");
        }

        //Get the data file from the numerator
        numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");

        //Get the data file from the denominator
        denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");

        if(debug) {
            std::cout << cn << mn << "Successfully parsed data / data string: " << std::endl;
            std::ostringstream oss;
            oss << numeratorDataFile << " / " << denominatorDataFile;
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    //Get the graphs based on the steering files given
    GetGraphs();
}

void SPXRatio::GetGraphs(void) {
    return;
}

bool SPXRatio::MatchesConvoluteString(std::string &s) {
    std::string mn = "MatchesConvoluteString: ";

    SPXStringUtilities::RemoveCharacters(s, "()");

    if(debug) std::cout << cn << mn << "Checking \"" << s << "\" against convolute pattern" << std::endl;

    //Convolute strings MUST begin with '[', end with ']', and have a ',' somewhere in the middle
    if((s.at(0) == '[') && (s.at(s.size() - 1) == ']') && (s.find(",") != std::string::npos)) {
        if(debug) std::cout << cn << mn << s << " matches convolute pattern" << std::endl;
        return true;
    } else {
        if(debug) std::cout << cn << mn << s << " does NOT match convolute pattern" << std::endl;
        return false;
    }
}
<commit_msg>Working on SPXRatio<commit_after>//************************************************************/
//
//	Ratio Implementation
//
//	Implements the SPXRatio class, which validates the ratio
//  type string, and then grabs the required TGraphs and
//  performs the necessary divisions, returning a fully
//  configured and ready-to-draw TGraph.
//
//	@Author: 	J. Gibson, C. Embree, T. Carli - CERN ATLAS
//	@Date:		25.09.2014
//	@Email:		gibsjose@mail.gvsu.edu
//
//************************************************************/

#include <iostream>
#include <sstream>

#include "SPXRatio.h"
#include "SPXUtilities.h"
#include "SPXException.h"

//Class name for debug statements
const std::string cn = "SPXRatio::";

//Must define the static debug variable in the implementation
bool SPXRatio::debug;

//Takes a string argument in the following form:
//
//	(numerator) / (denominator) 							<-- MUST have the parenthesis!
//
// 	Where the options for numerator and denominator are:
//
//		[grid_steering_file.txt, pdf_steering_file.txt]		<-- Convolute
//		data_steering file									<-- Data
//		grid_steering file 									<-- Reference
//
//	And the numerator/denominator pair options are:
//
//		data / convolute
//		convolute / data
//		data / data
//		convolute / reference
//
void SPXRatio::Parse(std::string &s) {
    std::string mn = "Parse: ";

	std::string numBlob;
	std::string denBlob;

    if(debug) std::cout << cn << mn << "Parsing ratio string: " << s << std::endl;

    //Parse the string into numerator and denominator (delimit with '/')
    std::vector<std::string> v = SPXStringUtilities::ParseString(s, '/');

    //Make sure vector is EXACTLY 2 strings long
    if(v.size() != 2) {
    	throw SPXParseException(cn + mn + "Ratio string: " + s + " is NOT in the form (numerator) / (denominator)");
    }

    //Obtain the numerator and denominator blobs from parsed list
	numBlob = v.at(0);
	denBlob = v.at(1);

	if(numBlob.empty()) {
		throw SPXParseException(cn + mn + "Numerator blob is empty");
	} else {
		numeratorBlob = numBlob;
	}

	if(denBlob.empty()) {
		throw SPXParseException(cn + mn + "Denominator blob is empty");
	} else {
		denominatorBlob = denBlob;
	}

	if(debug) {
		std::cout << cn << mn << "Numerator blob parsed as: " << numeratorBlob << std::endl;
		std::cout << cn << mn << "Denominator blob parsed as: " << denominatorBlob << std::endl;
	}

    if(debug) std::cout << cn << mn << "Ratio style is: " << ratioStyle.ToString() << "(" << ratioStyle.GetNumerator() \
        << " / " << ratioStyle.GetDenominator() << ")" << std::endl;

    //Check the RatioStyle:
    if(ratioStyle.IsDataOverConvolute()) {
        if(debug) std::cout << cn << mn << "Data over Convolute" << std::endl;

        //Error if numBlob matches a convolute string
        if(MatchesConvoluteString(numBlob)) {
            throw SPXParseException(cn + mn + "Numerator blob should have a \"data\" style, but has \"convolute\" style");
        }

        //Error if denBlob does NOT match a convolute string
        if(!MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Denominator blob should have a \"convolute\" style, but does not");
        }

        //Get the data steering file from the numerator
        numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");

        //Get the grid/pdf steering files from the denominator
        SPXStringUtilities::RemoveCharacters(denBlob, "()");
        SPXStringUtilities::RemoveCharacters(denBlob, "[]");
        std::vector<std::string> v_den = SPXStringUtilities::CommaSeparatedListToVector(denBlob);
        if(v_den.size() != 2) {
            throw SPXParseException(cn + mn + "Denominator blob is NOT of the form \"[grid_file, pdf_file]\"");
        }
        denominatorConvoluteGridFile = v_den.at(0);
        denominatorConvolutePDFFile = v_den.at(1);

        if(debug) {
            std::cout << cn << mn << "Successfully parsed data / convolute string: " << std::endl;

            std::ostringstream oss;
            oss << numeratorDataFile << " / " << "[" << denominatorConvoluteGridFile << ", " << denominatorConvolutePDFFile << "]";
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    else if(ratioStyle.IsConvoluteOverData()) {
        if(debug) std::cout << cn << mn << "Convolute over Data" << std::endl;

        //Error if numBlob does NOT match a convolute string
        if(!MatchesConvoluteString(numBlob)) {
            throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
        }

        //Error if denBlob matches a convolute string
        if(MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Denominator blob should have a \"data\" style, but has \"convolute\" style");
        }

        //Get the grid/pdf steering files from the numerator
        SPXStringUtilities::RemoveCharacters(numBlob, "()");
        SPXStringUtilities::RemoveCharacters(numBlob, "[]");
        std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
        if(v_num.size() != 2) {
            throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
        }
        numeratorConvoluteGridFile = v_num.at(0);
        numeratorConvolutePDFFile = v_num.at(1);

        //Get the data steering file from the denominator
        denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");

        if(debug) {
            std::cout << cn << mn << "Successfully parsed convolute / data string: " << std::endl;
            std::ostringstream oss;
            oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorDataFile;
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    else if(ratioStyle.IsConvoluteOverReference()) {
        if(debug) std::cout << cn << mn << "Convolute over reference" << std::endl;

        //Error if numBlob does NOT match a convolute string
        if(!MatchesConvoluteString(numBlob)) {
            throw SPXParseException(cn + mn + "Numerator blob should have a \"convolute\" style, but does not");
        }

        //Error if denBlob matches a convolute string
        if(MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Denominator blob should have a \"reference\" style, but has \"convolute\" style");
        }

        //Get the grid/pdf steering files from the numerator
        SPXStringUtilities::RemoveCharacters(numBlob, "()");
        SPXStringUtilities::RemoveCharacters(numBlob, "[]");
        std::vector<std::string> v_num = SPXStringUtilities::CommaSeparatedListToVector(numBlob);
        if(v_num.size() != 2) {
            throw SPXParseException(cn + mn + "Numerator blob is NOT of the form \"[grid_file, pdf_file]\"");
        }
        numeratorConvoluteGridFile = v_num.at(0);
        numeratorConvolutePDFFile = v_num.at(1);

        //Get the reference grid steering file from the denominator
        denominatorReferenceGridFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");

        //Error if reference grid steering file does NOT match the convolute grid file
        if(numeratorConvoluteGridFile.compare(denominatorReferenceGridFile) != 0) {
            throw SPXParseException(cn + mn + "Numerator's convolute grid file \"" + numeratorConvoluteGridFile + \
                "\" MUST match the denominator's refererence grid file: \"" + denominatorReferenceGridFile + "\"");
        }

        if(debug) {
            std::cout << cn << mn << "Successfully parsed convolute / reference string: " << std::endl;
            std::ostringstream oss;
            oss << "[" << numeratorConvoluteGridFile << ", " << numeratorConvolutePDFFile << "]" << " / " << denominatorReferenceGridFile;
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    else if(ratioStyle.IsDataOverData()) {
        if(debug) std::cout << cn << mn << "Data Over Data" << std::endl;

        //Error if numerator or denominator matches convolute string
        if(MatchesConvoluteString(numBlob) || MatchesConvoluteString(denBlob)) {
            throw SPXParseException(cn + mn + "Numerator AND denominator blob should have a \"data\" style, but at least one has \"convolute\" style");
        }

        //Get the data file from the numerator
        numeratorDataFile = SPXStringUtilities::RemoveCharacters(numBlob, "()");

        //Get the data file from the denominator
        denominatorDataFile = SPXStringUtilities::RemoveCharacters(denBlob, "()");

        if(debug) {
            std::cout << cn << mn << "Successfully parsed data / data string: " << std::endl;
            std::ostringstream oss;
            oss << numeratorDataFile << " / " << denominatorDataFile;
            ratioString = oss.str();
            std::cout << "\t " << ratioString << std::endl;
        }
    }

    //Get the graphs based on the steering files given
    GetGraphs();
}

void SPXRatio::GetGraphs(void) {
    return;
}

bool SPXRatio::MatchesConvoluteString(std::string &s) {
    std::string mn = "MatchesConvoluteString: ";

    SPXStringUtilities::RemoveCharacters(s, "()");

    if(debug) std::cout << cn << mn << "Checking \"" << s << "\" against convolute pattern" << std::endl;

    //Convolute strings MUST begin with '[', end with ']', and have a ',' somewhere in the middle
    if((s.at(0) == '[') && (s.at(s.size() - 1) == ']') && (s.find(",") != std::string::npos)) {
        if(debug) std::cout << cn << mn << s << " matches convolute pattern" << std::endl;
        return true;
    } else {
        if(debug) std::cout << cn << mn << s << " does NOT match convolute pattern" << std::endl;
        return false;
    }
}
<|endoftext|>


<commit_before>//
//  Settings.cpp
//  RunParticles
//
//  Created by Doug Letterman on 11/1/14.
//
//

#include "Settings.h"

#include <fnmatch.h>

TrackStyleRule::TrackStyleRule() :
    pattern("*"),
    color(QColor(255,0,0)),
    width(1.0)
{

}

QVariant
TrackStyleRule::toVariant() const
{
    QList<QVariant> var;
    var.append(QVariant(pattern));
    var.append(QVariant(color.rgba()));
    var.append(QVariant(width));
    return var;
}

TrackStyleRule
TrackStyleRule::fromVariant(const QVariant &var)
{
    TrackStyleRule pref;
    QList<QVariant> parts = var.toList();
    int size = parts.size();
    if (size >= 1) {
        pref.pattern = parts[0].toString();
        if (size >= 2) {
            pref.color = QColor::fromRgba(parts[1].toUInt());
            if (size >= 3)
                pref.width = parts[2].toUInt();
        }
    }
    return pref;
}

QVariant
TrackStyleRules::toVariant() const
{
    QList<QVariant> vars;
    TrackStyleRule myPref;
    foreach(myPref, prefs) {
        vars.append(myPref.toVariant());
    }
    return QVariant(vars);
}

TrackStyleRule
TrackStyleRules::getStyleForTrackType(const QString &type) const
{
    TrackStyleRule myPref;
    const char* theType = type.toStdString().c_str();
    foreach(myPref, prefs) {
        const char* myPattern = myPref.pattern.toStdString().c_str();
        if (fnmatch(myPattern, theType, FNM_PATHNAME) == 0) {
            return myPref;
        }
    }
    return TrackStyleRule();
}

TrackStyleRules
TrackStyleRules::fromVariant(const QVariant &var)
{
    TrackStyleRules myPrefs;
    QList<QVariant> vars = var.toList();
    QVariant myVar;
    foreach(myVar, vars)
    {
        myPrefs.prefs.append(TrackStyleRule::fromVariant(myVar));
    }
    return myPrefs;
}

TrackStyleRules
TrackStyleRules::getDefaultRules()
{
    TrackStyleRules myPrefs;
    TrackStyleRule runPref, bikePref, cyclingPref, otherPrefs;
    runPref.pattern = QString("Running");
    runPref.color = QColor(255, 0, 0);
    bikePref.pattern = QString("Biking");
    bikePref.color = QColor(0, 0, 255);
    cyclingPref.pattern = QString("Cycling");
    cyclingPref.color = QColor(0, 0, 255);
    otherPrefs.pattern = QString("*");
    otherPrefs.color = QColor(0, 255, 0);
    myPrefs.prefs << runPref << bikePref << cyclingPref << otherPrefs;
    return myPrefs;
}

Settings::Settings(QObject *parent) :
    QObject(parent),
    _settings(new QSettings(this))
{

}

void
Settings::clear()
{
    _settings->clear();
}

bool
Settings::restoreWidgetState(QWidget *widget)
{
    _settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
    bool hasState;
    if ((hasState = _settings->contains("size")))
        widget->resize(_settings->value("size").toSize());
    if (_settings->contains("pos"))
        widget->move(_settings->value("pos").toPoint());
    _settings->endGroup();
    return hasState;
}

void
Settings::saveWidgetState(const QWidget *widget)
{
    _settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
    _settings->setValue("size", widget->size());
    _settings->setValue("pos", widget->pos());
    _settings->endGroup();
}

QStringList
Settings::getRecentMapFiles()
{
    return _getList("recentMapFiles");
}

void
Settings::setRecentMapFiles(const QList<QString> &files)
{
    _setList("recentMapFiles", files);
}

QStringList
Settings::getRecentLayerFiles()
{
    return _getList("recentLayerFiles");
}

void
Settings::setRecentLayerFiles(const QList<QString> &files)
{
    _setList("recentLayerFiles", files);
}

TrackStyleRules
Settings::getTrackStyleRules()
{
    if (_settings->contains("trackStyleRules"))
        return TrackStyleRules::fromVariant(_settings->value("trackStyleRules"));
    return TrackStyleRules::getDefaultRules();
}

void
Settings::setTrackStyleRules(const TrackStyleRules &rules)
{
    _settings->setValue("trackStyleRules", rules.toVariant());
}

LonLatBox
Settings::getStartingViewArea()
{
    if (_settings->contains("startingViewArea")) {
        QVariantList vars = _settings->value("startingViewArea").toList();
        if (vars.length() == 4) {
            double bounds[4];
            bool ok = true;
            for (int i=0; i<4 && ok; i++) {
                bounds[i] = vars[i].toDouble(&ok);
            }
            if (ok)
                return LonLatBox(bounds[0], bounds[1], bounds[2], bounds[3]);
        }
    }
    // Default is centered over Oakland
    return LonLatBox(-122.37, 37.93, -122.27, 37.73);
}

void
Settings::setStartingViewArea(const LonLatBox &viewArea)
{
    QVariantList bounds;
    bounds << QVariant(viewArea.upperLeft.x)
           << QVariant(viewArea.upperLeft.y)
           << QVariant(viewArea.lowerRight.x)
           << QVariant(viewArea.lowerRight.y);
    _settings->setValue("startingViewArea", bounds);
}

bool
Settings::getShowOpenStreetMap()
{
    return _settings->value("showOpenStreetMap", QVariant(true)).toBool();
}

void
Settings::setShowOpenStreetMap(bool show)
{
    _settings->setValue("showOpenStreetMap", show);
}

bool
Settings::getFrameLastAddedLayer()
{
    return _settings->value("frameLastAddedLayer", QVariant(true)).toBool();
}

void
Settings::setFrameLastAddedLayer(bool frame)
{
    _settings->setValue("frameLastAddedLayer", frame);
}

QStringList
Settings::_getList(const QString &key)
{
    QList<QString> files;
    QList<QVariant> strVars = _settings->value(key).toList();
    QVariant myvar;
    foreach(myvar, strVars) {
        files.append(myvar.toString());
    }
    return files;
}

void
Settings::_setList(const QString &key, const QList<QString> &files)
{
    QList<QVariant> varList;
    QString myFile;
    foreach(myFile, files) {
        varList.append(QVariant(myFile));
    }
    _settings->setValue(key, QVariant(varList));
}

<commit_msg>Added a y offset to saveWidgetState to work around an apparent Qt bug.<commit_after>//
//  Settings.cpp
//  RunParticles
//
//  Created by Doug Letterman on 11/1/14.
//
//

#include "Settings.h"

#include <QApplication>
#include <QDesktopWidget>

#include <fnmatch.h>

TrackStyleRule::TrackStyleRule() :
    pattern("*"),
    color(QColor(255,0,0)),
    width(1.0)
{

}

QVariant
TrackStyleRule::toVariant() const
{
    QList<QVariant> var;
    var.append(QVariant(pattern));
    var.append(QVariant(color.rgba()));
    var.append(QVariant(width));
    return var;
}

TrackStyleRule
TrackStyleRule::fromVariant(const QVariant &var)
{
    TrackStyleRule pref;
    QList<QVariant> parts = var.toList();
    int size = parts.size();
    if (size >= 1) {
        pref.pattern = parts[0].toString();
        if (size >= 2) {
            pref.color = QColor::fromRgba(parts[1].toUInt());
            if (size >= 3)
                pref.width = parts[2].toUInt();
        }
    }
    return pref;
}

QVariant
TrackStyleRules::toVariant() const
{
    QList<QVariant> vars;
    TrackStyleRule myPref;
    foreach(myPref, prefs) {
        vars.append(myPref.toVariant());
    }
    return QVariant(vars);
}

TrackStyleRule
TrackStyleRules::getStyleForTrackType(const QString &type) const
{
    TrackStyleRule myPref;
    const char* theType = type.toStdString().c_str();
    foreach(myPref, prefs) {
        const char* myPattern = myPref.pattern.toStdString().c_str();
        if (fnmatch(myPattern, theType, FNM_PATHNAME) == 0) {
            return myPref;
        }
    }
    return TrackStyleRule();
}

TrackStyleRules
TrackStyleRules::fromVariant(const QVariant &var)
{
    TrackStyleRules myPrefs;
    QList<QVariant> vars = var.toList();
    QVariant myVar;
    foreach(myVar, vars)
    {
        myPrefs.prefs.append(TrackStyleRule::fromVariant(myVar));
    }
    return myPrefs;
}

TrackStyleRules
TrackStyleRules::getDefaultRules()
{
    TrackStyleRules myPrefs;
    TrackStyleRule runPref, bikePref, cyclingPref, otherPrefs;
    runPref.pattern = QString("Running");
    runPref.color = QColor(255, 0, 0);
    bikePref.pattern = QString("Biking");
    bikePref.color = QColor(0, 0, 255);
    cyclingPref.pattern = QString("Cycling");
    cyclingPref.color = QColor(0, 0, 255);
    otherPrefs.pattern = QString("*");
    otherPrefs.color = QColor(0, 255, 0);
    myPrefs.prefs << runPref << bikePref << cyclingPref << otherPrefs;
    return myPrefs;
}

Settings::Settings(QObject *parent) :
    QObject(parent),
    _settings(new QSettings(this))
{

}

void
Settings::clear()
{
    _settings->clear();
}

bool
Settings::restoreWidgetState(QWidget *widget)
{
    _settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
    bool hasState;
    if ((hasState = _settings->contains("size")))
        widget->resize(_settings->value("size").toSize());
    if (_settings->contains("pos"))
        widget->move(_settings->value("pos").toPoint());
    _settings->endGroup();
    return hasState;
}

void
Settings::saveWidgetState(const QWidget *widget)
{
    /* There is a Qt bug where pos() does not properly account for the size
       of the application's menu bar, so calling move() on the result of pos()
       causes QWidgets to creep slowly down the screen after each restore.
     */
    QDesktopWidget *desktop = QApplication::desktop();
    int yOffset = desktop->screenGeometry().height() -
                desktop->availableGeometry().height() - 4;
    _settings->beginGroup(QString("widgetGeometry/%0").arg(widget->objectName()));
    QPoint pos = widget->pos();
    pos.setY(pos.y() - yOffset);
    _settings->setValue("size", widget->size());
    _settings->setValue("pos", pos);
    _settings->endGroup();
}

QStringList
Settings::getRecentMapFiles()
{
    return _getList("recentMapFiles");
}

void
Settings::setRecentMapFiles(const QList<QString> &files)
{
    _setList("recentMapFiles", files);
}

QStringList
Settings::getRecentLayerFiles()
{
    return _getList("recentLayerFiles");
}

void
Settings::setRecentLayerFiles(const QList<QString> &files)
{
    _setList("recentLayerFiles", files);
}

TrackStyleRules
Settings::getTrackStyleRules()
{
    if (_settings->contains("trackStyleRules"))
        return TrackStyleRules::fromVariant(_settings->value("trackStyleRules"));
    return TrackStyleRules::getDefaultRules();
}

void
Settings::setTrackStyleRules(const TrackStyleRules &rules)
{
    _settings->setValue("trackStyleRules", rules.toVariant());
}

LonLatBox
Settings::getStartingViewArea()
{
    if (_settings->contains("startingViewArea")) {
        QVariantList vars = _settings->value("startingViewArea").toList();
        if (vars.length() == 4) {
            double bounds[4];
            bool ok = true;
            for (int i=0; i<4 && ok; i++) {
                bounds[i] = vars[i].toDouble(&ok);
            }
            if (ok)
                return LonLatBox(bounds[0], bounds[1], bounds[2], bounds[3]);
        }
    }
    // Default is centered over Oakland
    return LonLatBox(-122.37, 37.93, -122.27, 37.73);
}

void
Settings::setStartingViewArea(const LonLatBox &viewArea)
{
    QVariantList bounds;
    bounds << QVariant(viewArea.upperLeft.x)
           << QVariant(viewArea.upperLeft.y)
           << QVariant(viewArea.lowerRight.x)
           << QVariant(viewArea.lowerRight.y);
    _settings->setValue("startingViewArea", bounds);
}

bool
Settings::getShowOpenStreetMap()
{
    return _settings->value("showOpenStreetMap", QVariant(true)).toBool();
}

void
Settings::setShowOpenStreetMap(bool show)
{
    _settings->setValue("showOpenStreetMap", show);
}

bool
Settings::getFrameLastAddedLayer()
{
    return _settings->value("frameLastAddedLayer", QVariant(true)).toBool();
}

void
Settings::setFrameLastAddedLayer(bool frame)
{
    _settings->setValue("frameLastAddedLayer", frame);
}

QStringList
Settings::_getList(const QString &key)
{
    QList<QString> files;
    QList<QVariant> strVars = _settings->value(key).toList();
    QVariant myvar;
    foreach(myvar, strVars) {
        files.append(myvar.toString());
    }
    return files;
}

void
Settings::_setList(const QString &key, const QList<QString> &files)
{
    QList<QVariant> varList;
    QString myFile;
    foreach(myFile, files) {
        varList.append(QVariant(myFile));
    }
    _settings->setValue(key, QVariant(varList));
}

<|endoftext|>


<commit_before>#ifndef STLTOOLS_H
#define STLTOOLS_H

#include <utility>
#include <vector>
#include <algorithm>

namespace RAILS
{

static bool eigenvalue_sorter(std::pair<int, double> const &a, std::pair<int, double> const &b)
{
    return std::abs(a.second) > std::abs(b.second);
}

template<class DenseMatrix>
int find_largest_eigenvalues(DenseMatrix const &eigenvalues, std::vector<int> &indices, int N)
{
    std::vector<std::pair<int, double> > index_to_value;
    for (int i = 0; i < eigenvalues.M(); i++)
        index_to_value.push_back(std::pair<int, double>(i, eigenvalues(i)));

    std::sort(index_to_value.begin(), index_to_value.end(), eigenvalue_sorter);

    for (int i = 0; i < N; i++)
        indices.push_back(index_to_value[i].first);

    return 0;
}

}

#endif
<commit_msg>Fix ambiguous function error due to missing include.<commit_after>#ifndef STLTOOLS_H
#define STLTOOLS_H

#include <cmath>
#include <utility>
#include <vector>
#include <algorithm>

namespace RAILS
{

static bool eigenvalue_sorter(std::pair<int, double> const &a, std::pair<int, double> const &b)
{
    return std::abs(a.second) > std::abs(b.second);
}

template<class DenseMatrix>
int find_largest_eigenvalues(DenseMatrix const &eigenvalues, std::vector<int> &indices, int N)
{
    std::vector<std::pair<int, double> > index_to_value;
    for (int i = 0; i < eigenvalues.M(); i++)
        index_to_value.push_back(std::pair<int, double>(i, eigenvalues(i)));

    std::sort(index_to_value.begin(), index_to_value.end(), eigenvalue_sorter);

    for (int i = 0; i < N; i++)
        indices.push_back(index_to_value[i].first);

    return 0;
}

}

#endif
<|endoftext|>


<commit_before>#include "BinEP.h"
#include "check_params.h"

#include <epbin.h>
#include <drag2d.h>

namespace edb
{

std::string BinEP::Command() const
{
	return "epbin";
}

std::string BinEP::Description() const
{
	return "pack ejoy2d's .lua and images to binary";
}

std::string BinEP::Usage() const
{
	return Command() + " [filename] [type] [output]";
}

void BinEP::Run(int argc, char *argv[])
{
	// epbin E:\debug\sg_ui\ui2 png E:\debug\sg_ui\ui2.epp

	if (!check_number(this, argc, 5)) return;

	Trigger(argv[2], argv[3], argv[4]);
}

void BinEP::Trigger(const std::string& filename, const std::string& type,
					const std::string& output)
{
	epbin::TextureType t;
	if (type == "png4") {
		t = epbin::TT_PNG4;
	} else if (type == "png8") {
		t = epbin::TT_PNG8;
	} else if (type == "pvr") {
		t = epbin::TT_PVR;
	} else if (type == "pkm") {
		t = epbin::TT_PKM;
	} else {
		throw d2d::Exception("BinEP::Trigger unknown type: %s\n", type);
	}

	epbin::BinaryEPP epp(filename, t);
	epp.Pack(output);
}

}<commit_msg>[FIXED] bin ep<commit_after>#include "BinEP.h"
#include "check_params.h"

#include <epbin.h>
#include <drag2d.h>

namespace edb
{

std::string BinEP::Command() const
{
	return "epbin";
}

std::string BinEP::Description() const
{
	return "pack ejoy2d's .lua and images to binary";
}

std::string BinEP::Usage() const
{
	return Command() + " [filename] [type] [output]";
}

void BinEP::Run(int argc, char *argv[])
{
	// epbin E:\debug\sg_ui\ui2 png E:\debug\sg_ui\ui2

	if (!check_number(this, argc, 5)) return;

	Trigger(argv[2], argv[3], argv[4]);
}

void BinEP::Trigger(const std::string& filename, const std::string& type,
					const std::string& output)
{
	epbin::BinaryEPD epd(filename + ".lua");
	epd.Pack(output + ".epd", true);

	epbin::TextureType t;
	if (type == "png4") {
		t = epbin::TT_PNG4;
	} else if (type == "png8") {
		t = epbin::TT_PNG8;
	} else if (type == "pvr") {
		t = epbin::TT_PVR;
	} else if (type == "pkm") {
		t = epbin::TT_PKM;
	} else {
		throw d2d::Exception("BinEP::Trigger unknown type: %s\n", type);
	}
	epbin::BinaryEPP epp(filename, t);
	epp.Pack(output + ".epp");
}

}<|endoftext|>


<commit_before>// WinClient.cc for Fluxbox - an X11 Window manager
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// 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.

// $Id: WinClient.cc,v 1.2 2003/04/14 12:08:21 fluxgen Exp $

#include "WinClient.hh"

#include "Window.hh"
#include "fluxbox.hh"
#include "Screen.hh"
#include "i18n.hh"

#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

WinClient::WinClient(Window win, FluxboxWindow &fbwin):FbTk::FbWindow(win),
                     transient_for(0),
                     window_group(0),
                     x(0), y(0), old_bw(0),
                     min_width(1), min_height(1),
                     max_width(1), max_height(1),
                     width_inc(1), height_inc(1),
                     min_aspect_x(1), min_aspect_y(1),
                     max_aspect_x(1), max_aspect_y(1),
                     base_width(1), base_height(1),
                     win_gravity(0),
                     initial_state(0),
                     normal_hint_flags(0),
                     wm_hint_flags(0),
                     mwm_hint(0),
                     blackbox_hint(0),
                     m_win(&fbwin),
                     m_title(""), m_icon_title(""),
                     m_diesig(*this) { }

WinClient::~WinClient() {
#ifdef DEBUG
    cerr<<__FILE__<<"(~"<<__FUNCTION__<<")[this="<<this<<"]"<<endl;
#endif // DEBUG

    m_diesig.notify();

    Fluxbox *fluxbox = Fluxbox::instance();

    if (transient_for != 0) {
        if (transientFor() == m_win) {
            transient_for = 0;
        }

        fluxbox->setFocusedWindow(transient_for);

        if (transient_for != 0) {
            FluxboxWindow::ClientList::iterator client_it =
                transientFor()->clientList().begin();
            FluxboxWindow::ClientList::iterator client_it_end =
                transientFor()->clientList().end();
            for (; client_it != client_it_end; ++client_it) {
                (*client_it)->transientList().remove(m_win);
            }

            transient_for->setInputFocus();
            transient_for = 0;
        }
    }

    while (!transients.empty()) {
        FluxboxWindow::ClientList::iterator it =
            transients.back()->clientList().begin();
        FluxboxWindow::ClientList::iterator it_end =
            transients.back()->clientList().end();
        for (; it != it_end; ++it) {
            if ((*it)->transientFor() == m_win)
                (*it)->transient_for = 0;
        }

        transients.pop_back();
    }

    if (window_group != 0) {
        fluxbox->removeGroupSearch(window_group);
        window_group = 0;
    }

    if (mwm_hint != 0)
        XFree(mwm_hint);

    if (blackbox_hint != 0)
        XFree(blackbox_hint);

    if (window())
        fluxbox->removeWindowSearch(window());

    if (m_win != 0)
        m_win->removeClient(*this);
    m_win = 0;

}

void WinClient::updateRect(int x, int y,
                        unsigned int width, unsigned int height) {
    Display *disp = FbTk::App::instance()->display();
    XEvent event;
    event.type = ConfigureNotify;

    event.xconfigure.display = disp;
    event.xconfigure.event = window();
    event.xconfigure.window = window();
    event.xconfigure.x = x;
    event.xconfigure.y = y;
    event.xconfigure.width = width;
    event.xconfigure.height = height;
    //!! TODO
    event.xconfigure.border_width = 1;//client.old_bw;
    //!! TODO
    event.xconfigure.above = None; //m_frame.window().window();
    event.xconfigure.override_redirect = false;

    XSendEvent(disp, window(), False, StructureNotifyMask, &event);

}

void WinClient::sendFocus() {
    Display *disp = FbTk::App::instance()->display();
    // setup focus msg
    XEvent ce;
    ce.xclient.type = ClientMessage;
    ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
    ce.xclient.display = disp;
    ce.xclient.window = window();
    ce.xclient.format = 32;
    ce.xclient.data.l[0] = FbAtoms::instance()->getWMTakeFocusAtom();
    ce.xclient.data.l[1] = Fluxbox::instance()->getLastTime();
    ce.xclient.data.l[2] = 0l;
    ce.xclient.data.l[3] = 0l;
    ce.xclient.data.l[4] = 0l;
    // send focus msg
    XSendEvent(disp, window(), false, NoEventMask, &ce);
}

void WinClient::sendClose() {
    Display *disp = FbTk::App::instance()->display();
    // fill in XClientMessage structure for delete message
    XEvent ce;
    ce.xclient.type = ClientMessage;
    ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
    ce.xclient.display = disp;
    ce.xclient.window = window();
    ce.xclient.format = 32;
    ce.xclient.data.l[0] = FbAtoms::instance()->getWMDeleteAtom();
    ce.xclient.data.l[1] = CurrentTime;
    ce.xclient.data.l[2] = 0l;
    ce.xclient.data.l[3] = 0l;
    ce.xclient.data.l[4] = 0l;
    // send event delete message to client window
    XSendEvent(disp, window(), false, NoEventMask, &ce);
}

void WinClient::reparent(Window win, int x, int y) {
    XReparentWindow(FbTk::App::instance()->display(), window(), win, x, y);
}

bool WinClient::getAttrib(XWindowAttributes &attr) const {
    return XGetWindowAttributes(FbTk::App::instance()->display(), window(), &attr);
}

bool WinClient::getWMName(XTextProperty &textprop) const {
    return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}

bool WinClient::getWMIconName(XTextProperty &textprop) const {
    return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}

void WinClient::updateTransientInfo() {
    if (m_win == 0)
        return;
    // remove us from parent
    if (transientFor() != 0) {
        //!! TODO
        // since we don't know which client in transientFor()
        // that we're transient for then we just remove us
        // from every client in transientFor() clientlist
        FluxboxWindow::ClientList::iterator client_it =
            transientFor()->clientList().begin();
        FluxboxWindow::ClientList::iterator client_it_end =
            transientFor()->clientList().end();
        for (; client_it != client_it_end; ++client_it) {
            (*client_it)->transientList().remove(m_win);
        }
    }

    transient_for = 0;
    Display *disp = FbTk::App::instance()->display();
    // determine if this is a transient window
    Window win;
    if (!XGetTransientForHint(disp, window(), &win))
        return;

    // we can't be transient to ourself
    if (win == window())
        return;

    if (win != 0 && m_win->getScreen().getRootWindow() == win) {
        m_win->modal = true;
        return;
    }

    transient_for = Fluxbox::instance()->searchWindow(win);
    if (transient_for != 0 &&
        window_group != None && win == window_group) {
        transient_for = Fluxbox::instance()->searchGroup(win, m_win);
    }

    // make sure we don't have deadlock loop in transient chain
    for (FluxboxWindow *w = m_win; w != 0; w = w->m_client->transient_for) {
        if (w == w->m_client->transient_for) {
            w->m_client->transient_for = 0;
            break;
        }
    }

    if (transientFor() != 0) {
        // we need to add ourself to the right client in
        // the transientFor() window so we search client
        WinClient *client = transientFor()->findClient(win);
        assert(client != 0);
        client->transientList().push_back(m_win);
        // make sure we only have on instance of this
        client->transientList().unique();
        if (transientFor()->isStuck())
            m_win->stick();
    }
}

void WinClient::updateTitle() {
    XTextProperty text_prop;
    char **list = 0;
    int num = 0;
    I18n *i18n = I18n::instance();

    if (getWMName(text_prop)) {
        if (text_prop.value && text_prop.nitems > 0) {
            if (text_prop.encoding != XA_STRING) {

                text_prop.nitems = strlen((char *) text_prop.value);

                if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
                                              &list, &num) == Success &&
                    num > 0 && *list) {
                    m_title = static_cast<char *>(*list);
                    XFreeStringList(list);
                } else
                    m_title = (char *)text_prop.value;

            } else
                m_title = (char *)text_prop.value;
            XFree((char *) text_prop.value);
        } else { // ok, we don't have a name, set default name
            m_title = i18n->getMessage(
                                       FBNLS::WindowSet, FBNLS::WindowUnnamed,
                                       "Unnamed");
        }
    } else {
        m_title = i18n->getMessage(
                                   FBNLS::WindowSet, FBNLS::WindowUnnamed,
                                   "Unnamed");
    }

}

void WinClient::updateIconTitle() {
    XTextProperty text_prop;
    char **list = 0;
    int num = 0;

    if (getWMIconName(text_prop)) {
        if (text_prop.value && text_prop.nitems > 0) {
            if (text_prop.encoding != XA_STRING) {
                text_prop.nitems = strlen((char *) text_prop.value);

                if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
                                               &list, &num) == Success &&
                    num > 0 && *list) {
                    m_icon_title = (char *)*list;
                    XFreeStringList(list);
                } else
                    m_icon_title = (char *)text_prop.value;
            } else
                m_icon_title = (char *)text_prop.value;

            XFree((char *) text_prop.value);
        } else
            m_icon_title = title();
    } else
        m_icon_title = title();

}
<commit_msg>need fbatoms<commit_after>// WinClient.cc for Fluxbox - an X11 Window manager
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// 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.

// $Id: WinClient.cc,v 1.3 2003/04/15 12:12:29 fluxgen Exp $

#include "WinClient.hh"

#include "Window.hh"
#include "fluxbox.hh"
#include "Screen.hh"
#include "i18n.hh"
#include "FbAtoms.hh"

#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

WinClient::WinClient(Window win, FluxboxWindow &fbwin):FbTk::FbWindow(win),
                     transient_for(0),
                     window_group(0),
                     x(0), y(0), old_bw(0),
                     min_width(1), min_height(1),
                     max_width(1), max_height(1),
                     width_inc(1), height_inc(1),
                     min_aspect_x(1), min_aspect_y(1),
                     max_aspect_x(1), max_aspect_y(1),
                     base_width(1), base_height(1),
                     win_gravity(0),
                     initial_state(0),
                     normal_hint_flags(0),
                     wm_hint_flags(0),
                     mwm_hint(0),
                     blackbox_hint(0),
                     m_win(&fbwin),
                     m_title(""), m_icon_title(""),
                     m_diesig(*this) { }

WinClient::~WinClient() {
#ifdef DEBUG
    cerr<<__FILE__<<"(~"<<__FUNCTION__<<")[this="<<this<<"]"<<endl;
#endif // DEBUG

    m_diesig.notify();

    Fluxbox *fluxbox = Fluxbox::instance();

    if (transient_for != 0) {
        if (transientFor() == m_win) {
            transient_for = 0;
        }

        fluxbox->setFocusedWindow(transient_for);

        if (transient_for != 0) {
            FluxboxWindow::ClientList::iterator client_it =
                transientFor()->clientList().begin();
            FluxboxWindow::ClientList::iterator client_it_end =
                transientFor()->clientList().end();
            for (; client_it != client_it_end; ++client_it) {
                (*client_it)->transientList().remove(m_win);
            }

            transient_for->setInputFocus();
            transient_for = 0;
        }
    }

    while (!transients.empty()) {
        FluxboxWindow::ClientList::iterator it =
            transients.back()->clientList().begin();
        FluxboxWindow::ClientList::iterator it_end =
            transients.back()->clientList().end();
        for (; it != it_end; ++it) {
            if ((*it)->transientFor() == m_win)
                (*it)->transient_for = 0;
        }

        transients.pop_back();
    }

    if (window_group != 0) {
        fluxbox->removeGroupSearch(window_group);
        window_group = 0;
    }

    if (mwm_hint != 0)
        XFree(mwm_hint);

    if (blackbox_hint != 0)
        XFree(blackbox_hint);

    if (window())
        fluxbox->removeWindowSearch(window());

    if (m_win != 0)
        m_win->removeClient(*this);
    m_win = 0;

}

void WinClient::updateRect(int x, int y,
                        unsigned int width, unsigned int height) {
    Display *disp = FbTk::App::instance()->display();
    XEvent event;
    event.type = ConfigureNotify;

    event.xconfigure.display = disp;
    event.xconfigure.event = window();
    event.xconfigure.window = window();
    event.xconfigure.x = x;
    event.xconfigure.y = y;
    event.xconfigure.width = width;
    event.xconfigure.height = height;
    //!! TODO
    event.xconfigure.border_width = 1;//client.old_bw;
    //!! TODO
    event.xconfigure.above = None; //m_frame.window().window();
    event.xconfigure.override_redirect = false;

    XSendEvent(disp, window(), False, StructureNotifyMask, &event);

}

void WinClient::sendFocus() {
    Display *disp = FbTk::App::instance()->display();
    // setup focus msg
    XEvent ce;
    ce.xclient.type = ClientMessage;
    ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
    ce.xclient.display = disp;
    ce.xclient.window = window();
    ce.xclient.format = 32;
    ce.xclient.data.l[0] = FbAtoms::instance()->getWMTakeFocusAtom();
    ce.xclient.data.l[1] = Fluxbox::instance()->getLastTime();
    ce.xclient.data.l[2] = 0l;
    ce.xclient.data.l[3] = 0l;
    ce.xclient.data.l[4] = 0l;
    // send focus msg
    XSendEvent(disp, window(), false, NoEventMask, &ce);
}

void WinClient::sendClose() {
    Display *disp = FbTk::App::instance()->display();
    // fill in XClientMessage structure for delete message
    XEvent ce;
    ce.xclient.type = ClientMessage;
    ce.xclient.message_type = FbAtoms::instance()->getWMProtocolsAtom();
    ce.xclient.display = disp;
    ce.xclient.window = window();
    ce.xclient.format = 32;
    ce.xclient.data.l[0] = FbAtoms::instance()->getWMDeleteAtom();
    ce.xclient.data.l[1] = CurrentTime;
    ce.xclient.data.l[2] = 0l;
    ce.xclient.data.l[3] = 0l;
    ce.xclient.data.l[4] = 0l;
    // send event delete message to client window
    XSendEvent(disp, window(), false, NoEventMask, &ce);
}

void WinClient::reparent(Window win, int x, int y) {
    XReparentWindow(FbTk::App::instance()->display(), window(), win, x, y);
}

bool WinClient::getAttrib(XWindowAttributes &attr) const {
    return XGetWindowAttributes(FbTk::App::instance()->display(), window(), &attr);
}

bool WinClient::getWMName(XTextProperty &textprop) const {
    return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}

bool WinClient::getWMIconName(XTextProperty &textprop) const {
    return XGetWMName(FbTk::App::instance()->display(), window(), &textprop);
}

void WinClient::updateTransientInfo() {
    if (m_win == 0)
        return;
    // remove us from parent
    if (transientFor() != 0) {
        //!! TODO
        // since we don't know which client in transientFor()
        // that we're transient for then we just remove us
        // from every client in transientFor() clientlist
        FluxboxWindow::ClientList::iterator client_it =
            transientFor()->clientList().begin();
        FluxboxWindow::ClientList::iterator client_it_end =
            transientFor()->clientList().end();
        for (; client_it != client_it_end; ++client_it) {
            (*client_it)->transientList().remove(m_win);
        }
    }

    transient_for = 0;
    Display *disp = FbTk::App::instance()->display();
    // determine if this is a transient window
    Window win;
    if (!XGetTransientForHint(disp, window(), &win))
        return;

    // we can't be transient to ourself
    if (win == window())
        return;

    if (win != 0 && m_win->getScreen().getRootWindow() == win) {
        m_win->modal = true;
        return;
    }

    transient_for = Fluxbox::instance()->searchWindow(win);
    if (transient_for != 0 &&
        window_group != None && win == window_group) {
        transient_for = Fluxbox::instance()->searchGroup(win, m_win);
    }

    // make sure we don't have deadlock loop in transient chain
    for (FluxboxWindow *w = m_win; w != 0; w = w->m_client->transient_for) {
        if (w == w->m_client->transient_for) {
            w->m_client->transient_for = 0;
            break;
        }
    }

    if (transientFor() != 0) {
        // we need to add ourself to the right client in
        // the transientFor() window so we search client
        WinClient *client = transientFor()->findClient(win);
        assert(client != 0);
        client->transientList().push_back(m_win);
        // make sure we only have on instance of this
        client->transientList().unique();
        if (transientFor()->isStuck())
            m_win->stick();
    }
}

void WinClient::updateTitle() {
    XTextProperty text_prop;
    char **list = 0;
    int num = 0;
    I18n *i18n = I18n::instance();

    if (getWMName(text_prop)) {
        if (text_prop.value && text_prop.nitems > 0) {
            if (text_prop.encoding != XA_STRING) {

                text_prop.nitems = strlen((char *) text_prop.value);

                if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
                                              &list, &num) == Success &&
                    num > 0 && *list) {
                    m_title = static_cast<char *>(*list);
                    XFreeStringList(list);
                } else
                    m_title = (char *)text_prop.value;

            } else
                m_title = (char *)text_prop.value;
            XFree((char *) text_prop.value);
        } else { // ok, we don't have a name, set default name
            m_title = i18n->getMessage(
                                       FBNLS::WindowSet, FBNLS::WindowUnnamed,
                                       "Unnamed");
        }
    } else {
        m_title = i18n->getMessage(
                                   FBNLS::WindowSet, FBNLS::WindowUnnamed,
                                   "Unnamed");
    }

}

void WinClient::updateIconTitle() {
    XTextProperty text_prop;
    char **list = 0;
    int num = 0;

    if (getWMIconName(text_prop)) {
        if (text_prop.value && text_prop.nitems > 0) {
            if (text_prop.encoding != XA_STRING) {
                text_prop.nitems = strlen((char *) text_prop.value);

                if (XmbTextPropertyToTextList(FbTk::App::instance()->display(), &text_prop,
                                               &list, &num) == Success &&
                    num > 0 && *list) {
                    m_icon_title = (char *)*list;
                    XFreeStringList(list);
                } else
                    m_icon_title = (char *)text_prop.value;
            } else
                m_icon_title = (char *)text_prop.value;

            XFree((char *) text_prop.value);
        } else
            m_icon_title = title();
    } else
        m_icon_title = title();

}
<|endoftext|>


<commit_before>/*
  Transport PK

  Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
  Amanzi is released under the three-clause BSD License.
  The terms of use and "as is" disclaimer for this license are
  provided in the top-level COPYRIGHT file.

  Authors: Neil Carlson
           Ethan Coon
           Konstantin Lipnikov (lipnikov@lanl.gov)
*/

#ifndef AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_
#define AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_

#include <vector>
#include <map>
#include <string>

#include "Epetra_MultiVector.h"
#include "Teuchos_RCP.hpp"

#include "CommonDefs.hh"
#include "Mesh.hh"
//#include "DenseVector.hh"

class State;

namespace Amanzi {
namespace Transport {

class TransportDomainFunction {
 public:
  TransportDomainFunction() : domain_volume_(-1.0) {};
  TransportDomainFunction(const Teuchos::ParameterList& plist) : domain_volume_(-1.0) {};
  ~TransportDomainFunction() {};

  // source term on time interval (t0, t1]
  virtual void Compute(double t0, double t1) { ASSERT(false); }

  // model name
  virtual std::string name() const { return "undefined"; }

  // access
  // -- volume of the regions
  double domain_volume() { return domain_volume_; }
  // -- nick-name of the function
  std::string keyword() { return keyword_; }

  std::vector<std::string>& tcc_names() { return tcc_names_; }
  std::vector<int>& tcc_index() { return tcc_index_; }
  virtual void set_state(const Teuchos::RCP<State>& S) {S_ = S;}

  // iterator methods
  typedef std::map<int, std::vector<double> >::iterator Iterator;
  Iterator begin() { return value_.begin(); }
  Iterator end() { return value_.end(); }
  std::map<int, std::vector<double> >::size_type size() { return value_.size(); }

protected:

  double domain_volume_;
  std::map<int, std::vector<double> > value_;  // tcc values on boundary faces
  std::string keyword_;
  Teuchos::RCP<const State> S_;

  std::vector<std::string> tcc_names_;  // list of component names
  std::vector<int> tcc_index_;  // index of component in the global list
};

}  // namespace Transport
}  // namespace Amanzi

#endif
<commit_msg>cleanup<commit_after>/*
  Transport PK

  Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
  Amanzi is released under the three-clause BSD License.
  The terms of use and "as is" disclaimer for this license are
  provided in the top-level COPYRIGHT file.

  Authors: Neil Carlson
           Ethan Coon
           Konstantin Lipnikov (lipnikov@lanl.gov)
*/

#ifndef AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_
#define AMANZI_TRANSPORT_DOMAIN_FUNCTION_HH_

#include <vector>
#include <map>
#include <string>

#include "Epetra_MultiVector.h"
#include "Teuchos_RCP.hpp"

#include "CommonDefs.hh"
#include "Mesh.hh"
//#include "DenseVector.hh"

class State;

namespace Amanzi {
namespace Transport {

class TransportDomainFunction {
 public:
  TransportDomainFunction() : domain_volume_(-1.0) {};
  TransportDomainFunction(const Teuchos::ParameterList& plist) : domain_volume_(-1.0) {};
  ~TransportDomainFunction() {};

  // source term on time interval (t0, t1]
  virtual void Compute(double t0, double t1) { ASSERT(false); }

  // model name
  virtual std::string name() const { return "undefined"; }

  // access
  // -- volume of the regions
  double domain_volume() { return domain_volume_; }
  // -- nick-name of the function
  std::string keyword() { return keyword_; }

  std::vector<std::string>& tcc_names() { return tcc_names_; }
  std::vector<int>& tcc_index() { return tcc_index_; }
  virtual void set_state(const Teuchos::RCP<State>& S) {}

  // iterator methods
  typedef std::map<int, std::vector<double> >::iterator Iterator;
  Iterator begin() { return value_.begin(); }
  Iterator end() { return value_.end(); }
  std::map<int, std::vector<double> >::size_type size() { return value_.size(); }

protected:

  double domain_volume_;
  std::map<int, std::vector<double> > value_;  // tcc values on boundary faces
  std::string keyword_;

  std::vector<std::string> tcc_names_;  // list of component names
  std::vector<int> tcc_index_;  // index of component in the global list
};

}  // namespace Transport
}  // namespace Amanzi

#endif
<|endoftext|>


<commit_before>#include<KrUIManager.h>

LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {

	return ui.HandleMessage(hwnd,Message,wParam,lParam);
}

static KrUIManager* KrUIManager::GetpKrUIManager()
{
	if(m_pKrUIManager==NULL)
		m_pKrUIManager=new KrUIManager();
	return m_pKrUIManager;
}

bool      KrUIManager::Initialize(HINSTANCE hInstance)
{
	m_hInstance=hInstance;
	memset(&wc,0,sizeof(wc));
	wc.cbSize		 = sizeof(WNDCLASSEX);
	wc.lpfnWndProc	 = WndProc;
	wc.hInstance	 = m_hInstance;
	wc.hCursor		 = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
	wc.lpszClassName = GetWindowClassName();
	wc.hIcon		 = LoadIcon(NULL, IDI_APPLICATION);
	wc.hIconSm		 = LoadIcon(NULL, IDI_APPLICATION);

	if(!RegisterClassEx(&wc))
	{
		return false;
	}

	return true;
	//TODO
}

KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height,DWORD dwStyle)
{
	KrWindow* pKrWindow=new KrWindow;
	if(!pKrWindow) return false;
	pKrWindow->SetWindowName(lpWindowName);
	RECT rect;
	rect.left  =x;
	rect.top   =y;
	rect.right =x + width;
	rect.bottom=y + height;
	pKrWindow->SetRect(&rect);
	pKrWindow->SetStyle(dwStyle);
	pKrWindow->Create();
	m_WndList.push_back(pKrWindow);
	return pKrWindow;
}

KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height)
{
	return AddWindow(lpWindowName,x,y,width,height,WS_BORDER);
}

LPCTSTR   KrUIManager::GetWindowClassName()
{
	return m_lpWindowClassName;
}

HINSTANCE KrUIManager::GetHINSTANCE()
{
	return m_hInstance;
}

int  MsgLoop()
{
	while(GetMessage(&msg, NULL, 0, 0) > 0)
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return msg.wParam;
}

LRESULT   KrUIManager::HandleMessage(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{

	switch(Message) {
		case WM_DESTROY: {
			PostQuitMessage(0);
			break;
		}

		default:
			return DefWindowProc(hwnd, Message, wParam, lParam);
	}
	return 0;

}

<commit_msg>Create KrUIManager.cpp<commit_after>#include<KrUIManager.h>

LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {

	return ui.HandleMessage(hwnd,Message,wParam,lParam);
}

static KrUIManager* KrUIManager::GetpKrUIManager()
{
	if(m_pKrUIManager==NULL)
		m_pKrUIManager=new KrUIManager();
	return m_pKrUIManager;
}

bool      KrUIManager::Initialize(HINSTANCE hInstance)
{
	m_hInstance=hInstance;
	memset(&wc,0,sizeof(wc));
	wc.cbSize		 = sizeof(WNDCLASSEX);
	wc.lpfnWndProc	 = WndProc;
	wc.hInstance	 = m_hInstance;
	wc.hCursor		 = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
	wc.lpszClassName = GetWindowClassName();
	wc.hIcon		 = LoadIcon(NULL, IDI_APPLICATION);
	wc.hIconSm		 = LoadIcon(NULL, IDI_APPLICATION);

	if(!RegisterClassEx(&wc))
	{
		return false;
	}

	return true;
	//TODO
}

KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height,DWORD dwStyle)
{
	KrWindow* pKrWindow=new KrWindow;
	if(!pKrWindow) return false;
	pKrWindow->SetWindowName(lpWindowName);
	RECT rect;
	rect.left  =x;
	rect.top   =y;
	rect.right =x + width;
	rect.bottom=y + height;
	pKrWindow->SetRect(&rect);
	pKrWindow->SetStyle(dwStyle);
	pKrWindow->Create();
	m_WndList.push_back(pKrWindow);
	return pKrWindow;
}

KrWindow* KrUIManager::AddWindow(LPCTSTR lpWindowName,int x,int y,int width,int height)
{
	return AddWindow(lpWindowName,x,y,width,height,WS_BORDER);
}

LPCTSTR   KrUIManager::GetWindowClassName()
{
	return m_lpWindowClassName;
}

HINSTANCE KrUIManager::GetHINSTANCE()
{
	return m_hInstance;
}

int  KrUIManager::MessageLoop()
{
	while(GetMessage(&msg, NULL, 0, 0) > 0)
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return msg.wParam;
}

LRESULT   KrUIManager::HandleMessage(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam)
{

	switch(Message) {
		case WM_DESTROY: {
			PostQuitMessage(0);
			break;
		}

		default:
			return DefWindowProc(hwnd, Message, wParam, lParam);
	}
	return 0;

}

<|endoftext|>


<commit_before>//===- Symbols.cpp --------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"

#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>

using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;

using namespace lld;
using namespace lld::elf;

template <class ELFT>
static typename ELFT::uint getSymVA(const SymbolBody &Body,
                                    typename ELFT::uint &Addend) {
  typedef typename ELFT::uint uintX_t;

  switch (Body.kind()) {
  case SymbolBody::DefinedSyntheticKind: {
    auto &D = cast<DefinedSynthetic<ELFT>>(Body);
    const OutputSectionBase *Sec = D.Section;
    if (!Sec)
      return D.Value;
    if (D.Value == DefinedSynthetic<ELFT>::SectionEnd)
      return Sec->Addr + Sec->Size;
    return Sec->Addr + D.Value;
  }
  case SymbolBody::DefinedRegularKind: {
    auto &D = cast<DefinedRegular<ELFT>>(Body);
    InputSectionBase<ELFT> *SC = D.Section;

    // According to the ELF spec reference to a local symbol from outside
    // the group are not allowed. Unfortunately .eh_frame breaks that rule
    // and must be treated specially. For now we just replace the symbol with
    // 0.
    if (SC == &InputSection<ELFT>::Discarded)
      return 0;

    // This is an absolute symbol.
    if (!SC)
      return D.Value;

    uintX_t Offset = D.Value;
    if (D.isSection()) {
      Offset += Addend;
      Addend = 0;
    }
    uintX_t VA = (SC->OutSec ? SC->OutSec->Addr : 0) + SC->getOffset(Offset);
    if (D.isTls() && !Config->Relocatable) {
      if (!Out<ELFT>::TlsPhdr)
        fatal(toString(D.File) +
              " has a STT_TLS symbol but doesn't have a PT_TLS section");
      return VA - Out<ELFT>::TlsPhdr->p_vaddr;
    }
    return VA;
  }
  case SymbolBody::DefinedCommonKind:
    return In<ELFT>::Common->OutSec->Addr + In<ELFT>::Common->OutSecOff +
           cast<DefinedCommon>(Body).Offset;
  case SymbolBody::SharedKind: {
    auto &SS = cast<SharedSymbol<ELFT>>(Body);
    if (!SS.NeedsCopyOrPltAddr)
      return 0;
    if (SS.isFunc())
      return Body.getPltVA<ELFT>();
    return Out<ELFT>::Bss->Addr + SS.OffsetInBss;
  }
  case SymbolBody::UndefinedKind:
    return 0;
  case SymbolBody::LazyArchiveKind:
  case SymbolBody::LazyObjectKind:
    assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
    return 0;
  }
  llvm_unreachable("invalid symbol kind");
}

SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
                       uint8_t Type)
    : SymbolKind(K), NeedsCopyOrPltAddr(false), IsLocal(IsLocal),
      IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
      IsInIgot(false), Type(Type), StOther(StOther), Name(Name) {}

// Returns true if a symbol can be replaced at load-time by a symbol
// with the same name defined in other ELF executable or DSO.
bool SymbolBody::isPreemptible() const {
  if (isLocal())
    return false;

  // Shared symbols resolve to the definition in the DSO. The exceptions are
  // symbols with copy relocations (which resolve to .bss) or preempt plt
  // entries (which resolve to that plt entry).
  if (isShared())
    return !NeedsCopyOrPltAddr;

  // That's all that can be preempted in a non-DSO.
  if (!Config->Shared)
    return false;

  // Only symbols that appear in dynsym can be preempted.
  if (!symbol()->includeInDynsym())
    return false;

  // Only default visibility symbols can be preempted.
  if (symbol()->Visibility != STV_DEFAULT)
    return false;

  // -Bsymbolic means that definitions are not preempted.
  if (Config->Bsymbolic || (Config->BsymbolicFunctions && isFunc()))
    return !isDefined();
  return true;
}

template <class ELFT> bool SymbolBody::hasThunk() const {
  if (auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
    return DR->ThunkData != nullptr;
  if (auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
    return S->ThunkData != nullptr;
  return false;
}

template <class ELFT>
typename ELFT::uint SymbolBody::getVA(typename ELFT::uint Addend) const {
  typename ELFT::uint OutVA = getSymVA<ELFT>(*this, Addend);
  return OutVA + Addend;
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotVA() const {
  return In<ELFT>::Got->getVA() + getGotOffset<ELFT>();
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotOffset() const {
  return GotIndex * Target->GotEntrySize;
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotPltVA() const {
  if (this->IsInIgot)
    return In<ELFT>::IgotPlt->getVA() + getGotPltOffset<ELFT>();
  return In<ELFT>::GotPlt->getVA() + getGotPltOffset<ELFT>();
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotPltOffset() const {
  return GotPltIndex * Target->GotPltEntrySize;
}

template <class ELFT> typename ELFT::uint SymbolBody::getPltVA() const {
  if (this->IsInIplt)
    return In<ELFT>::Iplt->getVA() + PltIndex * Target->PltEntrySize;
  return In<ELFT>::Plt->getVA() + Target->PltHeaderSize +
         PltIndex * Target->PltEntrySize;
}

template <class ELFT> typename ELFT::uint SymbolBody::getThunkVA() const {
  if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
    return DR->ThunkData->getVA();
  if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
    return S->ThunkData->getVA();
  fatal("getThunkVA() not supported for Symbol class\n");
}

template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
  if (const auto *C = dyn_cast<DefinedCommon>(this))
    return C->Size;
  if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
    return DR->Size;
  if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
    return S->Sym.st_size;
  return 0;
}

// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
  StringRef S = getName();
  size_t Pos = S.find('@');
  if (Pos == 0 || Pos == StringRef::npos)
    return;
  StringRef Verstr = S.substr(Pos + 1);
  if (Verstr.empty())
    return;

  // Truncate the symbol name so that it doesn't include the version string.
  Name = {S.data(), Pos};

  // '@@' in a symbol name means the default version.
  // It is usually the most recent one.
  bool IsDefault = (Verstr[0] == '@');
  if (IsDefault)
    Verstr = Verstr.substr(1);

  for (VersionDefinition &Ver : Config->VersionDefinitions) {
    if (Ver.Name != Verstr)
      continue;

    if (IsDefault)
      symbol()->VersionId = Ver.Id;
    else
      symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
    return;
  }

  // It is an error if the specified version is not defined.
  error(toString(File) + ": symbol " + S + " has undefined version " + Verstr);
}

Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
                 uint8_t Type)
    : SymbolBody(K, Name, IsLocal, StOther, Type) {}

template <class ELFT> bool DefinedRegular<ELFT>::isMipsPIC() const {
  if (!Section || !isFunc())
    return false;
  return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
         (Section->getFile()->getObj().getHeader()->e_flags & EF_MIPS_PIC);
}

Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
                     uint8_t Type, InputFile *File)
    : SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {
  this->File = File;
}

template <typename ELFT>
DefinedSynthetic<ELFT>::DefinedSynthetic(StringRef Name, uintX_t Value,
                                         const OutputSectionBase *Section)
    : Defined(SymbolBody::DefinedSyntheticKind, Name, /*IsLocal=*/false,
              STV_HIDDEN, 0 /* Type */),
      Value(Value), Section(Section) {}

DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint64_t Alignment,
                             uint8_t StOther, uint8_t Type, InputFile *File)
    : Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
              Type),
      Alignment(Alignment), Size(Size) {
  this->File = File;
}

InputFile *Lazy::fetch() {
  if (auto *S = dyn_cast<LazyArchive>(this))
    return S->fetch();
  return cast<LazyObject>(this)->fetch();
}

LazyArchive::LazyArchive(ArchiveFile &File,
                         const llvm::object::Archive::Symbol S, uint8_t Type)
    : Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {
  this->File = &File;
}

LazyObject::LazyObject(StringRef Name, LazyObjectFile &File, uint8_t Type)
    : Lazy(LazyObjectKind, Name, Type) {
  this->File = &File;
}

InputFile *LazyArchive::fetch() {
  std::pair<MemoryBufferRef, uint64_t> MBInfo = file()->getMember(&Sym);

  // getMember returns an empty buffer if the member was already
  // read from the library.
  if (MBInfo.first.getBuffer().empty())
    return nullptr;
  return createObjectFile(MBInfo.first, file()->getName(), MBInfo.second);
}

InputFile *LazyObject::fetch() {
  MemoryBufferRef MBRef = file()->getBuffer();
  if (MBRef.getBuffer().empty())
    return nullptr;
  return createObjectFile(MBRef);
}

bool Symbol::includeInDynsym() const {
  if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
    return false;
  return (ExportDynamic && VersionId != VER_NDX_LOCAL) || body()->isShared() ||
         (body()->isUndefined() && Config->Shared);
}

// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
  SymbolBody *B = Sym->body();
  outs() << toString(B->File);

  if (B->isUndefined())
    outs() << ": reference to ";
  else if (B->isCommon())
    outs() << ": common definition of ";
  else
    outs() << ": definition of ";
  outs() << B->getName() << "\n";
}

// Returns a symbol for an error message.
std::string elf::toString(const SymbolBody &B) {
  if (Config->Demangle)
    if (Optional<std::string> S = demangle(B.getName()))
      return *S;
  return B.getName();
}

template bool SymbolBody::hasThunk<ELF32LE>() const;
template bool SymbolBody::hasThunk<ELF32BE>() const;
template bool SymbolBody::hasThunk<ELF64LE>() const;
template bool SymbolBody::hasThunk<ELF64BE>() const;

template uint32_t SymbolBody::template getVA<ELF32LE>(uint32_t) const;
template uint32_t SymbolBody::template getVA<ELF32BE>(uint32_t) const;
template uint64_t SymbolBody::template getVA<ELF64LE>(uint64_t) const;
template uint64_t SymbolBody::template getVA<ELF64BE>(uint64_t) const;

template uint32_t SymbolBody::template getGotVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64BE>() const;

template uint32_t SymbolBody::template getGotOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64BE>() const;

template uint32_t SymbolBody::template getGotPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64BE>() const;

template uint32_t SymbolBody::template getThunkVA<ELF32LE>() const;
template uint32_t SymbolBody::template getThunkVA<ELF32BE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64LE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64BE>() const;

template uint32_t SymbolBody::template getGotPltOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64BE>() const;

template uint32_t SymbolBody::template getPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64BE>() const;

template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;

template class elf::DefinedRegular<ELF32LE>;
template class elf::DefinedRegular<ELF32BE>;
template class elf::DefinedRegular<ELF64LE>;
template class elf::DefinedRegular<ELF64BE>;

template class elf::DefinedSynthetic<ELF32LE>;
template class elf::DefinedSynthetic<ELF32BE>;
template class elf::DefinedSynthetic<ELF64LE>;
template class elf::DefinedSynthetic<ELF64BE>;
<commit_msg>Rename this variable.<commit_after>//===- Symbols.cpp --------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Symbols.h"
#include "Error.h"
#include "InputFiles.h"
#include "InputSection.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SyntheticSections.h"
#include "Target.h"

#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include <cstring>

using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;

using namespace lld;
using namespace lld::elf;

template <class ELFT>
static typename ELFT::uint getSymVA(const SymbolBody &Body,
                                    typename ELFT::uint &Addend) {
  typedef typename ELFT::uint uintX_t;

  switch (Body.kind()) {
  case SymbolBody::DefinedSyntheticKind: {
    auto &D = cast<DefinedSynthetic<ELFT>>(Body);
    const OutputSectionBase *Sec = D.Section;
    if (!Sec)
      return D.Value;
    if (D.Value == DefinedSynthetic<ELFT>::SectionEnd)
      return Sec->Addr + Sec->Size;
    return Sec->Addr + D.Value;
  }
  case SymbolBody::DefinedRegularKind: {
    auto &D = cast<DefinedRegular<ELFT>>(Body);
    InputSectionBase<ELFT> *IS = D.Section;

    // According to the ELF spec reference to a local symbol from outside
    // the group are not allowed. Unfortunately .eh_frame breaks that rule
    // and must be treated specially. For now we just replace the symbol with
    // 0.
    if (IS == &InputSection<ELFT>::Discarded)
      return 0;

    // This is an absolute symbol.
    if (!IS)
      return D.Value;

    uintX_t Offset = D.Value;
    if (D.isSection()) {
      Offset += Addend;
      Addend = 0;
    }
    uintX_t VA = (IS->OutSec ? IS->OutSec->Addr : 0) + IS->getOffset(Offset);
    if (D.isTls() && !Config->Relocatable) {
      if (!Out<ELFT>::TlsPhdr)
        fatal(toString(D.File) +
              " has a STT_TLS symbol but doesn't have a PT_TLS section");
      return VA - Out<ELFT>::TlsPhdr->p_vaddr;
    }
    return VA;
  }
  case SymbolBody::DefinedCommonKind:
    return In<ELFT>::Common->OutSec->Addr + In<ELFT>::Common->OutSecOff +
           cast<DefinedCommon>(Body).Offset;
  case SymbolBody::SharedKind: {
    auto &SS = cast<SharedSymbol<ELFT>>(Body);
    if (!SS.NeedsCopyOrPltAddr)
      return 0;
    if (SS.isFunc())
      return Body.getPltVA<ELFT>();
    return Out<ELFT>::Bss->Addr + SS.OffsetInBss;
  }
  case SymbolBody::UndefinedKind:
    return 0;
  case SymbolBody::LazyArchiveKind:
  case SymbolBody::LazyObjectKind:
    assert(Body.symbol()->IsUsedInRegularObj && "lazy symbol reached writer");
    return 0;
  }
  llvm_unreachable("invalid symbol kind");
}

SymbolBody::SymbolBody(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
                       uint8_t Type)
    : SymbolKind(K), NeedsCopyOrPltAddr(false), IsLocal(IsLocal),
      IsInGlobalMipsGot(false), Is32BitMipsGot(false), IsInIplt(false),
      IsInIgot(false), Type(Type), StOther(StOther), Name(Name) {}

// Returns true if a symbol can be replaced at load-time by a symbol
// with the same name defined in other ELF executable or DSO.
bool SymbolBody::isPreemptible() const {
  if (isLocal())
    return false;

  // Shared symbols resolve to the definition in the DSO. The exceptions are
  // symbols with copy relocations (which resolve to .bss) or preempt plt
  // entries (which resolve to that plt entry).
  if (isShared())
    return !NeedsCopyOrPltAddr;

  // That's all that can be preempted in a non-DSO.
  if (!Config->Shared)
    return false;

  // Only symbols that appear in dynsym can be preempted.
  if (!symbol()->includeInDynsym())
    return false;

  // Only default visibility symbols can be preempted.
  if (symbol()->Visibility != STV_DEFAULT)
    return false;

  // -Bsymbolic means that definitions are not preempted.
  if (Config->Bsymbolic || (Config->BsymbolicFunctions && isFunc()))
    return !isDefined();
  return true;
}

template <class ELFT> bool SymbolBody::hasThunk() const {
  if (auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
    return DR->ThunkData != nullptr;
  if (auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
    return S->ThunkData != nullptr;
  return false;
}

template <class ELFT>
typename ELFT::uint SymbolBody::getVA(typename ELFT::uint Addend) const {
  typename ELFT::uint OutVA = getSymVA<ELFT>(*this, Addend);
  return OutVA + Addend;
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotVA() const {
  return In<ELFT>::Got->getVA() + getGotOffset<ELFT>();
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotOffset() const {
  return GotIndex * Target->GotEntrySize;
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotPltVA() const {
  if (this->IsInIgot)
    return In<ELFT>::IgotPlt->getVA() + getGotPltOffset<ELFT>();
  return In<ELFT>::GotPlt->getVA() + getGotPltOffset<ELFT>();
}

template <class ELFT> typename ELFT::uint SymbolBody::getGotPltOffset() const {
  return GotPltIndex * Target->GotPltEntrySize;
}

template <class ELFT> typename ELFT::uint SymbolBody::getPltVA() const {
  if (this->IsInIplt)
    return In<ELFT>::Iplt->getVA() + PltIndex * Target->PltEntrySize;
  return In<ELFT>::Plt->getVA() + Target->PltHeaderSize +
         PltIndex * Target->PltEntrySize;
}

template <class ELFT> typename ELFT::uint SymbolBody::getThunkVA() const {
  if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
    return DR->ThunkData->getVA();
  if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
    return S->ThunkData->getVA();
  fatal("getThunkVA() not supported for Symbol class\n");
}

template <class ELFT> typename ELFT::uint SymbolBody::getSize() const {
  if (const auto *C = dyn_cast<DefinedCommon>(this))
    return C->Size;
  if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(this))
    return DR->Size;
  if (const auto *S = dyn_cast<SharedSymbol<ELFT>>(this))
    return S->Sym.st_size;
  return 0;
}

// If a symbol name contains '@', the characters after that is
// a symbol version name. This function parses that.
void SymbolBody::parseSymbolVersion() {
  StringRef S = getName();
  size_t Pos = S.find('@');
  if (Pos == 0 || Pos == StringRef::npos)
    return;
  StringRef Verstr = S.substr(Pos + 1);
  if (Verstr.empty())
    return;

  // Truncate the symbol name so that it doesn't include the version string.
  Name = {S.data(), Pos};

  // '@@' in a symbol name means the default version.
  // It is usually the most recent one.
  bool IsDefault = (Verstr[0] == '@');
  if (IsDefault)
    Verstr = Verstr.substr(1);

  for (VersionDefinition &Ver : Config->VersionDefinitions) {
    if (Ver.Name != Verstr)
      continue;

    if (IsDefault)
      symbol()->VersionId = Ver.Id;
    else
      symbol()->VersionId = Ver.Id | VERSYM_HIDDEN;
    return;
  }

  // It is an error if the specified version is not defined.
  error(toString(File) + ": symbol " + S + " has undefined version " + Verstr);
}

Defined::Defined(Kind K, StringRefZ Name, bool IsLocal, uint8_t StOther,
                 uint8_t Type)
    : SymbolBody(K, Name, IsLocal, StOther, Type) {}

template <class ELFT> bool DefinedRegular<ELFT>::isMipsPIC() const {
  if (!Section || !isFunc())
    return false;
  return (this->StOther & STO_MIPS_MIPS16) == STO_MIPS_PIC ||
         (Section->getFile()->getObj().getHeader()->e_flags & EF_MIPS_PIC);
}

Undefined::Undefined(StringRefZ Name, bool IsLocal, uint8_t StOther,
                     uint8_t Type, InputFile *File)
    : SymbolBody(SymbolBody::UndefinedKind, Name, IsLocal, StOther, Type) {
  this->File = File;
}

template <typename ELFT>
DefinedSynthetic<ELFT>::DefinedSynthetic(StringRef Name, uintX_t Value,
                                         const OutputSectionBase *Section)
    : Defined(SymbolBody::DefinedSyntheticKind, Name, /*IsLocal=*/false,
              STV_HIDDEN, 0 /* Type */),
      Value(Value), Section(Section) {}

DefinedCommon::DefinedCommon(StringRef Name, uint64_t Size, uint64_t Alignment,
                             uint8_t StOther, uint8_t Type, InputFile *File)
    : Defined(SymbolBody::DefinedCommonKind, Name, /*IsLocal=*/false, StOther,
              Type),
      Alignment(Alignment), Size(Size) {
  this->File = File;
}

InputFile *Lazy::fetch() {
  if (auto *S = dyn_cast<LazyArchive>(this))
    return S->fetch();
  return cast<LazyObject>(this)->fetch();
}

LazyArchive::LazyArchive(ArchiveFile &File,
                         const llvm::object::Archive::Symbol S, uint8_t Type)
    : Lazy(LazyArchiveKind, S.getName(), Type), Sym(S) {
  this->File = &File;
}

LazyObject::LazyObject(StringRef Name, LazyObjectFile &File, uint8_t Type)
    : Lazy(LazyObjectKind, Name, Type) {
  this->File = &File;
}

InputFile *LazyArchive::fetch() {
  std::pair<MemoryBufferRef, uint64_t> MBInfo = file()->getMember(&Sym);

  // getMember returns an empty buffer if the member was already
  // read from the library.
  if (MBInfo.first.getBuffer().empty())
    return nullptr;
  return createObjectFile(MBInfo.first, file()->getName(), MBInfo.second);
}

InputFile *LazyObject::fetch() {
  MemoryBufferRef MBRef = file()->getBuffer();
  if (MBRef.getBuffer().empty())
    return nullptr;
  return createObjectFile(MBRef);
}

bool Symbol::includeInDynsym() const {
  if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
    return false;
  return (ExportDynamic && VersionId != VER_NDX_LOCAL) || body()->isShared() ||
         (body()->isUndefined() && Config->Shared);
}

// Print out a log message for --trace-symbol.
void elf::printTraceSymbol(Symbol *Sym) {
  SymbolBody *B = Sym->body();
  outs() << toString(B->File);

  if (B->isUndefined())
    outs() << ": reference to ";
  else if (B->isCommon())
    outs() << ": common definition of ";
  else
    outs() << ": definition of ";
  outs() << B->getName() << "\n";
}

// Returns a symbol for an error message.
std::string elf::toString(const SymbolBody &B) {
  if (Config->Demangle)
    if (Optional<std::string> S = demangle(B.getName()))
      return *S;
  return B.getName();
}

template bool SymbolBody::hasThunk<ELF32LE>() const;
template bool SymbolBody::hasThunk<ELF32BE>() const;
template bool SymbolBody::hasThunk<ELF64LE>() const;
template bool SymbolBody::hasThunk<ELF64BE>() const;

template uint32_t SymbolBody::template getVA<ELF32LE>(uint32_t) const;
template uint32_t SymbolBody::template getVA<ELF32BE>(uint32_t) const;
template uint64_t SymbolBody::template getVA<ELF64LE>(uint64_t) const;
template uint64_t SymbolBody::template getVA<ELF64BE>(uint64_t) const;

template uint32_t SymbolBody::template getGotVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotVA<ELF64BE>() const;

template uint32_t SymbolBody::template getGotOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotOffset<ELF64BE>() const;

template uint32_t SymbolBody::template getGotPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltVA<ELF64BE>() const;

template uint32_t SymbolBody::template getThunkVA<ELF32LE>() const;
template uint32_t SymbolBody::template getThunkVA<ELF32BE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64LE>() const;
template uint64_t SymbolBody::template getThunkVA<ELF64BE>() const;

template uint32_t SymbolBody::template getGotPltOffset<ELF32LE>() const;
template uint32_t SymbolBody::template getGotPltOffset<ELF32BE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64LE>() const;
template uint64_t SymbolBody::template getGotPltOffset<ELF64BE>() const;

template uint32_t SymbolBody::template getPltVA<ELF32LE>() const;
template uint32_t SymbolBody::template getPltVA<ELF32BE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64LE>() const;
template uint64_t SymbolBody::template getPltVA<ELF64BE>() const;

template uint32_t SymbolBody::template getSize<ELF32LE>() const;
template uint32_t SymbolBody::template getSize<ELF32BE>() const;
template uint64_t SymbolBody::template getSize<ELF64LE>() const;
template uint64_t SymbolBody::template getSize<ELF64BE>() const;

template class elf::DefinedRegular<ELF32LE>;
template class elf::DefinedRegular<ELF32BE>;
template class elf::DefinedRegular<ELF64LE>;
template class elf::DefinedRegular<ELF64BE>;

template class elf::DefinedSynthetic<ELF32LE>;
template class elf::DefinedSynthetic<ELF32BE>;
template class elf::DefinedSynthetic<ELF64LE>;
template class elf::DefinedSynthetic<ELF64BE>;
<|endoftext|>