<commit_before>/* The MIT License

   Copyright (c) 2014 Adrian Tan <atks@umich.edu>

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

#include "gencode.h"

class GTFRecord : public Interval
{
    public:
    std::string gene;
    std::string feature;
    std::string chrom;
    char strand;
    int32_t frame;
    int32_t exonNo;
    bool fivePrimeConservedEssentialSpliceSite;
    bool threePrimeConservedEssentialSpliceSite;
    bool containsStartCodon;
    bool containsStopCodon;
    uint32_t level;
    std::string attrib;

    GTFRecord(std::string& _chrom, uint32_t _start, uint32_t _end, char _strand,
              std::string& _gene, std::string& _feature, int32_t _frame, int32_t _exonNo,
              bool _fivePrimeConservedEssentialSpliceSite, bool _threePrimeConservedEssentialSpliceSite,
              bool _containsStartCodon, bool _containsStopCodon,
              uint32_t _level, std::string& _attrib)
    {
        chrom = _chrom;
        start = _start;
        end = _end;
        strand = _strand;
        gene = _gene;
        feature = _feature;
        frame = _frame;
        exonNo = _exonNo;
        fivePrimeConservedEssentialSpliceSite = _fivePrimeConservedEssentialSpliceSite;
        threePrimeConservedEssentialSpliceSite = _threePrimeConservedEssentialSpliceSite;
        containsStartCodon = _containsStartCodon;
        containsStopCodon = _containsStopCodon;
        level = _level;
        attrib = _attrib;
    };

    void print()
    {
        std::cerr << "chrom   : " << chrom << "\n";
        std::cerr << "[" << start << "," << end << "]\n";
        std::cerr << "strand                    : " << strand << "\n";
        std::cerr << "address                   : " << this << "\n";
        std::cerr << "gene                      : " << gene << "\n";
        std::cerr << "feature                   : " << feature << "\n";
        std::cerr << "frame                     : " << frame << "\n";
        std::cerr << "exon number               : " << exonNo << "\n";
        std::cerr << "5' conserved splice site  : " << fivePrimeConservedEssentialSpliceSite << "\n";
        std::cerr << "3' conserved splice site  : " << threePrimeConservedEssentialSpliceSite << "\n";
        std::cerr << "contains start codon      : " << containsStartCodon << "\n";
        std::cerr << "contains stop codon       : " << containsStopCodon << "\n";
        std::cerr << "level                     : " << level << "\n";
        std::cerr << "attrib                    : " << attrib << "\n";
    };

    private:
};

class GENCODE
{
    public:

    /**
     * Constructs and initialized a GENCODE objet.
     */
    GENCODE()
    {
        std::string line;
        std::vector<std::string> fields;
        std::vector<std::string> alleles;

        std::clog << "Populating GENCODE tree ... \n";

        std::vector<GTFRecord*> exons;
        std::vector<Interval*> intervals;
        uint32_t noRecords = 0;

        //for gencode records
        uint32_t noConservedSpliced = 0;
        uint32_t noUnconservedSpliced = 0;

//          std::stringstream region;
//      kstring_t s;
//        s.s = 0; s.l = s.m = 0;
//        for (int32_t i = 0; i < nseqs; ++i)
//      {
//            //choose records from chromosome i
//          region.str("");
//          region << "chr" << seqnames[i] ;
//          if (!(iter = tbx_itr_querys(tbx, region.str().c_str())))
//          {
//              continue;
//          }
//
//          region << "processing\n" ;
//
//          while (tbx_itr_next(gffgz, tbx, iter, &s) >= 0)
//            {
//
//                //populate interval trees with reference sets
//                //gene transfer format
//                //1   chr1
//                //2   HAVANA - source
//                //3   exon   - feature
//                //4   13221  - start
//                //5   14409  - end
//                //6   .      - score
//                //7   +      - strand
//                //8   .      - frame
//                //9   gene_id "ENSG - attribute
//
//                //std::cerr << s.s << "\n";
//
//                std::string line = std::string(s.s);
//
//              if(line.at(0)!='#')
//              {
//                  split(fields, '\t', line, 9);
//                    std::string chrom = fields[0];
//
//                  if (boost::regex_match(chrom, regexResult, regex))
//                  {
//                      chrom = regexResult[1];
//                  }
//
//                    std::string feature = fields[2];
//
//                    if (feature!="exon" && feature!="CDS" && feature!="start_codon" && feature!="stop_codon")
//                    {
//                        continue;
//                    }
//
//                    //create tree for chromosome
//                    if(!exists(GENCODE, chrom))
//                    {
//                        std::clog << "Creating tree for chromosome " << chrom << "\n";
//                        GENCODE[chrom] = new IntervalTree();
//                    }
//
//                    //process fields
//                    std::map<std::string, std::string> attrib_map;
//                    splitGTFAttributeFields(attrib_map, fields[8]);
//
////                    std::cerr << line << "\n";
////                    for (std::map<std::string, std::string>::iterator i=attrib_map.begin(); i!=attrib_map.end() ; ++i)
////                    {
////                        std::cerr << i->first << " => " << i->second << "\n";
////                    }
//                    //exit(1);
//                  uint32_t start = boost::lexical_cast<int32_t>(fields[3]);
//                  uint32_t end = boost::lexical_cast<int32_t>(fields[4]);
//                  char strand = fields[6].at(0);
//                    std::string gene = attrib_map["gene_id"];
//                  int32_t frame = fields[7]=="." ? -1 : boost::lexical_cast<int32_t>(fields[7]);
//                    int32_t exonNo = !existsInMap(attrib_map, "exon_number") ? -1 : boost::lexical_cast<int32_t>(attrib_map["exon_number"]);
//                  uint32_t level = boost::lexical_cast<uint32_t>(attrib_map["level"]);
//                  bool fivePrimeConservedEssentialSpliceSite = false;
//                  bool threePrimeConservedEssentialSpliceSite = false;
//                  bool containsStartCodon = false;
//                  bool containsStopCodon = false;
//                  std::string attrib = fields[8];
//
//                  if (feature=="exon")
//                  {
//                      if (attrib_map["gene_type"]!="protein_coding")
//                        {
//                          continue;
//                      }
//
//                        std::string dnc1;
//                        std::string dnc2;
//                        uint32_t chromNo = ref_seq->getChromosome(chrom=="M"?"MT":chrom.c_str());
//
//                        if(strand=='+')
//                        {
//                            ref_seq->getString(dnc1, chromNo, (genomeIndex_t) start-2, 2);
//                            ref_seq->getString(dnc2, chromNo, (genomeIndex_t) end+1, 2);
//
//                            if (dnc1=="AG")
//                            {
//                                fivePrimeConservedEssentialSpliceSite = true;
//                            }
//
//                            if (dnc2=="GT")
//                            {
//                                threePrimeConservedEssentialSpliceSite = true;
//                            }
//                        }
//
//                        if(strand=='-')
//                        {
//                            ref_seq->getString(dnc2, chromNo, (genomeIndex_t) start-2, 2);
//                            ref_seq->getString(dnc1, chromNo, (genomeIndex_t) end+1, 2);
//
//                            if (dnc1=="CT")
//                            {
//                                fivePrimeConservedEssentialSpliceSite = true;
//                            }
//
//                            if (dnc2=="AC")
//                            {
//                                threePrimeConservedEssentialSpliceSite = true;
//                            }
//                        }
//                  }
//
//                    if (feature=="stop_codon")
//                    {
//                        if (exists(GENCODE, chrom))
//                        {
//                            GENCODE[chrom]->search(start, end, intervals);
//                        }
//
//                        for (uint32_t i=0; i<intervals.size(); ++i)
//                        {
//                            GTFRecord* record = (GTFRecord*)intervals[i];
//                            if (record->feature == "exon" && record->gene == gene)
//                            {
//                                record->containsStopCodon = true;
//                            }
//                        }
//                    }
//
//                    if (feature=="start_codon")
//                    {
//                        if (exists(GENCODE, chrom))
//                        {
//                            GENCODE[chrom]->search(start, end, intervals);
//                        }
//
//                        for (uint32_t i=0; i<intervals.size(); ++i)
//                        {
//                            GTFRecord* record = (GTFRecord*)intervals[i];
//                            if (record->feature == "exon" && record->gene == gene)
//                            {
//                                record->containsStartCodon = true;
//                            }
//                        }
//                    }
//
//                    GTFRecord* gtfRecord = new GTFRecord(chrom, start, end, strand,
//                                                         gene, feature, frame, exonNo,
//                                                         fivePrimeConservedEssentialSpliceSite, threePrimeConservedEssentialSpliceSite,
//                                                         containsStartCodon, containsStopCodon,
//                                                         level, attrib);
//
//                    //std::cerr << "chromosome " << chrom << "\n";
//                    GENCODE[chrom]->insert(gtfRecord);
//        //
//                    ++noRecords;
//                }
//
//
//            }
//
//        }
//
//
//
//      std::clog << " ... completed\n";
//      if (GENCODE.size()==0)
//      {
//          std::cerr << "No reference GENCODE features!\n";
//            exit(1);
//      }
//
//      std::cerr << "start validation\n";
//        GENCODE["X"]->validate();
//        //G = GENCODE["chr20"];
//        //G->validate();
////        std::cerr << "end validation\n";
////        std::cerr << "height : " << GENCODE["X"]->height << "\n";
////        std::cerr << "size : " << GENCODE["X"]->size() << "\n";
////        std::cerr << "height : " << G->height << "\n";
////        std::cerr << "size : " << G->size() << "\n";
    }
};

/**
Splits a line into a map - PERL style
*/
void splitGTFAttributeFields(std::map<std::string, std::string>& map, std::string& str)
{
    map.clear();
    const char* tempStr = str.c_str();
    int32_t i=0, lastIndex = str.size()-1;
    std::string key;
    std::string val;
    std::stringstream token;

    if (lastIndex<0) return;

    while (i<=lastIndex)
    {
        //read next character
        if(tempStr[i]!=';' && tempStr[i]!=' ')
        {
            token << tempStr[i];
        }

        //store key-value pair
        if (i==lastIndex || (tempStr[i]==';' && tempStr[i+1]==' '))
        {
            val = token.str();
            if (val.at(0)=='"')
            {
                val = token.str();
                val = val.substr(1,val.size()-2);
            }
            map[key] = val;

            token.str("");
            key.clear();

            if (i!=lastIndex)
                ++i;
        }

        //store key
        if (tempStr[i]==' ')
        {
            key = token.str();
            token.str("");
        }

        ++i;
    }
};

<commit_msg>minor changes<commit_after>/* The MIT License

   Copyright (c) 2014 Adrian Tan <atks@umich.edu>

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

#include "gencode.h"

class GTFRecord : public Interval
{
    public:
    std::string gene;
    std::string feature;
    std::string chrom;
    char strand;
    int32_t frame;
    int32_t exonNo;
    bool fivePrimeConservedEssentialSpliceSite;
    bool threePrimeConservedEssentialSpliceSite;
    bool containsStartCodon;
    bool containsStopCodon;
    uint32_t level;
    std::string attrib;

    GTFRecord(std::string& _chrom, uint32_t _start, uint32_t _end, char _strand,
              std::string& _gene, std::string& _feature, int32_t _frame, int32_t _exonNo,
              bool _fivePrimeConservedEssentialSpliceSite, bool _threePrimeConservedEssentialSpliceSite,
              bool _containsStartCodon, bool _containsStopCodon,
              uint32_t _level, std::string& _attrib)
    {
        chrom = _chrom;
        start = _start;
        end = _end;
        strand = _strand;
        gene = _gene;
        feature = _feature;
        frame = _frame;
        exonNo = _exonNo;
        fivePrimeConservedEssentialSpliceSite = _fivePrimeConservedEssentialSpliceSite;
        threePrimeConservedEssentialSpliceSite = _threePrimeConservedEssentialSpliceSite;
        containsStartCodon = _containsStartCodon;
        containsStopCodon = _containsStopCodon;
        level = _level;
        attrib = _attrib;
    };

    void print()
    {
        std::cerr << "chrom   : " << chrom << "\n";
        std::cerr << "[" << start << "," << end << "]\n";
        std::cerr << "strand                    : " << strand << "\n";
        std::cerr << "address                   : " << this << "\n";
        std::cerr << "gene                      : " << gene << "\n";
        std::cerr << "feature                   : " << feature << "\n";
        std::cerr << "frame                     : " << frame << "\n";
        std::cerr << "exon number               : " << exonNo << "\n";
        std::cerr << "5' conserved splice site  : " << fivePrimeConservedEssentialSpliceSite << "\n";
        std::cerr << "3' conserved splice site  : " << threePrimeConservedEssentialSpliceSite << "\n";
        std::cerr << "contains start codon      : " << containsStartCodon << "\n";
        std::cerr << "contains stop codon       : " << containsStopCodon << "\n";
        std::cerr << "level                     : " << level << "\n";
        std::cerr << "attrib                    : " << attrib << "\n";
    };

    private:
};

class GENCODE
{
    public:
    char* gencode_gtf_file;

    /**
     * Constructs and initialized a GENCODE objet.
     */
    GENCODE(char* gencode_gtf_file)
    {

        std::string line;
        std::vector<std::string> fields;
        std::vector<std::string> alleles;

        std::vector<GTFRecord*> exons;
        std::vector<Interval*> intervals;
        uint32_t noRecords = 0;

        //for gencode records
        uint32_t noConservedSpliced = 0;
        uint32_t noUnconservedSpliced = 0;

//          std::stringstream region;
//      kstring_t s;
//        s.s = 0; s.l = s.m = 0;
//        for (int32_t i = 0; i < nseqs; ++i)
//      {
//            //choose records from chromosome i
//          region.str("");
//          region << "chr" << seqnames[i] ;
//          if (!(iter = tbx_itr_querys(tbx, region.str().c_str())))
//          {
//              continue;
//          }
//
//          region << "processing\n" ;
//
//          while (tbx_itr_next(gffgz, tbx, iter, &s) >= 0)
//            {
//
//                //populate interval trees with reference sets
//                //gene transfer format
//                //1   chr1
//                //2   HAVANA - source
//                //3   exon   - feature
//                //4   13221  - start
//                //5   14409  - end
//                //6   .      - score
//                //7   +      - strand
//                //8   .      - frame
//                //9   gene_id "ENSG - attribute
//
//                //std::cerr << s.s << "\n";
//
//                std::string line = std::string(s.s);
//
//              if(line.at(0)!='#')
//              {
//                  split(fields, '\t', line, 9);
//                    std::string chrom = fields[0];
//
//                  if (boost::regex_match(chrom, regexResult, regex))
//                  {
//                      chrom = regexResult[1];
//                  }
//
//                    std::string feature = fields[2];
//
//                    if (feature!="exon" && feature!="CDS" && feature!="start_codon" && feature!="stop_codon")
//                    {
//                        continue;
//                    }
//
//                    //create tree for chromosome
//                    if(!exists(GENCODE, chrom))
//                    {
//                        std::clog << "Creating tree for chromosome " << chrom << "\n";
//                        GENCODE[chrom] = new IntervalTree();
//                    }
//
//                    //process fields
//                    std::map<std::string, std::string> attrib_map;
//                    splitGTFAttributeFields(attrib_map, fields[8]);
//
////                    std::cerr << line << "\n";
////                    for (std::map<std::string, std::string>::iterator i=attrib_map.begin(); i!=attrib_map.end() ; ++i)
////                    {
////                        std::cerr << i->first << " => " << i->second << "\n";
////                    }
//                    //exit(1);
//                  uint32_t start = boost::lexical_cast<int32_t>(fields[3]);
//                  uint32_t end = boost::lexical_cast<int32_t>(fields[4]);
//                  char strand = fields[6].at(0);
//                    std::string gene = attrib_map["gene_id"];
//                  int32_t frame = fields[7]=="." ? -1 : boost::lexical_cast<int32_t>(fields[7]);
//                    int32_t exonNo = !existsInMap(attrib_map, "exon_number") ? -1 : boost::lexical_cast<int32_t>(attrib_map["exon_number"]);
//                  uint32_t level = boost::lexical_cast<uint32_t>(attrib_map["level"]);
//                  bool fivePrimeConservedEssentialSpliceSite = false;
//                  bool threePrimeConservedEssentialSpliceSite = false;
//                  bool containsStartCodon = false;
//                  bool containsStopCodon = false;
//                  std::string attrib = fields[8];
//
//                  if (feature=="exon")
//                  {
//                      if (attrib_map["gene_type"]!="protein_coding")
//                        {
//                          continue;
//                      }
//
//                        std::string dnc1;
//                        std::string dnc2;
//                        uint32_t chromNo = ref_seq->getChromosome(chrom=="M"?"MT":chrom.c_str());
//
//                        if(strand=='+')
//                        {
//                            ref_seq->getString(dnc1, chromNo, (genomeIndex_t) start-2, 2);
//                            ref_seq->getString(dnc2, chromNo, (genomeIndex_t) end+1, 2);
//
//                            if (dnc1=="AG")
//                            {
//                                fivePrimeConservedEssentialSpliceSite = true;
//                            }
//
//                            if (dnc2=="GT")
//                            {
//                                threePrimeConservedEssentialSpliceSite = true;
//                            }
//                        }
//
//                        if(strand=='-')
//                        {
//                            ref_seq->getString(dnc2, chromNo, (genomeIndex_t) start-2, 2);
//                            ref_seq->getString(dnc1, chromNo, (genomeIndex_t) end+1, 2);
//
//                            if (dnc1=="CT")
//                            {
//                                fivePrimeConservedEssentialSpliceSite = true;
//                            }
//
//                            if (dnc2=="AC")
//                            {
//                                threePrimeConservedEssentialSpliceSite = true;
//                            }
//                        }
//                  }
//
//                    if (feature=="stop_codon")
//                    {
//                        if (exists(GENCODE, chrom))
//                        {
//                            GENCODE[chrom]->search(start, end, intervals);
//                        }
//
//                        for (uint32_t i=0; i<intervals.size(); ++i)
//                        {
//                            GTFRecord* record = (GTFRecord*)intervals[i];
//                            if (record->feature == "exon" && record->gene == gene)
//                            {
//                                record->containsStopCodon = true;
//                            }
//                        }
//                    }
//
//                    if (feature=="start_codon")
//                    {
//                        if (exists(GENCODE, chrom))
//                        {
//                            GENCODE[chrom]->search(start, end, intervals);
//                        }
//
//                        for (uint32_t i=0; i<intervals.size(); ++i)
//                        {
//                            GTFRecord* record = (GTFRecord*)intervals[i];
//                            if (record->feature == "exon" && record->gene == gene)
//                            {
//                                record->containsStartCodon = true;
//                            }
//                        }
//                    }
//
//                    GTFRecord* gtfRecord = new GTFRecord(chrom, start, end, strand,
//                                                         gene, feature, frame, exonNo,
//                                                         fivePrimeConservedEssentialSpliceSite, threePrimeConservedEssentialSpliceSite,
//                                                         containsStartCodon, containsStopCodon,
//                                                         level, attrib);
//
//                    //std::cerr << "chromosome " << chrom << "\n";
//                    GENCODE[chrom]->insert(gtfRecord);
//        //
//                    ++noRecords;
//                }
//
//
//            }
//
//        }
//
//
//
//      std::clog << " ... completed\n";
//      if (GENCODE.size()==0)
//      {
//          std::cerr << "No reference GENCODE features!\n";
//            exit(1);
//      }
//
//      std::cerr << "start validation\n";
//        GENCODE["X"]->validate();
//        //G = GENCODE["chr20"];
//        //G->validate();
////        std::cerr << "end validation\n";
////        std::cerr << "height : " << GENCODE["X"]->height << "\n";
////        std::cerr << "size : " << GENCODE["X"]->size() << "\n";
////        std::cerr << "height : " << G->height << "\n";
////        std::cerr << "size : " << G->size() << "\n";
    }
};

/**
Splits a line into a map - PERL style
*/
void splitGTFAttributeFields(std::map<std::string, std::string>& map, std::string& str)
{
    map.clear();
    const char* tempStr = str.c_str();
    int32_t i=0, lastIndex = str.size()-1;
    std::string key;
    std::string val;
    std::stringstream token;

    if (lastIndex<0) return;

    while (i<=lastIndex)
    {
        //read next character
        if(tempStr[i]!=';' && tempStr[i]!=' ')
        {
            token << tempStr[i];
        }

        //store key-value pair
        if (i==lastIndex || (tempStr[i]==';' && tempStr[i+1]==' '))
        {
            val = token.str();
            if (val.at(0)=='"')
            {
                val = token.str();
                val = val.substr(1,val.size()-2);
            }
            map[key] = val;

            token.str("");
            key.clear();

            if (i!=lastIndex)
                ++i;
        }

        //store key
        if (tempStr[i]==' ')
        {
            key = token.str();
            token.str("");
        }

        ++i;
    }
};

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>

#include "acmacs-base/argv.hh"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/settings.hh"
#include "acmacs-map-draw/mod-applicator.hh"
#include "acmacs-map-draw/setup-dbs.hh"

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

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    option<size_t>    p1{*this, "p1", dflt{0UL}, desc{"projection number of the first chart"}};
    option<size_t>    p2{*this, "p2", dflt{0UL}, desc{"projection number of the second chart"}};
    option<str_array> settings{*this, 's', desc{"settings.json (multiple -s possible)"}};
    option<double>    threshold{*this, "threshold", dflt{0.1}, desc{"arrow threshold"}};
    option<str>       subset{*this, "subset", dflt{"all"}, desc{"all, antigens, sera"}};
    option<str>       subset_antigens_clade{*this, "subset-antigens-clade", desc{"for antigens from this clade only"}};
    option<bool>      report{*this, "report", desc{"report common antigens/sera"}};
    option<bool>      clade{*this, "clade", desc{"color by clade"}};
    option<str>       viewport{*this, "viewport", dflt{""}, desc{"\"rel\" array of viewport, e.g. 2,2,-4"}};
    option<bool>      open{*this, "open"};

    argument<str>     chart1{*this, arg_name{"chart"}, mandatory};
    argument<str>     chart2{*this, arg_name{"secondary-chart"}};
    argument<str>     pdf{*this, arg_name{"output-pdf"}};
};

int main(int argc, char* const argv[])
{
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        ChartDraw chart_draw(std::make_shared<acmacs::chart::ChartModify>(acmacs::chart::import_from_file(opt.chart1, acmacs::chart::Verify::None, report_time::no)), opt.p1);
        const std::string secondary_chart((!opt.chart2->empty() && !string::ends_with(*opt.chart2, ".pdf")) ? opt.chart2 : opt.chart1);

        auto settings = settings_default();
        settings.update(settings_builtin_mods());
        for (size_t sett_no = 0; sett_no < opt.settings->size(); ++sett_no) {
            settings.update(rjson::parse_file(opt.settings->at(sett_no), rjson::remove_comments::no));
        }

        if (!opt.viewport->empty()) {
            const auto values = acmacs::string::split_into_double(*opt.viewport);
            settings["apply"].append(rjson::object{{"N", "viewport"}, {"rel", rjson::array(values.begin(), values.end())}});
        }
        if (opt.clade) {
            settings["apply"].append("size_reset");
            settings["apply"].append("all_grey");
            settings["apply"].append("egg");
            settings["apply"].append("clades");
            settings["apply"].append("vaccines");
        }

        if (opt.subset_antigens_clade.has_value())
            settings["apply"].append(rjson::object{{"N", "procrustes_arrows"},
                                                   {"chart", secondary_chart},
                                                   {"projection", *opt.p2},
                                                   {"subset_antigens", rjson::object{{"clade", *opt.subset_antigens_clade}}},
                                                   {"threshold", *opt.threshold},
                                                   {"report", *opt.report}});
        else
            settings["apply"].append(
                rjson::object{{"N", "procrustes_arrows"}, {"chart", secondary_chart}, {"projection", *opt.p2}, {"subset", *opt.subset}, {"threshold", *opt.threshold}, {"report", *opt.report}});

        try {
            apply_mods(chart_draw, settings["apply"], settings);
        }
        catch (std::exception& err) {
            throw std::runtime_error{"Cannot apply " + rjson::to_string(settings["apply"]) + ": " + err.what() + "\n settings:\n" + rjson::pretty(settings, rjson::emacs_indent::no) + '\n'};
        }

        chart_draw.calculate_viewport();

        const std::string output_file{!opt.chart2->empty() && string::ends_with(*opt.chart2, ".pdf") ? *opt.chart2 : *opt.pdf};
        acmacs::file::temp temp_file(".pdf");
        const std::string output = output_file.empty() ? static_cast<std::string>(temp_file) : output_file;
        chart_draw.draw(output, 800, report_time::yes);

        if (opt.open || output_file.empty())
            acmacs::quicklook(output, 2);
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>less verbose error reporting<commit_after>#include <iostream>
#include <fstream>
#include <string>

#include "acmacs-base/fmt.hh"
#include "acmacs-base/argv.hh"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/string-split.hh"
#include "acmacs-base/quicklook.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/settings.hh"
#include "acmacs-map-draw/mod-applicator.hh"
#include "acmacs-map-draw/setup-dbs.hh"

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

using namespace acmacs::argv;
struct Options : public argv
{
    Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }

    option<size_t>    p1{*this, "p1", dflt{0UL}, desc{"projection number of the first chart"}};
    option<size_t>    p2{*this, "p2", dflt{0UL}, desc{"projection number of the second chart"}};
    option<str_array> settings{*this, 's', desc{"settings.json (multiple -s possible)"}};
    option<double>    threshold{*this, "threshold", dflt{0.1}, desc{"arrow threshold"}};
    option<str>       subset{*this, "subset", dflt{"all"}, desc{"all, antigens, sera"}};
    option<str>       subset_antigens_clade{*this, "subset-antigens-clade", desc{"for antigens from this clade only"}};
    option<bool>      report{*this, "report", desc{"report common antigens/sera"}};
    option<bool>      clade{*this, "clade", desc{"color by clade"}};
    option<str>       viewport{*this, "viewport", dflt{""}, desc{"\"rel\" array of viewport, e.g. 2,2,-4"}};
    option<bool>      open{*this, "open"};

    argument<str>     chart1{*this, arg_name{"chart"}, mandatory};
    argument<str>     chart2{*this, arg_name{"secondary-chart"}};
    argument<str>     pdf{*this, arg_name{"output-pdf"}};
};

int main(int argc, char* const argv[])
{
    int exit_code = 0;
    try {
        Options opt(argc, argv);
        ChartDraw chart_draw(std::make_shared<acmacs::chart::ChartModify>(acmacs::chart::import_from_file(opt.chart1, acmacs::chart::Verify::None, report_time::no)), opt.p1);
        const std::string secondary_chart((!opt.chart2->empty() && !string::ends_with(*opt.chart2, ".pdf")) ? opt.chart2 : opt.chart1);

        auto settings = settings_default();
        settings.update(settings_builtin_mods());
        for (size_t sett_no = 0; sett_no < opt.settings->size(); ++sett_no) {
            settings.update(rjson::parse_file(opt.settings->at(sett_no), rjson::remove_comments::no));
        }

        if (!opt.viewport->empty()) {
            const auto values = acmacs::string::split_into_double(*opt.viewport);
            settings["apply"].append(rjson::object{{"N", "viewport"}, {"rel", rjson::array(values.begin(), values.end())}});
        }
        if (opt.clade) {
            settings["apply"].append("size_reset");
            settings["apply"].append("all_grey");
            settings["apply"].append("egg");
            settings["apply"].append("clades");
            settings["apply"].append("vaccines");
        }

        if (opt.subset_antigens_clade.has_value())
            settings["apply"].append(rjson::object{{"N", "procrustes_arrows"},
                                                   {"chart", secondary_chart},
                                                   {"projection", *opt.p2},
                                                   {"subset_antigens", rjson::object{{"clade", *opt.subset_antigens_clade}}},
                                                   {"threshold", *opt.threshold},
                                                   {"report", *opt.report}});
        else
            settings["apply"].append(
                rjson::object{{"N", "procrustes_arrows"}, {"chart", secondary_chart}, {"projection", *opt.p2}, {"subset", *opt.subset}, {"threshold", *opt.threshold}, {"report", *opt.report}});

        try {
            apply_mods(chart_draw, settings["apply"], settings);
        }
        catch (std::exception& err) {
            // throw std::runtime_error{"Cannot apply " + rjson::to_string(settings["apply"]) + ": " + err.what() + "\n settings:\n" + rjson::pretty(settings, rjson::emacs_indent::no) + '\n'};
            throw std::runtime_error{fmt::format("{}", err)};
        }

        chart_draw.calculate_viewport();

        const std::string output_file{!opt.chart2->empty() && string::ends_with(*opt.chart2, ".pdf") ? *opt.chart2 : *opt.pdf};
        acmacs::file::temp temp_file(".pdf");
        const std::string output = output_file.empty() ? static_cast<std::string>(temp_file) : output_file;
        chart_draw.draw(output, 800, report_time::yes);

        if (opt.open || output_file.empty())
            acmacs::quicklook(output, 2);
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        exit_code = 2;
    }
    return exit_code;
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/**
 * @file   Survivor3v1.cpp
 *
 * @author F. Narenji, O. Richit, H. Morales, V. Pelegrin
 *
 * @date   12/01/2014
 *
 * @brief  Survivor 3v1 game mode
 *
 **/
#include <algorithm>
#include <sstream>

#include "Survivor3v1.h"
#include "Helpers.h"

#include "../Game.h"
#include "../Menu.h"

using namespace std;

namespace
{
	nsGame::CPositions ObstaclesPositions;
    array<unsigned, 4> AlonePlayerTurnCounters;

    int AlonePlayer = -1;
} // namespace

void nsSurvivor3v1::GetSize (CPosition& Size)
{
    nsMenu::Clear ();

    nsMenu::AddItem ("Small map", [&Size] () { Size = { 5, 10 }; });
    nsMenu::AddItem ("Medium map", [&Size] () { Size = { 10, 20 }; });
    nsMenu::AddItem ("Great map", [&Size] () { Size = { 20, 40 }; });

    nsMenu::Run ();
} // GetSize

void nsSurvivor3v1::MovePlayer (const CMatrix& Matrix, CPosition& PlayerPosition, const CPosition& MatrixSize, const PlayerMovesY MoveY, const PlayerMovesX MoveX)
{
    nsHelpers::MovePlayer (Matrix, PlayerPosition, MatrixSize, MoveY, MoveX);
} // MovePlayer

void nsSurvivor3v1::ValidatePlayerPositions (const CMatrix& Matrix, const CPositions& PlayerPositions, unsigned CurrentPlayer, vector<bool>& PlayerLifeStates)
{
    if (CurrentPlayer == AlonePlayer)
    {
		++AlonePlayerTurnCounters [AlonePlayer];

        for (unsigned i = 0; i < PlayerPositions.size (); ++i)
            if (PlayerPositions [i] == PlayerPositions [CurrentPlayer] && i != CurrentPlayer)
                PlayerLifeStates [CurrentPlayer] = false;
    }
    else
    {
        if (PlayerPositions [CurrentPlayer] == PlayerPositions [AlonePlayer])
            PlayerLifeStates [AlonePlayer] = false;

        if (PlayerLifeStates [CurrentPlayer] && find (ObstaclesPositions.cbegin(), ObstaclesPositions.cend(), PlayerPositions [CurrentPlayer]) == ObstaclesPositions.cend()) // If Position is not obstacle
            ObstaclesPositions.push_back (PlayerPositions [CurrentPlayer]);
        else
            PlayerLifeStates [CurrentPlayer] = false;
    } // else (not current player)

    int Y = PlayerPositions [CurrentPlayer].first, X = PlayerPositions [CurrentPlayer].second;

    bool SurroundedByObstacles = true;
    std::vector<CPosition> PositionsNearby;

    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KStay, PlayerMovesX::KRight));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KStay, PlayerMovesX::KLeft));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KUp,   PlayerMovesX::KRight));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KUp,   PlayerMovesX::KLeft));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KUp,   PlayerMovesX::KStay));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KDown, PlayerMovesX::KRight));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KDown, PlayerMovesX::KLeft));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KDown, PlayerMovesX::KStay));

    for (CPosition Position : PositionsNearby)
        if (Matrix [Position.first] [Position.second] != KTokens [KTokenObstacle])
            SurroundedByObstacles = false;

    if (SurroundedByObstacles)
        PlayerLifeStates [CurrentPlayer] = false;
} // ValidatePlayerPositions

void nsSurvivor3v1::InitializeRound (CPositions& PlayerPositions, const unsigned PlayerCount, const CPosition& MaxSize)
{
    PlayerPositions.resize (PlayerCount);

    PlayerPositions [0] = { 0, MaxSize.second - 1 }; // Top right
    PlayerPositions [1] = { MaxSize.first - 1, 0 }; // Bottom left
    PlayerPositions [2] = { 0, 0 }; // Top left
    PlayerPositions [3] = { MaxSize.first - 1, MaxSize.second - 1 }; // Bottom right

    ++AlonePlayer;

    nsMenu::Clear ();

    std::stringstream Text;
    Text << "The lone player is '" << KTokens [AlonePlayer] << "'.";
    nsMenu::AddItem (Text.str ());

    nsMenu::Run ();

    ObstaclesPositions.clear ();
    nsHelpers::LoadObstaclesFromFile (ObstaclesPositions, MaxSize);

    if (*AlonePlayerTurnCounters.crbegin() != 0) // If each player has played its turn, reset all state if they want to replay the round.
    {
        fill (AlonePlayerTurnCounters.begin (), AlonePlayerTurnCounters.end (), 0);
        AlonePlayer = 0;
    }
} // InitializeRound

void nsSurvivor3v1::BuildMatrix (CMatrix& Matrix, const CPositions& PlayerPositions, const vector<bool>& PlayerLifeStates, const char EmptyToken)
{
    nsHelpers::AddObstaclesAndPlayersToMatrix (Matrix, PlayerPositions, PlayerLifeStates, ObstaclesPositions, EmptyToken);
} // BuildMatrix

bool nsSurvivor3v1::IsGameOver (const vector<bool>& PlayerLifeStates)
{
    unsigned DeadChaserCount = 0;
    for (unsigned i = 0; i < PlayerLifeStates.size (); ++i)
        if (i != AlonePlayer && !PlayerLifeStates [i])
            ++DeadChaserCount;

    return !PlayerLifeStates [AlonePlayer] || DeadChaserCount == 3;
} // IsGameOver

void nsSurvivor3v1::ShowWinScreen (const std::vector< bool >& PlayerLifeStates, const std::vector<char>& Tokens, const vector<unsigned>& TurnCounters)
{
    nsMenu::Clear ();

    vector<pair<unsigned, unsigned>> TurnCounterById;
    for (unsigned i = 0; i < 4; ++i)
        TurnCounterById.push_back (make_pair (i, AlonePlayerTurnCounters [i]));

    std::sort (TurnCounterById.begin (), TurnCounterById.end (),
               [] (pair<unsigned, unsigned> a, pair<unsigned, unsigned> b) { return a.second < b.second; });

    for (pair<unsigned, unsigned> TurnCounter : TurnCounterById)
    {
        stringstream Winner;
        Winner << "Player " << KTokens [TurnCounter.first] << " lasted " << TurnCounter.second << " rounds.";
        nsMenu::AddItem(Winner.str());
    }

    nsMenu::Run (true);
} // ShowWinScreen
<commit_msg>Update Survivor3v1.cpp<commit_after>/**
 * @file   Survivor3v1.cpp
 *
 * @author F. Narenji, O. Richit, H. Morales, V. Pelegrin
 *
 * @date   12/01/2014
 *
 * @brief  Survivor 3v1 game mode
 *
 **/
#include <algorithm>
#include <sstream>
#include <array>

#include "Survivor3v1.h"
#include "Helpers.h"

#include "../Game.h"
#include "../Menu.h"

using namespace std;

namespace
{
    nsGame::CPositions ObstaclesPositions;
    array<unsigned, 4> AlonePlayerTurnCounters;

    int AlonePlayer = -1;
} // namespace

void nsSurvivor3v1::GetSize (CPosition& Size)
{
    nsMenu::Clear ();

    nsMenu::AddItem ("Small map", [&Size] () { Size = { 5, 10 }; });
    nsMenu::AddItem ("Medium map", [&Size] () { Size = { 10, 20 }; });
    nsMenu::AddItem ("Great map", [&Size] () { Size = { 20, 40 }; });

    nsMenu::Run ();
} // GetSize

void nsSurvivor3v1::MovePlayer (const CMatrix& Matrix, CPosition& PlayerPosition, const CPosition& MatrixSize, const PlayerMovesY MoveY, const PlayerMovesX MoveX)
{
    nsHelpers::MovePlayer (Matrix, PlayerPosition, MatrixSize, MoveY, MoveX);
} // MovePlayer

void nsSurvivor3v1::ValidatePlayerPositions (const CMatrix& Matrix, const CPositions& PlayerPositions, unsigned CurrentPlayer, vector<bool>& PlayerLifeStates)
{
    if (CurrentPlayer == AlonePlayer)
    {
		++AlonePlayerTurnCounters [AlonePlayer];

        for (unsigned i = 0; i < PlayerPositions.size (); ++i)
            if (PlayerPositions [i] == PlayerPositions [CurrentPlayer] && i != CurrentPlayer)
                PlayerLifeStates [CurrentPlayer] = false;
    }
    else
    {
        if (PlayerPositions [CurrentPlayer] == PlayerPositions [AlonePlayer])
            PlayerLifeStates [AlonePlayer] = false;

        if (PlayerLifeStates [CurrentPlayer] && find (ObstaclesPositions.cbegin(), ObstaclesPositions.cend(), PlayerPositions [CurrentPlayer]) == ObstaclesPositions.cend()) // If Position is not obstacle
            ObstaclesPositions.push_back (PlayerPositions [CurrentPlayer]);
        else
            PlayerLifeStates [CurrentPlayer] = false;
    } // else (not current player)

    int Y = PlayerPositions [CurrentPlayer].first, X = PlayerPositions [CurrentPlayer].second;

    bool SurroundedByObstacles = true;
    std::vector<CPosition> PositionsNearby;

    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KStay, PlayerMovesX::KRight));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KStay, PlayerMovesX::KLeft));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KUp,   PlayerMovesX::KRight));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KUp,   PlayerMovesX::KLeft));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KUp,   PlayerMovesX::KStay));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KDown, PlayerMovesX::KRight));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KDown, PlayerMovesX::KLeft));
    PositionsNearby.push_back (nsHelpers::MakePosition (Matrix, PlayerPositions [CurrentPlayer], PlayerMovesY::KDown, PlayerMovesX::KStay));

    for (CPosition Position : PositionsNearby)
        if (Matrix [Position.first] [Position.second] != KTokens [KTokenObstacle])
            SurroundedByObstacles = false;

    if (SurroundedByObstacles)
        PlayerLifeStates [CurrentPlayer] = false;
} // ValidatePlayerPositions

void nsSurvivor3v1::InitializeRound (CPositions& PlayerPositions, const unsigned PlayerCount, const CPosition& MaxSize)
{
    PlayerPositions.resize (PlayerCount);

    PlayerPositions [0] = { 0, MaxSize.second - 1 }; // Top right
    PlayerPositions [1] = { MaxSize.first - 1, 0 }; // Bottom left
    PlayerPositions [2] = { 0, 0 }; // Top left
    PlayerPositions [3] = { MaxSize.first - 1, MaxSize.second - 1 }; // Bottom right

    ++AlonePlayer;

    nsMenu::Clear ();

    std::stringstream Text;
    Text << "The lone player is '" << KTokens [AlonePlayer] << "'.";
    nsMenu::AddItem (Text.str ());

    nsMenu::Run ();

    ObstaclesPositions.clear ();
    nsHelpers::LoadObstaclesFromFile (ObstaclesPositions, MaxSize);

    if (*AlonePlayerTurnCounters.crbegin() != 0) // If each player has played its turn, reset all state if they want to replay the round.
    {
        fill (AlonePlayerTurnCounters.begin (), AlonePlayerTurnCounters.end (), 0);
        AlonePlayer = 0;
    }
} // InitializeRound

void nsSurvivor3v1::BuildMatrix (CMatrix& Matrix, const CPositions& PlayerPositions, const vector<bool>& PlayerLifeStates, const char EmptyToken)
{
    nsHelpers::AddObstaclesAndPlayersToMatrix (Matrix, PlayerPositions, PlayerLifeStates, ObstaclesPositions, EmptyToken);
} // BuildMatrix

bool nsSurvivor3v1::IsGameOver (const vector<bool>& PlayerLifeStates)
{
    unsigned DeadChaserCount = 0;
    for (unsigned i = 0; i < PlayerLifeStates.size (); ++i)
        if (i != AlonePlayer && !PlayerLifeStates [i])
            ++DeadChaserCount;

    return !PlayerLifeStates [AlonePlayer] || DeadChaserCount == 3;
} // IsGameOver

void nsSurvivor3v1::ShowWinScreen (const std::vector< bool >& PlayerLifeStates, const std::vector<char>& Tokens, const vector<unsigned>& TurnCounters)
{
    nsMenu::Clear ();

    vector<pair<unsigned, unsigned>> TurnCounterById;
    for (unsigned i = 0; i < 4; ++i)
        TurnCounterById.push_back (make_pair (i, AlonePlayerTurnCounters [i]));

    std::sort (TurnCounterById.begin (), TurnCounterById.end (),
               [] (pair<unsigned, unsigned> a, pair<unsigned, unsigned> b) { return a.second < b.second; });

    for (pair<unsigned, unsigned> TurnCounter : TurnCounterById)
    {
        stringstream Winner;
        Winner << "Player " << KTokens [TurnCounter.first] << " lasted " << TurnCounter.second << " rounds.";
        nsMenu::AddItem(Winner.str());
    }

    nsMenu::Run (true);
} // ShowWinScreen
<|endoftext|>


<commit_before>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <knotifyclient.h>
#include <dcopclient.h>
#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface.h" // to call control center of master kmail

#include "aboutdata.h"

#include "kmstartup.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of message."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'address'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to message."), 0 },
  { "msg <file>",		I18N_NOOP("Read message body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of message."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 },
  { "check",			I18N_NOOP("Only check for new mail."), 0 },
  { "composer",			I18N_NOOP("Only open composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send message to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile.setPath( QString::fromLocal8Bit(args->getOption("msg")) );
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
       if ( !(*it).isEmpty() )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  if (!kernel->firstInstance() || !kapp->isRestored())
    kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  kernel->setFirstInstance(FALSE);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KMail::AboutData about;

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options
  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  // Check that all updates have been run on the config file:
  KMail::checkConfigUpdates();

  // Make sure that the KNotify Daemon is running (this is necessary for people
  // using KMail without KDE)
  KNotifyClient::startDaemon();

  KMail::lockOrDie();

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  kmsetSignalHandler(kmsignalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  kernel->setStartingUp( false ); // Starting up is finished
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  KMail::cleanup();
  return ret;
}
<commit_msg>Forward port of fix for bug 56049: wrong encoding of command line arguments Fix by Choe Hwanjin <hjchoe@hancom.com>.<commit_after>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <knotifyclient.h>
#include <dcopclient.h>
#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface.h" // to call control center of master kmail

#include "aboutdata.h"

#include "kmstartup.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of message."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'address'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to message."), 0 },
  { "msg <file>",		I18N_NOOP("Read message body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of message."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 },
  { "check",			I18N_NOOP("Only check for new mail."), 0 },
  { "composer",			I18N_NOOP("Only open composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send message to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile.setPath( QString::fromLocal8Bit(args->getOption("msg")) );
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
       if ( !(*it).isEmpty() )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->url(i).path();
     else
       to += QString::fromLocal8Bit( args->arg(i) );
     mailto = true;
  }

  args->clear();

  if (!kernel->firstInstance() || !kapp->isRestored())
    kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  kernel->setFirstInstance(FALSE);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KMail::AboutData about;

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options
  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  // Check that all updates have been run on the config file:
  KMail::checkConfigUpdates();

  // Make sure that the KNotify Daemon is running (this is necessary for people
  // using KMail without KDE)
  KNotifyClient::startDaemon();

  KMail::lockOrDie();

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  kmsetSignalHandler(kmsignalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  kernel->setStartingUp( false ); // Starting up is finished
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  KMail::cleanup();
  return ret;
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <functional>

#include "enumerations.hxx"

namespace cl
{
	namespace internal
	{
		using error_handler_ = ::std::function<void(const ::std::string&)>;

		// Struct holding all handler data that can be accessed
		// by global option tags
		struct handler_data
		{
			::std::string m_ApplicationName;
			::std::string m_ApplicationVersion;
			error_mode_ m_ErrorMode{ error_mode_::terminate };
			error_handler_ m_ErrorHandler;
			help_mode_ m_HelpMode{ help_mode_::show_summary };
			summary_style_ m_SummaryStyle{ summary_style_::dots };
			::std::size_t m_SummaryDescWidth{ 28U };
			::std::size_t m_SummaryLabelWidth{ 60U };
		};
	}
}
<commit_msg>Fixed some faulty global data defaults<commit_after>#pragma once

#include <string>
#include <functional>

#include "enumerations.hxx"

namespace cl
{
	namespace internal
	{
		using error_handler_ = ::std::function<void(const ::std::string&)>;

		// Struct holding all handler data that can be accessed
		// by global option tags
		struct handler_data
		{
			::std::string m_ApplicationName;
			::std::string m_ApplicationVersion;
			error_mode_ m_ErrorMode{ error_mode_::terminate };
			error_handler_ m_ErrorHandler;
			help_mode_ m_HelpMode{ help_mode_::show_summary };
			summary_style_ m_SummaryStyle{ summary_style_::dots };
			::std::size_t m_SummaryDescWidth{ 60U };
			::std::size_t m_SummaryLabelWidth{ 28U };
		};
	}
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "kitinformationconfigwidget.h"

#include "devicesupport/devicemanager.h"
#include "devicesupport/devicemanagermodel.h"
#include "devicesupport/idevicefactory.h"
#include "projectexplorerconstants.h"
#include "kit.h"
#include "kitinformation.h"
#include "toolchain.h"
#include "toolchainmanager.h"

#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/pathchooser.h>

#include <QComboBox>
#include <QLabel>
#include <QPushButton>

using namespace Core;

namespace ProjectExplorer {
namespace Internal {

// --------------------------------------------------------------------------
// SysRootInformationConfigWidget:
// --------------------------------------------------------------------------

SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k) :
    KitConfigWidget(k),
    m_ignoreChange(false)
{
    m_chooser = new Utils::PathChooser;
    m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);
    m_chooser->setFileName(SysRootKitInformation::sysRoot(k));
    connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}

QString SysRootInformationConfigWidget::displayName() const
{
    return tr("Sysroot:");
}

QString SysRootInformationConfigWidget::toolTip() const
{
    return tr("The root directory of the system image to use.
"
                  "Leave empty when building for the desktop.");
}

void SysRootInformationConfigWidget::refresh()
{
    if (!m_ignoreChange)
        m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit));
}

void SysRootInformationConfigWidget::makeReadOnly()
{
    m_chooser->setEnabled(false);
}

QWidget *SysRootInformationConfigWidget::mainWidget() const
{
    return m_chooser->lineEdit();
}

QWidget *SysRootInformationConfigWidget::buttonWidget() const
{
    return m_chooser->buttonAtIndex(0);
}

void SysRootInformationConfigWidget::pathWasChanged()
{
    m_ignoreChange = true;
    SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName());
    m_ignoreChange = false;
}

// --------------------------------------------------------------------------
// ToolChainInformationConfigWidget:
// --------------------------------------------------------------------------

ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k) :
    KitConfigWidget(k), m_isReadOnly(false)
{
    ToolChainManager *tcm = ToolChainManager::instance();

    m_comboBox = new QComboBox;
    m_comboBox->setEnabled(false);

    foreach (ToolChain *tc, tcm->toolChains())
        toolChainAdded(tc);

    updateComboBox();

    refresh();
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int)));

    m_manageButton = new QPushButton(tr("Manage..."));
    m_manageButton->setContentsMargins(0, 0, 0, 0);
    connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));

    connect(tcm, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
            this, SLOT(toolChainAdded(ProjectExplorer::ToolChain*)));
    connect(tcm, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
            this, SLOT(toolChainRemoved(ProjectExplorer::ToolChain*)));
    connect(tcm, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
            this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*)));
}

QString ToolChainInformationConfigWidget::displayName() const
{
    return tr("Compiler:");
}

QString ToolChainInformationConfigWidget::toolTip() const
{
    return tr("The compiler to use for building.
"
              "Make sure the compiler will produce binaries compatible with the target device, "
              "Qt version and other libraries used.");
}

void ToolChainInformationConfigWidget::refresh()
{
    m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit)));
}

void ToolChainInformationConfigWidget::makeReadOnly()
{
    m_comboBox->setEnabled(false);
}

QWidget *ToolChainInformationConfigWidget::mainWidget() const
{
    return m_comboBox;
}

QWidget *ToolChainInformationConfigWidget::buttonWidget() const
{
    return m_manageButton;
}

void ToolChainInformationConfigWidget::toolChainAdded(ProjectExplorer::ToolChain *tc)
{
    m_comboBox->addItem(tc->displayName(), tc->id());
    updateComboBox();
}

void ToolChainInformationConfigWidget::toolChainRemoved(ProjectExplorer::ToolChain *tc)
{
    const int pos = indexOf(tc);
    if (pos < 0)
        return;
    m_comboBox->removeItem(pos);
    updateComboBox();
}
void ToolChainInformationConfigWidget::toolChainUpdated(ProjectExplorer::ToolChain *tc)
{
    const int pos = indexOf(tc);
    if (pos < 0)
        return;
    m_comboBox->setItemText(pos, tc->displayName());
}

void ToolChainInformationConfigWidget::manageToolChains()
{
    Core::ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
                                   Constants::TOOLCHAIN_SETTINGS_PAGE_ID);
}

void ToolChainInformationConfigWidget::currentToolChainChanged(int idx)
{
    const QString id = m_comboBox->itemData(idx).toString();
    ToolChain *tc = ToolChainManager::instance()->findToolChain(id);
    ToolChainKitInformation::setToolChain(m_kit, tc);
}

void ToolChainInformationConfigWidget::updateComboBox()
{
    // remove unavailable tool chain:
    int pos = indexOf(0);
    if (pos >= 0)
        m_comboBox->removeItem(pos);

    if (m_comboBox->count() == 0) {
        m_comboBox->addItem(tr("<No compiler available>"), QString());
        m_comboBox->setEnabled(false);
    } else {
        m_comboBox->setEnabled(!m_isReadOnly);
    }
}

int ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)
{
    const QString id = tc ? tc->id() : QString();
    for (int i = 0; i < m_comboBox->count(); ++i) {
        if (id == m_comboBox->itemData(i).toString())
            return i;
    }
    return -1;
}

// --------------------------------------------------------------------------
// DeviceTypeInformationConfigWidget:
// --------------------------------------------------------------------------

DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy) :
    KitConfigWidget(workingCopy), m_isReadOnly(false), m_comboBox(new QComboBox)
{
    QList<IDeviceFactory *> factories
            = ExtensionSystem::PluginManager::instance()->getObjects<IDeviceFactory>();
    foreach (IDeviceFactory *factory, factories) {
        foreach (Core::Id id, factory->availableCreationIds())
            m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());
    }

    refresh();
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));
}

QWidget *DeviceTypeInformationConfigWidget::mainWidget() const
{
    return m_comboBox;
}

QString DeviceTypeInformationConfigWidget::displayName() const
{
    return tr("Device type:");
}

QString DeviceTypeInformationConfigWidget::toolTip() const
{
    return tr("The type of device to run applications on.");
}

void DeviceTypeInformationConfigWidget::refresh()
{
    Core::Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);
    if (!devType.isValid())
        m_comboBox->setCurrentIndex(-1);
    for (int i = 0; i < m_comboBox->count(); ++i) {
        if (m_comboBox->itemData(i).toInt() == devType.uniqueIdentifier()) {
            m_comboBox->setCurrentIndex(i);
            break;
        }
    }
}

void DeviceTypeInformationConfigWidget::makeReadOnly()
{
    m_comboBox->setEnabled(false);
}

void DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)
{
    Core::Id type = idx < 0 ? Core::Id() : Core::Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt());
    DeviceTypeKitInformation::setDeviceTypeId(m_kit, type);
}

// --------------------------------------------------------------------------
// DeviceInformationConfigWidget:
// --------------------------------------------------------------------------

DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy) :
    KitConfigWidget(workingCopy),
    m_isReadOnly(false),
    m_comboBox(new QComboBox),
    m_model(new DeviceManagerModel(DeviceManager::instance()))
{
    m_comboBox->setModel(m_model);

    m_manageButton = new QPushButton(tr("Manage"));

    refresh();
    connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));
    connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged()));
    connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices()));
}

QWidget *DeviceInformationConfigWidget::mainWidget() const
{
    return m_comboBox;
}

QString DeviceInformationConfigWidget::displayName() const
{
    return tr("Device:");
}

QString DeviceInformationConfigWidget::toolTip() const
{
    return tr("The device to run the applications on.");
}

void DeviceInformationConfigWidget::refresh()
{
    m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit));
    m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit)));
}

void DeviceInformationConfigWidget::makeReadOnly()
{
    m_comboBox->setEnabled(false);
}

QWidget *DeviceInformationConfigWidget::buttonWidget() const
{
    return m_manageButton;
}

void DeviceInformationConfigWidget::manageDevices()
{
    ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_CATEGORY,
                             Constants::DEVICE_SETTINGS_PAGE_ID);
}

void DeviceInformationConfigWidget::modelAboutToReset()
{
    m_selectedId = m_model->deviceId(m_comboBox->currentIndex());
    m_ignoreChange = true;
}

void DeviceInformationConfigWidget::modelReset()
{
    m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId));
    m_ignoreChange = false;
}

void DeviceInformationConfigWidget::currentDeviceChanged()
{
    if (m_ignoreChange)
        return;
    DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex()));
}

} // namespace Internal
} // namespace ProjectExplorer
<commit_msg>ProjectExplorer: Fixed kit sometimes not being marked dirty<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "kitinformationconfigwidget.h"

#include "devicesupport/devicemanager.h"
#include "devicesupport/devicemanagermodel.h"
#include "devicesupport/idevicefactory.h"
#include "projectexplorerconstants.h"
#include "kit.h"
#include "kitinformation.h"
#include "toolchain.h"
#include "toolchainmanager.h"

#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/pathchooser.h>

#include <QComboBox>
#include <QLabel>
#include <QPushButton>

using namespace Core;

namespace ProjectExplorer {
namespace Internal {

// --------------------------------------------------------------------------
// SysRootInformationConfigWidget:
// --------------------------------------------------------------------------

SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k) :
    KitConfigWidget(k),
    m_ignoreChange(false)
{
    m_chooser = new Utils::PathChooser;
    m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);
    m_chooser->setFileName(SysRootKitInformation::sysRoot(k));
    connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}

QString SysRootInformationConfigWidget::displayName() const
{
    return tr("Sysroot:");
}

QString SysRootInformationConfigWidget::toolTip() const
{
    return tr("The root directory of the system image to use.
"
                  "Leave empty when building for the desktop.");
}

void SysRootInformationConfigWidget::refresh()
{
    if (!m_ignoreChange)
        m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit));
}

void SysRootInformationConfigWidget::makeReadOnly()
{
    m_chooser->setEnabled(false);
}

QWidget *SysRootInformationConfigWidget::mainWidget() const
{
    return m_chooser->lineEdit();
}

QWidget *SysRootInformationConfigWidget::buttonWidget() const
{
    return m_chooser->buttonAtIndex(0);
}

void SysRootInformationConfigWidget::pathWasChanged()
{
    m_ignoreChange = true;
    SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName());
    m_ignoreChange = false;
}

// --------------------------------------------------------------------------
// ToolChainInformationConfigWidget:
// --------------------------------------------------------------------------

ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k) :
    KitConfigWidget(k), m_isReadOnly(false)
{
    ToolChainManager *tcm = ToolChainManager::instance();

    m_comboBox = new QComboBox;
    m_comboBox->setEnabled(false);

    foreach (ToolChain *tc, tcm->toolChains())
        toolChainAdded(tc);

    updateComboBox();

    refresh();
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int)));

    m_manageButton = new QPushButton(tr("Manage..."));
    m_manageButton->setContentsMargins(0, 0, 0, 0);
    connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));

    connect(tcm, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
            this, SLOT(toolChainAdded(ProjectExplorer::ToolChain*)));
    connect(tcm, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
            this, SLOT(toolChainRemoved(ProjectExplorer::ToolChain*)));
    connect(tcm, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)),
            this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*)));
}

QString ToolChainInformationConfigWidget::displayName() const
{
    return tr("Compiler:");
}

QString ToolChainInformationConfigWidget::toolTip() const
{
    return tr("The compiler to use for building.
"
              "Make sure the compiler will produce binaries compatible with the target device, "
              "Qt version and other libraries used.");
}

void ToolChainInformationConfigWidget::refresh()
{
    m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit)));
}

void ToolChainInformationConfigWidget::makeReadOnly()
{
    m_comboBox->setEnabled(false);
}

QWidget *ToolChainInformationConfigWidget::mainWidget() const
{
    return m_comboBox;
}

QWidget *ToolChainInformationConfigWidget::buttonWidget() const
{
    return m_manageButton;
}

void ToolChainInformationConfigWidget::toolChainAdded(ProjectExplorer::ToolChain *tc)
{
    m_comboBox->addItem(tc->displayName(), tc->id());
    updateComboBox();
}

void ToolChainInformationConfigWidget::toolChainRemoved(ProjectExplorer::ToolChain *tc)
{
    const int pos = indexOf(tc);
    if (pos < 0)
        return;
    m_comboBox->removeItem(pos);
    updateComboBox();
}
void ToolChainInformationConfigWidget::toolChainUpdated(ProjectExplorer::ToolChain *tc)
{
    const int pos = indexOf(tc);
    if (pos < 0)
        return;
    m_comboBox->setItemText(pos, tc->displayName());
}

void ToolChainInformationConfigWidget::manageToolChains()
{
    Core::ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
                                   Constants::TOOLCHAIN_SETTINGS_PAGE_ID);
}

void ToolChainInformationConfigWidget::currentToolChainChanged(int idx)
{
    const QString id = m_comboBox->itemData(idx).toString();
    ToolChain *tc = ToolChainManager::instance()->findToolChain(id);
    ToolChainKitInformation::setToolChain(m_kit, tc);
}

void ToolChainInformationConfigWidget::updateComboBox()
{
    // remove unavailable tool chain:
    int pos = indexOf(0);
    if (pos >= 0)
        m_comboBox->removeItem(pos);

    if (m_comboBox->count() == 0) {
        m_comboBox->addItem(tr("<No compiler available>"), QString());
        m_comboBox->setEnabled(false);
    } else {
        m_comboBox->setEnabled(!m_isReadOnly);
    }
}

int ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)
{
    const QString id = tc ? tc->id() : QString();
    for (int i = 0; i < m_comboBox->count(); ++i) {
        if (id == m_comboBox->itemData(i).toString())
            return i;
    }
    return -1;
}

// --------------------------------------------------------------------------
// DeviceTypeInformationConfigWidget:
// --------------------------------------------------------------------------

DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy) :
    KitConfigWidget(workingCopy), m_isReadOnly(false), m_comboBox(new QComboBox)
{
    QList<IDeviceFactory *> factories
            = ExtensionSystem::PluginManager::instance()->getObjects<IDeviceFactory>();
    foreach (IDeviceFactory *factory, factories) {
        foreach (Core::Id id, factory->availableCreationIds())
            m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());
    }

    refresh();
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));
}

QWidget *DeviceTypeInformationConfigWidget::mainWidget() const
{
    return m_comboBox;
}

QString DeviceTypeInformationConfigWidget::displayName() const
{
    return tr("Device type:");
}

QString DeviceTypeInformationConfigWidget::toolTip() const
{
    return tr("The type of device to run applications on.");
}

void DeviceTypeInformationConfigWidget::refresh()
{
    Core::Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);
    if (!devType.isValid())
        m_comboBox->setCurrentIndex(-1);
    for (int i = 0; i < m_comboBox->count(); ++i) {
        if (m_comboBox->itemData(i).toInt() == devType.uniqueIdentifier()) {
            m_comboBox->setCurrentIndex(i);
            break;
        }
    }
}

void DeviceTypeInformationConfigWidget::makeReadOnly()
{
    m_comboBox->setEnabled(false);
}

void DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)
{
    Core::Id type = idx < 0 ? Core::Id() : Core::Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt());
    DeviceTypeKitInformation::setDeviceTypeId(m_kit, type);
}

// --------------------------------------------------------------------------
// DeviceInformationConfigWidget:
// --------------------------------------------------------------------------

DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy) :
    KitConfigWidget(workingCopy),
    m_isReadOnly(false),
    m_ignoreChange(false),
    m_comboBox(new QComboBox),
    m_model(new DeviceManagerModel(DeviceManager::instance()))
{
    m_comboBox->setModel(m_model);

    m_manageButton = new QPushButton(tr("Manage"));

    refresh();
    connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));
    connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));
    connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged()));
    connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices()));
}

QWidget *DeviceInformationConfigWidget::mainWidget() const
{
    return m_comboBox;
}

QString DeviceInformationConfigWidget::displayName() const
{
    return tr("Device:");
}

QString DeviceInformationConfigWidget::toolTip() const
{
    return tr("The device to run the applications on.");
}

void DeviceInformationConfigWidget::refresh()
{
    m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit));
    m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit)));
}

void DeviceInformationConfigWidget::makeReadOnly()
{
    m_comboBox->setEnabled(false);
}

QWidget *DeviceInformationConfigWidget::buttonWidget() const
{
    return m_manageButton;
}

void DeviceInformationConfigWidget::manageDevices()
{
    ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_CATEGORY,
                             Constants::DEVICE_SETTINGS_PAGE_ID);
}

void DeviceInformationConfigWidget::modelAboutToReset()
{
    m_selectedId = m_model->deviceId(m_comboBox->currentIndex());
    m_ignoreChange = true;
}

void DeviceInformationConfigWidget::modelReset()
{
    m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId));
    m_ignoreChange = false;
}

void DeviceInformationConfigWidget::currentDeviceChanged()
{
    if (m_ignoreChange)
        return;
    DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex()));
}

} // namespace Internal
} // namespace ProjectExplorer
<|endoftext|>


<commit_before>#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH
# define MIMOSA_TPL_ABSTRACT_VALUE_HH

# include "../ref-countable.hh"
# include "../stream/stream.hh"
# include "../string/string-ref.hh"

namespace mimosa
{
  namespace tpl
  {
    class AbstractValue
    {
    public:
      virtual const AbstractValue * lookup(const string::StringRef & var) const = 0;
      virtual void write(stream::Stream::Ptr stream) const = 0;

      class Iterator
      {
        virtual const AbstractValue & operator*() const = 0;
        virtual const AbstractValue * operator->() const = 0;
        virtual Iterator & operator++() = 0;
        virtual bool operator==(const Iterator &) const = 0;
      };

      virtual Iterator begin() const = 0;
      virtual Iterator end() const = 0;
      virtual bool empty() const = 0;

      AbstractValue * parent_;
    };
  }
}

#endif /* !MIMOSA_TPL_ABSTRACT_VALUE_HH */
<commit_msg>template: symplifying abstract value<commit_after>#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH
# define MIMOSA_TPL_ABSTRACT_VALUE_HH

# include "../ref-countable.hh"
# include "../stream/stream.hh"
# include "../string/string-ref.hh"

namespace mimosa
{
  namespace tpl
  {
    class AbstractValue
    {
    public:
      virtual const AbstractValue * lookup(const string::StringRef & var) const = 0;
      virtual void write(stream::Stream::Ptr stream) const = 0;

      class Iterator : public RefCountable<Iterator>
      {
        virtual const AbstractValue & value() const = 0;
        virtual void next() = 0;
        virtual bool end() const = 0;
      };

      virtual Iterator::Ptr begin() const = 0;
      virtual bool empty() const = 0;

      AbstractValue * parent_;
    };
  }
}

#endif /* !MIMOSA_TPL_ABSTRACT_VALUE_HH */
<|endoftext|>