<commit_before>/*************************************************************************
 *
 *  $RCSfile: contexts.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: dvo $ $Date: 2001-06-29 21:07:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLMETAI_HXX
#include "xmlmetai.hxx"
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include "xmlstyle.hxx"
#endif
#ifndef SCH_XMLIMPORT_HXX_
#include "SchXMLImport.hxx"
#endif

//  #ifndef _XMLOFF_XMLCHARTSTYLECONTEXT_HXX_
//  #include "XMLChartStyleContext.hxx"
//  #endif

#ifndef _COM_SUN_STAR_CHART_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_XCHARTDATAARRAY_HPP_
#include <com/sun/star/chart/XChartDataArray.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_CHARTDATAROWSOURCE_HPP_
#include <com/sun/star/chart/ChartDataRowSource.hpp>
#endif

#include "contexts.hxx"
#include "SchXMLChartContext.hxx"

using namespace com::sun::star;
using namespace ::xmloff::token;

// ==================================================

SchXMLDocContext::SchXMLDocContext( SchXMLImportHelper& rImpHelper,
                                    SvXMLImport& rImport,
                                    USHORT nPrefix,
                                    const rtl::OUString& rLName ) :
        SvXMLImportContext( rImport, nPrefix, rLName ),
        mrImportHelper( rImpHelper )
{
    DBG_ASSERT( XML_NAMESPACE_OFFICE == nPrefix &&
        ( IsXMLToken( rLName, XML_DOCUMENT ) ||
          IsXMLToken( rLName, XML_DOCUMENT_META) ||
          IsXMLToken( rLName, XML_DOCUMENT_STYLES) ||
          IsXMLToken( rLName, XML_DOCUMENT_CONTENT) ),
                "SchXMLDocContext instanciated with no <office:document> element" );
}

SchXMLDocContext::~SchXMLDocContext()
{}

SvXMLImportContext* SchXMLDocContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const ::rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = 0;
    const SvXMLTokenMap& rTokenMap = mrImportHelper.GetDocElemTokenMap();
    sal_uInt16 nFlags = GetImport().getImportFlags();

    switch( rTokenMap.Get( nPrefix, rLocalName ))
    {
        case XML_TOK_DOC_AUTOSTYLES:
            if( nFlags & IMPORT_AUTOSTYLES )
            {
                SvXMLStylesContext* pStylesCtxt =
                    new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
                mrImportHelper.SetAutoStylesContext( pStylesCtxt );
                pContext = pStylesCtxt;
            }
            break;
        case XML_TOK_DOC_STYLES:
            // for draw styles containing gradients/hatches/markers and dashes
            if( nFlags & IMPORT_STYLES )
                pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
            break;
        case XML_TOK_DOC_META:
            if( nFlags & IMPORT_META )
                pContext = new SfxXMLMetaContext( GetImport(), nPrefix, rLocalName, GetImport().GetModel());
            break;
        case XML_TOK_DOC_BODY:
            if( nFlags & IMPORT_CONTENT )
                pContext = new SchXMLBodyContext( mrImportHelper, GetImport(), nPrefix, rLocalName );
            break;
    }

    // call parent when no own context was created
    if( ! pContext )
        pContext = SvXMLImportContext::CreateChildContext( nPrefix, rLocalName, xAttrList );

    return pContext;
}

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

SchXMLBodyContext::SchXMLBodyContext( SchXMLImportHelper& rImpHelper,
                                      SvXMLImport& rImport,
                                      USHORT nPrefix,
                                      const rtl::OUString& rLName ) :
        SvXMLImportContext( rImport, nPrefix, rLName ),
        mrImportHelper( rImpHelper )
{
    DBG_ASSERT( XML_NAMESPACE_OFFICE == nPrefix &&
                IsXMLToken( rLName, XML_BODY ),
                "SchXMLBodyContext instanciated with no <office:body> element" );
}

SchXMLBodyContext::~SchXMLBodyContext()
{}

void SchXMLBodyContext::EndElement()
{
}

SvXMLImportContext* SchXMLBodyContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = 0;

    // <chart:chart> element
    if( nPrefix == XML_NAMESPACE_CHART &&
        IsXMLToken( rLocalName, XML_CHART ) )
    {
        pContext = mrImportHelper.CreateChartContext( GetImport(),
                                                      nPrefix, rLocalName,
                                                      GetImport().GetModel(),
                                                      xAttrList );
    }
    else
    {
        pContext = SvXMLImportContext::CreateChildContext( nPrefix, rLocalName, xAttrList );
    }

    return pContext;
}

<commit_msg>#97452# create styles-context using CreateStylesContext method at SchXMLImport<commit_after>/*************************************************************************
 *
 *  $RCSfile: contexts.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: bm $ $Date: 2002-02-11 09:56:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLMETAI_HXX
#include "xmlmetai.hxx"
#endif
#ifndef _XMLOFF_XMLSTYLE_HXX
#include "xmlstyle.hxx"
#endif
#ifndef SCH_XMLIMPORT_HXX_
#include "SchXMLImport.hxx"
#endif

//  #ifndef _XMLOFF_XMLCHARTSTYLECONTEXT_HXX_
//  #include "XMLChartStyleContext.hxx"
//  #endif

#ifndef _COM_SUN_STAR_CHART_XCHARTDOCUMENT_HPP_
#include <com/sun/star/chart/XChartDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_XCHARTDATAARRAY_HPP_
#include <com/sun/star/chart/XChartDataArray.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART_CHARTDATAROWSOURCE_HPP_
#include <com/sun/star/chart/ChartDataRowSource.hpp>
#endif

#include "contexts.hxx"
#include "SchXMLChartContext.hxx"

using namespace com::sun::star;
using namespace ::xmloff::token;

// ==================================================

SchXMLDocContext::SchXMLDocContext( SchXMLImportHelper& rImpHelper,
                                    SvXMLImport& rImport,
                                    USHORT nPrefix,
                                    const rtl::OUString& rLName ) :
        SvXMLImportContext( rImport, nPrefix, rLName ),
        mrImportHelper( rImpHelper )
{
    DBG_ASSERT( XML_NAMESPACE_OFFICE == nPrefix &&
        ( IsXMLToken( rLName, XML_DOCUMENT ) ||
          IsXMLToken( rLName, XML_DOCUMENT_META) ||
          IsXMLToken( rLName, XML_DOCUMENT_STYLES) ||
          IsXMLToken( rLName, XML_DOCUMENT_CONTENT) ),
                "SchXMLDocContext instanciated with no <office:document> element" );
}

SchXMLDocContext::~SchXMLDocContext()
{}

SvXMLImportContext* SchXMLDocContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const ::rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = 0;
    const SvXMLTokenMap& rTokenMap = mrImportHelper.GetDocElemTokenMap();
    sal_uInt16 nFlags = GetImport().getImportFlags();

    switch( rTokenMap.Get( nPrefix, rLocalName ))
    {
        case XML_TOK_DOC_AUTOSTYLES:
            if( nFlags & IMPORT_AUTOSTYLES )
                // not nice, but this is safe, as the SchXMLDocContext class can only by
                // instantiated by the chart import class SchXMLImport (header is not exported)
                pContext =
                    static_cast< SchXMLImport& >( GetImport() ).CreateStylesContext( rLocalName, xAttrList );
            break;
        case XML_TOK_DOC_STYLES:
            // for draw styles containing gradients/hatches/markers and dashes
            if( nFlags & IMPORT_STYLES )
                pContext = new SvXMLStylesContext( GetImport(), nPrefix, rLocalName, xAttrList );
            break;
        case XML_TOK_DOC_META:
            if( nFlags & IMPORT_META )
                pContext = new SfxXMLMetaContext( GetImport(), nPrefix, rLocalName, GetImport().GetModel());
            break;
        case XML_TOK_DOC_BODY:
            if( nFlags & IMPORT_CONTENT )
                pContext = new SchXMLBodyContext( mrImportHelper, GetImport(), nPrefix, rLocalName );
            break;
    }

    // call parent when no own context was created
    if( ! pContext )
        pContext = SvXMLImportContext::CreateChildContext( nPrefix, rLocalName, xAttrList );

    return pContext;
}

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

SchXMLBodyContext::SchXMLBodyContext( SchXMLImportHelper& rImpHelper,
                                      SvXMLImport& rImport,
                                      USHORT nPrefix,
                                      const rtl::OUString& rLName ) :
        SvXMLImportContext( rImport, nPrefix, rLName ),
        mrImportHelper( rImpHelper )
{
    DBG_ASSERT( XML_NAMESPACE_OFFICE == nPrefix &&
                IsXMLToken( rLName, XML_BODY ),
                "SchXMLBodyContext instanciated with no <office:body> element" );
}

SchXMLBodyContext::~SchXMLBodyContext()
{}

void SchXMLBodyContext::EndElement()
{
}

SvXMLImportContext* SchXMLBodyContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const rtl::OUString& rLocalName,
    const uno::Reference< xml::sax::XAttributeList >& xAttrList )
{
    SvXMLImportContext* pContext = 0;

    // <chart:chart> element
    if( nPrefix == XML_NAMESPACE_CHART &&
        IsXMLToken( rLocalName, XML_CHART ) )
    {
        pContext = mrImportHelper.CreateChartContext( GetImport(),
                                                      nPrefix, rLocalName,
                                                      GetImport().GetModel(),
                                                      xAttrList );
    }
    else
    {
        pContext = SvXMLImportContext::CreateChildContext( nPrefix, rLocalName, xAttrList );
    }

    return pContext;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <popt.h>
#include "nfa.hxx"

extern int yyparse (void*);
extern FILE* yyin;
extern char* filename;

#define OPT_RENAME 0
#define OPT_DOT 1
#define OPT_VCG 2
#define OPT_NOTHING 3
#define OPT_INFILE 4
#define OPT_OUTFILE 5
#define OPT_MINIMIZE 6
#define OPT_COUNT (OPT_MINIMIZE+1)

union optionValue
{
  char* str;
  int val;
};

optionValue options[OPT_COUNT] = {0};
const poptOption optionsDesc[] = {
  {"rename", 'r', POPT_ARG_NONE, &options[OPT_RENAME], 1,
   "rename states", NULL},
  {"dot", 'd', POPT_ARG_NONE, &options[OPT_DOT], 1,
   "generate dot graph description", NULL},
  {"vcg", 'v', POPT_ARG_NONE, &options[OPT_VCG], 1,
   "generate VCG graph description", NULL},
  {"do-nothing", 'n', POPT_ARG_NONE, &options[OPT_NOTHING], 1,
   "don't convert, just print input to output", NULL},
  {"input", 'i', POPT_ARG_STRING, &options[OPT_INFILE], 1,
   "name of input file","file name"},
  {"output", 'o', POPT_ARG_STRING, &options[OPT_OUTFILE], 1,
   "name of output file", "file name"},
  {"minimize", 'm', POPT_ARG_NONE, &options[OPT_MINIMIZE], 1,
   "minimize states", NULL},
  POPT_AUTOHELP
  {NULL, '\0', 0, 0, 0, NULL, NULL}
};

int
main (int argc, const char* argv[])
{
  try
    {
      /* Analyzuj prikazovou radku pro paramatry. */
      poptContext context = poptGetContext(NULL, argc, argv, optionsDesc,0);
      int rc;
      while ((rc = poptGetNextOpt(context)) > 0);
      if (rc < -1)
        {
          std::cerr << poptStrerror(rc) << std::endl;
          poptPrintHelp(context, stderr, 0);
          exit(EXIT_FAILURE);
        }

      /* Osetreni parametru vstupniho souboru */
      if (options[OPT_INFILE].str != NULL)
        {
          if (!(yyin = fopen(options[OPT_INFILE].str,"r")))
            {
              perror("chyba fopen()");
              exit(EXIT_FAILURE);
            }
          filename = options[OPT_INFILE].str;
        }
      else
        {
          yyin = stdin;
          filename = "<stdin>";
        }

      /* Osetreni parametru vystupniho souboru */
      std::ofstream outfile;
      std::ostream* os = NULL;
      if (options[OPT_OUTFILE].str != NULL)
        {
          outfile.open(options[OPT_OUTFILE].str);
          if (!outfile)
            {
              std::cerr << "chyba pri otevirani vystupniho souboru"
                        << std::endl;
              exit(EXIT_FAILURE);
            }
          os = &outfile;
        }
      else
        {
          os = &std::cout;
        }

      NFA nfa;
      NFA_conv nfa_conv;
      int ret = yyparse((void*)&nfa);
      if (ret == 1)
        {
          std::cerr << "chyba pri parsovani vstupu" << std::endl;
          exit(EXIT_FAILURE);
        }

      if (! options[OPT_NOTHING].val)
        {
          remove_epsilons (nfa);
          nfa_conv = convert_NFA2DFA(nfa);
          nfa = fix_converted(nfa_conv);
        }

      if (options[OPT_MINIMIZE].val)
        minimize (nfa);

      if (options[OPT_RENAME].val)
        rename_states(nfa);

      if (options[OPT_DOT].val)
        *os << printNFA2dot(nfa);
      else if (options[OPT_VCG].val)
        *os << printNFA2vcg(nfa);
      else
        *os << printNFA(nfa);
    }
  catch (const state_not_found& e)
    {
      std::cerr << "chyba pri prevodu v convert_NFA2DFA(): "
                << e.what() << std::endl;
      std::cerr << "zobrazeni delta na neznamy stav" << std::endl;
      exit(EXIT_FAILURE);
    }
  catch (const std::exception& e)
    {
      std::cerr << "vyjimka: " << e.what() << std::endl;
      exit(EXIT_FAILURE);
    }
  catch (const std::string& e)
    {
      std::cerr << "vyjimka: " << e << std::endl;
      exit(EXIT_FAILURE);
    }
  catch (...)
    {
      std::cerr << "nastala neznama vyjimka" << std::endl;
      exit(EXIT_FAILURE);
    }

  exit(EXIT_SUCCESS);
}
<commit_msg>nfa2dfa.cxx: Fix missing braces around initializer.<commit_after>#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <popt.h>
#include "nfa.hxx"

extern int yyparse (void*);
extern FILE* yyin;
extern char* filename;

#define OPT_RENAME 0
#define OPT_DOT 1
#define OPT_VCG 2
#define OPT_NOTHING 3
#define OPT_INFILE 4
#define OPT_OUTFILE 5
#define OPT_MINIMIZE 6
#define OPT_COUNT (OPT_MINIMIZE+1)

union optionValue
{
  char* str;
  int val;
};

optionValue options[OPT_COUNT] = {{0}};
const poptOption optionsDesc[] = {
  {"rename", 'r', POPT_ARG_NONE, &options[OPT_RENAME], 1,
   "rename states", NULL},
  {"dot", 'd', POPT_ARG_NONE, &options[OPT_DOT], 1,
   "generate dot graph description", NULL},
  {"vcg", 'v', POPT_ARG_NONE, &options[OPT_VCG], 1,
   "generate VCG graph description", NULL},
  {"do-nothing", 'n', POPT_ARG_NONE, &options[OPT_NOTHING], 1,
   "don't convert, just print input to output", NULL},
  {"input", 'i', POPT_ARG_STRING, &options[OPT_INFILE], 1,
   "name of input file","file name"},
  {"output", 'o', POPT_ARG_STRING, &options[OPT_OUTFILE], 1,
   "name of output file", "file name"},
  {"minimize", 'm', POPT_ARG_NONE, &options[OPT_MINIMIZE], 1,
   "minimize states", NULL},
  POPT_AUTOHELP
  {NULL, '\0', 0, 0, 0, NULL, NULL}
};

int
main (int argc, const char* argv[])
{
  try
    {
      /* Analyzuj prikazovou radku pro paramatry. */
      poptContext context = poptGetContext(NULL, argc, argv, optionsDesc,0);
      int rc;
      while ((rc = poptGetNextOpt(context)) > 0);
      if (rc < -1)
        {
          std::cerr << poptStrerror(rc) << std::endl;
          poptPrintHelp(context, stderr, 0);
          exit(EXIT_FAILURE);
        }

      /* Osetreni parametru vstupniho souboru */
      if (options[OPT_INFILE].str != NULL)
        {
          if (!(yyin = fopen(options[OPT_INFILE].str,"r")))
            {
              perror("chyba fopen()");
              exit(EXIT_FAILURE);
            }
          filename = options[OPT_INFILE].str;
        }
      else
        {
          yyin = stdin;
          filename = "<stdin>";
        }

      /* Osetreni parametru vystupniho souboru */
      std::ofstream outfile;
      std::ostream* os = NULL;
      if (options[OPT_OUTFILE].str != NULL)
        {
          outfile.open(options[OPT_OUTFILE].str);
          if (!outfile)
            {
              std::cerr << "chyba pri otevirani vystupniho souboru"
                        << std::endl;
              exit(EXIT_FAILURE);
            }
          os = &outfile;
        }
      else
        {
          os = &std::cout;
        }

      NFA nfa;
      NFA_conv nfa_conv;
      int ret = yyparse((void*)&nfa);
      if (ret == 1)
        {
          std::cerr << "chyba pri parsovani vstupu" << std::endl;
          exit(EXIT_FAILURE);
        }

      if (! options[OPT_NOTHING].val)
        {
          remove_epsilons (nfa);
          nfa_conv = convert_NFA2DFA(nfa);
          nfa = fix_converted(nfa_conv);
        }

      if (options[OPT_MINIMIZE].val)
        minimize (nfa);

      if (options[OPT_RENAME].val)
        rename_states(nfa);

      if (options[OPT_DOT].val)
        *os << printNFA2dot(nfa);
      else if (options[OPT_VCG].val)
        *os << printNFA2vcg(nfa);
      else
        *os << printNFA(nfa);
    }
  catch (const state_not_found& e)
    {
      std::cerr << "chyba pri prevodu v convert_NFA2DFA(): "
                << e.what() << std::endl;
      std::cerr << "zobrazeni delta na neznamy stav" << std::endl;
      exit(EXIT_FAILURE);
    }
  catch (const std::exception& e)
    {
      std::cerr << "vyjimka: " << e.what() << std::endl;
      exit(EXIT_FAILURE);
    }
  catch (const std::string& e)
    {
      std::cerr << "vyjimka: " << e << std::endl;
      exit(EXIT_FAILURE);
    }
  catch (...)
    {
      std::cerr << "nastala neznama vyjimka" << std::endl;
      exit(EXIT_FAILURE);
    }

  exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#include <tuple>

#include "acmacs-base/enumerate.hh"
#include "acmacs-base/fmt.hh"
#include "seqdb-3/compare.hh"
#include "acmacs-map-draw/mod-amino-acids.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/report-antigens.hh"
#include "acmacs-map-draw/select.hh"

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

void ModAminoAcids::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    const auto verbose = rjson::get_or(args(), "report", false);
    const auto report_names_threshold = rjson::get_or(args(), "report_names_threshold", 10UL);
    if (const auto& pos = args()["pos"]; !pos.is_null()) {
        aa_pos(aChartDraw, pos, verbose, report_names_threshold);
    }
    else if (const auto& groups = args()["groups"]; !groups.is_null()) {
        rjson::for_each(groups, [this,&aChartDraw,verbose,report_names_threshold](const rjson::value& group) { aa_group(aChartDraw, group, verbose, report_names_threshold); });
    }
    else {
        std::cerr << "No pos no groups" << '\n';
        throw unrecognized_mod{"expected either \"pos\":[] or \"groups\":[] mod: " + rjson::to_string(args())};
    }

} // ModAminoAcids::apply

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

void ModAminoAcids::aa_pos(ChartDraw& aChartDraw, const rjson::value& aPos, bool aVerbose, size_t report_names_threshold)
{
    std::vector<size_t> positions;
    rjson::copy(aPos, positions);
    const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions);
    // aa_indices is std::map<std::string, std::vector<size_t>>
    std::vector<std::string> aa_sorted(aa_indices.size()); // most frequent aa first
    std::transform(std::begin(aa_indices), std::end(aa_indices), std::begin(aa_sorted), [](const auto& entry) -> std::string { return entry.first; });
    std::sort(std::begin(aa_sorted), std::end(aa_sorted), [&aa_indices](const auto& n1, const auto& n2) -> bool { return aa_indices.find(n1)->second.size() > aa_indices.find(n2)->second.size(); });
    std::map<std::string, Color> color_for_aa;
    make_color_for_aa(color_for_aa, aa_sorted);
    for (auto [index, aa] : acmacs::enumerate(aa_sorted)) {
        const auto& indices_for_aa = aa_indices.find(aa)->second;
        auto styl = style();
        if (auto ca = color_for_aa.find(aa); ca == color_for_aa.end())
            throw unrecognized_mod{"cannot find color for AA: " + aa + ", \"colors\" in the settings is not complete?"};
        else
            styl.fill = ca->second;
        aChartDraw.modify(indices_for_aa, styl, drawing_order());
        if (const auto& legend = args()["legend"]; !legend.is_null())
            add_legend(aChartDraw, indices_for_aa, styl, aa, legend);
        if (aVerbose) {
            fmt::print(stderr, "INFO: amino-acids at {}: {} {}\n", aPos, aa, indices_for_aa.size());
            report_antigens(std::begin(indices_for_aa), std::end(indices_for_aa), aChartDraw, report_names_threshold);
        }
    }

    if (auto make_centroid = rjson::get_or(args(), "centroid", false); make_centroid) {
        auto layout = aChartDraw.projection().transformed_layout();
        for (auto [aa, indexes] : aa_indices) {
            if (indexes.size() > 1) {
                const auto sum_vectors = [](acmacs::PointCoordinates sum, const auto& point) {
                    for (auto dim : acmacs::range(std::get<0>(point).number_of_dimensions()))
                        sum[dim] += std::get<0>(point)[dim];
                    return sum;
                };

                // coordinates, distance to centroid of all points, distance to centroid of 90% closest points
                using element_t = std::tuple<acmacs::PointCoordinates, double, double>;
                std::vector<element_t> points(indexes.size(), {acmacs::PointCoordinates(layout->number_of_dimensions()), 0.0, 0.0});
                std::transform(indexes.begin(), indexes.end(), points.begin(), [layout](auto index) -> element_t { return {layout->get(index), -1, -1}; });
                acmacs::PointCoordinates centroid = std::accumulate(points.begin(), points.end(), acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors);
                centroid /= points.size();
                std::for_each(points.begin(), points.end(), [&centroid](auto& point) { std::get<1>(point) = acmacs::distance(std::get<0>(point), centroid); });
                std::sort(points.begin(), points.end(), [](const auto& p1, const auto& p2) { return std::get<1>(p1) < std::get<1>(p2); });
                const auto radius = std::get<1>(points.back());
                // std::cerr << "DEBUG: min dist:" << std::get<1>(points.front()) << " max:" << radius << '\n';

                const auto num_points_90 = static_cast<long>(points.size() * 0.9);
                acmacs::PointCoordinates centroid_90 = std::accumulate(points.begin(), points.begin() + num_points_90, acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors);
                centroid_90 /= num_points_90;
                std::for_each(points.begin(), points.begin() + num_points_90, [&centroid_90](auto& point) { std::get<2>(point) = acmacs::distance(std::get<0>(point), centroid_90); });
                std::sort(points.begin(), points.begin() + num_points_90, [](const auto& p1, const auto& p2) { return std::get<2>(p1) < std::get<2>(p2); });
                const auto radius_90 = std::get<2>(*(points.begin() + num_points_90 - 1));

                // aChartDraw.point(centroid, Pixels{10}).color(color_for_aa.find(aa)->second, GREEN);
                aChartDraw.circle(centroid, Scaled{radius * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second);
                aChartDraw.circle(centroid, Scaled{radius_90 * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second);
            }
        }
    }

} // ModAminoAcids::aa_pos

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

void ModAminoAcids::make_color_for_aa(std::map<std::string, Color>& color_for_aa, const std::vector<std::string>& aa_sorted)
{
    if (const auto& colors = args()["colors"]; !colors.is_null()) {
        std::vector<std::string> aa_without_colors;
        for (const auto& aa : aa_sorted) {
            if (const auto& color = colors[aa]; !color.is_null()) {
                color_for_aa[aa] = Color(static_cast<std::string_view>(color));
            }
            else
                aa_without_colors.push_back(aa);
        }
        if (!aa_without_colors.empty())
            throw unrecognized_mod{"the following AAs has no colors defined in settings \"colors\": " + acmacs::to_string(aa_without_colors)};
    }
    else {
        for (auto [index, aa]: acmacs::enumerate(aa_sorted)) {
            color_for_aa[aa] = fill_color_default(index, aa);
        }
    }

} // ModAminoAcids::make_color_for_aa

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

void ModAminoAcids::aa_group(ChartDraw& aChartDraw, const rjson::value& aGroup, bool aVerbose, size_t report_names_threshold)
{
    const auto& pos_aa = aGroup["pos_aa"];
    std::vector<size_t> positions(pos_aa.size());
    rjson::transform(pos_aa, std::begin(positions), [](const rjson::value& src) -> size_t { return std::stoul(static_cast<std::string>(src)); });
    std::string target_aas(pos_aa.size(), ' ');
    rjson::transform(pos_aa, std::begin(target_aas), [](const rjson::value& src) { return static_cast<std::string_view>(src).back(); });
    const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions);
    if (const auto aap = aa_indices.find(target_aas); aap != aa_indices.end()) {
        auto styl = style();
        styl = point_style_from_json(aGroup);
        aChartDraw.modify(aap->second, styl, drawing_order());
        if (const auto& legend = args()["legend"]; !legend.is_null())
            add_legend(aChartDraw, aap->second, styl, string::join(" ", positions), legend);
        if (aVerbose) {
            fmt::print(stderr, "INFO: amino-acids group {}: {}\n", pos_aa, aap->second.size());
            report_antigens(std::begin(aap->second), std::end(aap->second), aChartDraw, report_names_threshold);
        }
    }
    else {
        std::cerr << "WARNING: no \"" << target_aas << "\" in " << aa_indices << '\n';
    }

} // ModAminoAcids::aa_group

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

Color ModAminoAcids::fill_color_default(size_t aIndex, std::string aAA)
{
    if (aAA == "X") {
        ++mIndexDiff;
        return Color(rjson::get_or(args(), "X_color", "grey25"));
    }
    if (mColors.empty()) {
        const auto ct = rjson::get_or(args(), "color_set", "ana");
        mColors = Color::distinct(ct == "google" ? Color::distinct_t::GoogleMaps : Color::distinct_t::Ana);
    }
    const auto index = aIndex - mIndexDiff;
    if (index < mColors.size())
        return mColors[index];
    else
        throw unrecognized_mod{fmt::format("too few distinct colors in mod ({}): {}", mColors.size(), rjson::to_string(args()))};

} // ModAminoAcids::fill_color_default

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

void ModCompareSequences::apply(ChartDraw& aChartDraw, const rjson::value& aModData)
{
    acmacs::chart::Indexes indexes1, indexes2;
    if (const auto& select1 = args()["select1"]; !select1.is_null())
        indexes1 = SelectAntigens(false, 10).select(aChartDraw, select1);
    else
        throw unrecognized_mod{fmt::format("no select1 in mod: {}", rjson::to_string(args()))};
    if (const auto& select2 = args()["select2"]; !select2.is_null())
        indexes2 = SelectAntigens(false, 10).select(aChartDraw, select2);
    else
        throw unrecognized_mod{fmt::format("no select2 in mod: {}", rjson::to_string(args()))};
    // fmt::print(stderr, "DEBUG: select1: {} select2: {}\n", indexes1, indexes2);

    const auto& matched = aChartDraw.match_seqdb();
    auto set1 = matched.filter_by_indexes(indexes1);
    auto set2 = matched.filter_by_indexes(indexes2);
    set1.append(set2);

    fmt::print("{}\n", acmacs::seqdb::compare_report_text(set1));

} // ModCompareSequences::apply

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

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>ModCompareSequences<commit_after>#include <tuple>

#include "acmacs-base/enumerate.hh"
#include "acmacs-base/fmt.hh"
#include "seqdb-3/compare.hh"
#include "acmacs-map-draw/mod-amino-acids.hh"
#include "acmacs-map-draw/draw.hh"
#include "acmacs-map-draw/report-antigens.hh"
#include "acmacs-map-draw/select.hh"

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

void ModAminoAcids::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    const auto verbose = rjson::get_or(args(), "report", false);
    const auto report_names_threshold = rjson::get_or(args(), "report_names_threshold", 10UL);
    if (const auto& pos = args()["pos"]; !pos.is_null()) {
        aa_pos(aChartDraw, pos, verbose, report_names_threshold);
    }
    else if (const auto& groups = args()["groups"]; !groups.is_null()) {
        rjson::for_each(groups, [this,&aChartDraw,verbose,report_names_threshold](const rjson::value& group) { aa_group(aChartDraw, group, verbose, report_names_threshold); });
    }
    else {
        std::cerr << "No pos no groups" << '\n';
        throw unrecognized_mod{"expected either \"pos\":[] or \"groups\":[] mod: " + rjson::to_string(args())};
    }

} // ModAminoAcids::apply

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

void ModAminoAcids::aa_pos(ChartDraw& aChartDraw, const rjson::value& aPos, bool aVerbose, size_t report_names_threshold)
{
    std::vector<size_t> positions;
    rjson::copy(aPos, positions);
    const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions);
    // aa_indices is std::map<std::string, std::vector<size_t>>
    std::vector<std::string> aa_sorted(aa_indices.size()); // most frequent aa first
    std::transform(std::begin(aa_indices), std::end(aa_indices), std::begin(aa_sorted), [](const auto& entry) -> std::string { return entry.first; });
    std::sort(std::begin(aa_sorted), std::end(aa_sorted), [&aa_indices](const auto& n1, const auto& n2) -> bool { return aa_indices.find(n1)->second.size() > aa_indices.find(n2)->second.size(); });
    std::map<std::string, Color> color_for_aa;
    make_color_for_aa(color_for_aa, aa_sorted);
    for (auto [index, aa] : acmacs::enumerate(aa_sorted)) {
        const auto& indices_for_aa = aa_indices.find(aa)->second;
        auto styl = style();
        if (auto ca = color_for_aa.find(aa); ca == color_for_aa.end())
            throw unrecognized_mod{"cannot find color for AA: " + aa + ", \"colors\" in the settings is not complete?"};
        else
            styl.fill = ca->second;
        aChartDraw.modify(indices_for_aa, styl, drawing_order());
        if (const auto& legend = args()["legend"]; !legend.is_null())
            add_legend(aChartDraw, indices_for_aa, styl, aa, legend);
        if (aVerbose) {
            fmt::print(stderr, "INFO: amino-acids at {}: {} {}\n", aPos, aa, indices_for_aa.size());
            report_antigens(std::begin(indices_for_aa), std::end(indices_for_aa), aChartDraw, report_names_threshold);
        }
    }

    if (auto make_centroid = rjson::get_or(args(), "centroid", false); make_centroid) {
        auto layout = aChartDraw.projection().transformed_layout();
        for (auto [aa, indexes] : aa_indices) {
            if (indexes.size() > 1) {
                const auto sum_vectors = [](acmacs::PointCoordinates sum, const auto& point) {
                    for (auto dim : acmacs::range(std::get<0>(point).number_of_dimensions()))
                        sum[dim] += std::get<0>(point)[dim];
                    return sum;
                };

                // coordinates, distance to centroid of all points, distance to centroid of 90% closest points
                using element_t = std::tuple<acmacs::PointCoordinates, double, double>;
                std::vector<element_t> points(indexes.size(), {acmacs::PointCoordinates(layout->number_of_dimensions()), 0.0, 0.0});
                std::transform(indexes.begin(), indexes.end(), points.begin(), [layout](auto index) -> element_t { return {layout->get(index), -1, -1}; });
                acmacs::PointCoordinates centroid = std::accumulate(points.begin(), points.end(), acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors);
                centroid /= points.size();
                std::for_each(points.begin(), points.end(), [&centroid](auto& point) { std::get<1>(point) = acmacs::distance(std::get<0>(point), centroid); });
                std::sort(points.begin(), points.end(), [](const auto& p1, const auto& p2) { return std::get<1>(p1) < std::get<1>(p2); });
                const auto radius = std::get<1>(points.back());
                // std::cerr << "DEBUG: min dist:" << std::get<1>(points.front()) << " max:" << radius << '\n';

                const auto num_points_90 = static_cast<long>(points.size() * 0.9);
                acmacs::PointCoordinates centroid_90 = std::accumulate(points.begin(), points.begin() + num_points_90, acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors);
                centroid_90 /= num_points_90;
                std::for_each(points.begin(), points.begin() + num_points_90, [&centroid_90](auto& point) { std::get<2>(point) = acmacs::distance(std::get<0>(point), centroid_90); });
                std::sort(points.begin(), points.begin() + num_points_90, [](const auto& p1, const auto& p2) { return std::get<2>(p1) < std::get<2>(p2); });
                const auto radius_90 = std::get<2>(*(points.begin() + num_points_90 - 1));

                // aChartDraw.point(centroid, Pixels{10}).color(color_for_aa.find(aa)->second, GREEN);
                aChartDraw.circle(centroid, Scaled{radius * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second);
                aChartDraw.circle(centroid, Scaled{radius_90 * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second);
            }
        }
    }

} // ModAminoAcids::aa_pos

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

void ModAminoAcids::make_color_for_aa(std::map<std::string, Color>& color_for_aa, const std::vector<std::string>& aa_sorted)
{
    if (const auto& colors = args()["colors"]; !colors.is_null()) {
        std::vector<std::string> aa_without_colors;
        for (const auto& aa : aa_sorted) {
            if (const auto& color = colors[aa]; !color.is_null()) {
                color_for_aa[aa] = Color(static_cast<std::string_view>(color));
            }
            else
                aa_without_colors.push_back(aa);
        }
        if (!aa_without_colors.empty())
            throw unrecognized_mod{"the following AAs has no colors defined in settings \"colors\": " + acmacs::to_string(aa_without_colors)};
    }
    else {
        for (auto [index, aa]: acmacs::enumerate(aa_sorted)) {
            color_for_aa[aa] = fill_color_default(index, aa);
        }
    }

} // ModAminoAcids::make_color_for_aa

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

void ModAminoAcids::aa_group(ChartDraw& aChartDraw, const rjson::value& aGroup, bool aVerbose, size_t report_names_threshold)
{
    const auto& pos_aa = aGroup["pos_aa"];
    std::vector<size_t> positions(pos_aa.size());
    rjson::transform(pos_aa, std::begin(positions), [](const rjson::value& src) -> size_t { return std::stoul(static_cast<std::string>(src)); });
    std::string target_aas(pos_aa.size(), ' ');
    rjson::transform(pos_aa, std::begin(target_aas), [](const rjson::value& src) { return static_cast<std::string_view>(src).back(); });
    const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions);
    if (const auto aap = aa_indices.find(target_aas); aap != aa_indices.end()) {
        auto styl = style();
        styl = point_style_from_json(aGroup);
        aChartDraw.modify(aap->second, styl, drawing_order());
        if (const auto& legend = args()["legend"]; !legend.is_null())
            add_legend(aChartDraw, aap->second, styl, string::join(" ", positions), legend);
        if (aVerbose) {
            fmt::print(stderr, "INFO: amino-acids group {}: {}\n", pos_aa, aap->second.size());
            report_antigens(std::begin(aap->second), std::end(aap->second), aChartDraw, report_names_threshold);
        }
    }
    else {
        std::cerr << "WARNING: no \"" << target_aas << "\" in " << aa_indices << '\n';
    }

} // ModAminoAcids::aa_group

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

Color ModAminoAcids::fill_color_default(size_t aIndex, std::string aAA)
{
    if (aAA == "X") {
        ++mIndexDiff;
        return Color(rjson::get_or(args(), "X_color", "grey25"));
    }
    if (mColors.empty()) {
        const auto ct = rjson::get_or(args(), "color_set", "ana");
        mColors = Color::distinct(ct == "google" ? Color::distinct_t::GoogleMaps : Color::distinct_t::Ana);
    }
    const auto index = aIndex - mIndexDiff;
    if (index < mColors.size())
        return mColors[index];
    else
        return mColors.back();
    // throw unrecognized_mod{fmt::format("too few distinct colors in mod ({}): {}", mColors.size(), rjson::to_string(args()))};

} // ModAminoAcids::fill_color_default

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

void ModCompareSequences::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/)
{
    acmacs::chart::Indexes indexes1, indexes2;
    if (const auto& select1 = args()["select1"]; !select1.is_null())
        indexes1 = SelectAntigens(false, 10).select(aChartDraw, select1);
    else
        throw unrecognized_mod{fmt::format("no select1 in mod: {}", rjson::to_string(args()))};
    if (const auto& select2 = args()["select2"]; !select2.is_null())
        indexes2 = SelectAntigens(false, 10).select(aChartDraw, select2);
    else
        throw unrecognized_mod{fmt::format("no select2 in mod: {}", rjson::to_string(args()))};
    // fmt::print(stderr, "DEBUG: select1: {} select2: {}\n", indexes1, indexes2);

    const auto& matched = aChartDraw.match_seqdb();
    auto set1 = matched.filter_by_indexes(indexes1);
    auto set2 = matched.filter_by_indexes(indexes2);
    set1.append(set2);

    fmt::print("{}\n", acmacs::seqdb::compare_report_text(set1));

} // ModCompareSequences::apply

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

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


<commit_before>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/

#ifndef __itktubeTubeXIO_hxx
#define __itktubeTubeXIO_hxx

#include "itktubeTubeXIO.h"

#include "metaUtils.h"

namespace itk
{

namespace tube
{

template< unsigned int TDimension >
TubeXIO< TDimension >
::TubeXIO()
{
  m_TubeGroup = TubeGroupType::New();
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    m_Dimensions[i] = 1;
    }
}

template< unsigned int TDimension >
TubeXIO< TDimension >
::~TubeXIO( void )
{
}

//
template< unsigned int TDimension >
void
TubeXIO< TDimension >
::PrintSelf( std::ostream & os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );

  if( this->m_TubeGroup.IsNotNull() )
    {
    os << indent << "Tube Group = " << this->m_TubeGroup << std::endl;
    }
  else
    {
    os << indent << "Tube Group = NULL" << std::endl;
    }
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Read( const std::string & _fileName )
{
  std::vector< MET_FieldRecordType * > fields;

  MET_FieldRecordType * mF;

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NDims", MET_INT, false);
  fields.push_back(mF);
  int nDimsRecNum = MET_GetFieldRecordNumber("NDims", &fields);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Dimensions", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "VoxelSize", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NObjects", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "End Header", MET_NONE, false);
  mF->terminateRead = true;
  fields.push_back(mF);

  std::ifstream tmpReadStream( _fileName.c_str(), std::ios::binary |
    std::ios::in );

  if( !tmpReadStream.rdbuf()->is_open() )
    {
    return false;
    }

  std::vector< MET_FieldRecordType * > extraFields;
  if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
    {
    std::cerr << "Tube: Read failed" << std::endl;
    return false;
    }

  mF = MET_GetFieldRecord( "NDims", &fields );
  if( mF->defined )
    {
    int nDims = (int)mF->value[0];

    if( (int)mF->value[0] != TDimension )
      {
      std::cerr << "Tube: Read failed: object is " << nDims
        << " dimensional and was expecting " << TDimension << " dimensional."
        << std::endl;
      return false;
      }
    }

  mF = MET_GetFieldRecord( "Dimensions", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      this->m_Dimensions[i] = (int)( mF->value[i] );
      }
    }

  double voxelSize[ TDimension ];
  mF = MET_GetFieldRecord( "VoxelSize", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      voxelSize[i] = (float)( mF->value[i] );
      }
    }

  int nObjects = 0;
  mF = MET_GetFieldRecord( "NObjects", &fields );
  if(mF->defined)
    {
    nObjects = (int)mF->value[0];
    }

  fields.clear();

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "ID", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Type", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Anat", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "TreeType", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Color", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "PointDim", MET_STRING, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NPoints", MET_INT, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Points", MET_NONE, true);
  mF->terminateRead = true;
  fields.push_back(mF);

  for( int obj = 0; obj < nObjects; ++obj )
    {
    if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
      {
      std::cerr << "Tube: Read failed" << std::endl;
      return false;
      }

    int tubeId = 0;
    mF = MET_GetFieldRecord( "ID", &fields );
    if(mF->defined)
      {
      tubeId = (int)( mF->value[0] );
      }

    char tubeType[80];
    strcpy( tubeType, "" );
    mF = MET_GetFieldRecord( "Type", &fields );
    if(mF->defined)
      {
      strcpy( tubeType, (char *)(mF->value) );
      }

    char tubeAnat[80];
    strcpy( tubeAnat, "" );
    mF = MET_GetFieldRecord( "Anat", &fields );
    if(mF->defined)
      {
      strcpy( tubeAnat, (char *)(mF->value) );
      }

    char tubeTreeType[80];
    strcpy( tubeTreeType, "" );
    mF = MET_GetFieldRecord( "TreeType", &fields );
    if(mF->defined)
      {
      strcpy( tubeTreeType, (char *)(mF->value) );
      }

    char tubeColor[80];
    strcpy( tubeColor, "" );
    mF = MET_GetFieldRecord( "Color", &fields );
    if(mF->defined)
      {
      strcpy( tubeColor, (char *)(mF->value) );
      }

    char tubePointDim[80];
    strcpy( tubePointDim, "" );
    mF = MET_GetFieldRecord( "PointDim", &fields );
    if(mF->defined)
      {
      strcpy( tubePointDim, (char *)(mF->value) );
      }

    unsigned int nPoints = 0;
    mF = MET_GetFieldRecord( "NPoints", &fields );
    if(mF->defined)
      {
      nPoints = (unsigned int)( mF->value[0] );
      }

    typename TubeType::Pointer tube = TubeType::New();

    for( unsigned int j=0; j<nPoints; ++j )
      {
      typename TubeType::TubePointType pnt;

      typename TubeType::TubePointType::PointType x;
      for( unsigned int d=0; d<TDimension; ++d )
        {
        tmpReadStream >> x[d];
        tmpReadStream.get();
        }
      pnt.SetPosition( x );

      double r;
      tmpReadStream >> r;
      pnt.SetRadius( r );

      tube->GetPoints().push_back( pnt );
      }

    char c = ' ';
    while( c != '\n' && !tmpReadStream.eof() )
      {
      c = tmpReadStream.get();// to avoid unrecognize charactere
      }

    tube->SetSpacing( voxelSize );
    tube->SetId( tubeId );
    tube->ComputeTangentAndNormals();

    m_TubeGroup->AddSpatialObject( tube );
    }

  tmpReadStream.close();

  return true;
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Write( const std::string & _fileName )
{
  typedef typename TubeType::PointListType  PointListType;

  std::ofstream tmpWriteStream( _fileName.c_str(), std::ios::binary |
    std::ios::out);

  tmpWriteStream << "NDims: " << TDimension << std::endl;
  tmpWriteStream << "Dimensions: ";
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    tmpWriteStream << this->m_Dimensions[i];
    if ( i != TDimension - 1 )
      {
      tmpWriteStream << " ";
      }
    }
  tmpWriteStream << std::endl;

  char soType[80];
  sprintf( soType, "Tube" );
  typename TubeType::ChildrenListType * tubeList =
    m_TubeGroup->GetChildren( 99999, soType );
  tmpWriteStream << "VoxelSize:";
  for( unsigned int i=0; i<TDimension; ++i )
    {
    tmpWriteStream << " " << ( *(tubeList->begin()) )->GetSpacing()[i];
    }
  tmpWriteStream << std::endl;

  unsigned int nObjects = tubeList->size();
  tmpWriteStream << "NObjects: " << nObjects << std::endl;

  tmpWriteStream << "End Header:" << std::endl << std::endl;

  typename TubeType::ChildrenListType::iterator tIt = tubeList->begin();
  typename TubeType::ChildrenListType::iterator tEnd = tubeList->end();
  while( tIt != tEnd )
    {
    typename TubeType::Pointer tube = ((TubeType *)(tIt->GetPointer()));

    tmpWriteStream << "ID: " << tube->GetId() << std::endl;
    tmpWriteStream << "Type: Tube" << std::endl;
    tmpWriteStream << "Anat: artery" << std::endl;
    tmpWriteStream << "TreeType: orphan" << std::endl;
    tmpWriteStream << "Color: 1 0.3 0.21" << std::endl;
    tmpWriteStream << "PointDim: 4 x y z r" << std::endl;
    unsigned int nPoints = tube ->GetNumberOfPoints();
    tmpWriteStream << "NPoints: " << nPoints << std::endl;
    tmpWriteStream << "Points:" << std::endl;
    for( unsigned int i=0; i<nPoints; ++i )
      {
      typedef const typename TubeType::TubePointType  TubePointType;
      TubePointType * pnt;
      pnt = static_cast< TubePointType * >( tube->GetPoint( i ) );
      for( unsigned int k=0; k<TDimension; ++k )
        {
        tmpWriteStream << pnt->GetPosition()[k] << " ";
        }
      tmpWriteStream << pnt->GetRadius() << std::endl;
      }
    tmpWriteStream << std::endl;

    ++tIt;
    }
  tmpWriteStream.close();

  return true;
}

template< unsigned int TDimension >
void
TubeXIO< TDimension >
::SetTubeGroup( TubeGroupType * _tubes )
{
  m_TubeGroup = _tubes;
}

template< unsigned int TDimension >
typename GroupSpatialObject< TDimension >::Pointer &
TubeXIO< TDimension >
::GetTubeGroup( void )
{
  return m_TubeGroup;
}

}; // tube namespace

}; // itk namespace

#endif

<commit_msg>ENH: Remove duplicate points when converting TubeX to TubeTK format<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/

#ifndef __itktubeTubeXIO_hxx
#define __itktubeTubeXIO_hxx

#include "itktubeTubeXIO.h"

#include "metaUtils.h"

namespace itk
{

namespace tube
{

template< unsigned int TDimension >
TubeXIO< TDimension >
::TubeXIO()
{
  m_TubeGroup = TubeGroupType::New();
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    m_Dimensions[i] = 1;
    }
}

template< unsigned int TDimension >
TubeXIO< TDimension >
::~TubeXIO( void )
{
}

//
template< unsigned int TDimension >
void
TubeXIO< TDimension >
::PrintSelf( std::ostream & os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );

  if( this->m_TubeGroup.IsNotNull() )
    {
    os << indent << "Tube Group = " << this->m_TubeGroup << std::endl;
    }
  else
    {
    os << indent << "Tube Group = NULL" << std::endl;
    }
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Read( const std::string & _fileName )
{
  std::vector< MET_FieldRecordType * > fields;

  MET_FieldRecordType * mF;

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NDims", MET_INT, false);
  fields.push_back(mF);
  int nDimsRecNum = MET_GetFieldRecordNumber("NDims", &fields);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Dimensions", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "VoxelSize", MET_FLOAT_ARRAY, false, nDimsRecNum);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NObjects", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "End Header", MET_NONE, false);
  mF->terminateRead = true;
  fields.push_back(mF);

  std::ifstream tmpReadStream( _fileName.c_str(), std::ios::binary |
    std::ios::in );

  if( !tmpReadStream.rdbuf()->is_open() )
    {
    return false;
    }

  std::vector< MET_FieldRecordType * > extraFields;
  if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
    {
    std::cerr << "Tube: Read failed" << std::endl;
    return false;
    }

  mF = MET_GetFieldRecord( "NDims", &fields );
  if( mF->defined )
    {
    int nDims = (int)mF->value[0];

    if( (int)mF->value[0] != TDimension )
      {
      std::cerr << "Tube: Read failed: object is " << nDims
        << " dimensional and was expecting " << TDimension << " dimensional."
        << std::endl;
      return false;
      }
    }

  mF = MET_GetFieldRecord( "Dimensions", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      this->m_Dimensions[i] = (int)( mF->value[i] );
      }
    }

  double voxelSize[ TDimension ];
  mF = MET_GetFieldRecord( "VoxelSize", &fields );
  if(mF->defined)
    {
    for( unsigned int i=0; i<TDimension; ++i )
      {
      voxelSize[i] = (float)( mF->value[i] );
      }
    }

  int nObjects = 0;
  mF = MET_GetFieldRecord( "NObjects", &fields );
  if(mF->defined)
    {
    nObjects = (int)mF->value[0];
    }

  fields.clear();

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "ID", MET_INT, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Type", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Anat", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "TreeType", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Color", MET_STRING, false);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "PointDim", MET_STRING, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "NPoints", MET_INT, true);
  fields.push_back(mF);

  mF = new MET_FieldRecordType;
  MET_InitReadField(mF, "Points", MET_NONE, true);
  mF->terminateRead = true;
  fields.push_back(mF);

  for( int obj = 0; obj < nObjects; ++obj )
    {
    if( !MET_Read( tmpReadStream, &fields, ':', false, true, &extraFields ) )
      {
      std::cerr << "Tube: Read failed" << std::endl;
      return false;
      }

    int tubeId = 0;
    mF = MET_GetFieldRecord( "ID", &fields );
    if(mF->defined)
      {
      tubeId = (int)( mF->value[0] );
      }

    char tubeType[80];
    strcpy( tubeType, "" );
    mF = MET_GetFieldRecord( "Type", &fields );
    if(mF->defined)
      {
      strcpy( tubeType, (char *)(mF->value) );
      }

    char tubeAnat[80];
    strcpy( tubeAnat, "" );
    mF = MET_GetFieldRecord( "Anat", &fields );
    if(mF->defined)
      {
      strcpy( tubeAnat, (char *)(mF->value) );
      }

    char tubeTreeType[80];
    strcpy( tubeTreeType, "" );
    mF = MET_GetFieldRecord( "TreeType", &fields );
    if(mF->defined)
      {
      strcpy( tubeTreeType, (char *)(mF->value) );
      }

    char tubeColor[80];
    strcpy( tubeColor, "" );
    mF = MET_GetFieldRecord( "Color", &fields );
    if(mF->defined)
      {
      strcpy( tubeColor, (char *)(mF->value) );
      }

    char tubePointDim[80];
    strcpy( tubePointDim, "" );
    mF = MET_GetFieldRecord( "PointDim", &fields );
    if(mF->defined)
      {
      strcpy( tubePointDim, (char *)(mF->value) );
      }

    unsigned int nPoints = 0;
    mF = MET_GetFieldRecord( "NPoints", &fields );
    if(mF->defined)
      {
      nPoints = (unsigned int)( mF->value[0] );
      }

    typename TubeType::Pointer tube = TubeType::New();

    for( unsigned int j=0; j<nPoints; ++j )
      {
      typename TubeType::TubePointType pnt;

      typename TubeType::TubePointType::PointType x;
      for( unsigned int d=0; d<TDimension; ++d )
        {
        tmpReadStream >> x[d];
        tmpReadStream.get();
        }
      pnt.SetPosition( x );

      double r;
      tmpReadStream >> r;
      pnt.SetRadius( r );

      tube->GetPoints().push_back( pnt );
      }

    char c = ' ';
    while( c != '\n' && !tmpReadStream.eof() )
      {
      c = tmpReadStream.get();// to avoid unrecognize charactere
      }

    tube->SetSpacing( voxelSize );
    tube->SetId( tubeId );
    tube->RemoveDuplicatePoints();
    tube->ComputeTangentAndNormals();

    m_TubeGroup->AddSpatialObject( tube );
    }

  tmpReadStream.close();

  return true;
}

template< unsigned int TDimension >
bool
TubeXIO< TDimension >
::Write( const std::string & _fileName )
{
  typedef typename TubeType::PointListType  PointListType;

  std::ofstream tmpWriteStream( _fileName.c_str(), std::ios::binary |
    std::ios::out);

  tmpWriteStream << "NDims: " << TDimension << std::endl;
  tmpWriteStream << "Dimensions: ";
  for ( unsigned int i = 0; i < TDimension; ++i )
    {
    tmpWriteStream << this->m_Dimensions[i];
    if ( i != TDimension - 1 )
      {
      tmpWriteStream << " ";
      }
    }
  tmpWriteStream << std::endl;

  char soType[80];
  sprintf( soType, "Tube" );
  typename TubeType::ChildrenListType * tubeList =
    m_TubeGroup->GetChildren( 99999, soType );
  tmpWriteStream << "VoxelSize:";
  for( unsigned int i=0; i<TDimension; ++i )
    {
    tmpWriteStream << " " << ( *(tubeList->begin()) )->GetSpacing()[i];
    }
  tmpWriteStream << std::endl;

  unsigned int nObjects = tubeList->size();
  tmpWriteStream << "NObjects: " << nObjects << std::endl;

  tmpWriteStream << "End Header:" << std::endl << std::endl;

  typename TubeType::ChildrenListType::iterator tIt = tubeList->begin();
  typename TubeType::ChildrenListType::iterator tEnd = tubeList->end();
  while( tIt != tEnd )
    {
    typename TubeType::Pointer tube = ((TubeType *)(tIt->GetPointer()));

    tmpWriteStream << "ID: " << tube->GetId() << std::endl;
    tmpWriteStream << "Type: Tube" << std::endl;
    tmpWriteStream << "Anat: artery" << std::endl;
    tmpWriteStream << "TreeType: orphan" << std::endl;
    tmpWriteStream << "Color: 1 0.3 0.21" << std::endl;
    tmpWriteStream << "PointDim: 4 x y z r" << std::endl;
    unsigned int nPoints = tube ->GetNumberOfPoints();
    tmpWriteStream << "NPoints: " << nPoints << std::endl;
    tmpWriteStream << "Points:" << std::endl;
    for( unsigned int i=0; i<nPoints; ++i )
      {
      typedef const typename TubeType::TubePointType  TubePointType;
      TubePointType * pnt;
      pnt = static_cast< TubePointType * >( tube->GetPoint( i ) );
      for( unsigned int k=0; k<TDimension; ++k )
        {
        tmpWriteStream << pnt->GetPosition()[k] << " ";
        }
      tmpWriteStream << pnt->GetRadius() << std::endl;
      }
    tmpWriteStream << std::endl;

    ++tIt;
    }
  tmpWriteStream.close();

  return true;
}

template< unsigned int TDimension >
void
TubeXIO< TDimension >
::SetTubeGroup( TubeGroupType * _tubes )
{
  m_TubeGroup = _tubes;
}

template< unsigned int TDimension >
typename GroupSpatialObject< TDimension >::Pointer &
TubeXIO< TDimension >
::GetTubeGroup( void )
{
  return m_TubeGroup;
}

}; // tube namespace

}; // itk namespace

#endif

<|endoftext|>


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

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "PipelineView.h"

#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"

#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>

#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>

namespace tomviz {

PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
  setIndentation(20);
  setRootIsDecorated(false);
  setItemsExpandable(false);

  QString customStyle = "QTreeView::branch { background-color: white; }";
  this->setStyleSheet(customStyle);
  setAlternatingRowColors(true);
  setSelectionBehavior(QAbstractItemView::SelectRows);

  // track selection to update ActiveObjects.
  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
          SLOT(setCurrent(DataSource*)));
  connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)),
          SLOT(setCurrent(Module*)));

  connect(this, SIGNAL(doubleClicked(QModelIndex)),
          SLOT(rowDoubleClicked(QModelIndex)));
}

PipelineView::~PipelineView() = default;

void PipelineView::keyPressEvent(QKeyEvent* e)
{
  QTreeView::keyPressEvent(e);
  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
    deleteItem(currentIndex());
  }
}

void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
  auto idx = this->indexAt(e->pos());
  if (!idx.isValid()) {
    return;
  }

  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  auto dataSource = pipelineModel->dataSource(idx);
  auto result = pipelineModel->result(idx);

  bool childData =
    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
    (result && qobject_cast<Operator*>(result->parent()));
  if (childData) {
    return;
  }

  QMenu contextMenu;
  QAction* cloneAction = nullptr;
  QAction* markAsAction = nullptr;
  if (dataSource != nullptr) {
    cloneAction = contextMenu.addAction("Clone");
    new CloneDataReaction(cloneAction);
    if (dataSource->type() == DataSource::Volume) {
      markAsAction = contextMenu.addAction("Mark as Tilt Series");
    } else {
      markAsAction = contextMenu.addAction("Mark as Volume");
    }
  }
  QAction* deleteAction = contextMenu.addAction("Delete");
  auto globalPoint = mapToGlobal(e->pos());
  QAction* selectedItem = contextMenu.exec(globalPoint);
  // Some action was selected, so process it.
  if (selectedItem == deleteAction) {
    deleteItem(idx);
  } else if (markAsAction != nullptr && markAsAction == selectedItem) {
    QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());
    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
  }
}

void PipelineView::deleteItem(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(idx);
  auto module = pipelineModel->module(idx);
  auto op = pipelineModel->op(idx);
  if (dataSource) {
    pipelineModel->removeDataSource(dataSource);
  } else if (module) {
    pipelineModel->removeModule(module);
  } else if (op) {
    pipelineModel->removeOp(op);
  }
  ActiveObjects::instance().renderAllViews();
}

void PipelineView::rowActivated(const QModelIndex& idx)
{
  if (idx.isValid() && idx.column() == 1) {
    auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
    if (pipelineModel) {
      if (auto module = pipelineModel->module(idx)) {
        module->setVisibility(!module->visibility());
        if (pqView* view = tomviz::convert<pqView*>(module->view())) {
          view->render();
        }
      } else if (auto op = pipelineModel->op(idx)) {
        pipelineModel->removeOp(op);
        expandAll();
      }
    }
  }
}

void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  if (auto op = pipelineModel->op(idx)) {
    if (op->hasCustomUI()) {
      // Create a non-modal dialog, delete it once it has been closed.
      EditOperatorDialog* dialog = new EditOperatorDialog(
        op, op->dataSource(), false, pqCoreUtilities::mainWidget());
      dialog->setAttribute(Qt::WA_DeleteOnClose, true);
      dialog->show();
    }
  } else if (auto result = pipelineModel->result(idx)) {
    if (vtkTable::SafeDownCast(result->dataObject())) {
      auto view = ActiveObjects::instance().activeView();
      vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
      controller->ShowInPreferredView(result->producerProxy(), 0, view);
    }
  }
}

void PipelineView::currentChanged(const QModelIndex& current,
                                  const QModelIndex&)
{
  if (!current.isValid()) {
    return;
  }
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(current);
  auto module = pipelineModel->module(current);
  if (dataSource) {
    ActiveObjects::instance().setActiveDataSource(dataSource);
  } else if (module) {
    ActiveObjects::instance().setActiveModule(module);
  }
}

void PipelineView::setCurrent(DataSource* dataSource)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}

void PipelineView::setCurrent(Module* module)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->moduleIndex(module));
}

void PipelineView::setCurrent(Operator*)
{
}
}
<commit_msg>right click to save data<commit_after>/******************************************************************************

  This source file is part of the tomviz project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

******************************************************************************/

#include "PipelineView.h"

#include "ActiveObjects.h"
#include "CloneDataReaction.h"
#include "EditOperatorDialog.h"
#include "Module.h"
#include "ModuleManager.h"
#include "Operator.h"
#include "OperatorResult.h"
#include "PipelineModel.h"
#include "SaveDataReaction.h"
#include "ToggleDataTypeReaction.h"
#include "Utilities.h"

#include <pqCoreUtilities.h>
#include <pqSpreadSheetView.h>
#include <pqView.h>
#include <vtkNew.h>
#include <vtkSMParaViewPipelineControllerWithRendering.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>

#include <QKeyEvent>
#include <QMainWindow>
#include <QMenu>

namespace tomviz {

PipelineView::PipelineView(QWidget* p) : QTreeView(p)
{
  connect(this, SIGNAL(clicked(QModelIndex)), SLOT(rowActivated(QModelIndex)));
  setIndentation(20);
  setRootIsDecorated(false);
  setItemsExpandable(false);

  QString customStyle = "QTreeView::branch { background-color: white; }";
  this->setStyleSheet(customStyle);
  setAlternatingRowColors(true);
  setSelectionBehavior(QAbstractItemView::SelectRows);

  // track selection to update ActiveObjects.
  connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),
          SLOT(setCurrent(DataSource*)));
  connect(&ActiveObjects::instance(), SIGNAL(moduleChanged(Module*)),
          SLOT(setCurrent(Module*)));

  connect(this, SIGNAL(doubleClicked(QModelIndex)),
          SLOT(rowDoubleClicked(QModelIndex)));
}

PipelineView::~PipelineView() = default;

void PipelineView::keyPressEvent(QKeyEvent* e)
{
  QTreeView::keyPressEvent(e);
  if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace) {
    deleteItem(currentIndex());
  }
}

void PipelineView::contextMenuEvent(QContextMenuEvent* e)
{
  auto idx = this->indexAt(e->pos());
  if (!idx.isValid()) {
    return;
  }

  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  auto dataSource = pipelineModel->dataSource(idx);
  auto result = pipelineModel->result(idx);

  bool childData =
    (dataSource && qobject_cast<Operator*>(dataSource->parent())) ||
    (result && qobject_cast<Operator*>(result->parent()));
  if (childData) {
    return;
  }

  QMenu contextMenu;
  QAction* cloneAction = nullptr;
  QAction* markAsAction = nullptr;
  QAction* saveDataAction = nullptr;
  if (dataSource != nullptr) {
    cloneAction = contextMenu.addAction("Clone");
    new CloneDataReaction(cloneAction);
    if (dataSource->type() == DataSource::Volume) {
      saveDataAction = contextMenu.addAction("Save Data");
      new SaveDataReaction(saveDataAction);
      markAsAction = contextMenu.addAction("Mark as Tilt Series");
    } else {
      markAsAction = contextMenu.addAction("Mark as Volume");
    }
  }
  QAction* deleteAction = contextMenu.addAction("Delete");
  auto globalPoint = mapToGlobal(e->pos());
  QAction* selectedItem = contextMenu.exec(globalPoint);
  // Some action was selected, so process it.
  if (selectedItem == deleteAction) {
    deleteItem(idx);
  } else if (markAsAction != nullptr && markAsAction == selectedItem) {
    QMainWindow* mainWindow = qobject_cast<QMainWindow*>(this->window());
    ToggleDataTypeReaction::toggleDataType(mainWindow, dataSource);
  }
}

void PipelineView::deleteItem(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(idx);
  auto module = pipelineModel->module(idx);
  auto op = pipelineModel->op(idx);
  if (dataSource) {
    pipelineModel->removeDataSource(dataSource);
  } else if (module) {
    pipelineModel->removeModule(module);
  } else if (op) {
    pipelineModel->removeOp(op);
  }
  ActiveObjects::instance().renderAllViews();
}

void PipelineView::rowActivated(const QModelIndex& idx)
{
  if (idx.isValid() && idx.column() == 1) {
    auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
    if (pipelineModel) {
      if (auto module = pipelineModel->module(idx)) {
        module->setVisibility(!module->visibility());
        if (pqView* view = tomviz::convert<pqView*>(module->view())) {
          view->render();
        }
      } else if (auto op = pipelineModel->op(idx)) {
        pipelineModel->removeOp(op);
        expandAll();
      }
    }
  }
}

void PipelineView::rowDoubleClicked(const QModelIndex& idx)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(this->model());
  Q_ASSERT(pipelineModel);
  if (auto op = pipelineModel->op(idx)) {
    if (op->hasCustomUI()) {
      // Create a non-modal dialog, delete it once it has been closed.
      EditOperatorDialog* dialog = new EditOperatorDialog(
        op, op->dataSource(), false, pqCoreUtilities::mainWidget());
      dialog->setAttribute(Qt::WA_DeleteOnClose, true);
      dialog->show();
    }
  } else if (auto result = pipelineModel->result(idx)) {
    if (vtkTable::SafeDownCast(result->dataObject())) {
      auto view = ActiveObjects::instance().activeView();
      vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;
      controller->ShowInPreferredView(result->producerProxy(), 0, view);
    }
  }
}

void PipelineView::currentChanged(const QModelIndex& current,
                                  const QModelIndex&)
{
  if (!current.isValid()) {
    return;
  }
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  Q_ASSERT(pipelineModel);
  auto dataSource = pipelineModel->dataSource(current);
  auto module = pipelineModel->module(current);
  if (dataSource) {
    ActiveObjects::instance().setActiveDataSource(dataSource);
  } else if (module) {
    ActiveObjects::instance().setActiveModule(module);
  }
}

void PipelineView::setCurrent(DataSource* dataSource)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->dataSourceIndex(dataSource));
}

void PipelineView::setCurrent(Module* module)
{
  auto pipelineModel = qobject_cast<PipelineModel*>(model());
  this->setCurrentIndex(pipelineModel->moduleIndex(module));
}

void PipelineView::setCurrent(Operator*)
{
}
}
<|endoftext|>


<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{

    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    bool runOn = true;
    string choice;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - Add" << "\t" << "Add a person to the database." << endl;
        cout << " (2) - Remove" << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - View" << "\t" << "View the entire database." << endl;
        cout << " (4) - Save" << "\t" << "Save the database." << endl;
        cout << " (5) - Search" << "\t" << "Search the database." << endl;
        cout << " (6) - Sort" << "\t" << "Sort the database." << endl;
        cout << " (7) - Exit" << "\t" << "Exit." << endl;

        cout << "Enter your command (1 - 7): ";
        cin >> choice;

        if (choice != "7")
        {
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }

    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "6")
    {
        string sortcho;
        cout << "Enter your sort command (1, 2):" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - Sort by chronological order" << endl;
        cout << " (3) - Return to main menu" << endl;
        cin >> sortcho;

        if(sortcho == "1")
        {
            list.sortNames();
             viewAll();
        }
        else if(sortcho == "2")
        {
            list.sortBirth();
             viewAll();
        }
        else if(sortcho == "3")
        {
            mainMenu();
        }

    }
    else if(ch == "5")
    {
        searching();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "8")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? " << endl;
    cout << " (1) - Name -- Searches for a name." << endl;
    cout << " (2) - Gender -- Searches for a Gender." << endl;
    cout << " (3) - Year -- Searches for a year born." << endl;
    cout << " (4) - Exit -- Exit to the main menu" << endl;
    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void ClassUI::search()
{
        string searchChoice;
        cin >> searchChoice;
        if (searchChoice == "1")
        {

            string namesearch;
            cout << "Enter a name you want to search for: ";
            cin.ignore();
            std::getline(std::cin,namesearch);

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                std::size_t found = list.getName(i).find(namesearch);
                if (found!=std::string::npos)
                {
                    view(i);
                }

            }
            if(list.nameSearcher(namesearch) == false)
            {
                cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "2")
        {
            char gendersearch;

            cout << "Enter a gender you want to search for: (M/F)";
            cin >> gendersearch;
            if(gendersearch == 'm')
                {
                     gendersearch = 'M';
                }
            else if (gendersearch == 'f')
                {
                     gendersearch = 'F';
                }

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(gendersearch == list.getGender(i))
                {
                    gendersearch = list.getGender(i);
                    view(i);
                }
            }
            if(list.genderSearcher(gendersearch) == false)
            {
                cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "3")
        {
                int yearsearch;
                cout << "Enter a year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);
                        view(i);
                    }
                }
                if(list.yearSearcher(yearsearch) == false)
                {
                    cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                    searching();
                }
        }
        else if (searchChoice == "4")
        {
            mainMenu();
        }
        else
        {
            cout << "Error reading input. Please enter a number between 1- 3." << endl;
            search();
        }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
<commit_msg>upgradeing main menu navigation<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}

void ClassUI::run()
{

    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "-----------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    bool runOn = true;
    string choice;
    do
    {

        cout << "-----------------------------------------------------------" << endl;
        cout << " (1) - Add" << "\t" << "Add a person to the database." << endl;
        cout << " (2) - Remove" << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - View" << "\t" << "View the entire database." << endl;
        cout << " (4) - Save" << "\t" << "Save the database." << endl;
        cout << " (5) - Search" << "\t" << "Search the database." << endl;
        cout << " (6) - Sort" << "\t" << "Sort the database." << endl;
        cout << " (7) - Exit" << "\t" << "Exit." << endl;

        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else{
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}

void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }

    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "6")
    {
        string sortcho;
        cout << "Enter a sort command (1 - 3):" << endl;
        cout << "------------------------" << endl;
        cout << " (1) - Sort by alphabetical order" << endl;
        cout << " (2) - Sort by chronological order" << endl;
        cout << " (3) - Return to main menu" << endl;
        cout << "Enter your command (1 - 2): ";
        cin >> sortcho;
        cout << endl;

        if(sortcho == "1")
        {
            list.sortNames();
             viewAll();
        }
        else if(sortcho == "2")
        {
            list.sortBirth();
             viewAll();
        }
        else if(sortcho == "3")
        {
            mainMenu();
        }

    }
    else if(ch == "5")
    {
        searching();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "8")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);
    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;

    cout << list.getName(i);
    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }
    cout  << "|" << list.getBirth(i);
    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}

void ClassUI::searching()
{

    cout << "----------Select any of the following commands----------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Name -- Searches for a name." << endl;
    cout << " (2) - Gender -- Searches for a Gender." << endl;
    cout << " (3) - Year -- Searches for a year born." << endl;
    cout << " (4) - Exit -- Exit to the main menu" << endl;
    search();
}
void ClassUI::addPerson()
{
    string name;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;
    string comment;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;
    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }
    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n)";
       cin >> yesOrNo;
       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
        cout << "Input a comment about the individual: ";
        cin.ignore();
        std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }
    list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);

}

void ClassUI::search()
{
        string searchChoice;
        cout << "Enter your command (1 - 4): ";
        cin >> searchChoice;
        if (searchChoice == "1")
        {

            string namesearch;
            cout << "Enter a name you want to search for: ";
            cin.ignore();
            std::getline(std::cin,namesearch);

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                std::size_t found = list.getName(i).find(namesearch);
                if (found!=std::string::npos)
                {
                    view(i);
                }

            }
            if(list.nameSearcher(namesearch) == false)
            {
                cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "2")
        {
            char gendersearch;

            cout << "Enter a gender you want to search for: (M/F)";
            cin >> gendersearch;
            if(gendersearch == 'm')
                {
                     gendersearch = 'M';
                }
            else if (gendersearch == 'f')
                {
                     gendersearch = 'F';
                }

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(gendersearch == list.getGender(i))
                {
                    gendersearch = list.getGender(i);
                    view(i);
                }
            }
            if(list.genderSearcher(gendersearch) == false)
            {
                cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
        }
        else if (searchChoice == "3")
        {
                int yearsearch;
                cout << "Enter a year you want to search for: ";
                cin >> yearsearch;

                for(int i = 0; i < list.getPersonsSize();++i)
                {
                    if(yearsearch == list.getBirth(i))
                    {
                        yearsearch = list.getBirth(i);
                        view(i);
                    }
                }
                if(list.yearSearcher(yearsearch) == false)
                {
                    cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                    searching();
                }
        }
        else if (searchChoice == "4")
        {
            mainMenu();
        }
        else
        {
            cout << "Error reading input. Please enter a number between 1- 3." << endl;
            search();
        }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter a name of person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);
    if (list.removePerson(name) == true)
    {
        cout << "Person removed!" << endl;
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}

string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
<|endoftext|>