<commit_before>//__________________________________________________________________________
// Author: Claudio Pizzolato, October 2013
// email:  claudio.pizzolato@griffithuni.edu.au
//
// DO NOT REDISTRIBUTE WITHOUT PERMISSION
//__________________________________________________________________________
//

#include "Parameter.h"
#include <iostream>
#include <vector>
#include <algorithm>

template<typename NMSmodelT>
ParametersFromXml<NMSmodelT>::ParametersFromXml(NMSmodelT& subject, std::vector< std::string >& dofToCalibrate, const ParameterSet& parameterSet)
:subject_(subject), dofNames_(dofToCalibrate) {

    for(ParameterSet::const_iterator it(parameterSet.begin()); it != parameterSet.end(); ++it) {
        std::cout << "Parameter " << it->getName() << std::endl;
        ParameterDetails parameterDetails;
        ParameterID parameterId = it->getID();

        ParameterAssignment assignment = it->getAssignment();
        if(assignment == Parameter::Grouped) {
            MuscleGroups muscleGroups;
            it->getMuscleGroups(muscleGroups);
            getMuscleGroupIndex(muscleGroups, parameterDetails.muscleGroups);
        } else
            getMuscleGroupIndex(assignment, parameterDetails.muscleGroups);

        parameterDetails.boundaryType = it->getBoundariesType();
        parameterDetails.lowerLimit = it->getLowerLimit();
        parameterDetails.upperLimit = it->getUpperLimit();
        parameterDetails.size = parameterDetails.muscleGroups.size();
        parameterDetails.name = it->getName();

        std::pair<typename ParametersMap::iterator, bool> ret;
        ret = parameters_.insert(std::pair<ParameterID, ParameterDetails> (parameterId, parameterDetails));
        if (ret.second == false)
            std::cout << "parameter " << it->getName() << " already existed - skipped\n";
    }

    noParameters_ = 0;
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it)
        noParameters_ += it->second.muscleGroups.size();

    std::cout << "Number of Parameters " << noParameters_ << std::endl;
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getStartingVectorParameters(std::vector< double >& x) {

	x.clear();
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it) {

        std::vector<double> coefficients, groupedCoefficients;
		getCoefficients(it->first, coefficients);
		groupValues(it->second.muscleGroups, coefficients, groupedCoefficients);
		x.insert(x.end(), groupedCoefficients.begin(), groupedCoefficients.end());
	}
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::setVectorParameters(const std::vector<double>& x) {

    unsigned count = 0;
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it) {

        unsigned noCoefficients = it->second.size;
        std::vector<double>::const_iterator startIt(x.begin()+count);
        std::vector<double>::const_iterator endIt(x.begin()+count+noCoefficients);
        std::vector<double> groupedCoefficients(startIt, endIt);
        std::vector<double> coefficients;

        getCoefficients(it->first, coefficients);
        distributeValues(it->second.muscleGroups, coefficients, groupedCoefficients);
        setCoefficients(it->first, coefficients);

        count += noCoefficients;

    }

}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getUpperLowerBounds(std::vector<double>& upperBounds, std::vector<double>& lowerBounds) {

    upperBounds.clear(); lowerBounds.clear();
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it) {
        if(it->second.boundaryType == Parameter::RelativeToSubjectValue) {
            std::vector<double> coefficients;
            getCoefficients(it->first, coefficients);
            for(std::vector<double>::const_iterator cIt(coefficients.begin()); cIt != coefficients.end(); ++cIt) {
                double upperBoundValue = *cIt * (it->second.upperLimit);
                double lowerBoundValue = *cIt * (it->second.lowerLimit);
                upperBounds.push_back(upperBoundValue);
                lowerBounds.push_back(lowerBoundValue);
            }
        }
        else {
            upperBounds.insert(upperBounds.end(), it->second.size, it->second.upperLimit);
            lowerBounds.insert(lowerBounds.end(), it->second.size, it->second.lowerLimit);
        }
    }
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::groupValues(const MuscleGroupsIdx& muscleGroupsIdx, const std::vector<double>& distributedValues, std::vector<double>& groupedValues) {

    groupedValues.clear();
    for(typename MuscleGroupsIdx::const_iterator it(muscleGroupsIdx.begin()); it != muscleGroupsIdx.end(); ++it)
        groupedValues.push_back(distributedValues.at(it->front()));
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::distributeValues(const MuscleGroupsIdx& muscleGroupsIdx, std::vector<double>& distributedValues, const std::vector<double>& groupedValues) {

    for(unsigned i = 0; i < muscleGroupsIdx.size(); ++i)
        for(std::vector<unsigned>::const_iterator it(muscleGroupsIdx.at(i).begin()); it != muscleGroupsIdx.at(i).end(); ++it)
            distributedValues.at(*it) = groupedValues.at(i);
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getMuscleGroupIndex(const MuscleGroups& muscleGroups, MuscleGroupsIdx& muscleGroupsIdx) {

    muscleGroupsIdx.clear();
    std::vector<std::string> muscleNames;
    subject_.getMuscleNames(muscleNames);
    for(typename MuscleGroups::const_iterator gIt(muscleGroups.begin()); gIt != muscleGroups.end(); ++gIt) {
        std::vector<unsigned> muscleIndex;
        for(std::list<std::string>::const_iterator mIt(gIt->begin()); mIt != gIt->end(); ++mIt) {
            std::vector<std::string>::iterator fId;
            fId = std::find(muscleNames.begin(), muscleNames.end(), *mIt);
			if(fId != muscleNames.end())
	            muscleIndex.push_back(std::distance(muscleNames.begin(), fId));
			else {
				std::cout << *mIt << " not found.\n";
				exit(EXIT_FAILURE);
			}
        }
        muscleGroupsIdx.push_back(muscleIndex);
    }
}

//NOTE: when using global o single parameters, only the calibrating dofs are considered
template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getMuscleGroupIndex(ParameterAssignment parameterAssignment, MuscleGroupsIdx& muscleGroupsIdx) {

    muscleGroupsIdx.clear();
    std::vector<unsigned> musclesIndexList;
    subject_.getMusclesIndexFromDofs(musclesIndexList, dofNames_);
    if(parameterAssignment == Parameter::Single) {
        for(vector<unsigned>::const_iterator it(musclesIndexList.begin()); it != musclesIndexList.end(); ++it) {
            std::vector<unsigned> m; m.push_back(*it);
            muscleGroupsIdx.push_back(m);
        }
    }
    else if(parameterAssignment == Parameter::Global)
        muscleGroupsIdx.push_back(musclesIndexList);
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getCoefficients(ParameterID parameterID, std::vector<double>& coefficients) {

     switch(parameterID) {
            case Parameter::C1:
                subject_.getC1Coefficients(coefficients);
                break;
            case Parameter::C2:
                subject_.getC2Coefficients(coefficients);
                break;
            case Parameter::Damping:
                break;
            case Parameter::EmDelay:
                break;
            case Parameter::MaxIsometricForce:
                break;
            case Parameter::OptimalFibreLength:
                subject_.getOptimalFibreLengths(coefficients);
                break;
            case Parameter::PennationAngle:
                break;
            case Parameter::PercentageChange:
                break;
            case Parameter::ShapeFactor:
                subject_.getShapeFactors(coefficients);
                break;
            case Parameter::StrengthCoefficient:
                subject_.getStrengthCoefficients(coefficients);
                break;
            case Parameter::TendonSlackLength:
                subject_.getTendonSlackLengths(coefficients);
                break;
        }
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::setCoefficients(ParameterID parameterID, const std::vector<double>& coefficients) {

      switch(parameterID) {
            case Parameter::C1:
                subject_.setC1Coefficients(coefficients);
                break;
            case Parameter::C2:
                subject_.setC2Coefficients(coefficients);
                break;
            case Parameter::Damping:
                break;
            case Parameter::EmDelay:
                break;
            case Parameter::MaxIsometricForce:
                break;
            case Parameter::OptimalFibreLength:
                subject_.setOptimalFibreLengths(coefficients);
                break;
            case Parameter::PennationAngle:
                break;
            case Parameter::PercentageChange:
                break;
            case Parameter::ShapeFactor:
                subject_.setShapeFactors(coefficients);
                break;
            case Parameter::StrengthCoefficient:
                subject_.setStrengthCoefficients(coefficients);
                break;
            case Parameter::TendonSlackLength:
                subject_.setTendonSlackLengths(coefficients);
                break;
        }
}<commit_msg>Retrieve correct values for parameter limits<commit_after>//__________________________________________________________________________
// Author: Claudio Pizzolato, October 2013
// email:  claudio.pizzolato@griffithuni.edu.au
//
// DO NOT REDISTRIBUTE WITHOUT PERMISSION
//__________________________________________________________________________
//

#include "Parameter.h"
#include <iostream>
#include <vector>
#include <algorithm>

template<typename NMSmodelT>
ParametersFromXml<NMSmodelT>::ParametersFromXml(NMSmodelT& subject, std::vector< std::string >& dofToCalibrate, const ParameterSet& parameterSet)
:subject_(subject), dofNames_(dofToCalibrate) {

    for(ParameterSet::const_iterator it(parameterSet.begin()); it != parameterSet.end(); ++it) {
        std::cout << "Parameter " << it->getName() << std::endl;
        ParameterDetails parameterDetails;
        ParameterID parameterId = it->getID();

        ParameterAssignment assignment = it->getAssignment();
        if(assignment == Parameter::Grouped) {
            MuscleGroups muscleGroups;
            it->getMuscleGroups(muscleGroups);
            getMuscleGroupIndex(muscleGroups, parameterDetails.muscleGroups);
        } else
            getMuscleGroupIndex(assignment, parameterDetails.muscleGroups);

        parameterDetails.boundaryType = it->getBoundariesType();
        parameterDetails.lowerLimit = it->getLowerLimit();
        parameterDetails.upperLimit = it->getUpperLimit();
        parameterDetails.size = parameterDetails.muscleGroups.size();
        parameterDetails.name = it->getName();

        std::pair<typename ParametersMap::iterator, bool> ret;
        ret = parameters_.insert(std::pair<ParameterID, ParameterDetails> (parameterId, parameterDetails));
        if (ret.second == false)
            std::cout << "parameter " << it->getName() << " already existed - skipped\n";
    }

    noParameters_ = 0;
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it)
        noParameters_ += it->second.muscleGroups.size();

    std::cout << "Number of Parameters " << noParameters_ << std::endl;
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getStartingVectorParameters(std::vector< double >& x) {

	x.clear();
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it) {

        std::vector<double> coefficients, groupedCoefficients;
		getCoefficients(it->first, coefficients);
		groupValues(it->second.muscleGroups, coefficients, groupedCoefficients);
		x.insert(x.end(), groupedCoefficients.begin(), groupedCoefficients.end());
	}
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::setVectorParameters(const std::vector<double>& x) {

    unsigned count = 0;
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it) {

        unsigned noCoefficients = it->second.size;
        std::vector<double>::const_iterator startIt(x.begin()+count);
        std::vector<double>::const_iterator endIt(x.begin()+count+noCoefficients);
        std::vector<double> groupedCoefficients(startIt, endIt);
        std::vector<double> coefficients;

        getCoefficients(it->first, coefficients);
        distributeValues(it->second.muscleGroups, coefficients, groupedCoefficients);
        setCoefficients(it->first, coefficients);

        count += noCoefficients;

    }

}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getUpperLowerBounds(std::vector<double>& upperBounds, std::vector<double>& lowerBounds) {

    upperBounds.clear(); lowerBounds.clear();
    for(typename ParametersMap::const_iterator it(parameters_.begin()); it != parameters_.end(); ++it) {
        if(it->second.boundaryType == Parameter::RelativeToSubjectValue) {
            std::vector<double> coefficients, groupedCoefficients;
            getCoefficients(it->first, coefficients);
            groupValues(it->second.muscleGroups, coefficients, groupedCoefficients);
            for(std::vector<double>::const_iterator cIt(groupedCoefficients.begin()); cIt != groupedCoefficients.end(); ++cIt) {
                double upperBoundValue = *cIt * (it->second.upperLimit);
                double lowerBoundValue = *cIt * (it->second.lowerLimit);
                upperBounds.push_back(upperBoundValue);
                lowerBounds.push_back(lowerBoundValue);
            }
        }
        else {
            upperBounds.insert(upperBounds.end(), it->second.size, it->second.upperLimit);
            lowerBounds.insert(lowerBounds.end(), it->second.size, it->second.lowerLimit);
        }
    }
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::groupValues(const MuscleGroupsIdx& muscleGroupsIdx, const std::vector<double>& distributedValues, std::vector<double>& groupedValues) {

    groupedValues.clear();
    for(typename MuscleGroupsIdx::const_iterator it(muscleGroupsIdx.begin()); it != muscleGroupsIdx.end(); ++it)
        groupedValues.push_back(distributedValues.at(it->front()));
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::distributeValues(const MuscleGroupsIdx& muscleGroupsIdx, std::vector<double>& distributedValues, const std::vector<double>& groupedValues) {

    for(unsigned i = 0; i < muscleGroupsIdx.size(); ++i)
        for(std::vector<unsigned>::const_iterator it(muscleGroupsIdx.at(i).begin()); it != muscleGroupsIdx.at(i).end(); ++it)
            distributedValues.at(*it) = groupedValues.at(i);
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getMuscleGroupIndex(const MuscleGroups& muscleGroups, MuscleGroupsIdx& muscleGroupsIdx) {

    muscleGroupsIdx.clear();
    std::vector<std::string> muscleNames;
    subject_.getMuscleNames(muscleNames);
    for(typename MuscleGroups::const_iterator gIt(muscleGroups.begin()); gIt != muscleGroups.end(); ++gIt) {
        std::vector<unsigned> muscleIndex;
        for(std::list<std::string>::const_iterator mIt(gIt->begin()); mIt != gIt->end(); ++mIt) {
            std::vector<std::string>::iterator fId;
            fId = std::find(muscleNames.begin(), muscleNames.end(), *mIt);
			if(fId != muscleNames.end())
	            muscleIndex.push_back(std::distance(muscleNames.begin(), fId));
			else {
				std::cout << *mIt << " not found.\n";
				exit(EXIT_FAILURE);
			}
        }
        muscleGroupsIdx.push_back(muscleIndex);
    }
}

//NOTE: when using global o single parameters, only the calibrating dofs are considered
template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getMuscleGroupIndex(ParameterAssignment parameterAssignment, MuscleGroupsIdx& muscleGroupsIdx) {

    muscleGroupsIdx.clear();
    std::vector<unsigned> musclesIndexList;
    subject_.getMusclesIndexFromDofs(musclesIndexList, dofNames_);
    if(parameterAssignment == Parameter::Single) {
        for(vector<unsigned>::const_iterator it(musclesIndexList.begin()); it != musclesIndexList.end(); ++it) {
            std::vector<unsigned> m; m.push_back(*it);
            muscleGroupsIdx.push_back(m);
        }
    }
    else if(parameterAssignment == Parameter::Global)
        muscleGroupsIdx.push_back(musclesIndexList);
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::getCoefficients(ParameterID parameterID, std::vector<double>& coefficients) {

     switch(parameterID) {
            case Parameter::C1:
                subject_.getC1Coefficients(coefficients);
                break;
            case Parameter::C2:
                subject_.getC2Coefficients(coefficients);
                break;
            case Parameter::Damping:
                break;
            case Parameter::EmDelay:
                break;
            case Parameter::MaxIsometricForce:
                break;
            case Parameter::OptimalFibreLength:
                subject_.getOptimalFibreLengths(coefficients);
                break;
            case Parameter::PennationAngle:
                break;
            case Parameter::PercentageChange:
                break;
            case Parameter::ShapeFactor:
                subject_.getShapeFactors(coefficients);
                break;
            case Parameter::StrengthCoefficient:
                subject_.getStrengthCoefficients(coefficients);
                break;
            case Parameter::TendonSlackLength:
                subject_.getTendonSlackLengths(coefficients);
                break;
        }
}

template<typename NMSmodelT>
void ParametersFromXml<NMSmodelT>::setCoefficients(ParameterID parameterID, const std::vector<double>& coefficients) {

      switch(parameterID) {
            case Parameter::C1:
                subject_.setC1Coefficients(coefficients);
                break;
            case Parameter::C2:
                subject_.setC2Coefficients(coefficients);
                break;
            case Parameter::Damping:
                break;
            case Parameter::EmDelay:
                break;
            case Parameter::MaxIsometricForce:
                break;
            case Parameter::OptimalFibreLength:
                subject_.setOptimalFibreLengths(coefficients);
                break;
            case Parameter::PennationAngle:
                break;
            case Parameter::PercentageChange:
                break;
            case Parameter::ShapeFactor:
                subject_.setShapeFactors(coefficients);
                break;
            case Parameter::StrengthCoefficient:
                subject_.setStrengthCoefficients(coefficients);
                break;
            case Parameter::TendonSlackLength:
                subject_.setTendonSlackLengths(coefficients);
                break;
        }
}<|endoftext|>


<commit_before>//==-- AArch64DeadRegisterDefinitions.cpp - Replace dead defs w/ zero reg --==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// When allowed by the instruction, replace a dead definition of a GPR with
// the zero register. This makes the code a bit friendlier towards the
// hardware's register renamer.
//===----------------------------------------------------------------------===//

#include "AArch64.h"
#include "AArch64RegisterInfo.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;

#define DEBUG_TYPE "aarch64-dead-defs"

STATISTIC(NumDeadDefsReplaced, "Number of dead definitions replaced");

namespace llvm {
void initializeAArch64DeadRegisterDefinitionsPass(PassRegistry &);
}

#define AARCH64_DEAD_REG_DEF_NAME "AArch64 Dead register definitions"

namespace {
class AArch64DeadRegisterDefinitions : public MachineFunctionPass {
private:
  const TargetRegisterInfo *TRI;
  bool implicitlyDefinesOverlappingReg(unsigned Reg, const MachineInstr &MI);
  bool processMachineBasicBlock(MachineBasicBlock &MBB);
  bool usesFrameIndex(const MachineInstr &MI);
public:
  static char ID; // Pass identification, replacement for typeid.
  explicit AArch64DeadRegisterDefinitions() : MachineFunctionPass(ID) {
    initializeAArch64DeadRegisterDefinitionsPass(
        *PassRegistry::getPassRegistry());
  }

  bool runOnMachineFunction(MachineFunction &F) override;

  const char *getPassName() const override { return AARCH64_DEAD_REG_DEF_NAME; }

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.setPreservesCFG();
    MachineFunctionPass::getAnalysisUsage(AU);
  }
};
char AArch64DeadRegisterDefinitions::ID = 0;
} // end anonymous namespace

INITIALIZE_PASS(AArch64DeadRegisterDefinitions, "aarch64-dead-defs",
                AARCH64_DEAD_REG_DEF_NAME, false, false)

bool AArch64DeadRegisterDefinitions::implicitlyDefinesOverlappingReg(
    unsigned Reg, const MachineInstr &MI) {
  for (const MachineOperand &MO : MI.implicit_operands())
    if (MO.isReg() && MO.isDef())
      if (TRI->regsOverlap(Reg, MO.getReg()))
        return true;
  return false;
}

bool AArch64DeadRegisterDefinitions::usesFrameIndex(const MachineInstr &MI) {
  for (const MachineOperand &Op : MI.uses())
    if (Op.isFI())
      return true;
  return false;
}

bool AArch64DeadRegisterDefinitions::processMachineBasicBlock(
    MachineBasicBlock &MBB) {
  bool Changed = false;
  for (MachineInstr &MI : MBB) {
    if (usesFrameIndex(MI)) {
      // We need to skip this instruction because while it appears to have a
      // dead def it uses a frame index which might expand into a multi
      // instruction sequence during EPI.
      DEBUG(dbgs() << "    Ignoring, operand is frame index\n");
      continue;
    }
    for (int i = 0, e = MI.getDesc().getNumDefs(); i != e; ++i) {
      MachineOperand &MO = MI.getOperand(i);
      if (MO.isReg() && MO.isDead() && MO.isDef()) {
        assert(!MO.isImplicit() && "Unexpected implicit def!");
        DEBUG(dbgs() << "  Dead def operand #" << i << " in:\n    ";
              MI.print(dbgs()));
        // Be careful not to change the register if it's a tied operand.
        if (MI.isRegTiedToUseOperand(i)) {
          DEBUG(dbgs() << "    Ignoring, def is tied operand.\n");
          continue;
        }
        // Don't change the register if there's an implicit def of a subreg or
        // supperreg.
        if (implicitlyDefinesOverlappingReg(MO.getReg(), MI)) {
          DEBUG(dbgs() << "    Ignoring, implicitly defines overlap reg.\n");
          continue;
        }
        // Make sure the instruction take a register class that contains
        // the zero register and replace it if so.
        unsigned NewReg;
        switch (MI.getDesc().OpInfo[i].RegClass) {
        default:
          DEBUG(dbgs() << "    Ignoring, register is not a GPR.\n");
          continue;
        case AArch64::GPR32RegClassID:
          NewReg = AArch64::WZR;
          break;
        case AArch64::GPR64RegClassID:
          NewReg = AArch64::XZR;
          break;
        }
        DEBUG(dbgs() << "    Replacing with zero register. New:\n      ");
        MO.setReg(NewReg);
        DEBUG(MI.print(dbgs()));
        ++NumDeadDefsReplaced;
      }
    }
  }
  return Changed;
}

// Scan the function for instructions that have a dead definition of a
// register. Replace that register with the zero register when possible.
bool AArch64DeadRegisterDefinitions::runOnMachineFunction(MachineFunction &MF) {
  TRI = MF.getSubtarget().getRegisterInfo();
  bool Changed = false;
  DEBUG(dbgs() << "***** AArch64DeadRegisterDefinitions *****\n");

  for (auto &MBB : MF)
    if (processMachineBasicBlock(MBB))
      Changed = true;
  return Changed;
}

FunctionPass *llvm::createAArch64DeadRegisterDefinitions() {
  return new AArch64DeadRegisterDefinitions();
}
<commit_msg>[AArch64] Fix a typo. NFC.<commit_after>//==-- AArch64DeadRegisterDefinitions.cpp - Replace dead defs w/ zero reg --==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// When allowed by the instruction, replace a dead definition of a GPR with
// the zero register. This makes the code a bit friendlier towards the
// hardware's register renamer.
//===----------------------------------------------------------------------===//

#include "AArch64.h"
#include "AArch64RegisterInfo.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;

#define DEBUG_TYPE "aarch64-dead-defs"

STATISTIC(NumDeadDefsReplaced, "Number of dead definitions replaced");

namespace llvm {
void initializeAArch64DeadRegisterDefinitionsPass(PassRegistry &);
}

#define AARCH64_DEAD_REG_DEF_NAME "AArch64 Dead register definitions"

namespace {
class AArch64DeadRegisterDefinitions : public MachineFunctionPass {
private:
  const TargetRegisterInfo *TRI;
  bool implicitlyDefinesOverlappingReg(unsigned Reg, const MachineInstr &MI);
  bool processMachineBasicBlock(MachineBasicBlock &MBB);
  bool usesFrameIndex(const MachineInstr &MI);
public:
  static char ID; // Pass identification, replacement for typeid.
  explicit AArch64DeadRegisterDefinitions() : MachineFunctionPass(ID) {
    initializeAArch64DeadRegisterDefinitionsPass(
        *PassRegistry::getPassRegistry());
  }

  bool runOnMachineFunction(MachineFunction &F) override;

  const char *getPassName() const override { return AARCH64_DEAD_REG_DEF_NAME; }

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    AU.setPreservesCFG();
    MachineFunctionPass::getAnalysisUsage(AU);
  }
};
char AArch64DeadRegisterDefinitions::ID = 0;
} // end anonymous namespace

INITIALIZE_PASS(AArch64DeadRegisterDefinitions, "aarch64-dead-defs",
                AARCH64_DEAD_REG_DEF_NAME, false, false)

bool AArch64DeadRegisterDefinitions::implicitlyDefinesOverlappingReg(
    unsigned Reg, const MachineInstr &MI) {
  for (const MachineOperand &MO : MI.implicit_operands())
    if (MO.isReg() && MO.isDef())
      if (TRI->regsOverlap(Reg, MO.getReg()))
        return true;
  return false;
}

bool AArch64DeadRegisterDefinitions::usesFrameIndex(const MachineInstr &MI) {
  for (const MachineOperand &Op : MI.uses())
    if (Op.isFI())
      return true;
  return false;
}

bool AArch64DeadRegisterDefinitions::processMachineBasicBlock(
    MachineBasicBlock &MBB) {
  bool Changed = false;
  for (MachineInstr &MI : MBB) {
    if (usesFrameIndex(MI)) {
      // We need to skip this instruction because while it appears to have a
      // dead def it uses a frame index which might expand into a multi
      // instruction sequence during EPI.
      DEBUG(dbgs() << "    Ignoring, operand is frame index\n");
      continue;
    }
    for (int i = 0, e = MI.getDesc().getNumDefs(); i != e; ++i) {
      MachineOperand &MO = MI.getOperand(i);
      if (MO.isReg() && MO.isDead() && MO.isDef()) {
        assert(!MO.isImplicit() && "Unexpected implicit def!");
        DEBUG(dbgs() << "  Dead def operand #" << i << " in:\n    ";
              MI.print(dbgs()));
        // Be careful not to change the register if it's a tied operand.
        if (MI.isRegTiedToUseOperand(i)) {
          DEBUG(dbgs() << "    Ignoring, def is tied operand.\n");
          continue;
        }
        // Don't change the register if there's an implicit def of a subreg or
        // superreg.
        if (implicitlyDefinesOverlappingReg(MO.getReg(), MI)) {
          DEBUG(dbgs() << "    Ignoring, implicitly defines overlap reg.\n");
          continue;
        }
        // Make sure the instruction take a register class that contains
        // the zero register and replace it if so.
        unsigned NewReg;
        switch (MI.getDesc().OpInfo[i].RegClass) {
        default:
          DEBUG(dbgs() << "    Ignoring, register is not a GPR.\n");
          continue;
        case AArch64::GPR32RegClassID:
          NewReg = AArch64::WZR;
          break;
        case AArch64::GPR64RegClassID:
          NewReg = AArch64::XZR;
          break;
        }
        DEBUG(dbgs() << "    Replacing with zero register. New:\n      ");
        MO.setReg(NewReg);
        DEBUG(MI.print(dbgs()));
        ++NumDeadDefsReplaced;
      }
    }
  }
  return Changed;
}

// Scan the function for instructions that have a dead definition of a
// register. Replace that register with the zero register when possible.
bool AArch64DeadRegisterDefinitions::runOnMachineFunction(MachineFunction &MF) {
  TRI = MF.getSubtarget().getRegisterInfo();
  bool Changed = false;
  DEBUG(dbgs() << "***** AArch64DeadRegisterDefinitions *****\n");

  for (auto &MBB : MF)
    if (processMachineBasicBlock(MBB))
      Changed = true;
  return Changed;
}

FunctionPass *llvm::createAArch64DeadRegisterDefinitions() {
  return new AArch64DeadRegisterDefinitions();
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *  sample codes for algorithm.hpp
 *
 *  written by janus_wel<janus.wel.3@gmail.com>
 *  This source code is in public domain, and has NO WARRANTY.
 * */

#include "../../header/algorithm.hpp"

#include <algorithm>
#include <cstring>
#include <functional>
#include <iostream>
#include <list>
#include <locale>
#include <string>
#include <vector>

inline std::string pack(const char* const str) { return std::string(str); }

// We can't use std::mem_fun_ref() to compose functions for a non-static member
// function in g++ 4.3.3, so it is needed to wrap it.
#ifndef _MSC_VER
inline size_t length(const std::string& str) { return str.size(); }
#endif

template<typename Char>
inline bool is(const std::ctype_base::mask mask, const Char c) {
    static const std::ctype<Char>& ctype =
        std::use_facet<std::ctype<Char> >(std::locale::classic());
    return ctype.is(mask, c);
}

template<typename Char>
class has {
    private:
        const std::ctype_base::mask mask;
        has& operator=(const has&);

    public:
        has(const std::ctype_base::mask mask) : mask(mask) {}
        bool operator()(const std::basic_string<Char>& str) {
            return std::find_if(str.begin(), str.end(),
                    std::bind1st(std::ptr_fun(&(is<Char>)), mask))
                != str.end();
        }
};

int main(const int argc, const char* const argv[]) {
    typedef std::vector<std::string>    string_array_type;
    //typedef std::list<std::string>  string_array_type;

    std::cout << "argv\n";
    std::ostream_iterator<const char* const> coitr =
        util::algorithm::print<const char* const>(argv, argv + argc, std::cout, "\n");
// Above expression is equivalent to following codes
//    std::ostream_iterator<const char* const> coitr(std::cout, "\n");
//    util::algorithm::print(argv, argv + argc, coitr);
    std::cout << std::endl;

    string_array_type params(argc);
    std::transform(argv, argv + argc, params.begin(), pack);

    std::cout << "packed argv as std::string\n";
    std::ostream_iterator<std::string> soitr =
        util::algorithm::print<std::string>(params.begin(), params.end(), std::cout, "\n");
    std::cout << std::endl;

    std::cout << "lengths of argv\n";
    util::algorithm::print_op<size_t>(argv, argv + argc, std::cout, "\n", std::strlen);
    std::cout << std::endl;

    std::cout << "lengths of packed argv as std::string\n";
#ifdef _MSC_VER
    // In g++ 4.3.3, this expression can't be passed.
    util::algorithm::print_op<size_t>(
            params.begin(), params.end(),
            std::cout, "\n", std::mem_fun_ref(&(std::string::size)));
#else
    util::algorithm::print_op<size_t>(
            params.begin(), params.end(),
            std::cout, "\n", length);
#endif
    std::cout << std::endl;

    std::cout << "argv that has any digits\n";
    util::algorithm::print_if(argv, argv + argc, coitr, has<char>(std::ctype_base::digit));
    std::cout << std::endl;

    std::cout << "packed argv as std::string that has any punctuations\n";
    util::algorithm::print_if(params.begin(), params.end(), soitr, has<char>(std::ctype_base::punct));
    std::cout << std::endl;

// emulation of "grep" statement in Perl
//    string_array_type greped(std::count_if(params.begin(), params.end(), has_digit<char>()));
//    util::algorithm::copy_if(params.begin(), params.end(), greped.begin(), has_digit<char>());
//    util::algorithm::print(greped.begin(), greped.end(), soitr);

    return 0;
}

<commit_msg>Simplify<commit_after>/*
 * main.cpp
 *  sample codes for algorithm.hpp
 *
 *  written by janus_wel<janus.wel.3@gmail.com>
 *  This source code is in public domain, and has NO WARRANTY.
 * */

#include "../../header/algorithm.hpp"

#include <algorithm>
#include <cstring>
#include <functional>
#include <iostream>
#include <list>
#include <locale>
#include <string>
#include <vector>

// We can't use std::mem_fun_ref() to compose functions for a non-static member
// function in g++ 4.3.3, so it is needed to wrap it.
#ifndef _MSC_VER
inline size_t length(const std::string& str) { return str.size(); }
#endif

template<typename Char>
inline bool is(const std::ctype_base::mask mask, const Char c) {
    static const std::ctype<Char>& ctype =
        std::use_facet<std::ctype<Char> >(std::locale::classic());
    return ctype.is(mask, c);
}

template<typename Char>
class has {
    private:
        const std::ctype_base::mask mask;
        has& operator=(const has&);

    public:
        has(const std::ctype_base::mask mask) : mask(mask) {}
        bool operator()(const std::basic_string<Char>& str) {
            return std::find_if(str.begin(), str.end(),
                    std::bind1st(std::ptr_fun(&(is<Char>)), mask))
                != str.end();
        }
};

int main(const int argc, const char* const argv[]) {
    typedef std::vector<std::string>    string_array_type;
    //typedef std::list<std::string>  string_array_type;

    std::cout << "argv\n";
    std::ostream_iterator<const char* const> coitr =
        util::algorithm::print<const char* const>(argv, argv + argc, std::cout, "\n");
// Above expression is equivalent to following codes
//    std::ostream_iterator<const char* const> coitr(std::cout, "\n");
//    util::algorithm::print(argv, argv + argc, coitr);
    std::cout << std::endl;

    string_array_type params(argc);
    std::copy(argv, argv + argc, params.begin());

    std::cout << "packed argv as std::string\n";
    std::ostream_iterator<std::string> soitr =
        util::algorithm::print<std::string>(params.begin(), params.end(), std::cout, "\n");
    std::cout << std::endl;

    std::cout << "lengths of argv\n";
    util::algorithm::print_op<size_t>(argv, argv + argc, std::cout, "\n", std::strlen);
    std::cout << std::endl;

    std::cout << "lengths of packed argv as std::string\n";
#ifdef _MSC_VER
    // In g++ 4.3.3, this expression can't be passed.
    util::algorithm::print_op<size_t>(
            params.begin(), params.end(),
            std::cout, "\n", std::mem_fun_ref(&(std::string::size)));
#else
    util::algorithm::print_op<size_t>(
            params.begin(), params.end(),
            std::cout, "\n", length);
#endif
    std::cout << std::endl;

    std::cout << "argv that has any digits\n";
    util::algorithm::print_if(argv, argv + argc, coitr, has<char>(std::ctype_base::digit));
    std::cout << std::endl;

    std::cout << "packed argv as std::string that has any punctuations\n";
    util::algorithm::print_if(params.begin(), params.end(), soitr, has<char>(std::ctype_base::punct));
    std::cout << std::endl;

// emulation of "grep" statement in Perl
//    string_array_type greped(std::count_if(params.begin(), params.end(), has_digit<char>()));
//    util::algorithm::copy_if(params.begin(), params.end(), greped.begin(), has_digit<char>());
//    util::algorithm::print(greped.begin(), greped.end(), soitr);

    return 0;
}

<|endoftext|>


<commit_before>// NanoWin32
// -----------------------------------------------------------------------
// Simple library to subset Win32(64) API functions implemenation on POSIX
// This software distributed by MIT license

// MFC UI emulation class

#include <stdio.h>

#include "NanoWinMFCAfxNUI.h"

static void NanoWinNUILog(const char *format, ...)
{
  CStringA str;
  va_list  args;

  va_start(args,format);

  str.FormatV(format,args);

  va_end(args);

  printf("NUILog: %s\n",str.GetString());
}

static void NanoWinNUILog(const wchar_t *format, ...)
{
  CStringW str;
  va_list  args;

  va_start(args,format);

  str.FormatV(format,args);

  va_end(args);

  printf("NUILog: %s\n",CW2A(str.GetString()).c_str());
}

#if defined(UNICODE) || defined(_UNICODE)

void NanoWinTextStr::SetText(LPCSTR    lpszString)
{
  str.SetString(CA2W(lpszString));
}

void NanoWinTextStr::SetText(LPCWSTR   lpszString)
{
  str.SetString(lpsString);
}

void NanoWinTextStr::GetText(CStringA &rString) const
{
  rString.SetString(CW2A(str.GetString()));
}

void NanoWinTextStr::GetText (CStringW &rString) const
{
  rString = str;
}

#else

void NanoWinTextStr::SetText(LPCSTR    lpszString)
{
  str.SetString(lpszString);
}

void NanoWinTextStr::SetText(LPCWSTR   lpszString)
{
  str.SetString(CW2A(lpszString));
}

void NanoWinTextStr::GetText(CStringA &rString) const
{
  rString = str;
}

void NanoWinTextStr::GetText (CStringW &rString) const
{
  rString.SetString(CA2W(str.GetString()));
}

#endif

void CWnd::SetWindowTextA(LPCSTR    lpszString)
{
  windowText.SetText(lpszString);

  NanoWinNUILog("CWnd::SetWindowTextA(%s)",lpszString);
}

void CWnd::SetWindowTextW(LPCWSTR   lpszString)
{
  windowText.SetText(lpszString);

  NanoWinNUILog(L"CWnd::SetWindowTextW(%s)",lpszString);
}

void CWnd::GetWindowTextA(CStringA &rString) const
{
  windowText.GetText(rString);

  NanoWinNUILog("CWnd::GetWindowTextA(%s)",rString.GetString());
}

void CWnd::GetWindowTextW(CStringW &rString) const
{
  windowText.GetText(rString);

  NanoWinNUILog(L"CWnd::GetWindowTextW(%s)",rString.GetString());
}

BOOL    CListCtrl::SetItemText(int nItem, int nSubItem, LPCTSTR lpszText)
{
  itemStorage[IntPair(nItem,nSubItem)] = CString(lpszText);

  NanoWinNUILog(_T("CListCtrl::SetItemText(item: %d, subitem: %d, text: %s)"),nItem,nSubItem,lpszText);

  return TRUE;
}

CString CListCtrl::GetItemText(int nItem, int nSubItem) const
{
  auto it = itemStorage.find(IntPair(nItem,nSubItem));

  if (it != itemStorage.cend())
  {
    return it->second;
  }
  else
  {
    return CString();
  }
}

int  CListBox::GetCount() const
{
  return (int)listStorage.size();
}

void CListBox::GetText (int nIndex, CString& rString) const
{
  if (nIndex >= 0 && nIndex < GetCount())
  {
    rString = listStorage[nIndex];
  }
  else
  {
    rString.Empty();
  }
}

int  CListBox::AddString (LPCTSTR lpszItem)
{
  int index = (int)listStorage.size();

  listStorage.push_back(lpszItem);

  NanoWinNUILog(_T("CListBox::AddString(index: %d, text: %s)"),index,lpszItem);

  return index;
}

int  CComboBox::AddString (LPCTSTR lpszItem)
{
  int index = (int)listStorage.size();

  listStorage.push_back(lpszItem);

  NanoWinNUILog(_T("CComboBox::AddString(index: %d, text: %s)"),index,lpszItem);

  return index;
}
<commit_msg>fixed compilation error in UNICODE build in NanoWinMFCAfxNUI.cpp<commit_after>// NanoWin32
// -----------------------------------------------------------------------
// Simple library to subset Win32(64) API functions implemenation on POSIX
// This software distributed by MIT license

// MFC UI emulation class

#include <stdio.h>

#include "NanoWinMFCAfxNUI.h"

static void NanoWinNUILog(const char *format, ...)
{
  CStringA str;
  va_list  args;

  va_start(args,format);

  str.FormatV(format,args);

  va_end(args);

  printf("NUILog: %s\n",str.GetString());
}

static void NanoWinNUILog(const wchar_t *format, ...)
{
  CStringW str;
  va_list  args;

  va_start(args,format);

  str.FormatV(format,args);

  va_end(args);

  printf("NUILog: %s\n",CW2A(str.GetString()).c_str());
}

#if defined(UNICODE) || defined(_UNICODE)

void NanoWinTextStr::SetText(LPCSTR    lpszString)
{
  str.SetString(CA2W(lpszString));
}

void NanoWinTextStr::SetText(LPCWSTR   lpszString)
{
  str.SetString(lpszString);
}

void NanoWinTextStr::GetText(CStringA &rString) const
{
  rString.SetString(CW2A(str.GetString()));
}

void NanoWinTextStr::GetText (CStringW &rString) const
{
  rString = str;
}

#else

void NanoWinTextStr::SetText(LPCSTR    lpszString)
{
  str.SetString(lpszString);
}

void NanoWinTextStr::SetText(LPCWSTR   lpszString)
{
  str.SetString(CW2A(lpszString));
}

void NanoWinTextStr::GetText(CStringA &rString) const
{
  rString = str;
}

void NanoWinTextStr::GetText (CStringW &rString) const
{
  rString.SetString(CA2W(str.GetString()));
}

#endif

void CWnd::SetWindowTextA(LPCSTR    lpszString)
{
  windowText.SetText(lpszString);

  NanoWinNUILog("CWnd::SetWindowTextA(%s)",lpszString);
}

void CWnd::SetWindowTextW(LPCWSTR   lpszString)
{
  windowText.SetText(lpszString);

  NanoWinNUILog(L"CWnd::SetWindowTextW(%s)",lpszString);
}

void CWnd::GetWindowTextA(CStringA &rString) const
{
  windowText.GetText(rString);

  NanoWinNUILog("CWnd::GetWindowTextA(%s)",rString.GetString());
}

void CWnd::GetWindowTextW(CStringW &rString) const
{
  windowText.GetText(rString);

  NanoWinNUILog(L"CWnd::GetWindowTextW(%s)",rString.GetString());
}

BOOL    CListCtrl::SetItemText(int nItem, int nSubItem, LPCTSTR lpszText)
{
  itemStorage[IntPair(nItem,nSubItem)] = CString(lpszText);

  NanoWinNUILog(_T("CListCtrl::SetItemText(item: %d, subitem: %d, text: %s)"),nItem,nSubItem,lpszText);

  return TRUE;
}

CString CListCtrl::GetItemText(int nItem, int nSubItem) const
{
  auto it = itemStorage.find(IntPair(nItem,nSubItem));

  if (it != itemStorage.cend())
  {
    return it->second;
  }
  else
  {
    return CString();
  }
}

int  CListBox::GetCount() const
{
  return (int)listStorage.size();
}

void CListBox::GetText (int nIndex, CString& rString) const
{
  if (nIndex >= 0 && nIndex < GetCount())
  {
    rString = listStorage[nIndex];
  }
  else
  {
    rString.Empty();
  }
}

int  CListBox::AddString (LPCTSTR lpszItem)
{
  int index = (int)listStorage.size();

  listStorage.push_back(lpszItem);

  NanoWinNUILog(_T("CListBox::AddString(index: %d, text: %s)"),index,lpszItem);

  return index;
}

int  CComboBox::AddString (LPCTSTR lpszItem)
{
  int index = (int)listStorage.size();

  listStorage.push_back(lpszItem);

  NanoWinNUILog(_T("CComboBox::AddString(index: %d, text: %s)"),index,lpszItem);

  return index;
}
<|endoftext|>


<commit_before>/*
 * File:   main_voctreeLocalizer.cpp
 * Author: sgaspari
 *
 * Created on September 12, 2015, 3:16 PM
 */
#include <openMVG/localization/localization.hpp>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/progress.hpp>
#include <boost/program_options.hpp>

#include <iostream>
#include <string>

#define POPART_COUT(x) std::cout << x << std::endl
#define POPART_CERR(x) std::cerr << x << std::endl

namespace bfs = boost::filesystem;
namespace po = boost::program_options;

using namespace openMVG;

static const int DIMENSION = 128;

int main(int argc, char** argv)
{
  int numResults = 4; //< number of best matching images to retrieve from the database
  int numCommonViews = 3; //< number minimum common images in which a point must be seen to be used in cluster tracking
  std::string calibFile; //< the calibration file
  std::string sfmFilePath; ///< the OpenMVG .json data file
  std::string descriptorsFolder; ///< the OpenMVG .json data file
  std::string vocTreeFilepath; ///< the vocabulary tree file
  std::string weightsFilepath; ///< the vocabulary tree weights file
  std::string mediaFilepath; ///< the media file to localize
  std::string exportFilepath = "trackedcameras.json"; //!< the export file

  po::options_description desc(
                               "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n"
                               "and returns for each frame a pose estimation for the camera.");
  desc.add_options()
          ("help,h", "Print this message")
          ("results,r", po::value<int>(&numResults)->default_value(numResults), "Number of images to retrieve in database")
          ("commonviews,", po::value<int>(&numCommonViews)->default_value(numCommonViews), "Number of minimum images in which a point must be seen to be used in cluster tracking")
          ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file")
          ("voctree,t", po::value<std::string>(&vocTreeFilepath)->required(), "Filename for the vocabulary tree")
          ("weights,w", po::value<std::string>(&weightsFilepath), "Filename for the vocabulary tree weights")
          ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]")
          ("siftPath,s", po::value<std::string>(&descriptorsFolder), "Folder containing the .desc. If not provided, it will be assumed to be parent(sfmdata)/matches [for the older version of openMVG it is the list.txt]")
          ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track")
          ("export,e", po::value<std::string>(&exportFilepath)->default_value(exportFilepath), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name");

  po::variables_map vm;

  try
  {
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if(vm.count("help") || (argc == 1))
    {
      POPART_COUT(desc);
      return EXIT_SUCCESS;
    }

    po::notify(vm);
  }
  catch(boost::program_options::required_option& e)
  {
    POPART_CERR("ERROR: " << e.what() << std::endl);
    POPART_COUT("Usage:\n\n" << desc);
    return EXIT_FAILURE;
  }
  catch(boost::program_options::error& e)
  {
    POPART_CERR("ERROR: " << e.what() << std::endl);
    POPART_COUT("Usage:\n\n" << desc);
    return EXIT_FAILURE;
  }

}
<commit_msg>[software] added initialization<commit_after>/*
 * File:   main_voctreeLocalizer.cpp
 * Author: sgaspari
 *
 * Created on September 12, 2015, 3:16 PM
 */
#include <openMVG/localization/localization.hpp>
#include <openMVG/image/image_io.hpp>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/progress.hpp>
#include <boost/program_options.hpp>

#include <iostream>
#include <string>

#define POPART_COUT(x) std::cout << x << std::endl
#define POPART_CERR(x) std::cerr << x << std::endl

namespace bfs = boost::filesystem;
namespace po = boost::program_options;

using namespace openMVG;

static const int DIMENSION = 128;

int main(int argc, char** argv)
{
  int numResults = 4; //< number of best matching images to retrieve from the database
  int numCommonViews = 3; //< number minimum common images in which a point must be seen to be used in cluster tracking
  std::string calibFile; //< the calibration file
  std::string sfmFilePath; ///< the OpenMVG .json data file
  std::string descriptorsFolder; ///< the OpenMVG .json data file
  std::string vocTreeFilepath; ///< the vocabulary tree file
  std::string weightsFilepath; ///< the vocabulary tree weights file
  std::string mediaFilepath; ///< the media file to localize
  std::string exportFilepath = "trackedcameras.json"; //!< the export file

  po::options_description desc(
                               "This program takes as input a media (image, image sequence, video) and a database (voctree, 3D structure data) \n"
                               "and returns for each frame a pose estimation for the camera.");
  desc.add_options()
          ("help,h", "Print this message")
          ("results,r", po::value<int>(&numResults)->default_value(numResults), "Number of images to retrieve in database")
          ("commonviews,", po::value<int>(&numCommonViews)->default_value(numCommonViews), "Number of minimum images in which a point must be seen to be used in cluster tracking")
          ("calibration,c", po::value<std::string>(&calibFile)/*->required( )*/, "Calibration file")
          ("voctree,t", po::value<std::string>(&vocTreeFilepath)->required(), "Filename for the vocabulary tree")
          ("weights,w", po::value<std::string>(&weightsFilepath), "Filename for the vocabulary tree weights")
          ("sfmdata,d", po::value<std::string>(&sfmFilePath)->required(), "The sfm_data.json kind of file generated by OpenMVG [it could be also a bundle.out to use an older version of OpenMVG]")
          ("siftPath,s", po::value<std::string>(&descriptorsFolder), "Folder containing the .desc. If not provided, it will be assumed to be parent(sfmdata)/matches [for the older version of openMVG it is the list.txt]")
          ("mediafile,m", po::value<std::string>(&mediaFilepath)->required(), "The folder path or the filename for the media to track")
          ("export,e", po::value<std::string>(&exportFilepath)->default_value(exportFilepath), "Filename for the SfM_Data export file (where camera poses will be stored). Default : trackedcameras.json If Alambic is enable it will also export an .abc file of the scene with the same name");

  po::variables_map vm;

  try
  {
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if(vm.count("help") || (argc == 1))
    {
      POPART_COUT(desc);
      return EXIT_SUCCESS;
    }

    po::notify(vm);
  }
  catch(boost::program_options::required_option& e)
  {
    POPART_CERR("ERROR: " << e.what() << std::endl);
    POPART_COUT("Usage:\n\n" << desc);
    return EXIT_FAILURE;
  }
  catch(boost::program_options::error& e)
  {
    POPART_CERR("ERROR: " << e.what() << std::endl);
    POPART_COUT("Usage:\n\n" << desc);
    return EXIT_FAILURE;
  }

  // init the localizer
  localization::VoctreeLocalizer localizer;
  localizer.init(sfmFilePath, descriptorsFolder, vocTreeFilepath, weightsFilepath);

  // load the image
    POPART_COUT("Load the query image");
  // load the query image
  image::Image<unsigned char> imageGray;
  if(!image::ReadImage(mediaFilepath.c_str(), &imageGray))
    throw std::runtime_error("Unable to read the media file.");
  POPART_COUT("Image size: " << imageGray.Width() << "x" << imageGray.Height());

  // localize
//  localizer.Localize( imageGray)

  // save data

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

#ifdef ENABLE_QUICKSTART_APPLET

#include <unotools/moduleoptions.hxx>

#include <unotools/dynamicmenuoptions.hxx>

#include <gtk/gtk.h>
#include <glib.h>
#include <osl/mutex.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/bmpacc.hxx>
#include <sfx2/app.hxx>
#include "app.hrc"
#ifndef __SHUTDOWNICON_HXX__
#define USE_APP_SHORTCUTS
#include "shutdownicon.hxx"
#endif

#ifdef ENABLE_GIO
#include <gio/gio.h>
#endif

// Cut/paste from vcl/inc/svids.hrc
#define SV_ICON_SMALL_START                 25000

#define SV_ICON_ID_OFFICE                       1
#define SV_ICON_ID_TEXT                         2
#define SV_ICON_ID_SPREADSHEET                  4
#define SV_ICON_ID_DRAWING                      6
#define SV_ICON_ID_PRESENTATION                 8
#define SV_ICON_ID_DATABASE                    14
#define SV_ICON_ID_FORMULA                     15
#define SV_ICON_ID_TEMPLATE                    16

using namespace ::rtl;
using namespace ::osl;

static ResMgr *pVCLResMgr;
static GtkStatusIcon* pTrayIcon;
static GtkWidget *pExitMenuItem = NULL;
static GtkWidget *pOpenMenuItem = NULL;
static GtkWidget *pDisableMenuItem = NULL;
#ifdef ENABLE_GIO
GFileMonitor* pMonitor = NULL;
#endif

static void open_url_cb( GtkWidget *, gpointer data )
{
    ShutdownIcon::OpenURL( *(OUString *)data,
                           OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
}

static void open_file_cb( GtkWidget * )
{
    if ( !ShutdownIcon::bModalMode )
        ShutdownIcon::FileOpen();
}

static void open_template_cb( GtkWidget * )
{
    if ( !ShutdownIcon::bModalMode )
        ShutdownIcon::FromTemplate();
}

static void systray_disable_cb()
{
    ShutdownIcon::SetAutostart( false );
    ShutdownIcon::terminateDesktop();
}

static void exit_quickstarter_cb( GtkWidget * )
{
    if (pTrayIcon)
    {
        plugin_shutdown_sys_tray();
        //terminate may cause this .so to be unloaded. So we must be hands off
        //all calls into this .so after this call
        ShutdownIcon::terminateDesktop();
    }
}

static void menu_deactivate_cb( GtkWidget *pMenu )
{
    gtk_menu_popdown( GTK_MENU( pMenu ) );
}

static GdkPixbuf * ResIdToPixbuf( USHORT nResId )
{
    ResId aResId( SV_ICON_SMALL_START + nResId, *pVCLResMgr );
    BitmapEx aIcon( aResId );
    Bitmap pInSalBitmap = aIcon.GetBitmap();
    AlphaMask pInSalAlpha = aIcon.GetAlpha();

    BitmapReadAccess* pSalBitmap = pInSalBitmap.AcquireReadAccess();
    BitmapReadAccess* pSalAlpha = pInSalAlpha.AcquireReadAccess();

    g_return_val_if_fail( pSalBitmap != NULL, NULL );

    Size aSize( pSalBitmap->Width(), pSalBitmap->Height() );
    if (pSalAlpha)
        g_return_val_if_fail( Size( pSalAlpha->Width(), pSalAlpha->Height() ) == aSize, NULL );

    int nX, nY;
    guchar *pPixbufData = ( guchar * )g_malloc( 4 * aSize.Width() * aSize.Height() );
    guchar *pDestData = pPixbufData;

    for( nY = 0; nY < pSalBitmap->Height(); nY++ )
    {
        for( nX = 0; nX < pSalBitmap->Width(); nX++ )
        {
            BitmapColor aPix;
            aPix = pSalBitmap->GetPixel( nY, nX );
            pDestData[0] = aPix.GetRed();
            pDestData[1] = aPix.GetGreen();
            pDestData[2] = aPix.GetBlue();
            if (pSalAlpha)
            {
                aPix = pSalAlpha->GetPixel( nY, nX );
                pDestData[3] = 255 - aPix.GetIndex();
            }
            else
                pDestData[3] = 255;
            pDestData += 4;
        }
    }

    pInSalBitmap.ReleaseAccess( pSalBitmap );
    if( pSalAlpha )
        pInSalAlpha.ReleaseAccess( pSalAlpha );

    return gdk_pixbuf_new_from_data( pPixbufData,
        GDK_COLORSPACE_RGB, TRUE, 8,
        aSize.Width(), aSize.Height(),
        aSize.Width() * 4,
        (GdkPixbufDestroyNotify) g_free,
        NULL );
}

extern "C" {
static void oustring_delete (gpointer  data,
                             GClosure * /* closure */)
{
    OUString *pURL = (OUString *) data;
    delete pURL;
}
}

static void add_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
                      OUString *pOverrideLabel,
                      USHORT nResId, GCallback pFnCallback )
{
    OUString *pURL = new OUString (OStringToOUString( pAsciiURL,
                                                      RTL_TEXTENCODING_UTF8 ));
    OString aLabel;
    if (pOverrideLabel)
        aLabel = OUStringToOString (*pOverrideLabel, RTL_TEXTENCODING_UTF8);
    else
    {
        ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
        aLabel = OUStringToOString (pShutdownIcon->GetUrlDescription( *pURL ),
                                    RTL_TEXTENCODING_UTF8);
    }

    GdkPixbuf *pPixbuf= ResIdToPixbuf( nResId );
    GtkWidget *pImage = gtk_image_new_from_pixbuf( pPixbuf );
    g_object_unref( G_OBJECT( pPixbuf ) );

    GtkWidget *pMenuItem = gtk_image_menu_item_new_with_label( aLabel );
    gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );
    g_signal_connect_data( pMenuItem, "activate", pFnCallback, pURL,
                           oustring_delete, GConnectFlags(0));

    gtk_menu_shell_append( pMenuShell, pMenuItem );
}

// Unbelievably nasty
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;

static void add_ugly_db_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
                              USHORT nResId, GCallback pFnCallback )
{
    SvtDynamicMenuOptions aOpt;
    Sequence < Sequence < PropertyValue > > aMenu = aOpt.GetMenu( E_NEWMENU );
    for ( sal_Int32 n=0; n<aMenu.getLength(); n++ )
    {
        ::rtl::OUString aURL;
        ::rtl::OUString aDescription;
        Sequence < PropertyValue >& aEntry = aMenu[n];
        for ( sal_Int32 m=0; m<aEntry.getLength(); m++ )
        {
            if ( aEntry[m].Name.equalsAsciiL( "URL", 3 ) )
                aEntry[m].Value >>= aURL;
            if ( aEntry[m].Name.equalsAsciiL( "Title", 5 ) )
                aEntry[m].Value >>= aDescription;
        }

        if ( aURL.equalsAscii( BASE_URL ) && aDescription.getLength() )
        {
            add_item (pMenuShell, pAsciiURL, &aDescription, nResId, pFnCallback);
            break;
        }
    }
}

static GtkWidget *
add_image_menu_item( GtkMenuShell *pMenuShell,
                     const gchar *stock_id,
                     rtl::OUString aLabel,
                     GCallback     activate_cb )
{
    OString aUtfLabel = rtl::OUStringToOString (aLabel, RTL_TEXTENCODING_UTF8 );

    GtkWidget *pImage;
    pImage = gtk_image_new_from_stock( stock_id, GTK_ICON_SIZE_MENU );

    GtkWidget *pMenuItem;
    pMenuItem = gtk_image_menu_item_new_with_label( aUtfLabel );
    gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );

    gtk_menu_shell_append( pMenuShell, pMenuItem );
    g_signal_connect( pMenuItem, "activate", activate_cb, NULL);

    return pMenuItem;
}

static void populate_menu( GtkWidget *pMenu )
{
    ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
    GtkMenuShell *pMenuShell = GTK_MENU_SHELL( pMenu );
    SvtModuleOptions aModuleOptions;

    if ( aModuleOptions.IsWriter() )
        add_item (pMenuShell, WRITER_URL, NULL,
                  SV_ICON_ID_TEXT, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsCalc() )
        add_item (pMenuShell, CALC_URL, NULL,
                  SV_ICON_ID_SPREADSHEET, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsImpress() )
        add_item (pMenuShell, IMPRESS_URL, NULL,
                  SV_ICON_ID_PRESENTATION, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsDraw() )
        add_item (pMenuShell, DRAW_URL, NULL,
                  SV_ICON_ID_DRAWING, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsDataBase() )
        add_ugly_db_item (pMenuShell, BASE_URL,
                          SV_ICON_ID_DATABASE, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsMath() )
        add_item (pMenuShell, MATH_URL, NULL,
                  SV_ICON_ID_FORMULA, G_CALLBACK( open_url_cb ));

    OUString aULabel = pShutdownIcon->GetResString( STR_QUICKSTART_FROMTEMPLATE );
    add_item (pMenuShell, "dummy", &aULabel,
              SV_ICON_ID_TEMPLATE, G_CALLBACK( open_template_cb ));

    OString aLabel;
    GtkWidget *pMenuItem;

    pMenuItem = gtk_separator_menu_item_new();
    gtk_menu_shell_append( pMenuShell, pMenuItem );

    pOpenMenuItem = add_image_menu_item
        (pMenuShell, GTK_STOCK_OPEN,
         pShutdownIcon->GetResString( STR_QUICKSTART_FILEOPEN ),
         G_CALLBACK( open_file_cb ));

    pMenuItem = gtk_separator_menu_item_new();
    gtk_menu_shell_append( pMenuShell, pMenuItem );

    pDisableMenuItem = add_image_menu_item
        ( pMenuShell, GTK_STOCK_CLOSE,
          pShutdownIcon->GetResString( STR_QUICKSTART_PRELAUNCH_UNX ),
          G_CALLBACK( systray_disable_cb ) );

    pMenuItem = gtk_separator_menu_item_new();
    gtk_menu_shell_append( pMenuShell, pMenuItem );

    pExitMenuItem = add_image_menu_item
        ( pMenuShell, GTK_STOCK_QUIT,
          pShutdownIcon->GetResString( STR_QUICKSTART_EXIT ),
          G_CALLBACK( exit_quickstarter_cb ) );

    gtk_widget_show_all( pMenu );
}

static void refresh_menu( GtkWidget *pMenu )
{
    if (!pExitMenuItem)
        populate_menu( pMenu );

    bool bModal = ShutdownIcon::bModalMode;
    gtk_widget_set_sensitive( pExitMenuItem, !bModal);
    gtk_widget_set_sensitive( pOpenMenuItem, !bModal);
    gtk_widget_set_sensitive( pDisableMenuItem, !bModal);
}

static gboolean display_menu_cb( GtkWidget *,
                                 GdkEventButton *event, GtkWidget *pMenu )
{
    if (event->button == 2)
        return FALSE;

#ifdef TEMPLATE_DIALOG_MORE_POLISHED
    if (event->button == 1 &&
        event->type == GDK_2BUTTON_PRESS)
    {
        open_template_cb( NULL );
        return TRUE;
    }
    if (event->button == 3)
    {
        ... as below ...
#endif

    refresh_menu( pMenu );

    gtk_menu_popup( GTK_MENU( pMenu ), NULL, NULL,
                    gtk_status_icon_position_menu, pTrayIcon,
                    0, event->time );

    return TRUE;
}

#ifdef ENABLE_GIO
/*
 * See rhbz#610103. If the quickstarter is running, then LibreOffice is
 * upgraded, then the old quickstarter is still running, but is now unreliable
 * as the old install has been deleted. A fairly intractable problem but we
 * can avoid much of the pain if we turn off the quickstarter if we detect
 * that it has been physically deleted.
*/
static void notify_file_changed(GFileMonitor * /*gfilemonitor*/, GFile * /*arg1*/,
    GFile * /*arg2*/, GFileMonitorEvent event_type, gpointer /*user_data*/)
{
    if (event_type == G_FILE_MONITOR_EVENT_DELETED)
        exit_quickstarter_cb(NULL);
}
#endif

void SAL_DLLPUBLIC_EXPORT plugin_init_sys_tray()
{
    ::SolarMutexGuard aGuard;

    if( !g_type_from_name( "GdkDisplay" ) )
        return;

    OString aLabel;
    ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();

    aLabel = rtl::OUStringToOString (
            pShutdownIcon->GetResString( STR_QUICKSTART_TIP ),
            RTL_TEXTENCODING_UTF8 );

    pVCLResMgr = CREATEVERSIONRESMGR( vcl );

    GdkPixbuf *pPixbuf = ResIdToPixbuf( SV_ICON_ID_OFFICE );
    pTrayIcon = gtk_status_icon_new_from_pixbuf(pPixbuf);
    g_object_unref( pPixbuf );

    gtk_status_icon_set_title(pTrayIcon, aLabel);
    gtk_status_icon_set_tooltip_text(pTrayIcon, aLabel);

    GtkWidget *pMenu = gtk_menu_new();
    g_signal_connect (pMenu, "deactivate",
                      G_CALLBACK (menu_deactivate_cb), NULL);
    g_signal_connect(pTrayIcon,  "button_press_event",
                     G_CALLBACK(display_menu_cb), pMenu);

    // disable shutdown
    pShutdownIcon->SetVeto( true );
    pShutdownIcon->addTerminateListener();

#ifdef ENABLE_GIO
    GFile* pFile = NULL;
    rtl::OUString sLibraryFileUrl;
    if (osl::Module::getUrlFromAddress(plugin_init_sys_tray, sLibraryFileUrl))
        pFile = g_file_new_for_uri(rtl::OUStringToOString(sLibraryFileUrl, RTL_TEXTENCODING_UTF8).getStr());

    if (pFile)
    {
        if ((pMonitor = g_file_monitor_file(pFile, G_FILE_MONITOR_NONE, NULL, NULL)))
            g_signal_connect(pMonitor, "changed", (GCallback)notify_file_changed, NULL);
        g_object_unref(pFile);
    }
#endif
}

void SAL_DLLPUBLIC_EXPORT plugin_shutdown_sys_tray()
{
    ::SolarMutexGuard aGuard;
    if( !pTrayIcon )
        return;

#ifdef ENABLE_GIO
    if (pMonitor)
    {
        g_signal_handlers_disconnect_by_func(pMonitor,
            (void*)notify_file_changed, pMonitor);
        g_file_monitor_cancel(pMonitor);
        g_object_unref(pMonitor);
        pMonitor = NULL;
    }
#endif

    g_object_unref(pTrayIcon);
    pTrayIcon = NULL;

    pExitMenuItem = NULL;
    pOpenMenuItem = NULL;
    pDisableMenuItem = NULL;
}

#endif // ENABLE_QUICKSTART_APPLET

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>audit API usage for 2.10 & fix.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

#ifdef ENABLE_QUICKSTART_APPLET

#include <unotools/moduleoptions.hxx>

#include <unotools/dynamicmenuoptions.hxx>

#include <gtk/gtk.h>
#include <glib.h>
#include <osl/mutex.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/bmpacc.hxx>
#include <sfx2/app.hxx>
#include "app.hrc"
#ifndef __SHUTDOWNICON_HXX__
#define USE_APP_SHORTCUTS
#include "shutdownicon.hxx"
#endif

#ifdef ENABLE_GIO
#include <gio/gio.h>
#endif

// Cut/paste from vcl/inc/svids.hrc
#define SV_ICON_SMALL_START                 25000

#define SV_ICON_ID_OFFICE                       1
#define SV_ICON_ID_TEXT                         2
#define SV_ICON_ID_SPREADSHEET                  4
#define SV_ICON_ID_DRAWING                      6
#define SV_ICON_ID_PRESENTATION                 8
#define SV_ICON_ID_DATABASE                    14
#define SV_ICON_ID_FORMULA                     15
#define SV_ICON_ID_TEMPLATE                    16

using namespace ::rtl;
using namespace ::osl;

static ResMgr *pVCLResMgr;
static GtkStatusIcon* pTrayIcon;
static GtkWidget *pExitMenuItem = NULL;
static GtkWidget *pOpenMenuItem = NULL;
static GtkWidget *pDisableMenuItem = NULL;
#ifdef ENABLE_GIO
GFileMonitor* pMonitor = NULL;
#endif

static void open_url_cb( GtkWidget *, gpointer data )
{
    ShutdownIcon::OpenURL( *(OUString *)data,
                           OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ) );
}

static void open_file_cb( GtkWidget * )
{
    if ( !ShutdownIcon::bModalMode )
        ShutdownIcon::FileOpen();
}

static void open_template_cb( GtkWidget * )
{
    if ( !ShutdownIcon::bModalMode )
        ShutdownIcon::FromTemplate();
}

static void systray_disable_cb()
{
    ShutdownIcon::SetAutostart( false );
    ShutdownIcon::terminateDesktop();
}

static void exit_quickstarter_cb( GtkWidget * )
{
    if (pTrayIcon)
    {
        plugin_shutdown_sys_tray();
        //terminate may cause this .so to be unloaded. So we must be hands off
        //all calls into this .so after this call
        ShutdownIcon::terminateDesktop();
    }
}

static void menu_deactivate_cb( GtkWidget *pMenu )
{
    gtk_menu_popdown( GTK_MENU( pMenu ) );
}

static GdkPixbuf * ResIdToPixbuf( USHORT nResId )
{
    ResId aResId( SV_ICON_SMALL_START + nResId, *pVCLResMgr );
    BitmapEx aIcon( aResId );
    Bitmap pInSalBitmap = aIcon.GetBitmap();
    AlphaMask pInSalAlpha = aIcon.GetAlpha();

    BitmapReadAccess* pSalBitmap = pInSalBitmap.AcquireReadAccess();
    BitmapReadAccess* pSalAlpha = pInSalAlpha.AcquireReadAccess();

    g_return_val_if_fail( pSalBitmap != NULL, NULL );

    Size aSize( pSalBitmap->Width(), pSalBitmap->Height() );
    if (pSalAlpha)
        g_return_val_if_fail( Size( pSalAlpha->Width(), pSalAlpha->Height() ) == aSize, NULL );

    int nX, nY;
    guchar *pPixbufData = ( guchar * )g_malloc( 4 * aSize.Width() * aSize.Height() );
    guchar *pDestData = pPixbufData;

    for( nY = 0; nY < pSalBitmap->Height(); nY++ )
    {
        for( nX = 0; nX < pSalBitmap->Width(); nX++ )
        {
            BitmapColor aPix;
            aPix = pSalBitmap->GetPixel( nY, nX );
            pDestData[0] = aPix.GetRed();
            pDestData[1] = aPix.GetGreen();
            pDestData[2] = aPix.GetBlue();
            if (pSalAlpha)
            {
                aPix = pSalAlpha->GetPixel( nY, nX );
                pDestData[3] = 255 - aPix.GetIndex();
            }
            else
                pDestData[3] = 255;
            pDestData += 4;
        }
    }

    pInSalBitmap.ReleaseAccess( pSalBitmap );
    if( pSalAlpha )
        pInSalAlpha.ReleaseAccess( pSalAlpha );

    return gdk_pixbuf_new_from_data( pPixbufData,
        GDK_COLORSPACE_RGB, TRUE, 8,
        aSize.Width(), aSize.Height(),
        aSize.Width() * 4,
        (GdkPixbufDestroyNotify) g_free,
        NULL );
}

extern "C" {
static void oustring_delete (gpointer  data,
                             GClosure * /* closure */)
{
    OUString *pURL = (OUString *) data;
    delete pURL;
}
}

static void add_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
                      OUString *pOverrideLabel,
                      USHORT nResId, GCallback pFnCallback )
{
    OUString *pURL = new OUString (OStringToOUString( pAsciiURL,
                                                      RTL_TEXTENCODING_UTF8 ));
    OString aLabel;
    if (pOverrideLabel)
        aLabel = OUStringToOString (*pOverrideLabel, RTL_TEXTENCODING_UTF8);
    else
    {
        ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
        aLabel = OUStringToOString (pShutdownIcon->GetUrlDescription( *pURL ),
                                    RTL_TEXTENCODING_UTF8);
    }

    GdkPixbuf *pPixbuf= ResIdToPixbuf( nResId );
    GtkWidget *pImage = gtk_image_new_from_pixbuf( pPixbuf );
    g_object_unref( G_OBJECT( pPixbuf ) );

    GtkWidget *pMenuItem = gtk_image_menu_item_new_with_label( aLabel );
    gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );
    g_signal_connect_data( pMenuItem, "activate", pFnCallback, pURL,
                           oustring_delete, GConnectFlags(0));

    gtk_menu_shell_append( pMenuShell, pMenuItem );
}

// Unbelievably nasty
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::task;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::beans;

static void add_ugly_db_item( GtkMenuShell *pMenuShell, const char *pAsciiURL,
                              USHORT nResId, GCallback pFnCallback )
{
    SvtDynamicMenuOptions aOpt;
    Sequence < Sequence < PropertyValue > > aMenu = aOpt.GetMenu( E_NEWMENU );
    for ( sal_Int32 n=0; n<aMenu.getLength(); n++ )
    {
        ::rtl::OUString aURL;
        ::rtl::OUString aDescription;
        Sequence < PropertyValue >& aEntry = aMenu[n];
        for ( sal_Int32 m=0; m<aEntry.getLength(); m++ )
        {
            if ( aEntry[m].Name.equalsAsciiL( "URL", 3 ) )
                aEntry[m].Value >>= aURL;
            if ( aEntry[m].Name.equalsAsciiL( "Title", 5 ) )
                aEntry[m].Value >>= aDescription;
        }

        if ( aURL.equalsAscii( BASE_URL ) && aDescription.getLength() )
        {
            add_item (pMenuShell, pAsciiURL, &aDescription, nResId, pFnCallback);
            break;
        }
    }
}

static GtkWidget *
add_image_menu_item( GtkMenuShell *pMenuShell,
                     const gchar *stock_id,
                     rtl::OUString aLabel,
                     GCallback     activate_cb )
{
    OString aUtfLabel = rtl::OUStringToOString (aLabel, RTL_TEXTENCODING_UTF8 );

    GtkWidget *pImage;
    pImage = gtk_image_new_from_stock( stock_id, GTK_ICON_SIZE_MENU );

    GtkWidget *pMenuItem;
    pMenuItem = gtk_image_menu_item_new_with_label( aUtfLabel );
    gtk_image_menu_item_set_image( GTK_IMAGE_MENU_ITEM( pMenuItem ), pImage );

    gtk_menu_shell_append( pMenuShell, pMenuItem );
    g_signal_connect( pMenuItem, "activate", activate_cb, NULL);

    return pMenuItem;
}

static void populate_menu( GtkWidget *pMenu )
{
    ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();
    GtkMenuShell *pMenuShell = GTK_MENU_SHELL( pMenu );
    SvtModuleOptions aModuleOptions;

    if ( aModuleOptions.IsWriter() )
        add_item (pMenuShell, WRITER_URL, NULL,
                  SV_ICON_ID_TEXT, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsCalc() )
        add_item (pMenuShell, CALC_URL, NULL,
                  SV_ICON_ID_SPREADSHEET, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsImpress() )
        add_item (pMenuShell, IMPRESS_URL, NULL,
                  SV_ICON_ID_PRESENTATION, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsDraw() )
        add_item (pMenuShell, DRAW_URL, NULL,
                  SV_ICON_ID_DRAWING, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsDataBase() )
        add_ugly_db_item (pMenuShell, BASE_URL,
                          SV_ICON_ID_DATABASE, G_CALLBACK( open_url_cb ));

    if ( aModuleOptions.IsMath() )
        add_item (pMenuShell, MATH_URL, NULL,
                  SV_ICON_ID_FORMULA, G_CALLBACK( open_url_cb ));

    OUString aULabel = pShutdownIcon->GetResString( STR_QUICKSTART_FROMTEMPLATE );
    add_item (pMenuShell, "dummy", &aULabel,
              SV_ICON_ID_TEMPLATE, G_CALLBACK( open_template_cb ));

    OString aLabel;
    GtkWidget *pMenuItem;

    pMenuItem = gtk_separator_menu_item_new();
    gtk_menu_shell_append( pMenuShell, pMenuItem );

    pOpenMenuItem = add_image_menu_item
        (pMenuShell, GTK_STOCK_OPEN,
         pShutdownIcon->GetResString( STR_QUICKSTART_FILEOPEN ),
         G_CALLBACK( open_file_cb ));

    pMenuItem = gtk_separator_menu_item_new();
    gtk_menu_shell_append( pMenuShell, pMenuItem );

    pDisableMenuItem = add_image_menu_item
        ( pMenuShell, GTK_STOCK_CLOSE,
          pShutdownIcon->GetResString( STR_QUICKSTART_PRELAUNCH_UNX ),
          G_CALLBACK( systray_disable_cb ) );

    pMenuItem = gtk_separator_menu_item_new();
    gtk_menu_shell_append( pMenuShell, pMenuItem );

    pExitMenuItem = add_image_menu_item
        ( pMenuShell, GTK_STOCK_QUIT,
          pShutdownIcon->GetResString( STR_QUICKSTART_EXIT ),
          G_CALLBACK( exit_quickstarter_cb ) );

    gtk_widget_show_all( pMenu );
}

static void refresh_menu( GtkWidget *pMenu )
{
    if (!pExitMenuItem)
        populate_menu( pMenu );

    bool bModal = ShutdownIcon::bModalMode;
    gtk_widget_set_sensitive( pExitMenuItem, !bModal);
    gtk_widget_set_sensitive( pOpenMenuItem, !bModal);
    gtk_widget_set_sensitive( pDisableMenuItem, !bModal);
}

static gboolean display_menu_cb( GtkWidget *,
                                 GdkEventButton *event, GtkWidget *pMenu )
{
    if (event->button == 2)
        return FALSE;

#ifdef TEMPLATE_DIALOG_MORE_POLISHED
    if (event->button == 1 &&
        event->type == GDK_2BUTTON_PRESS)
    {
        open_template_cb( NULL );
        return TRUE;
    }
    if (event->button == 3)
    {
        ... as below ...
#endif

    refresh_menu( pMenu );

    gtk_menu_popup( GTK_MENU( pMenu ), NULL, NULL,
                    gtk_status_icon_position_menu, pTrayIcon,
                    0, event->time );

    return TRUE;
}

#ifdef ENABLE_GIO
/*
 * See rhbz#610103. If the quickstarter is running, then LibreOffice is
 * upgraded, then the old quickstarter is still running, but is now unreliable
 * as the old install has been deleted. A fairly intractable problem but we
 * can avoid much of the pain if we turn off the quickstarter if we detect
 * that it has been physically deleted.
*/
static void notify_file_changed(GFileMonitor * /*gfilemonitor*/, GFile * /*arg1*/,
    GFile * /*arg2*/, GFileMonitorEvent event_type, gpointer /*user_data*/)
{
    if (event_type == G_FILE_MONITOR_EVENT_DELETED)
        exit_quickstarter_cb(NULL);
}
#endif

void SAL_DLLPUBLIC_EXPORT plugin_init_sys_tray()
{
    ::SolarMutexGuard aGuard;

    if( !g_type_from_name( "GdkDisplay" ) )
        return;

    OString aLabel;
    ShutdownIcon *pShutdownIcon = ShutdownIcon::getInstance();

    aLabel = rtl::OUStringToOString (
            pShutdownIcon->GetResString( STR_QUICKSTART_TIP ),
            RTL_TEXTENCODING_UTF8 );

    pVCLResMgr = CREATEVERSIONRESMGR( vcl );

    GdkPixbuf *pPixbuf = ResIdToPixbuf( SV_ICON_ID_OFFICE );
    pTrayIcon = gtk_status_icon_new_from_pixbuf(pPixbuf);
    g_object_unref( pPixbuf );

    g_object_set (pTrayIcon, "title", aLabel.getStr(),
                  "tooltip_text", aLabel.getStr(), NULL);

    GtkWidget *pMenu = gtk_menu_new();
    g_signal_connect (pMenu, "deactivate",
                      G_CALLBACK (menu_deactivate_cb), NULL);
    g_signal_connect(pTrayIcon,  "button_press_event",
                     G_CALLBACK(display_menu_cb), pMenu);

    // disable shutdown
    pShutdownIcon->SetVeto( true );
    pShutdownIcon->addTerminateListener();

#ifdef ENABLE_GIO
    GFile* pFile = NULL;
    rtl::OUString sLibraryFileUrl;
    if (osl::Module::getUrlFromAddress(plugin_init_sys_tray, sLibraryFileUrl))
        pFile = g_file_new_for_uri(rtl::OUStringToOString(sLibraryFileUrl, RTL_TEXTENCODING_UTF8).getStr());

    if (pFile)
    {
        if ((pMonitor = g_file_monitor_file(pFile, G_FILE_MONITOR_NONE, NULL, NULL)))
            g_signal_connect(pMonitor, "changed", (GCallback)notify_file_changed, NULL);
        g_object_unref(pFile);
    }
#endif
}

void SAL_DLLPUBLIC_EXPORT plugin_shutdown_sys_tray()
{
    ::SolarMutexGuard aGuard;
    if( !pTrayIcon )
        return;

#ifdef ENABLE_GIO
    if (pMonitor)
    {
        g_signal_handlers_disconnect_by_func(pMonitor,
            (void*)notify_file_changed, pMonitor);
        g_file_monitor_cancel(pMonitor);
        g_object_unref(pMonitor);
        pMonitor = NULL;
    }
#endif

    g_object_unref(pTrayIcon);
    pTrayIcon = NULL;

    pExitMenuItem = NULL;
    pOpenMenuItem = NULL;
    pDisableMenuItem = NULL;
}

#endif // ENABLE_QUICKSTART_APPLET

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#ifndef __SIMFQT_CMD_INDEXBUILDER_HPP
#define __SIMFQT_CMD_INDEXBUILDER_HPP

// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// Simfqt
#include <simfqt/SIMFQT_Types.hpp>

namespace SIMFQT {

  /** Command wrapping the pricing request process. */
  class FareQuoter {
    friend class SIMFQT_Service;
  private:

    /** Quote (with a price) a travel request. */
    static Price_T priceQuote (const FareQuoteID_T&,
                               const AirlineCode_T&, const PartySize_T&);

  private:
    /** Constructors. */
    FareQuoter() {}
    FareQuoter(const FareQuoter&) {}
    /** Destructor. */
    ~FareQuoter() {}
  };

}
#endif // __SIMFQT_CMD_INDEXBUILDER_HPP
<commit_msg>[Dev] Fixed typo in the header protection definition.<commit_after>#ifndef __SIMFQT_CMD_FAREQUOTER_HPP
#define __SIMFQT_CMD_FAREQUOTER_HPP

// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// Simfqt
#include <simfqt/SIMFQT_Types.hpp>

namespace SIMFQT {

  /** Command wrapping the pricing request process. */
  class FareQuoter {
    friend class SIMFQT_Service;
  private:

    /** Quote (with a price) a travel request. */
    static Price_T priceQuote (const FareQuoteID_T&,
                               const AirlineCode_T&, const PartySize_T&);

  private:
    /** Constructors. */
    FareQuoter() {}
    FareQuoter(const FareQuoter&) {}
    /** Destructor. */
    ~FareQuoter() {}
  };

}
#endif // __SIMFQT_CMD_FAREQUOTER_HPP
<|endoftext|>