<commit_before>/*
    ------------------------------------------------------------------

    This file is part of the Open Ephys GUI
    Copyright (C) 2013 Open Ephys

    ------------------------------------------------------------------

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <stdio.h>
#include "EvntTrigAvg.h"
#include "EvntTrigAvgCanvas.h"
#include "HistogramLib/HistogramLib.h"
class EvntTrigAvg;

EvntTrigAvg::EvntTrigAvg()
    : GenericProcessor("Evnt Trig Avg")

{
    setProcessorType (PROCESSOR_TYPE_FILTER);
    windowSize = getDefaultSampleRate(); // 1 sec in samples
    binSize = getDefaultSampleRate()/100; // 10 milliseconds in samples
}

EvntTrigAvg::~EvntTrigAvg()
{

}

void EvntTrigAvg::setParameter(int parameterIndex, float newValue){
    bool changed = false;
    if (parameterIndex == 0 && triggerEvent != static_cast<int>(newValue)){
        triggerEvent = static_cast<int>(newValue);
        changed = true;
    }
    else if (parameterIndex == 1 && triggerChannel != static_cast<int>(newValue)){
        triggerChannel = static_cast<int>(newValue);
        changed = true;
    }
    else if(parameterIndex == 2 && binSize != newValue*(getSampleRate()/1000)){
        binSize = newValue*(getSampleRate()/1000);
        changed = true;
    }
    else if(parameterIndex == 3 && windowSize != newValue*(getSampleRate()/1000)){
        windowSize = newValue*(getSampleRate()/1000);
        changed = true;
    }
    else if (parameterIndex == 4)
        changed = true;
    // If anything was changed, delete all data and start over
    if (changed){
        minMaxMean.clear();
        spikeData.clear();
        ttlTimestampBuffer.clear();
        histogramData.clear();
        lastTTLCalculated=0;
        updateSettings();
        //recalc=true;
    }
}

void EvntTrigAvg::updateSettings(){
    electrodeMap.clear();
    electrodeMap = createElectrodeMap();
    electrodeLabels.clear();
    electrodeLabels = createElectrodeLabels();
    if(spikeData.size()!=getTotalSpikeChannels()){
        spikeData.resize(getTotalSpikeChannels());
        minMaxMean.resize(getTotalSpikeChannels());
    }
    for(int electrodeIt = 0 ; electrodeIt < spikeData.size() ; electrodeIt++){
        if(spikeData[electrodeIt].size()<1){
            spikeData[electrodeIt].resize(1);
            minMaxMean[electrodeIt].resize(1);
        }
        for(int sortedIdIt = 0 ; sortedIdIt < spikeData[electrodeIt].size() ; sortedIdIt++){
            spikeData[electrodeIt][sortedIdIt].reserve(spikeData[electrodeIt][sortedIdIt].size()+200);
            minMaxMean[electrodeIt][sortedIdIt]={0,0,0};
        }
    }
}

bool EvntTrigAvg::enable(){
    return true;
}

bool EvntTrigAvg::disable(){
    return true;
}

void EvntTrigAvg::process(AudioSampleBuffer& buffer){
    checkForEvents(true);
    if(buffer.getNumChannels() != numChannels)
        numChannels = buffer.getNumChannels();
    if(ttlTimestampBuffer.size() > lastTTLCalculated && buffer.getNumSamples() + getTimestamp(0) >= ttlTimestampBuffer[lastTTLCalculated+1] + windowSize/2){
        recalc = true;
    }
    if(recalc){
        histogramData=processSpikeData(spikeData, ttlTimestampBuffer);
        lastTTLCalculated+=1;
        recalc=false;
        readHistoData=true;
    }
}

void EvntTrigAvg::handleEvent(const EventChannel* eventInfo, const MidiMessage& event, int sampleNum){
    if (triggerEvent < 0) return;
    else if (eventInfo->getChannelType() == EventChannel::TTL && eventInfo == eventChannelArray[triggerEvent])
    {
        TTLEventPtr ttl = TTLEvent::deserializeFromMessage(event, eventInfo);
        if (ttl->getChannel() == triggerChannel)
            ttlTimestampBuffer.push_back(Event::getTimestamp(event));
    }
}

void EvntTrigAvg::handleSpike(const SpikeChannel* spikeInfo, const MidiMessage& event, int samplePosition){
    SpikeEventPtr newSpike = SpikeEvent::deserializeFromMessage(event, spikeInfo);
    if (!newSpike)
        return;
    else { // need to address resizing
        const SpikeChannel* chan = newSpike->getChannelInfo();
        Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
        int chanIDX = chanInfo[0].channelIDX;
        int sortedID = newSpike->getSortedID();
        int electrode = electrodeMap[chanIDX];
        if (sortedID+1>spikeData[electrode].size()){
            spikeData[electrode].resize(sortedID+1);
        }
        if (sortedID+1>minMaxMean[electrode].size()){
            minMaxMean[electrode].resize(sortedID+1);
            minMaxMean[electrode][sortedID]={0,0,0};
        }
        if(spikeData[electrode][sortedID].size() == spikeData[electrode][sortedID].capacity())
            spikeData[electrode][sortedID].reserve(spikeData[electrode][sortedID].size()+200);
        spikeData[electrode][sortedID].push_back(newSpike->getTimestamp());
        if (sortedID>0)
            spikeData[electrode][0].push_back(newSpike->getTimestamp());

    }
}

AudioProcessorEditor* EvntTrigAvg::createEditor(){
    editor = new EvntTrigAvgEditor (this, true);
    return editor;
}

void EvntTrigAvg::clearTTLTimestampBuffer(){
    ttlTimestampBuffer.clear();
}

float EvntTrigAvg::getSampleRate(){
    return juce::AudioProcessor::getSampleRate();
}

std::vector<uint64> EvntTrigAvg::getTTLTimestampBuffer(){
    return ttlTimestampBuffer;
}

int EvntTrigAvg::getLastTTLCalculated(){
    return lastTTLCalculated;
}

/** creates map to convert channelIDX to electrode number */
std::vector<int> EvntTrigAvg::createElectrodeMap(){
    std::vector<int> map;
    int numSpikeChannels = getTotalSpikeChannels();
    int electrodeCounter=0;
    for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
        const SpikeChannel* chan = getSpikeChannel(chanIt);
        // add to running count of each electrode
        map.resize(map.size()+chan->getNumChannels());
        Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
        for (int subChanIt = 0 ; subChanIt < chan->getNumChannels() ; subChanIt++){
            map[chanInfo[subChanIt].channelIDX] = electrodeCounter;
        }
        electrodeCounter+=1;
    }
    return map;
}

std::vector<String> EvntTrigAvg::createElectrodeLabels(){
    std::vector<String> map;
    int numSpikeChannels = getTotalSpikeChannels();
    map.resize(numSpikeChannels);
    String electrodeNames[3]{"Si ","St ","TT "};
    int electrodeCounter[3]{0};
    for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
        const SpikeChannel* chan = getSpikeChannel(chanIt);
        // add to running count of each electrode
        int chanType = chan->getChannelType();
        electrodeCounter[chanType]+=1;
        map[chanIt]=electrodeNames[chanType]+String(electrodeCounter[chanType]);
    }
    return map;
}

/** pass data into createHistogramData() by electrode and sorted ID */
// TODO modify so only new data is analyzed to save processing time/memory
std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::processSpikeData(std::vector<std::vector<std::vector<uint64>>> spikeData,std::vector<uint64> ttlData){
    //std::cout<<"processing spike data \n";
    std::vector<std::vector<std::vector<uint64>>> processedSpikeData;
    processedSpikeData.resize(spikeData.size());
    for (int channelIterator = 0 ; channelIterator < getTotalSpikeChannels() ; channelIterator++){
        processedSpikeData[channelIterator].resize(spikeData[channelIterator].size());
        for (int sortedIdIterator = 0 ; sortedIdIterator < spikeData[channelIterator].size() ; sortedIdIterator++){
            //if(spikeData[channelIterator][sortedIdIterator].size()>0){
                std::vector<uint64> toAdd = createHistogramData(spikeData[channelIterator][sortedIdIterator],ttlData);
                if(minMaxMean.size()<channelIterator+1)
                    minMaxMean.resize(channelIterator+1);
                if(minMaxMean[channelIterator].size()<sortedIdIterator+1)
                    minMaxMean[channelIterator].resize(channelIterator+1);
                if(minMaxMean[channelIterator][sortedIdIterator].size()<3)
                    minMaxMean[channelIterator][sortedIdIterator].resize(3);
                minMaxMean[channelIterator][sortedIdIterator][0]=findMin(toAdd);
                minMaxMean[channelIterator][sortedIdIterator][1]=findMax(toAdd);
                minMaxMean[channelIterator][sortedIdIterator][2]=findMean(toAdd);
                for (int i = 0 ; i < toAdd.size() ; i++){
                    if (i >= processedSpikeData.size()){
                        processedSpikeData.resize(i+1);
                    }
                    processedSpikeData[channelIterator][sortedIdIterator].push_back(toAdd[i]);
                }
            //}
        }
    }
    return processedSpikeData;
}

/** returns bin counts */
std::vector<uint64> EvntTrigAvg::createHistogramData(std::vector<uint64> spikeData, std::vector<uint64> ttlData){
    uint64 numberOfBins = windowSize/binSize;
    std::vector<uint64> histoData;
    histoData.reserve(numberOfBins);
    for(int ttlIterator = 0 ; ttlIterator < ttlData.size() ; ttlIterator++){
        for(int spikeIterator = 0 ; spikeIterator < spikeData.size() ; spikeIterator++){
            int relativeSpikeValue = int(spikeData[spikeIterator])-int(ttlData[ttlIterator]);
            if (relativeSpikeValue >= -int(windowSize)/2 && relativeSpikeValue <= int(windowSize)/2){
                uint64 bin = binDataPoint(0, numberOfBins, binSize, relativeSpikeValue+windowSize/2);
                histoData.push_back(bin);
            }
        }
    }
    return binCount(histoData,numberOfBins);
}

// Returns the bin a data point belongs to given the very first value covered by the bins, the very last value covered by then bins, bin size and the data point to bin, currently only works for positive numbers (can get around by adding minimum value to all values
uint64 EvntTrigAvg::binDataPoint(uint64 startBin, uint64 endBin, uint64 binSize, uint64 dataPoint){
    uint64 binsInRange = (endBin-startBin)+1;
    uint64 binsToSearch = binsInRange/2;
    if (binsToSearch <= 1){
        return startBin;
    }
    else if (dataPoint < (startBin+binsToSearch)*binSize){ // if in first half of search range
        return binDataPoint(startBin,startBin+(binsToSearch-1),binSize,dataPoint);
    }
    else if (dataPoint >= (startBin+binsToSearch) * binSize){ // if in second half of search range
        return binDataPoint(startBin+(binsToSearch-1),endBin,binSize,dataPoint);
    }
    else{
        return NULL;
    }
}

std::vector<uint64> EvntTrigAvg::binCount(std::vector<uint64> binData, uint64 numberOfBins){
    std::vector<uint64> bins(numberOfBins,0); // initialize with 0
    for (int dataIterator = 0 ; dataIterator < binData.size() ; dataIterator++){
        bins[binData[dataIterator]]+=1;
    }
    return bins;
}

uint64 EvntTrigAvg::getBinSize(){
    return binSize;
}

uint64 EvntTrigAvg::getWindowSize(){
    return windowSize;
}

std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::getHistoData(){
        readHistoData=false;
        return histogramData;
}

bool EvntTrigAvg::shouldReadHistoData(){
    return readHistoData;
}

//TODO change int_max and int_min to numbers
int EvntTrigAvg::findMin(std::vector<uint64> data){
    //int min = INT_MAX;
    int min = 2147483647;
    for (int i = 0 ; i < data.size() ; i++){
        if(data[i]<min){
            min=data[i];
        }
    }
    return min;
}

int EvntTrigAvg::findMax(std::vector<uint64> data){
    //int max = INT_MIN;
    int max =-2147483647;
    for (int i = 0 ; i < data.size() ; i++){
        int dataPoint = data[i];
        if(dataPoint>max){
            max=dataPoint;
        }
    }
    return max;
}

float EvntTrigAvg::findMean(std::vector<uint64> data){
    int runningSum=0;
    for(int i=0 ; i < data.size() ; i++){
        runningSum += data[i];
    }
    float mean = float(runningSum)/float(data.size());
    return mean;
}

std::vector<std::vector<std::vector<float>>> EvntTrigAvg::getMinMaxMean(){
    return minMaxMean;
}

std::vector<String> EvntTrigAvg::getElectrodeLabels(){
    return electrodeLabels;
}

<commit_msg>pre major change<commit_after>/*
    ------------------------------------------------------------------

    This file is part of the Open Ephys GUI
    Copyright (C) 2013 Open Ephys

    ------------------------------------------------------------------

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <stdio.h>
#include "EvntTrigAvg.h"
#include "EvntTrigAvgCanvas.h"
#include "HistogramLib/HistogramLib.h"
class EvntTrigAvg;

EvntTrigAvg::EvntTrigAvg()
    : GenericProcessor("Evnt Trig Avg")

{
    setProcessorType (PROCESSOR_TYPE_FILTER);
    windowSize = getDefaultSampleRate(); // 1 sec in samples
    binSize = getDefaultSampleRate()/100; // 10 milliseconds in samples
}

EvntTrigAvg::~EvntTrigAvg()
{

}

void EvntTrigAvg::setParameter(int parameterIndex, float newValue){
    bool changed = false;
    if (parameterIndex == 0 && triggerEvent != static_cast<int>(newValue)){
        triggerEvent = static_cast<int>(newValue);
        changed = true;
    }
    else if (parameterIndex == 1 && triggerChannel != static_cast<int>(newValue)){
        triggerChannel = static_cast<int>(newValue);
        changed = true;
    }
    else if(parameterIndex == 2 && binSize != newValue*(getSampleRate()/1000)){
        binSize = newValue*(getSampleRate()/1000);
        changed = true;
    }
    else if(parameterIndex == 3 && windowSize != newValue*(getSampleRate()/1000)){
        windowSize = newValue*(getSampleRate()/1000);
        changed = true;
    }
    else if (parameterIndex == 4)
        changed = true;
    // If anything was changed, delete all data and start over
    if (changed){
        minMaxMean.clear();
        spikeData.clear();
        ttlTimestampBuffer.clear();
        histogramData.clear();
        lastTTLCalculated=0;
        updateSettings();
        //recalc=true;
    }
}

void EvntTrigAvg::updateSettings(){
    electrodeMap.clear();
    electrodeMap = createElectrodeMap();
    electrodeLabels.clear();
    electrodeLabels = createElectrodeLabels();
    if(spikeData.size()!=getTotalSpikeChannels()){
        spikeData.resize(getTotalSpikeChannels());
        minMaxMean.resize(getTotalSpikeChannels());
    }
    for(int electrodeIt = 0 ; electrodeIt < spikeData.size() ; electrodeIt++){
        if(spikeData[electrodeIt].size()<1){
            spikeData[electrodeIt].resize(1);
            minMaxMean[electrodeIt].resize(1);
        }
        for(int sortedIdIt = 0 ; sortedIdIt < spikeData[electrodeIt].size() ; sortedIdIt++){
            spikeData[electrodeIt][sortedIdIt].reserve(spikeData[electrodeIt][sortedIdIt].size()+200);
            minMaxMean[electrodeIt][sortedIdIt]={0,0,0};
        }
    }
}

bool EvntTrigAvg::enable(){
    return true;
}

bool EvntTrigAvg::disable(){
    return true;
}

void EvntTrigAvg::process(AudioSampleBuffer& buffer){
    checkForEvents(true);
    if(buffer.getNumChannels() != numChannels)
        numChannels = buffer.getNumChannels();
    if(ttlTimestampBuffer.size() > lastTTLCalculated && buffer.getNumSamples() + getTimestamp(0) >= ttlTimestampBuffer[lastTTLCalculated+1] + windowSize/2){
        recalc = true;
    }
    if(recalc){
        histogramData=processSpikeData(spikeData, ttlTimestampBuffer);
        lastTTLCalculated+=1;
        recalc=false;
        readHistoData=true;
    }
}

void EvntTrigAvg::handleEvent(const EventChannel* eventInfo, const MidiMessage& event, int sampleNum){
    if (triggerEvent < 0) return;
    else if (eventInfo->getChannelType() == EventChannel::TTL && eventInfo == eventChannelArray[triggerEvent])
    {
        TTLEventPtr ttl = TTLEvent::deserializeFromMessage(event, eventInfo);
        if (ttl->getChannel() == triggerChannel)
            ttlTimestampBuffer.push_back(Event::getTimestamp(event));
    }
}

void EvntTrigAvg::handleSpike(const SpikeChannel* spikeInfo, const MidiMessage& event, int samplePosition){
    SpikeEventPtr newSpike = SpikeEvent::deserializeFromMessage(event, spikeInfo);
    if (!newSpike)
        return;
    else { // need to address resizing
        const SpikeChannel* chan = newSpike->getChannelInfo();
        Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
        int chanIDX = chanInfo[0].channelIDX;
        int sortedID = newSpike->getSortedID();
        int electrode = electrodeMap[chanIDX];
        if (sortedID+1>spikeData[electrode].size()){
            spikeData[electrode].resize(sortedID+1);
        }
        if (sortedID+1>minMaxMean[electrode].size()){
            minMaxMean[electrode].resize(sortedID+1);
            minMaxMean[electrode][sortedID]={0,0,0};
        }
        if(spikeData[electrode][sortedID].size() == spikeData[electrode][sortedID].capacity())
            spikeData[electrode][sortedID].reserve(spikeData[electrode][sortedID].size()+200);
        spikeData[electrode][sortedID].push_back(newSpike->getTimestamp());
        if (sortedID>0)
            spikeData[electrode][0].push_back(newSpike->getTimestamp());

    }
}

AudioProcessorEditor* EvntTrigAvg::createEditor(){
    editor = new EvntTrigAvgEditor (this, true);
    return editor;
}

void EvntTrigAvg::clearTTLTimestampBuffer(){
    ttlTimestampBuffer.clear();
}

float EvntTrigAvg::getSampleRate(){
    return juce::AudioProcessor::getSampleRate();
}

std::vector<uint64> EvntTrigAvg::getTTLTimestampBuffer(){
    return ttlTimestampBuffer;
}

int EvntTrigAvg::getLastTTLCalculated(){
    return lastTTLCalculated;
}

/** creates map to convert channelIDX to electrode number */
std::vector<int> EvntTrigAvg::createElectrodeMap(){
    std::vector<int> map;
    int numSpikeChannels = getTotalSpikeChannels();
    int electrodeCounter=0;
    for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
        const SpikeChannel* chan = getSpikeChannel(chanIt);
        // add to running count of each electrode
        map.resize(map.size()+chan->getNumChannels());
        Array<sourceChannelInfo> chanInfo = chan->getSourceChannelInfo();
        for (int subChanIt = 0 ; subChanIt < chan->getNumChannels() ; subChanIt++){
            map[chanInfo[subChanIt].channelIDX] = electrodeCounter;
        }
        electrodeCounter+=1;
    }
    return map;
}

std::vector<String> EvntTrigAvg::createElectrodeLabels(){
    std::vector<String> map;
    int numSpikeChannels = getTotalSpikeChannels();
    map.resize(numSpikeChannels);
    String electrodeNames[3]{"Si ","St ","TT "};
    int electrodeCounter[3]{0};
    for (int chanIt = 0 ; chanIt < numSpikeChannels ; chanIt++){
        const SpikeChannel* chan = getSpikeChannel(chanIt);
        // add to running count of each electrode
        int chanType = chan->getChannelType();
        electrodeCounter[chanType]+=1;
        map[chanIt]=electrodeNames[chanType]+String(electrodeCounter[chanType]);
    }
    return map;
}

/** pass data into createHistogramData() by electrode and sorted ID */
// TODO modify so only new data is analyzed to save processing time/memory
std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::processSpikeData(std::vector<std::vector<std::vector<uint64>>> spikeData,std::vector<uint64> ttlData){
    //std::cout<<"processing spike data \n";
    std::vector<std::vector<std::vector<uint64>>> processedSpikeData;
    processedSpikeData.resize(spikeData.size());
    for (int channelIterator = 0 ; channelIterator < getTotalSpikeChannels() ; channelIterator++){
        processedSpikeData[channelIterator].resize(spikeData[channelIterator].size());
        for (int sortedIdIterator = 0 ; sortedIdIterator < spikeData[channelIterator].size() ; sortedIdIterator++){
            //if(spikeData[channelIterator][sortedIdIterator].size()>0){
                std::vector<uint64> toAdd = createHistogramData(spikeData[channelIterator][sortedIdIterator],ttlData);
                if(minMaxMean.size()<channelIterator+1)
                    minMaxMean.resize(channelIterator+1);
                if(minMaxMean[channelIterator].size()<sortedIdIterator+1)
                    minMaxMean[channelIterator].resize(channelIterator+1);
                if(minMaxMean[channelIterator][sortedIdIterator].size()<3)
                    minMaxMean[channelIterator][sortedIdIterator].resize(3);
                minMaxMean[channelIterator][sortedIdIterator][0]=findMin(toAdd);
                minMaxMean[channelIterator][sortedIdIterator][1]=findMax(toAdd);
                minMaxMean[channelIterator][sortedIdIterator][2]=findMean(toAdd);
                for (int i = 0 ; i < toAdd.size() ; i++){
                    if (i >= processedSpikeData.size()){
                        processedSpikeData.resize(i+1);
                    }
                    processedSpikeData[channelIterator][sortedIdIterator].push_back(toAdd[i]);
                }
            //}
        }
    }
    return processedSpikeData;
}

/** returns bin counts */
std::vector<uint64> EvntTrigAvg::createHistogramData(std::vector<uint64> spikeData, std::vector<uint64> ttlData){
    uint64 numberOfBins = windowSize/binSize;
    std::vector<uint64> histoData;
    histoData.reserve(numberOfBins);
    for(int ttlIterator = 0 ; ttlIterator < ttlData.size() ; ttlIterator++){
        for(int spikeIterator = 0 ; spikeIterator < spikeData.size() ; spikeIterator++){
            int relativeSpikeValue = int(spikeData[spikeIterator])-int(ttlData[ttlIterator]);
            if (relativeSpikeValue >= -int(windowSize)/2 && relativeSpikeValue <= int(windowSize)/2){
                uint64 bin = binDataPoint(0, numberOfBins, binSize, relativeSpikeValue+windowSize/2);
                histoData.push_back(bin);
            }
        }
    }
    return binCount(histoData,numberOfBins);
}

// Returns the bin a data point belongs to given the very first value covered by the bins, the very last value covered by then bins, bin size and the data point to bin, currently only works for positive numbers (can get around by adding minimum value to all values
uint64 EvntTrigAvg::binDataPoint(uint64 startBin, uint64 endBin, uint64 binSize, uint64 dataPoint){
    uint64 binsInRange = (endBin-startBin)+1;
    uint64 binsToSearch = binsInRange/2;
    if (binsToSearch <= 1){
        return startBin;
    }
    else if (dataPoint < (startBin+binsToSearch)*binSize){ // if in first half of search range
        //return binDataPoint(startBin,startBin+(binsToSearch-1),binSize,dataPoint);
        return binDataPoint(startBin,startBin+(binsToSearch),binSize,dataPoint);
    }
    else if (dataPoint >= (startBin+binsToSearch) * binSize){ // if in second half of search range
        //return binDataPoint(startBin+(binsToSearch-1),endBin,binSize,dataPoint);
        return binDataPoint(startBin+(binsToSearch),endBin,binSize,dataPoint);
    }
    else{
        return NULL;
    }
}

std::vector<uint64> EvntTrigAvg::binCount(std::vector<uint64> binData, uint64 numberOfBins){
    std::vector<uint64> bins(numberOfBins,0); // initialize with 0
    for (int dataIterator = 0 ; dataIterator < binData.size() ; dataIterator++){
        bins[binData[dataIterator]]+=1;
    }
    return bins;
}

uint64 EvntTrigAvg::getBinSize(){
    return binSize;
}

uint64 EvntTrigAvg::getWindowSize(){
    return windowSize;
}

std::vector<std::vector<std::vector<uint64>>> EvntTrigAvg::getHistoData(){
        readHistoData=false;
        return histogramData;
}

bool EvntTrigAvg::shouldReadHistoData(){
    return readHistoData;
}

//TODO change int_max and int_min to numbers
int EvntTrigAvg::findMin(std::vector<uint64> data){
    //int min = INT_MAX;
    int min = 2147483647;
    for (int i = 0 ; i < data.size() ; i++){
        if(data[i]<min){
            min=data[i];
        }
    }
    return min;
}

int EvntTrigAvg::findMax(std::vector<uint64> data){
    //int max = INT_MIN;
    int max =-2147483647;
    for (int i = 0 ; i < data.size() ; i++){
        int dataPoint = data[i];
        if(dataPoint>max){
            max=dataPoint;
        }
    }
    return max;
}

float EvntTrigAvg::findMean(std::vector<uint64> data){
    int runningSum=0;
    for(int i=0 ; i < data.size() ; i++){
        runningSum += data[i];
    }
    float mean = float(runningSum)/float(data.size());
    return mean;
}

std::vector<std::vector<std::vector<float>>> EvntTrigAvg::getMinMaxMean(){
    return minMaxMean;
}

std::vector<String> EvntTrigAvg::getElectrodeLabels(){
    return electrodeLabels;
}

<|endoftext|>


<commit_before>#ifndef ANY_HPP
# define ANY_HPP
# pragma once

#include <cassert>

#include <cstdint>

#include <stdexcept>

#include <typeinfo>

#include <type_traits>

#include <utility>

namespace generic
{

class any
{
public:
  template <typename T>
  using remove_cvr = ::std::remove_cv<
    typename ::std::remove_reference<T>::type
  >;

  using typeid_t = void const*;

  template <typename T>
  static typeid_t type_id() noexcept
  {
    static struct tmp { tmp() noexcept {} } const type_id;

    return &type_id;
  }

  any() = default;

  any(any const& other) :
    content(other.content ? other.content->cloner_(other.content) : nullptr)
  {
  }

  any(any&& other) noexcept { *this = ::std::move(other); }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<
        any, typename ::std::decay<ValueType>::type
      >{}
    >::type
  >
  any(ValueType&& value) :
    content(new holder<typename remove_cvr<ValueType>::type>(
      ::std::forward<ValueType>(value)))
  {
  }

  ~any() { delete content; }

public: // modifiers
  void clear() { swap(any()); }

  bool empty() const noexcept { return !*this; }

  void swap(any& other) noexcept { ::std::swap(content, other.content); }

  void swap(any&& other) noexcept { ::std::swap(content, other.content); }

  any& operator=(any const& rhs)
  {
    return content == rhs.content ? *this : *this = any(rhs);
  }

  any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<
        any, typename ::std::decay<ValueType>::type
      >{}
    >::type
  >
  any& operator=(ValueType&& rhs)
  {
    return *this = any(::std::forward<ValueType>(rhs));
  }

public: // queries

  explicit operator bool() const noexcept { return content; }

  typeid_t type_id() const noexcept
  {
    return content ? content->type_id_ : type_id<void>();
  }

  auto type() const noexcept -> decltype(type_id()) { return type_id(); }

public: // get

  template <typename U>
  U& get()
#ifdef NDEBUG
    noexcept
#endif
  {
    using nonref = typename remove_cvr<U>::type;

#ifndef NDEBUG
    if (content && (type_id() ==
      type_id<typename remove_cvr<U>::type>()))
    {
      return static_cast<any::holder<nonref>*>(content)->held;
    }
    else
    {
      throw ::std::bad_typeid();
    }
#else
    return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
  }

  template <typename U>
  typename ::std::enable_if<
    !(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
    U const&
  >::type
  get() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
  {
    using nonref = typename remove_cvr<U>::type;

    return const_cast<any*>(this)->get<nonref const&>();
  }

  template <typename U>
  typename ::std::enable_if<
    ::std::is_enum<U>{} || ::std::is_fundamental<U>{},
    U
  >::type
  get() const noexcept(noexcept(::std::declval<any>().get<U>()))
  {
    using nonref = typename remove_cvr<U>::type;

    return const_cast<any*>(this)->get<nonref const&>();
  }

  template <typename U>
  typename ::std::enable_if<
    !(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
    U const&
  >::type
  cget() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
  {
    return get<U>();
  }

  template <typename U>
  typename ::std::enable_if<
    (::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
    U
  >::type
  cget() const noexcept(noexcept(::std::declval<any>().get<U>()))
  {
    return get<U>();
  }

private: // types

  template <typename T>
  static constexpr T* begin(T& value) noexcept
  {
    return &value;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  begin(T (&array)[N]) noexcept
  {
    return begin(*array);
  }

  template <typename T>
  static constexpr T* end(T& value) noexcept
  {
    return &value + 1;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  end(T (&array)[N]) noexcept
  {
    return end(array[N - 1]);
  }

  struct placeholder
  {
    typeid_t const type_id_;

    placeholder* (* const cloner_)(placeholder*);

    virtual ~placeholder() = default;

  protected:

    placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
      type_id_(ti),
      cloner_(c)
    {
    }
  };

  template <typename ValueType>
  struct holder : public placeholder
  {
  public: // constructor
    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        !::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        ::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        ::std::is_move_assignable<
          typename ::std::remove_const<
            typename ::std::remove_all_extents<U>::type
          >::type
        >{} &&
        ::std::is_rvalue_reference<T&&>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner)
    {
      ::std::copy(::std::make_move_iterator(begin(value)),
        ::std::make_move_iterator(end(value)),
        begin(held));
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        ::std::is_copy_assignable<
          typename ::std::remove_const<
            typename ::std::remove_all_extents<U>::type
          >::type
        >{} &&
        !::std::is_rvalue_reference<T&&>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner)
    {
      ::std::copy(begin(value), end(value), begin(held));
    }

    holder& operator=(holder const&) = delete;

    static placeholder* cloner(placeholder* const base)
    {
      return new holder<ValueType>(static_cast<holder*>(base)->held);
    }

    static placeholder* throwing_cloner(placeholder* const)
    {
      throw ::std::logic_error("");
    }

  public:
    typename ::std::remove_const<ValueType>::type held;
  };

private: // representation

  template<typename ValueType>
  friend ValueType* any_cast(any*) noexcept;

  template<typename ValueType>
  friend ValueType* unsafe_any_cast(any*) noexcept;

  placeholder* content{};
};

template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
  return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}

template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
  return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
  return operand &&
    (operand->type_id() ==
      any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
    &static_cast<any::holder<ValueType>*>(operand->content)->held :
    nullptr;
}

template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
  return any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType any_cast(any& operand)
#ifdef NDEBUG
  noexcept
#endif
{
  using nonref = typename any::remove_cvr<ValueType>::type;

#ifndef NDEBUG
  auto const result(any_cast<nonref>(&operand));

  if (result)
  {
    return *result;
  }
  else
  {
    throw ::std::bad_cast();
  }
#else
  return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}

template<typename ValueType>
inline ValueType any_cast(any const& operand) noexcept(
  noexcept(
    any_cast<typename any::remove_cvr<ValueType>::type>(
      const_cast<any&>(operand)
    )
  )
)
{
  using nonref = typename any::remove_cvr<ValueType>::type;

  return any_cast<nonref const&>(const_cast<any&>(operand));
}

}

#endif // ANY_HPP
<commit_msg>some fixes<commit_after>#ifndef ANY_HPP
# define ANY_HPP
# pragma once

#include <cassert>

#include <cstdint>

#include <stdexcept>

#include <typeinfo>

#include <type_traits>

#include <utility>

namespace generic
{

class any
{
public:
  template <typename T>
  using remove_cvr = ::std::remove_cv<
    typename ::std::remove_reference<T>::type
  >;

  using typeid_t = void const*;

  template <typename T>
  static typeid_t type_id() noexcept
  {
    static struct tmp { tmp() noexcept {} } const type_id;

    return &type_id;
  }

  any() = default;

  any(any const& other) :
    content(other.content ? other.content->cloner_(other.content) : nullptr)
  {
  }

  any(any&& other) noexcept { *this = ::std::move(other); }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<
        any, typename ::std::decay<ValueType>::type
      >{}
    >::type
  >
  any(ValueType&& value) :
    content(new holder<typename remove_cvr<ValueType>::type>(
      ::std::forward<ValueType>(value)))
  {
  }

  ~any() { delete content; }

public: // modifiers
  void clear() { swap(any()); }

  bool empty() const noexcept { return !*this; }

  void swap(any& other) noexcept { ::std::swap(content, other.content); }

  void swap(any&& other) noexcept { ::std::swap(content, other.content); }

  any& operator=(any const& rhs)
  {
    return content == rhs.content ? *this : *this = any(rhs);
  }

  any& operator=(any&& rhs) noexcept { swap(rhs); return *this; }

  template<typename ValueType,
    typename = typename ::std::enable_if<
      !::std::is_same<
        any, typename ::std::decay<ValueType>::type
      >{}
    >::type
  >
  any& operator=(ValueType&& rhs)
  {
    return *this = any(::std::forward<ValueType>(rhs));
  }

public: // queries

  explicit operator bool() const noexcept { return content; }

  typeid_t type_id() const noexcept
  {
    return content ? content->type_id_ : type_id<void>();
  }

  auto type() const noexcept -> decltype(type_id()) { return type_id(); }

public: // get

  template <typename U>
  U& get()
#ifdef NDEBUG
    noexcept
#endif
  {
    using nonref = typename remove_cvr<U>::type;

#ifndef NDEBUG
    if (content && (type_id() ==
      type_id<typename remove_cvr<U>::type>()))
    {
      return static_cast<any::holder<nonref>*>(content)->held;
    }
    else
    {
      throw ::std::bad_typeid();
    }
#else
    return static_cast<any::holder<nonref>*>(content)->held;
#endif // NDEBUG
  }

  template <typename U>
  typename ::std::enable_if<
    !(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
    U const&
  >::type
  get() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
  {
    using nonref = typename remove_cvr<U>::type;

    return const_cast<any*>(this)->get<nonref const&>();
  }

  template <typename U>
  typename ::std::enable_if<
    ::std::is_enum<U>{} || ::std::is_fundamental<U>{},
    U
  >::type
  get() const noexcept(noexcept(::std::declval<any>().get<U>()))
  {
    using nonref = typename remove_cvr<U>::type;

    return const_cast<any*>(this)->get<nonref const&>();
  }

  template <typename U>
  typename ::std::enable_if<
    !(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
    U const&
  >::type
  cget() const noexcept(noexcept(::std::declval<any>().get<U const&>()))
  {
    return get<U const&>();
  }

  template <typename U>
  typename ::std::enable_if<
    (::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
    U
  >::type
  cget() const noexcept(noexcept(::std::declval<any>().get<U>()))
  {
    return get<U>();
  }

private: // types

  template <typename T>
  static constexpr T* begin(T& value) noexcept
  {
    return &value;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  begin(T (&array)[N]) noexcept
  {
    return begin(*array);
  }

  template <typename T>
  static constexpr T* end(T& value) noexcept
  {
    return &value + 1;
  }

  template <typename T, ::std::size_t N>
  static constexpr typename ::std::remove_all_extents<T>::type*
  end(T (&array)[N]) noexcept
  {
    return end(array[N - 1]);
  }

  struct placeholder
  {
    typeid_t const type_id_;

    placeholder* (* const cloner_)(placeholder*);

    virtual ~placeholder() = default;

  protected:

    placeholder(typeid_t const ti, decltype(cloner_) const c) noexcept :
      type_id_(ti),
      cloner_(c)
    {
    }
  };

  template <typename ValueType>
  struct holder : public placeholder
  {
  public: // constructor
    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        !::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        !::std::is_array<U>{} &&
        ::std::is_copy_constructible<U>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner),
      held(::std::forward<T>(value))
    {
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        ::std::is_move_assignable<
          typename ::std::remove_const<
            typename ::std::remove_all_extents<U>::type
          >::type
        >{} &&
        ::std::is_rvalue_reference<T&&>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), throwing_cloner)
    {
      ::std::copy(::std::make_move_iterator(begin(value)),
        ::std::make_move_iterator(end(value)),
        begin(held));
    }

    template <class T, typename U = ValueType>
    holder(T&& value,
      typename ::std::enable_if<
        ::std::is_array<U>{} &&
        ::std::is_copy_assignable<
          typename ::std::remove_const<
            typename ::std::remove_all_extents<U>::type
          >::type
        >{} &&
        !::std::is_rvalue_reference<T&&>{}
      >::type* = nullptr) :
      placeholder(type_id<ValueType>(), cloner)
    {
      ::std::copy(begin(value), end(value), begin(held));
    }

    holder& operator=(holder const&) = delete;

    static placeholder* cloner(placeholder* const base)
    {
      return new holder<ValueType>(static_cast<holder*>(base)->held);
    }

    static placeholder* throwing_cloner(placeholder* const)
    {
      throw ::std::logic_error("");
    }

  public:
    typename ::std::remove_const<ValueType>::type held;
  };

private: // representation

  template<typename ValueType>
  friend ValueType* any_cast(any*) noexcept;

  template<typename ValueType>
  friend ValueType* unsafe_any_cast(any*) noexcept;

  placeholder* content{};
};

template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
  return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}

template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
  return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
  return operand &&
    (operand->type_id() ==
      any::type_id<typename any::remove_cvr<ValueType>::type>()) ?
    &static_cast<any::holder<ValueType>*>(operand->content)->held :
    nullptr;
}

template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
  return any_cast<ValueType>(const_cast<any*>(operand));
}

template<typename ValueType>
inline ValueType any_cast(any& operand)
#ifdef NDEBUG
  noexcept
#endif
{
  using nonref = typename any::remove_cvr<ValueType>::type;

#ifndef NDEBUG
  auto const result(any_cast<nonref>(&operand));

  if (result)
  {
    return *result;
  }
  else
  {
    throw ::std::bad_cast();
  }
#else
  return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}

template<typename ValueType>
inline ValueType any_cast(any const& operand) noexcept(
  noexcept(
    any_cast<typename any::remove_cvr<ValueType>::type>(
      const_cast<any&>(operand)
    )
  )
)
{
  using nonref = typename any::remove_cvr<ValueType>::type;

  return any_cast<nonref const&>(const_cast<any&>(operand));
}

}

#endif // ANY_HPP
<|endoftext|>


<commit_before>/*
 * File:   ast.cpp
 * Author: ghernan
 *
 * Abstract Syntax Tree classes
 *
 * Created on November 30, 2016, 7:56 PM
 */

#include "OS_support.h"
#include "ast.h"

using namespace std;

//Empty children list constant
const AstNodeList AstNode::ms_noChildren;

//  Constructor functions.
//
////////////////////////////////
Ref<AstNode> astCreateBlock(CScriptToken token)
{
    return refFromNew( new AstBranchNode(AST_BLOCK, token.getPosition()));
}

Ref<AstNode> astCreateIf (ScriptPosition pos,
                          Ref<AstNode> condition,
                          Ref<AstNode> thenSt,
                          Ref<AstNode> elseSt)
{

    auto result = refFromNew( new AstBranchNode(AST_IF, pos));

    result->addChild(condition);
    result->addChild(thenSt);
    result->addChild(elseSt);

    return result;
}

Ref<AstNode> astCreateConditional ( ScriptPosition pos,
                                    Ref<AstNode> condition,
                                    Ref<AstNode> thenExpr,
                                    Ref<AstNode> elseExpr)
{
    auto result = refFromNew( new AstBranchNode(AST_CONDITIONAL, pos));

    result->addChild(condition);
    result->addChild(thenExpr);
    result->addChild(elseExpr);

    return result;
}

Ref<AstNode> astCreateFor (ScriptPosition pos,
                          Ref<AstNode> initSt,
                          Ref<AstNode> condition,
                          Ref<AstNode> incrementSt,
                          Ref<AstNode> body)
{
    auto result = refFromNew( new AstBranchNode(AST_FOR, pos));

    result->addChild(initSt);
    result->addChild(condition);
    result->addChild(incrementSt);
    result->addChild(body);

    return result;
}

Ref<AstNode> astCreateReturn (ScriptPosition pos, Ref<AstNode> expr)
{
    auto result = refFromNew( new AstBranchNode(AST_RETURN, pos));

    result->addChild(expr);
    return result;
}

Ref<AstNode> astCreateAssignment(ScriptPosition pos,
                                 int opCode,
                                 Ref<AstNode> lexpr,
                                 Ref<AstNode> rexpr)
{
    auto result = refFromNew( new AstOperator(AST_ASSIGNMENT, pos, opCode));

    result->addChild(lexpr);
    result->addChild(rexpr);
    return result;
}

Ref<AstNode> astCreatePrefixOp(CScriptToken token, Ref<AstNode> rexpr)
{
    auto result = refFromNew( new AstOperator(AST_PREFIXOP,
                                              token.getPosition(),
                                              token.type()));

    result->addChild(rexpr);
    return result;
}

Ref<AstNode> astCreatePostfixOp(CScriptToken token, Ref<AstNode> lexpr)
{
    auto result = refFromNew( new AstOperator(AST_POSTFIXOP,
                                              token.getPosition(),
                                              token.type()));

    result->addChild(lexpr);
    return result;
}

Ref<AstNode> astCreateBinaryOp(CScriptToken token,
                                 Ref<AstNode> lexpr,
                                 Ref<AstNode> rexpr)
{
    auto result = refFromNew( new AstOperator(AST_BINARYOP,
                                              token.getPosition(),
                                              token.type()));

    result->addChild(lexpr);
    result->addChild(rexpr);
    return result;
}

Ref<AstNode> astCreateFnCall(ScriptPosition pos, Ref<AstNode> fnExpr, bool newCall)
{
    const AstNodeTypes  type = newCall ? AST_NEWCALL: AST_FNCALL;
    auto result = refFromNew( new AstBranchNode(type, pos));

    result->addChild(fnExpr);
    return result;
}

/**
 * Transforms a regular function call into a 'new' operator call.
 * @param callExpr
 * @return
 */
Ref<AstNode> astToNewCall(Ref<AstNode> callExpr)
{
    auto result = astCreateFnCall(callExpr->position(),
                                  callExpr->children()[0], true);

    auto children = callExpr->children();

    for (size_t i = 0; i < children.size(); ++i)
        result->addChild(children[i]);

    return result;
}

/**
 * Creates an array literal AST node.
 * @param pos
 * @return
 */
Ref<AstNode> astCreateArray(ScriptPosition pos)
{
    return refFromNew( new AstBranchNode(AST_ARRAY, pos));
}

Ref<AstNode> astCreateArrayAccess(ScriptPosition pos,
                                  Ref<AstNode> arrayExpr,
                                  Ref<AstNode> indexExpr)
{
    auto result = refFromNew( new AstBranchNode(AST_ARRAY_ACCESS, pos));

    result->addChild(arrayExpr);
    result->addChild(indexExpr);

    return result;
}

Ref<AstNode> astCreateMemberAccess(ScriptPosition pos,
                                  Ref<AstNode> objExpr,
                                  Ref<AstNode> identifier)
{
    auto result = refFromNew( new AstBranchNode(AST_MEMBER_ACCESS, pos));

    result->addChild(objExpr);
    result->addChild(identifier);

    return result;
}

/**
 * Creates an 'AstLiteral' object from a source token.
 * @param token
 * @return
 */
Ref<AstLiteral> AstLiteral::create(CScriptToken token)
{
    Ref<JSValue>    value;

    switch (token.type())
    {
    case LEX_R_TRUE:        value = jsTrue(); break;
    case LEX_R_FALSE:       value = jsFalse(); break;
    case LEX_R_NULL:        value = jsNull(); break;
    case LEX_R_UNDEFINED:   value = ::undefined(); break;
    case LEX_STR:
    case LEX_INT:
    case LEX_FLOAT:
        value = createConstant(token);
        break;

    default:
        ASSERT(!"Invalid token for a literal");
    }

    return refFromNew(new AstLiteral(token.getPosition(), value));
}

/**
 * Creates a literal form an integer
 * @param pos
 * @param value
 * @return
 */
Ref<AstLiteral> AstLiteral::create(ScriptPosition pos, int value)
{
    return refFromNew(new AstLiteral(pos, jsInt(value)));
}

/**
 * Transforms an AST statement into a Javascript object.
 * This particular version creates an object containing all its children
 * @return
 */
Ref<JSValue> AstNode::toJS()const
{
    Ref<JSObject>   obj = JSObject::create();

    obj->set("a_type", jsString(astTypeToString(getType())));

    const string name = getName();
    if (!name.empty())
        obj->set("b_name", jsString(name));

    const AstNodeList&  c = children();
    if (!c.empty())
        obj->set("z_children", toJSArray(c));

    const auto value = getValue();
    if (!value->isUndefined())
        obj->set("v_value", value);

    return obj;
}

/**
 * Function declaration to JSValue
 * @return
 */
Ref<JSValue> AstFunction::toJS()const
{
    Ref<JSObject>   obj = AstNode::toJS().staticCast<JSObject>();

    obj->set("c_parameters", JSArray::createStrArray(m_params));
    obj->set("d_code", m_code->toJS());

    return obj;
}

/**
 * Operator to JSValue
 * @return
 */
Ref<JSValue> AstOperator::toJS()const
{
    Ref<JSObject>   obj = AstBranchNode::toJS().staticCast<JSObject>();

    obj->set("d_operator", jsString(getTokenStr(code)));
    return obj;
}

/**
 * Object literal to JSValue
 * @return
 */
Ref<JSValue> AstObject::toJS()const
{
    Ref<JSObject>   obj = JSObject::create();
    Ref<JSObject>   props = JSObject::create();

    obj->set("a_type", jsString(astTypeToString(getType())));
    obj->set("b_properties", props);

    PropertyList::const_iterator it;
    for (it = m_properties.begin(); it != m_properties.end(); ++it)
        props->set(it->name, it->expr->toJS());

    return obj;
}

/**
 * Creates a undefined literal
 * @param pos
 * @return
 */
Ref<AstLiteral> AstLiteral::undefined(ScriptPosition pos)
{
    return refFromNew(new AstLiteral(pos, ::undefined()));
}

/**
 * Transforms a list of AstNodes into a Javascript Array.
 * @param statements
 * @return
 */
Ref<JSArray> toJSArray (const AstNodeList& statements)
{
    Ref<JSArray>    result = JSArray::create();

    for (size_t i = 0; i < statements.size(); ++i)
    {
        if (statements[i].notNull())
            result->push( statements[i]->toJS() );
        else
            result->push(jsNull());
    }

    return result;
}

/**
 * Generates a JSON file from a statements list
 * @param statements
 * @return
 */
std::string toJSON (const AstNodeList& statements)
{
    return toJSArray(statements)->getJSON(0);
}

/**
 * Gets the string representation of an AST type
 * @param type
 * @return
 */
std::string astTypeToString(AstNodeTypes type)
{
    typedef map<AstNodeTypes, string>   TypesMap;
    static TypesMap types;

    if (types.empty())
    {
        types[AST_BLOCK] = "AST_BLOCK";
        types[AST_VAR] = "AST_VAR";
        types[AST_IF] = "AST_IF";
        types[AST_FOR] = "AST_FOR";
        types[AST_RETURN] = "AST_RETURN";
        types[AST_FUNCTION] = "AST_FUNCTION";
        types[AST_ASSIGNMENT] = "AST_ASSIGNMENT";
        types[AST_FNCALL] = "AST_FNCALL";
        types[AST_NEWCALL] = "AST_NEWCALL";
        types[AST_LITERAL] = "AST_LITERAL";
        types[AST_IDENTIFIER] = "AST_IDENTIFIER";
        types[AST_ARRAY] = "AST_ARRAY";
        types[AST_OBJECT] = "AST_OBJECT";
        types[AST_ARRAY_ACCESS] = "AST_ARRAY_ACCESS";
        types[AST_MEMBER_ACCESS] = "AST_MEMBER_ACCESS";
        types[AST_CONDITIONAL] = "AST_CONDITIONAL";
        types[AST_BINARYOP] = "AST_BINARYOP";
        types[AST_PREFIXOP] = "AST_PREFIXOP";
        types[AST_POSTFIXOP] = "AST_POSTFIXOP";
        //types[AST_TYPES_COUNT] = "AST_TYPES_COUNT";
    }

    TypesMap::const_iterator it = types.find(type);

    if (it != types.end())
        return it->second;
    else
        return "BAD_AST_TYPE";
}<commit_msg>BUGFIX: Wrong start index in 'astToNewCall' function. It must skip the first child.<commit_after>/*
 * File:   ast.cpp
 * Author: ghernan
 *
 * Abstract Syntax Tree classes
 *
 * Created on November 30, 2016, 7:56 PM
 */

#include "OS_support.h"
#include "ast.h"

using namespace std;

//Empty children list constant
const AstNodeList AstNode::ms_noChildren;

//  Constructor functions.
//
////////////////////////////////
Ref<AstNode> astCreateBlock(CScriptToken token)
{
    return refFromNew( new AstBranchNode(AST_BLOCK, token.getPosition()));
}

Ref<AstNode> astCreateIf (ScriptPosition pos,
                          Ref<AstNode> condition,
                          Ref<AstNode> thenSt,
                          Ref<AstNode> elseSt)
{

    auto result = refFromNew( new AstBranchNode(AST_IF, pos));

    result->addChild(condition);
    result->addChild(thenSt);
    result->addChild(elseSt);

    return result;
}

Ref<AstNode> astCreateConditional ( ScriptPosition pos,
                                    Ref<AstNode> condition,
                                    Ref<AstNode> thenExpr,
                                    Ref<AstNode> elseExpr)
{
    auto result = refFromNew( new AstBranchNode(AST_CONDITIONAL, pos));

    result->addChild(condition);
    result->addChild(thenExpr);
    result->addChild(elseExpr);

    return result;
}

Ref<AstNode> astCreateFor (ScriptPosition pos,
                          Ref<AstNode> initSt,
                          Ref<AstNode> condition,
                          Ref<AstNode> incrementSt,
                          Ref<AstNode> body)
{
    auto result = refFromNew( new AstBranchNode(AST_FOR, pos));

    result->addChild(initSt);
    result->addChild(condition);
    result->addChild(incrementSt);
    result->addChild(body);

    return result;
}

Ref<AstNode> astCreateReturn (ScriptPosition pos, Ref<AstNode> expr)
{
    auto result = refFromNew( new AstBranchNode(AST_RETURN, pos));

    result->addChild(expr);
    return result;
}

Ref<AstNode> astCreateAssignment(ScriptPosition pos,
                                 int opCode,
                                 Ref<AstNode> lexpr,
                                 Ref<AstNode> rexpr)
{
    auto result = refFromNew( new AstOperator(AST_ASSIGNMENT, pos, opCode));

    result->addChild(lexpr);
    result->addChild(rexpr);
    return result;
}

Ref<AstNode> astCreatePrefixOp(CScriptToken token, Ref<AstNode> rexpr)
{
    auto result = refFromNew( new AstOperator(AST_PREFIXOP,
                                              token.getPosition(),
                                              token.type()));

    result->addChild(rexpr);
    return result;
}

Ref<AstNode> astCreatePostfixOp(CScriptToken token, Ref<AstNode> lexpr)
{
    auto result = refFromNew( new AstOperator(AST_POSTFIXOP,
                                              token.getPosition(),
                                              token.type()));

    result->addChild(lexpr);
    return result;
}

Ref<AstNode> astCreateBinaryOp(CScriptToken token,
                                 Ref<AstNode> lexpr,
                                 Ref<AstNode> rexpr)
{
    auto result = refFromNew( new AstOperator(AST_BINARYOP,
                                              token.getPosition(),
                                              token.type()));

    result->addChild(lexpr);
    result->addChild(rexpr);
    return result;
}

Ref<AstNode> astCreateFnCall(ScriptPosition pos, Ref<AstNode> fnExpr, bool newCall)
{
    const AstNodeTypes  type = newCall ? AST_NEWCALL: AST_FNCALL;
    auto result = refFromNew( new AstBranchNode(type, pos));

    result->addChild(fnExpr);
    return result;
}

/**
 * Transforms a regular function call into a 'new' operator call.
 * @param callExpr
 * @return
 */
Ref<AstNode> astToNewCall(Ref<AstNode> callExpr)
{
    auto result = astCreateFnCall(callExpr->position(),
                                  callExpr->children()[0], true);

    auto children = callExpr->children();

    for (size_t i = 1; i < children.size(); ++i)
        result->addChild(children[i]);

    return result;
}

/**
 * Creates an array literal AST node.
 * @param pos
 * @return
 */
Ref<AstNode> astCreateArray(ScriptPosition pos)
{
    return refFromNew( new AstBranchNode(AST_ARRAY, pos));
}

Ref<AstNode> astCreateArrayAccess(ScriptPosition pos,
                                  Ref<AstNode> arrayExpr,
                                  Ref<AstNode> indexExpr)
{
    auto result = refFromNew( new AstBranchNode(AST_ARRAY_ACCESS, pos));

    result->addChild(arrayExpr);
    result->addChild(indexExpr);

    return result;
}

Ref<AstNode> astCreateMemberAccess(ScriptPosition pos,
                                  Ref<AstNode> objExpr,
                                  Ref<AstNode> identifier)
{
    auto result = refFromNew( new AstBranchNode(AST_MEMBER_ACCESS, pos));

    result->addChild(objExpr);
    result->addChild(identifier);

    return result;
}

/**
 * Creates an 'AstLiteral' object from a source token.
 * @param token
 * @return
 */
Ref<AstLiteral> AstLiteral::create(CScriptToken token)
{
    Ref<JSValue>    value;

    switch (token.type())
    {
    case LEX_R_TRUE:        value = jsTrue(); break;
    case LEX_R_FALSE:       value = jsFalse(); break;
    case LEX_R_NULL:        value = jsNull(); break;
    case LEX_R_UNDEFINED:   value = ::undefined(); break;
    case LEX_STR:
    case LEX_INT:
    case LEX_FLOAT:
        value = createConstant(token);
        break;

    default:
        ASSERT(!"Invalid token for a literal");
    }

    return refFromNew(new AstLiteral(token.getPosition(), value));
}

/**
 * Creates a literal form an integer
 * @param pos
 * @param value
 * @return
 */
Ref<AstLiteral> AstLiteral::create(ScriptPosition pos, int value)
{
    return refFromNew(new AstLiteral(pos, jsInt(value)));
}

/**
 * Transforms an AST statement into a Javascript object.
 * This particular version creates an object containing all its children
 * @return
 */
Ref<JSValue> AstNode::toJS()const
{
    Ref<JSObject>   obj = JSObject::create();

    obj->set("a_type", jsString(astTypeToString(getType())));

    const string name = getName();
    if (!name.empty())
        obj->set("b_name", jsString(name));

    const AstNodeList&  c = children();
    if (!c.empty())
        obj->set("z_children", toJSArray(c));

    const auto value = getValue();
    if (!value->isUndefined())
        obj->set("v_value", value);

    return obj;
}

/**
 * Function declaration to JSValue
 * @return
 */
Ref<JSValue> AstFunction::toJS()const
{
    Ref<JSObject>   obj = AstNode::toJS().staticCast<JSObject>();

    obj->set("c_parameters", JSArray::createStrArray(m_params));
    obj->set("d_code", m_code->toJS());

    return obj;
}

/**
 * Operator to JSValue
 * @return
 */
Ref<JSValue> AstOperator::toJS()const
{
    Ref<JSObject>   obj = AstBranchNode::toJS().staticCast<JSObject>();

    obj->set("d_operator", jsString(getTokenStr(code)));
    return obj;
}

/**
 * Object literal to JSValue
 * @return
 */
Ref<JSValue> AstObject::toJS()const
{
    Ref<JSObject>   obj = JSObject::create();
    Ref<JSObject>   props = JSObject::create();

    obj->set("a_type", jsString(astTypeToString(getType())));
    obj->set("b_properties", props);

    PropertyList::const_iterator it;
    for (it = m_properties.begin(); it != m_properties.end(); ++it)
        props->set(it->name, it->expr->toJS());

    return obj;
}

/**
 * Creates a undefined literal
 * @param pos
 * @return
 */
Ref<AstLiteral> AstLiteral::undefined(ScriptPosition pos)
{
    return refFromNew(new AstLiteral(pos, ::undefined()));
}

/**
 * Transforms a list of AstNodes into a Javascript Array.
 * @param statements
 * @return
 */
Ref<JSArray> toJSArray (const AstNodeList& statements)
{
    Ref<JSArray>    result = JSArray::create();

    for (size_t i = 0; i < statements.size(); ++i)
    {
        if (statements[i].notNull())
            result->push( statements[i]->toJS() );
        else
            result->push(jsNull());
    }

    return result;
}

/**
 * Generates a JSON file from a statements list
 * @param statements
 * @return
 */
std::string toJSON (const AstNodeList& statements)
{
    return toJSArray(statements)->getJSON(0);
}

/**
 * Gets the string representation of an AST type
 * @param type
 * @return
 */
std::string astTypeToString(AstNodeTypes type)
{
    typedef map<AstNodeTypes, string>   TypesMap;
    static TypesMap types;

    if (types.empty())
    {
        types[AST_BLOCK] = "AST_BLOCK";
        types[AST_VAR] = "AST_VAR";
        types[AST_IF] = "AST_IF";
        types[AST_FOR] = "AST_FOR";
        types[AST_RETURN] = "AST_RETURN";
        types[AST_FUNCTION] = "AST_FUNCTION";
        types[AST_ASSIGNMENT] = "AST_ASSIGNMENT";
        types[AST_FNCALL] = "AST_FNCALL";
        types[AST_NEWCALL] = "AST_NEWCALL";
        types[AST_LITERAL] = "AST_LITERAL";
        types[AST_IDENTIFIER] = "AST_IDENTIFIER";
        types[AST_ARRAY] = "AST_ARRAY";
        types[AST_OBJECT] = "AST_OBJECT";
        types[AST_ARRAY_ACCESS] = "AST_ARRAY_ACCESS";
        types[AST_MEMBER_ACCESS] = "AST_MEMBER_ACCESS";
        types[AST_CONDITIONAL] = "AST_CONDITIONAL";
        types[AST_BINARYOP] = "AST_BINARYOP";
        types[AST_PREFIXOP] = "AST_PREFIXOP";
        types[AST_POSTFIXOP] = "AST_POSTFIXOP";
        //types[AST_TYPES_COUNT] = "AST_TYPES_COUNT";
    }

    TypesMap::const_iterator it = types.find(type);

    if (it != types.end())
        return it->second;
    else
        return "BAD_AST_TYPE";
}<|endoftext|>


<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);

}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"

using namespace MathLib;

CGameProcess::CGameProcess(void)
{

}

CGameProcess::~CGameProcess(void)
{

}
int CGameProcess::Init()
{
	g_Engine.pFileSystem->CacheFilesFormExt("char");
	g_Engine.pFileSystem->CacheFilesFormExt("node");
	g_Engine.pFileSystem->CacheFilesFormExt("smesh");
	g_Engine.pFileSystem->CacheFilesFormExt("sanim");

	g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
	//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
	g_Engine.pControls->SetKeyPressFunc(KeyPress);
	g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);

	m_pRole = new CFPSRoleLocal();
	m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char");		//ؽɫԴ

	m_pRole->SetActorPosition(vec3(0, 0, 0));	//ýɫʼλáŴΪԭ㣬άϵvec3
	m_pSkillSystem = new CSkillSystem(this);
	m_pCameraBase = new CCameraBase();
	m_pCameraBase->SetEnabled(1);
	g_pSysControl->SetMouseGrab(1);

}<|endoftext|>


<commit_before>/* This file is part of the KDE project
   Copyright (C) 2004 Mark Bucciarelli <mark@hubcapconsulting.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

#include <kdebug.h>
#include <qdir.h>
#include <qfile.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qtextstream.h>

#include "script.h"

static QString srcdir();
static int runscripts
( const QString &interpreter, const QString &extension, const QString &path );

// Read srcdir from Makefile (for builddir != srcdir).
QString srcdir()
{
  bool found = false;
  QString dir;

  QFile file( "Makefile" );
  if ( !file.open( IO_ReadOnly  | IO_Translate ) ) return "";

  QTextStream in( &file );
  QString line;
  while ( !found && !in.atEnd() )
  {
    line = in.readLine();
    if ( line.startsWith( "srcdir = " ) )
    {
      dir = line.mid( 9 );
      found = true;
    }
  }

  if ( !found ) dir = "";

  return dir;
}

int runscripts
( const QString &interpreter, const QString &extension, const QString &path )
{
  int rval = 0;
  QStringList files;

  QDir dir( path );

  Script* s = new Script( dir );

  dir.setNameFilter( extension );
  dir.setFilter( QDir::Files );
  dir.setSorting( QDir::Name | QDir::IgnoreCase );
  const QFileInfoList *list = dir.entryInfoList();
  QFileInfoListIterator it( *list );
  QFileInfo *fi;
  while ( !rval && ( fi = it.current() ) != 0 )
  {
    // Don't run scripts that are shared routines.
    if ( ! fi->fileName().startsWith( "__" ) )
    {
      kdDebug() << "runscripts: running " << fi->fileName() << endl;

      s->addArgument( interpreter );
      s->addArgument( path + QDir::separator() + fi->fileName().latin1() );

      // Thorsten's xautomation tests run with user interaction by default.
      if ( interpreter == "sh" ) s->addArgument( "--batch" );
      if ( interpreter == "php" ) s->addArgument( "--batch" );

      rval = s->run();
      delete s;
      s = new Script( dir );
    }
    ++it;
  }
  delete s;
  s = 0;

  return rval;
}

int main( int, char** )
{
  int rval = 0;

  QString path = srcdir();

  if ( !rval ) rval = runscripts( "python", "*.py *.Py *.PY *.pY", path );

  if ( !rval ) rval = runscripts( "sh", "*.sh *.Sh *.SH *.sH", path );

  if ( !rval ) rval = runscripts( "perl", "*.pl *.Pl *.PL *.pL", path );

  if ( !rval ) rval = runscripts( "php", "*.php *.php3 *.php4 *.php5", path );

  return rval;
}
<commit_msg>output PASS/FAIL result to console<commit_after>/* This file is part of the KDE project
   Copyright (C) 2004 Mark Bucciarelli <mark@hubcapconsulting.com>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

#include <kdebug.h>
#include <qdir.h>
#include <qfile.h>
#include <qstring.h>
#include <qstringlist.h>
#include <qtextstream.h>

#include "script.h"

static QString srcdir();
static int runscripts
( const QString &interpreter, const QString &extension, const QString &path );

const QString dots = "..................................................";

// Read srcdir from Makefile (for builddir != srcdir).
QString srcdir()
{
  bool found = false;
  QString dir;

  QFile file( "Makefile" );
  if ( !file.open( IO_ReadOnly  | IO_Translate ) ) return "";

  QTextStream in( &file );
  QString line;
  while ( !found && !in.atEnd() )
  {
    line = in.readLine();
    if ( line.startsWith( "srcdir = " ) )
    {
      dir = line.mid( 9 );
      found = true;
    }
  }

  if ( !found ) dir = "";

  return dir;
}

int runscripts
( const QString &interpreter, const QString &extension, const QString &path )
{
  int rval = 0;
  QStringList files;

  QDir dir( path );

  Script* s = new Script( dir );

  dir.setNameFilter( extension );
  dir.setFilter( QDir::Files );
  dir.setSorting( QDir::Name | QDir::IgnoreCase );
  const QFileInfoList *list = dir.entryInfoList();
  QFileInfoListIterator it( *list );
  QFileInfo *fi;
  while ( !rval && ( fi = it.current() ) != 0 )
  {
    // Don't run scripts that are shared routines.
    if ( ! fi->fileName().startsWith( "__" ) )
    {
      s->addArgument( interpreter );
      s->addArgument( path + QDir::separator() + fi->fileName().latin1() );

      // Thorsten's xautomation tests run with user interaction by default.
      if ( interpreter == "sh" ) s->addArgument( "--batch" );
      if ( interpreter == "php" ) s->addArgument( "--batch" );

      rval = s->run();

      kdDebug() << "runscripts: " << fi->fileName()
        << " " << dots.left( dots.length() - fi->fileName().length() )
        << " " << ( ! rval ? "PASS" : "FAIL" ) << endl;

      delete s;
      s = new Script( dir );
    }
    ++it;
  }
  delete s;
  s = 0;

  return rval;
}

int main( int, char** )
{
  int rval = 0;

  QString path = srcdir();

  if ( !rval ) rval = runscripts( "python", "*.py *.Py *.PY *.pY", path );

  if ( !rval ) rval = runscripts( "sh", "*.sh *.Sh *.SH *.sH", path );

  if ( !rval ) rval = runscripts( "perl", "*.pl *.Pl *.PL *.pL", path );

  if ( !rval ) rval = runscripts( "php", "*.php *.php3 *.php4 *.php5", path );

  return rval;
}
<|endoftext|>


<commit_before>/** -*- c++ -*-
 * progressdialog.cpp
 *
 *  Copyright (c) 2004 Till Adam <adam@kde.org>,
 *                     David Faure <faure@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of this program with any edition of
 *  the Qt library by Trolltech AS, Norway (or with modified versions
 *  of Qt that use the same license as Qt), and distribute linked
 *  combinations including the two.  You must obey the GNU General
 *  Public License in all respects for all of the code used other than
 *  Qt.  If you modify this file, you may extend this exception to
 *  your version of the file, but you are not obligated to do so.  If
 *  you do not wish to do so, delete this exception statement from
 *  your version.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>

#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include "kmmainwidget.h"

using KMail::ProgressItem;
using KMail::ProgressManager;

namespace KMail {

class TransactionItem;

TransactionItemView::TransactionItemView( QWidget * parent,
                                          const char * name,
                                          WFlags f )
    : QScrollView( parent, name, f ) {
  setFrameStyle( NoFrame );
  mBigBox = new QVBox( viewport() );
  mBigBox->setSpacing( 5 );
  addChild( mBigBox );
  setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}

TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
   TransactionItem *ti = new TransactionItem( mBigBox, item, first );
   ti->show();
   return ti;
}

void TransactionItemView::resizeContents( int w, int h )
{
  //kdDebug(5006) << k_funcinfo << w << "," << h << endl;
  QScrollView::resizeContents( w, h );
  // Tell the layout in the parent (progressdialog) that our size changed
  updateGeometry();
  // Resize the parent (progressdialog) - this works but resize horizontally too often
  //parentWidget()->adjustSize();

  QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
  QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
  QSize sz = parentWidget()->sizeHint();
  int currentWidth = parentWidget()->width();
  // Don't resize to sz.width() every time when it only reduces a little bit
  if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
    currentWidth = sz.width();
  parentWidget()->resize( currentWidth, sz.height() );
}

QSize TransactionItemView::sizeHint() const
{
  return minimumSizeHint();
}

QSize TransactionItemView::minimumSizeHint() const
{
  int f = 2 * frameWidth();
  // Make room for a vertical scrollbar in all cases, to avoid a horizontal one
  int vsbExt = verticalScrollBar()->sizeHint().width();
  int minw = topLevelWidget()->width() / 3;
  int maxh = topLevelWidget()->height() / 2;
  QSize sz( mBigBox->minimumSizeHint() );
  sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
  sz.setHeight( QMIN( sz.height(), maxh ) + f );
  return sz;
}

void TransactionItemView::slotLayoutFirstItem()
{
  /*
     The below relies on some details in Qt's behaviour regarding deleting
     objects. This slot is called from the destroyed signal of an item just
     going away. That item is at that point still in the  list of chilren, but
     since the vtable is already gone, it will have type QObject. The first
     one with both the right name and the right class therefor is what will
     be the first item very shortly. That's the one we want to remove the
     hline for.
  */
  QObject *o = mBigBox->child( "TransactionItem", "KMail::TransactionItem" );
  TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
  if ( ti ) {
    ti->hideHLine();
  }
}

// ----------------------------------------------------------------------------

TransactionItem::TransactionItem( QWidget* parent,
                                  ProgressItem *item, bool first )
  : QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )

{
  setSpacing( 2 );
  setMargin( 2 );
  setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );

  mFrame = new QFrame( this );
  mFrame->setFrameShape( QFrame::HLine );
  mFrame->setFrameShadow( QFrame::Raised );
  mFrame->show();
  setStretchFactor( mFrame, 3 );

  QHBox *h = new QHBox( this );
  h->setSpacing( 5 );

  mItemLabel = new QLabel( item->label(), h );
  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );

  if ( item->canBeCanceled() ) {
    mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
    connect ( mCancelButton, SIGNAL( clicked() ),
              this, SLOT( slotItemCanceled() ));
  }
  mProgress = new QProgressBar( 100, h );
  mProgress->setProgress( item->progress() );

  h = new QHBox( this );
  h->setSpacing( 5 );
  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
  mSSLLabel = new SSLLabel( h );
  mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
  mItemStatus =  new QLabel( item->status(), h );
  setCrypto( item->usesCrypto() );
  if( first ) hideHLine();
}

TransactionItem::~TransactionItem()
{
}

void TransactionItem::hideHLine()
{
    mFrame->hide();
}

void TransactionItem::setProgress( int progress )
{
  mProgress->setProgress( progress );
}

void TransactionItem::setLabel( const QString& label )
{
  mItemLabel->setText( label );
}

void TransactionItem::setStatus( const QString& status )
{
  mItemStatus->setText( status );
}

void TransactionItem::setCrypto( bool on )
{
  if (on)
    mSSLLabel->setEncrypted( true );
  else
    mSSLLabel->setEncrypted( false );

  mSSLLabel->setState( mSSLLabel->lastState() );
}

void TransactionItem::slotItemCanceled()
{
  if ( mItem )
    mItem->cancel();
}

void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{

}

// ---------------------------------------------------------------------------

ProgressDialog::ProgressDialog( QWidget* alignWidget, KMMainWidget* mainWidget, const char* name )
    : OverlayWidget( alignWidget, mainWidget, name )
{
    setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
    setSpacing( 0 ); // QHBox
    setMargin( 1 );

    mScrollView = new TransactionItemView( this, "ProgressScrollView" );

    QVBox* rightBox = new QVBox( this );
    QToolButton* pbClose = new QToolButton( rightBox );
    pbClose->setAutoRaise(true);
    pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
    pbClose->setFixedSize( 16, 16 );
    pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
    connect(pbClose, SIGNAL(clicked()), this, SLOT(close()));
    QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
    rightBox->setStretchFactor( spacer, 100 );

    /*
     * Get the singleton ProgressManager item which will inform us of
     * appearing and vanishing items.
     */
    ProgressManager *pm = ProgressManager::instance();
    connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
              this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
              this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
              this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
    connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
              this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
    connect ( pm, SIGNAL( progressItemLabel( ProgressItem*, const QString& ) ),
              this, SLOT( slotTransactionLabel( ProgressItem*, const QString& ) ) );
    connect ( pm, SIGNAL( progressItemUsesCrypto( ProgressItem*, bool ) ),
              this, SLOT( slotTransactionUsesCrypto( ProgressItem*, bool ) ) );
}

void ProgressDialog::closeEvent( QCloseEvent* e )
{
  e->accept();
  hide();
}

/*
 *  Destructor
 */
ProgressDialog::~ProgressDialog()
{
    // no need to delete child widgets.
}

void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
   TransactionItem *parent = 0;
   if ( item->parent() ) {
     if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
       parent = mTransactionsToListviewItems[ item->parent() ];
       parent->addSubTransaction( item );
     }
   } else {
     TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
     if ( ti )
       mTransactionsToListviewItems.replace( item, ti );
   }
}

void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     mTransactionsToListviewItems.remove( item );
     ti->setItemComplete();
     QTimer::singleShot( 5000, ti, SLOT( deleteLater() ) );
     // see the slot for comments as to why that works
     connect ( ti, SIGNAL( destroyed() ),
               mScrollView, SLOT( slotLayoutFirstItem() ) );
   }
   // This was the last item, hide.
   if ( mTransactionsToListviewItems.empty() )
     QTimer::singleShot( 5000, this, SLOT( slotHide() ) );
}

void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}

void ProgressDialog::slotTransactionProgress( ProgressItem *item,
                                              unsigned int progress )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setProgress( progress );
   }
}

void ProgressDialog::slotTransactionStatus( ProgressItem *item,
                                            const QString& status )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setStatus( status );
   }
}

void ProgressDialog::slotTransactionLabel( ProgressItem *item,
                                           const QString& label )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setLabel( label );
   }
}

void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
                                                bool value )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setCrypto( value );
   }
}

void ProgressDialog::slotHide()
{
  // check if a new item showed up since we started the timer. If not, hide
  if ( mTransactionsToListviewItems.isEmpty() ) {
    // [save a member var by simply getting the parent mainwidget from qwidget]
    KMMainWidget* mainWidget = ::qt_cast<KMMainWidget *>( parentWidget() );
    // not only hide(), but also toggling the statusbar icon
    mainWidget->setProgressDialogVisible( false );
  }
}

}

#include "progressdialog.moc"
<commit_msg>Add a tooltip for the cancel button.<commit_after>/** -*- c++ -*-
 * progressdialog.cpp
 *
 *  Copyright (c) 2004 Till Adam <adam@kde.org>,
 *                     David Faure <faure@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *  In addition, as a special exception, the copyright holders give
 *  permission to link the code of this program with any edition of
 *  the Qt library by Trolltech AS, Norway (or with modified versions
 *  of Qt that use the same license as Qt), and distribute linked
 *  combinations including the two.  You must obey the GNU General
 *  Public License in all respects for all of the code used other than
 *  Qt.  If you modify this file, you may extend this exception to
 *  your version of the file, but you are not obligated to do so.  If
 *  you do not wish to do so, delete this exception statement from
 *  your version.
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <qapplication.h>
#include <qlayout.h>
#include <qprogressbar.h>
#include <qtimer.h>
#include <qheader.h>
#include <qobject.h>
#include <qscrollview.h>
#include <qtoolbutton.h>
#include <qpushbutton.h>
#include <qvbox.h>
#include <qtooltip.h>

#include <klocale.h>
#include <kdialog.h>
#include <kstdguiitem.h>
#include <kiconloader.h>
#include <kdebug.h>

#include "progressdialog.h"
#include "progressmanager.h"
#include "ssllabel.h"
#include "kmmainwidget.h"

using KMail::ProgressItem;
using KMail::ProgressManager;

namespace KMail {

class TransactionItem;

TransactionItemView::TransactionItemView( QWidget * parent,
                                          const char * name,
                                          WFlags f )
    : QScrollView( parent, name, f ) {
  setFrameStyle( NoFrame );
  mBigBox = new QVBox( viewport() );
  mBigBox->setSpacing( 5 );
  addChild( mBigBox );
  setResizePolicy( QScrollView::AutoOneFit ); // Fit so that the box expands horizontally
}

TransactionItem* TransactionItemView::addTransactionItem( ProgressItem* item, bool first )
{
   TransactionItem *ti = new TransactionItem( mBigBox, item, first );
   ti->show();
   return ti;
}

void TransactionItemView::resizeContents( int w, int h )
{
  //kdDebug(5006) << k_funcinfo << w << "," << h << endl;
  QScrollView::resizeContents( w, h );
  // Tell the layout in the parent (progressdialog) that our size changed
  updateGeometry();
  // Resize the parent (progressdialog) - this works but resize horizontally too often
  //parentWidget()->adjustSize();

  QApplication::sendPostedEvents( 0, QEvent::ChildInserted );
  QApplication::sendPostedEvents( 0, QEvent::LayoutHint );
  QSize sz = parentWidget()->sizeHint();
  int currentWidth = parentWidget()->width();
  // Don't resize to sz.width() every time when it only reduces a little bit
  if ( currentWidth < sz.width() || currentWidth > sz.width() + 100 )
    currentWidth = sz.width();
  parentWidget()->resize( currentWidth, sz.height() );
}

QSize TransactionItemView::sizeHint() const
{
  return minimumSizeHint();
}

QSize TransactionItemView::minimumSizeHint() const
{
  int f = 2 * frameWidth();
  // Make room for a vertical scrollbar in all cases, to avoid a horizontal one
  int vsbExt = verticalScrollBar()->sizeHint().width();
  int minw = topLevelWidget()->width() / 3;
  int maxh = topLevelWidget()->height() / 2;
  QSize sz( mBigBox->minimumSizeHint() );
  sz.setWidth( QMAX( sz.width(), minw ) + f + vsbExt );
  sz.setHeight( QMIN( sz.height(), maxh ) + f );
  return sz;
}

void TransactionItemView::slotLayoutFirstItem()
{
  /*
     The below relies on some details in Qt's behaviour regarding deleting
     objects. This slot is called from the destroyed signal of an item just
     going away. That item is at that point still in the  list of chilren, but
     since the vtable is already gone, it will have type QObject. The first
     one with both the right name and the right class therefor is what will
     be the first item very shortly. That's the one we want to remove the
     hline for.
  */
  QObject *o = mBigBox->child( "TransactionItem", "KMail::TransactionItem" );
  TransactionItem *ti = dynamic_cast<TransactionItem*>( o );
  if ( ti ) {
    ti->hideHLine();
  }
}

// ----------------------------------------------------------------------------

TransactionItem::TransactionItem( QWidget* parent,
                                  ProgressItem *item, bool first )
  : QVBox( parent, "TransactionItem" ), mCancelButton( 0 ), mItem( item )

{
  setSpacing( 2 );
  setMargin( 2 );
  setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );

  mFrame = new QFrame( this );
  mFrame->setFrameShape( QFrame::HLine );
  mFrame->setFrameShadow( QFrame::Raised );
  mFrame->show();
  setStretchFactor( mFrame, 3 );

  QHBox *h = new QHBox( this );
  h->setSpacing( 5 );

  mItemLabel = new QLabel( item->label(), h );
  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );

  if ( item->canBeCanceled() ) {
    mCancelButton = new QPushButton( SmallIcon( "cancel" ), QString::null, h );
    QToolTip::add( mCancelButton, i18n("Cancel this operation.") );
    connect ( mCancelButton, SIGNAL( clicked() ),
              this, SLOT( slotItemCanceled() ));
  }
  mProgress = new QProgressBar( 100, h );
  mProgress->setProgress( item->progress() );

  h = new QHBox( this );
  h->setSpacing( 5 );
  h->setSizePolicy( QSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed ) );
  mSSLLabel = new SSLLabel( h );
  mSSLLabel->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
  mItemStatus =  new QLabel( item->status(), h );
  setCrypto( item->usesCrypto() );
  if( first ) hideHLine();
}

TransactionItem::~TransactionItem()
{
}

void TransactionItem::hideHLine()
{
    mFrame->hide();
}

void TransactionItem::setProgress( int progress )
{
  mProgress->setProgress( progress );
}

void TransactionItem::setLabel( const QString& label )
{
  mItemLabel->setText( label );
}

void TransactionItem::setStatus( const QString& status )
{
  mItemStatus->setText( status );
}

void TransactionItem::setCrypto( bool on )
{
  if (on)
    mSSLLabel->setEncrypted( true );
  else
    mSSLLabel->setEncrypted( false );

  mSSLLabel->setState( mSSLLabel->lastState() );
}

void TransactionItem::slotItemCanceled()
{
  if ( mItem )
    mItem->cancel();
}

void TransactionItem::addSubTransaction( ProgressItem* /*item*/ )
{

}

// ---------------------------------------------------------------------------

ProgressDialog::ProgressDialog( QWidget* alignWidget, KMMainWidget* mainWidget, const char* name )
    : OverlayWidget( alignWidget, mainWidget, name )
{
    setFrameStyle( QFrame::Panel | QFrame::Sunken ); // QFrame
    setSpacing( 0 ); // QHBox
    setMargin( 1 );

    mScrollView = new TransactionItemView( this, "ProgressScrollView" );

    QVBox* rightBox = new QVBox( this );
    QToolButton* pbClose = new QToolButton( rightBox );
    pbClose->setAutoRaise(true);
    pbClose->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
    pbClose->setFixedSize( 16, 16 );
    pbClose->setIconSet( KGlobal::iconLoader()->loadIconSet( "fileclose", KIcon::Small, 14 ) );
    connect(pbClose, SIGNAL(clicked()), this, SLOT(close()));
    QWidget* spacer = new QWidget( rightBox ); // don't let the close button take up all the height
    rightBox->setStretchFactor( spacer, 100 );

    /*
     * Get the singleton ProgressManager item which will inform us of
     * appearing and vanishing items.
     */
    ProgressManager *pm = ProgressManager::instance();
    connect ( pm, SIGNAL( progressItemAdded( ProgressItem* ) ),
              this, SLOT( slotTransactionAdded( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemCompleted( ProgressItem* ) ),
              this, SLOT( slotTransactionCompleted( ProgressItem* ) ) );
    connect ( pm, SIGNAL( progressItemProgress( ProgressItem*, unsigned int ) ),
              this, SLOT( slotTransactionProgress( ProgressItem*, unsigned int ) ) );
    connect ( pm, SIGNAL( progressItemStatus( ProgressItem*, const QString& ) ),
              this, SLOT( slotTransactionStatus( ProgressItem*, const QString& ) ) );
    connect ( pm, SIGNAL( progressItemLabel( ProgressItem*, const QString& ) ),
              this, SLOT( slotTransactionLabel( ProgressItem*, const QString& ) ) );
    connect ( pm, SIGNAL( progressItemUsesCrypto( ProgressItem*, bool ) ),
              this, SLOT( slotTransactionUsesCrypto( ProgressItem*, bool ) ) );
}

void ProgressDialog::closeEvent( QCloseEvent* e )
{
  e->accept();
  hide();
}

/*
 *  Destructor
 */
ProgressDialog::~ProgressDialog()
{
    // no need to delete child widgets.
}

void ProgressDialog::slotTransactionAdded( ProgressItem *item )
{
   TransactionItem *parent = 0;
   if ( item->parent() ) {
     if ( mTransactionsToListviewItems.contains( item->parent() ) ) {
       parent = mTransactionsToListviewItems[ item->parent() ];
       parent->addSubTransaction( item );
     }
   } else {
     TransactionItem *ti = mScrollView->addTransactionItem( item, mTransactionsToListviewItems.empty() );
     if ( ti )
       mTransactionsToListviewItems.replace( item, ti );
   }
}

void ProgressDialog::slotTransactionCompleted( ProgressItem *item )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     mTransactionsToListviewItems.remove( item );
     ti->setItemComplete();
     QTimer::singleShot( 5000, ti, SLOT( deleteLater() ) );
     // see the slot for comments as to why that works
     connect ( ti, SIGNAL( destroyed() ),
               mScrollView, SLOT( slotLayoutFirstItem() ) );
   }
   // This was the last item, hide.
   if ( mTransactionsToListviewItems.empty() )
     QTimer::singleShot( 5000, this, SLOT( slotHide() ) );
}

void ProgressDialog::slotTransactionCanceled( ProgressItem* )
{
}

void ProgressDialog::slotTransactionProgress( ProgressItem *item,
                                              unsigned int progress )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setProgress( progress );
   }
}

void ProgressDialog::slotTransactionStatus( ProgressItem *item,
                                            const QString& status )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setStatus( status );
   }
}

void ProgressDialog::slotTransactionLabel( ProgressItem *item,
                                           const QString& label )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setLabel( label );
   }
}

void ProgressDialog::slotTransactionUsesCrypto( ProgressItem *item,
                                                bool value )
{
   if ( mTransactionsToListviewItems.contains( item ) ) {
     TransactionItem *ti = mTransactionsToListviewItems[ item ];
     ti->setCrypto( value );
   }
}

void ProgressDialog::slotHide()
{
  // check if a new item showed up since we started the timer. If not, hide
  if ( mTransactionsToListviewItems.isEmpty() ) {
    // [save a member var by simply getting the parent mainwidget from qwidget]
    KMMainWidget* mainWidget = ::qt_cast<KMMainWidget *>( parentWidget() );
    // not only hide(), but also toggling the statusbar icon
    mainWidget->setProgressDialogVisible( false );
  }
}

}

#include "progressdialog.moc"
<|endoftext|>