<commit_before> /*************************************************************************
 *
 *  $RCSfile: impswfdialog.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: cl $ $Date: 2002-11-21 14:58:01 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "impswfdialog.hxx"
#include "impswfdialog.hrc"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;

// ----------------
// - ImpPDFDialog -
// ----------------

ImpSWFDialog::ImpSWFDialog( Window* pParent, ResMgr& rResMgr, Sequence< PropertyValue >& rFilterData ) :
    ModalDialog( pParent, ResId( DLG_OPTIONS, &rResMgr ) ),
    maFiDescr( this, ResId( FI_DESCR ) ),
    maNumFldQuality( this, ResId( NUM_FLD_QUALITY ) ),
    maFiExportAllDescr( this, ResId( FI_EXPORT_ALL_DESCR ) ),
    maCheckExportAll( this, ResId( BOOL_EXPORT_ALL ) ),
    maFiExportBackgroundsDescr( this, ResId( FI_EXPORT_BACKGROUNDS_DESCR ) ),
    maCheckExportBackgrounds( this, ResId( BOOL_EXPORT_BACKGROUNDS ) ),
    maFiExportBackgroundObjectsDescr( this, ResId( FI_EXPORT_BACKGROUND_OBJECTS_DESCR ) ),
    maCheckExportBackgroundObjects( this, ResId( BOOL_EXPORT_BACKGROUND_OBJECTS ) ),
    maFiExportSlideContentsDescr( this, ResId( FI_EXPORT_SLIDE_CONTENTS_DESCR ) ),
    maCheckExportSlideContents( this, ResId( BOOL_EXPORT_SLIDE_CONTENTS ) ),
    maFiExportSoundDescr( this, ResId( FI_EXPORT_SOUND_DESCR ) ),
    maCheckExportSound( this, ResId( BOOL_EXPORT_SOUND ) ),
    maFiExportOLEAsJPEGDescr( this, ResId( FI_EXPORT_OLE_AS_JPEG_DESCR ) ),
    maCheckExportOLEAsJPEG( this, ResId( BOOL_EXPORT_OLE_AS_JPEG ) ),
    maFiExportMultipleFilesDescr( this, ResId( FI_EXPORT_MULTIPLE_FILES_DESCR ) ),
    maCheckExportMultipleFiles( this, ResId( BOOL_EXPORT_MULTIPLE_FILES ) ),

    maBtnOK( this, ResId( BTN_OK ) ),
    maBtnCancel( this, ResId( BTN_CANCEL ) ),
    maBtnHelp( this, ResId( BTN_HELP ) ),
    maConfigItem( String( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Flash/Export/" ) ), &rFilterData )
{
    const ULONG nCompressMode = maConfigItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "CompressMode" ) ), 75 );
    maNumFldQuality.SetValue( nCompressMode );

    maCheckExportAll.Check();
    maCheckExportSlideContents.Check();
    maCheckExportSound.Check();

    maCheckExportAll.SetToggleHdl( LINK( this, ImpSWFDialog, OnToggleCheckbox ) );

    maCheckExportBackgrounds.Disable(); maFiExportBackgroundsDescr.Disable();
    maCheckExportBackgroundObjects.Disable(); maFiExportBackgroundObjectsDescr.Disable();
    maCheckExportSlideContents.Disable(); maFiExportSlideContentsDescr.Disable();

#ifdef AUGUSTUS
    maCheckExportMultipleFiles.Check();
#endif

    FreeResource();
}

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

ImpSWFDialog::~ImpSWFDialog()
{
}

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

Sequence< PropertyValue > ImpSWFDialog::GetFilterData()
{
    sal_Int32 nCompressMode = (sal_Int32)maNumFldQuality.GetValue();
    maConfigItem.WriteInt32( OUString( RTL_CONSTASCII_USTRINGPARAM( "CompressMode" ) ), nCompressMode );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportAll" ) ), maCheckExportAll.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportBackgrounds" ) ), maCheckExportBackgrounds.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportBackgroundObjects" ) ), maCheckExportBackgroundObjects.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportSlideContents" ) ), maCheckExportSlideContents.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportSound" ) ), maCheckExportSound.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportOLEAsJPEG" ) ), maCheckExportOLEAsJPEG.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportMultipleFiles" ) ), maCheckExportMultipleFiles.IsChecked() );

    Sequence< PropertyValue > aRet( maConfigItem.GetFilterData() );

    return aRet;
}

// AS: This is called whenever the user toggles one of the checkboxes
IMPL_LINK( ImpSWFDialog, OnToggleCheckbox, CheckBox*, pBox )
{
    if (pBox == &maCheckExportAll)
    {
        maCheckExportBackgrounds.Enable(!maCheckExportBackgrounds.IsEnabled());
        maFiExportBackgroundsDescr.Enable(!maFiExportBackgroundsDescr.IsEnabled());
        maCheckExportBackgroundObjects.Enable(!maCheckExportBackgroundObjects.IsEnabled());
        maFiExportBackgroundObjectsDescr.Enable(!maFiExportBackgroundObjectsDescr.IsEnabled());
        maCheckExportSlideContents.Enable(!maCheckExportSlideContents.IsEnabled());
        maFiExportSlideContentsDescr.Enable(!maFiExportSlideContentsDescr.IsEnabled());
    }

    return 0;
}<commit_msg>INTEGRATION: CWS rt02 (1.3.144); FILE MERGED 2003/10/01 10:52:36 rt 1.3.144.1: #i19697# No newline at end of file<commit_after> /*************************************************************************
 *
 *  $RCSfile: impswfdialog.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-10-06 14:16:47 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "impswfdialog.hxx"
#include "impswfdialog.hrc"

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;

// ----------------
// - ImpPDFDialog -
// ----------------

ImpSWFDialog::ImpSWFDialog( Window* pParent, ResMgr& rResMgr, Sequence< PropertyValue >& rFilterData ) :
    ModalDialog( pParent, ResId( DLG_OPTIONS, &rResMgr ) ),
    maFiDescr( this, ResId( FI_DESCR ) ),
    maNumFldQuality( this, ResId( NUM_FLD_QUALITY ) ),
    maFiExportAllDescr( this, ResId( FI_EXPORT_ALL_DESCR ) ),
    maCheckExportAll( this, ResId( BOOL_EXPORT_ALL ) ),
    maFiExportBackgroundsDescr( this, ResId( FI_EXPORT_BACKGROUNDS_DESCR ) ),
    maCheckExportBackgrounds( this, ResId( BOOL_EXPORT_BACKGROUNDS ) ),
    maFiExportBackgroundObjectsDescr( this, ResId( FI_EXPORT_BACKGROUND_OBJECTS_DESCR ) ),
    maCheckExportBackgroundObjects( this, ResId( BOOL_EXPORT_BACKGROUND_OBJECTS ) ),
    maFiExportSlideContentsDescr( this, ResId( FI_EXPORT_SLIDE_CONTENTS_DESCR ) ),
    maCheckExportSlideContents( this, ResId( BOOL_EXPORT_SLIDE_CONTENTS ) ),
    maFiExportSoundDescr( this, ResId( FI_EXPORT_SOUND_DESCR ) ),
    maCheckExportSound( this, ResId( BOOL_EXPORT_SOUND ) ),
    maFiExportOLEAsJPEGDescr( this, ResId( FI_EXPORT_OLE_AS_JPEG_DESCR ) ),
    maCheckExportOLEAsJPEG( this, ResId( BOOL_EXPORT_OLE_AS_JPEG ) ),
    maFiExportMultipleFilesDescr( this, ResId( FI_EXPORT_MULTIPLE_FILES_DESCR ) ),
    maCheckExportMultipleFiles( this, ResId( BOOL_EXPORT_MULTIPLE_FILES ) ),

    maBtnOK( this, ResId( BTN_OK ) ),
    maBtnCancel( this, ResId( BTN_CANCEL ) ),
    maBtnHelp( this, ResId( BTN_HELP ) ),
    maConfigItem( String( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Flash/Export/" ) ), &rFilterData )
{
    const ULONG nCompressMode = maConfigItem.ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "CompressMode" ) ), 75 );
    maNumFldQuality.SetValue( nCompressMode );

    maCheckExportAll.Check();
    maCheckExportSlideContents.Check();
    maCheckExportSound.Check();

    maCheckExportAll.SetToggleHdl( LINK( this, ImpSWFDialog, OnToggleCheckbox ) );

    maCheckExportBackgrounds.Disable(); maFiExportBackgroundsDescr.Disable();
    maCheckExportBackgroundObjects.Disable(); maFiExportBackgroundObjectsDescr.Disable();
    maCheckExportSlideContents.Disable(); maFiExportSlideContentsDescr.Disable();

#ifdef AUGUSTUS
    maCheckExportMultipleFiles.Check();
#endif

    FreeResource();
}

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

ImpSWFDialog::~ImpSWFDialog()
{
}

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

Sequence< PropertyValue > ImpSWFDialog::GetFilterData()
{
    sal_Int32 nCompressMode = (sal_Int32)maNumFldQuality.GetValue();
    maConfigItem.WriteInt32( OUString( RTL_CONSTASCII_USTRINGPARAM( "CompressMode" ) ), nCompressMode );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportAll" ) ), maCheckExportAll.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportBackgrounds" ) ), maCheckExportBackgrounds.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportBackgroundObjects" ) ), maCheckExportBackgroundObjects.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportSlideContents" ) ), maCheckExportSlideContents.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportSound" ) ), maCheckExportSound.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportOLEAsJPEG" ) ), maCheckExportOLEAsJPEG.IsChecked() );
    maConfigItem.WriteBool( OUString( RTL_CONSTASCII_USTRINGPARAM( "ExportMultipleFiles" ) ), maCheckExportMultipleFiles.IsChecked() );

    Sequence< PropertyValue > aRet( maConfigItem.GetFilterData() );

    return aRet;
}

// AS: This is called whenever the user toggles one of the checkboxes
IMPL_LINK( ImpSWFDialog, OnToggleCheckbox, CheckBox*, pBox )
{
    if (pBox == &maCheckExportAll)
    {
        maCheckExportBackgrounds.Enable(!maCheckExportBackgrounds.IsEnabled());
        maFiExportBackgroundsDescr.Enable(!maFiExportBackgroundsDescr.IsEnabled());
        maCheckExportBackgroundObjects.Enable(!maCheckExportBackgroundObjects.IsEnabled());
        maFiExportBackgroundObjectsDescr.Enable(!maFiExportBackgroundObjectsDescr.IsEnabled());
        maCheckExportSlideContents.Enable(!maCheckExportSlideContents.IsEnabled());
        maFiExportSlideContentsDescr.Enable(!maFiExportSlideContentsDescr.IsEnabled());
    }

    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2017 Global Phasing Ltd.

#include <cstdio>
#include <cstdlib>   // for getenv
#include <stdexcept>
#include <iostream>  // for cout
#include <gemmi/gzread.hpp>
#include <gemmi/chemcomp.hpp>  // for ChemComp
#include <gemmi/polyheur.hpp>  // for remove_hydrogens, setup_entities
#include <gemmi/to_cif.hpp>    // for write_cif_to_file
#include <gemmi/to_mmcif.hpp>  // for make_mmcif_document
#include <gemmi/to_pdb.hpp>    // for write_pdb
#include <gemmi/monlib.hpp>    // for MonLib, read_monomer_lib
#include <gemmi/topo.hpp>      // for Topo
#include <gemmi/fstream.hpp>   // for Ofstream
#include <gemmi/placeh.hpp>    // for prepare_topology

#define GEMMI_PROG h
#include "options.h"

namespace cif = gemmi::cif;

namespace {

enum OptionIndex { Monomers=4, RemoveH, KeepH, Water, Sort };

const option::Descriptor Usage[] = {
  { NoOp, 0, "", "", Arg::None,
    "Usage:"
    "\n " EXE_NAME " [options] INPUT_FILE OUTPUT_FILE"
    "\n\nAdd hydrogens in positions specified by the monomer library."
    "\nBy default, it removes and re-adds all hydrogens."
    "\nBy default, hydrogens are not added to water."
    "\n\nOptions:" },
  CommonUsage[Help],
  CommonUsage[Version],
  CommonUsage[Verbose],
  { Monomers, 0, "", "monomers", Arg::Required,
    "  --monomers=DIR  \tMonomer library dir (default: $CLIBD_MON)." },
  { RemoveH, 0, "", "remove", Arg::None,
    "  --remove  \tOnly remove hydrogens." },
  { KeepH, 0, "", "keep", Arg::None,
    "  --keep  \tDo not add/remove hydrogens, only change positions." },
  { Water, 0, "", "water", Arg::None,
    "  --water  \tAdd hydrogens also to waters." },
  { Sort, 0, "", "sort", Arg::None,
    "  --sort  \tOrder atoms in residues according to _chem_comp_atom." },
  { 0, 0, 0, 0, 0, 0 }
};

} // anonymous namespace

int GEMMI_MAIN(int argc, char **argv) {
  OptParser p(EXE_NAME);
  p.simple_parse(argc, argv, Usage);
  p.require_positional_args(2);
  const char* monomer_dir = p.options[Monomers] ? p.options[Monomers].arg
                                                : std::getenv("CLIBD_MON");
  if (monomer_dir == nullptr || *monomer_dir == '\0') {
    std::fprintf(stderr, "Set $CLIBD_MON or use option --monomers.\n");
    return 1;
  }
  std::string input = p.coordinate_input_file(0);
  std::string output = p.nonOption(1);
  p.check_exclusive_pair(KeepH, RemoveH);
  if (p.options[Verbose])
    std::printf("Reading coordinates from %s\n", input.c_str());
  try {
    gemmi::Structure st = gemmi::read_structure_gz(input,
                                            gemmi::CoorFormat::UnknownAny);
    if (st.models.empty() || st.models[0].chains.empty()) {
      std::fprintf(stderr, "No atoms in the input file. Wrong format?\n");
      return 1;
    }
    gemmi::setup_entities(st);
    size_t initial_h = 0;
    if (p.options[Verbose])
      initial_h = gemmi::count_hydrogen_sites(st);
    std::vector<std::string> res_names = st.models[0].get_all_residue_names();
    if (p.options[Verbose])
      std::printf("Reading %zu monomers and all links from %s\n",
                  res_names.size(), input.c_str());
    gemmi::MonLib monlib = gemmi::read_monomer_lib(monomer_dir, res_names,
                                                   gemmi::read_cif_gz);
    gemmi::HydrogenChange h_change = gemmi::HydrogenChange::ReAddButWater;
    if (p.options[RemoveH])
      h_change = gemmi::HydrogenChange::Remove;
    else if (p.options[KeepH])
      h_change = gemmi::HydrogenChange::Shift;
    else if (p.options[Water])
      h_change = gemmi::HydrogenChange::ReAdd;
    for (size_t i = 0; i != st.models.size(); ++i)
      // preparing topology modifies hydrogens in the model
      prepare_topology(st, monlib, i, h_change, p.options[Sort]);
    if (p.options[Verbose])
      std::printf("Hydrogen site count: %zu in input, %zu in output.\n",
                  initial_h, gemmi::count_hydrogen_sites(st));
    if (p.options[Verbose])
      std::printf("Writing coordinates to %s\n", output.c_str());
    gemmi::Ofstream os(output, &std::cout);
    if (gemmi::coor_format_from_ext_gz(output) == gemmi::CoorFormat::Pdb)
      gemmi::write_pdb(st, os.ref());
    else
      cif::write_cif_to_stream(os.ref(), gemmi::make_mmcif_document(st),
                               cif::Style::PreferPairs);
  } catch (std::runtime_error& e) {
    std::fprintf(stderr, "ERROR: %s\n", e.what());
    return 1;
  } catch (std::out_of_range& e) {
    std::fprintf(stderr, "ERROR: %s\n", e.what());
    return 1;
  }
  return 0;
}

// vim:sw=2:ts=2:et:path^=../include
<commit_msg>gemmi-h: avoid reading monomer library when option --remove is given<commit_after>// Copyright 2017 Global Phasing Ltd.

#include <cstdio>
#include <cstdlib>   // for getenv
#include <stdexcept>
#include <iostream>  // for cout
#include <gemmi/gzread.hpp>
#include <gemmi/chemcomp.hpp>  // for ChemComp
#include <gemmi/polyheur.hpp>  // for remove_hydrogens, setup_entities
#include <gemmi/to_cif.hpp>    // for write_cif_to_file
#include <gemmi/to_mmcif.hpp>  // for make_mmcif_document
#include <gemmi/to_pdb.hpp>    // for write_pdb
#include <gemmi/monlib.hpp>    // for MonLib, read_monomer_lib
#include <gemmi/topo.hpp>      // for Topo
#include <gemmi/fstream.hpp>   // for Ofstream
#include <gemmi/placeh.hpp>    // for prepare_topology

#define GEMMI_PROG h
#include "options.h"

namespace cif = gemmi::cif;

namespace {

enum OptionIndex { Monomers=4, RemoveH, KeepH, Water, Sort };

const option::Descriptor Usage[] = {
  { NoOp, 0, "", "", Arg::None,
    "Usage:"
    "\n " EXE_NAME " [options] INPUT_FILE OUTPUT_FILE"
    "\n\nAdd hydrogens in positions specified by the monomer library."
    "\nBy default, it removes and re-adds all hydrogens."
    "\nBy default, hydrogens are not added to water."
    "\n\nOptions:" },
  CommonUsage[Help],
  CommonUsage[Version],
  CommonUsage[Verbose],
  { Monomers, 0, "", "monomers", Arg::Required,
    "  --monomers=DIR  \tMonomer library dir (default: $CLIBD_MON)." },
  { RemoveH, 0, "", "remove", Arg::None,
    "  --remove  \tOnly remove hydrogens." },
  { KeepH, 0, "", "keep", Arg::None,
    "  --keep  \tDo not add/remove hydrogens, only change positions." },
  { Water, 0, "", "water", Arg::None,
    "  --water  \tAdd hydrogens also to waters." },
  { Sort, 0, "", "sort", Arg::None,
    "  --sort  \tOrder atoms in residues according to _chem_comp_atom." },
  { 0, 0, 0, 0, 0, 0 }
};

} // anonymous namespace

int GEMMI_MAIN(int argc, char **argv) {
  OptParser p(EXE_NAME);
  p.simple_parse(argc, argv, Usage);
  p.require_positional_args(2);
  const char* monomer_dir = p.options[Monomers] ? p.options[Monomers].arg
                                                : std::getenv("CLIBD_MON");
  std::string input = p.coordinate_input_file(0);
  std::string output = p.nonOption(1);
  p.check_exclusive_pair(KeepH, RemoveH);

  gemmi::HydrogenChange h_change = gemmi::HydrogenChange::ReAddButWater;
  if (p.options[RemoveH])
    h_change = gemmi::HydrogenChange::Remove;
  else if (p.options[KeepH])
    h_change = gemmi::HydrogenChange::Shift;
  else if (p.options[Water])
    h_change = gemmi::HydrogenChange::ReAdd;

  if (p.options[Verbose])
    std::printf("Reading coordinates from %s\n", input.c_str());
  try {
    gemmi::Structure st = gemmi::read_structure_gz(input,
                                            gemmi::CoorFormat::UnknownAny);
    if (st.models.empty() || st.models[0].chains.empty()) {
      std::fprintf(stderr, "No atoms in the input file. Wrong format?\n");
      return 1;
    }
    gemmi::setup_entities(st);
    size_t initial_h = 0;
    if (p.options[Verbose])
      initial_h = gemmi::count_hydrogen_sites(st);
    if (h_change == gemmi::HydrogenChange::Remove) {
      gemmi::remove_hydrogens(st);
    } else {
      if (monomer_dir == nullptr || *monomer_dir == '\0') {
        std::fprintf(stderr, "Set $CLIBD_MON or use option --monomers.\n");
        return 1;
      }
      std::vector<std::string> res_names = st.models[0].get_all_residue_names();
      if (p.options[Verbose])
        std::printf("Reading %zu monomers and all links from %s\n",
                    res_names.size(), input.c_str());
      gemmi::MonLib monlib = gemmi::read_monomer_lib(monomer_dir, res_names,
                                                     gemmi::read_cif_gz);
      for (size_t i = 0; i != st.models.size(); ++i)
        // preparing topology modifies hydrogens in the model
        prepare_topology(st, monlib, i, h_change, p.options[Sort]);
    }
    if (p.options[Verbose])
      std::printf("Hydrogen site count: %zu in input, %zu in output.\n",
                  initial_h, gemmi::count_hydrogen_sites(st));
    if (p.options[Verbose])
      std::printf("Writing coordinates to %s\n", output.c_str());
    gemmi::Ofstream os(output, &std::cout);
    if (gemmi::coor_format_from_ext_gz(output) == gemmi::CoorFormat::Pdb)
      gemmi::write_pdb(st, os.ref());
    else
      cif::write_cif_to_stream(os.ref(), gemmi::make_mmcif_document(st),
                               cif::Style::PreferPairs);
  } catch (std::runtime_error& e) {
    std::fprintf(stderr, "ERROR: %s\n", e.what());
    return 1;
  } catch (std::out_of_range& e) {
    std::fprintf(stderr, "ERROR: %s\n", e.what());
    return 1;
  }
  return 0;
}

// vim:sw=2:ts=2:et:path^=../include
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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.
 *****************************************************************************/

#include "modules/planning/integration_tests/planning_test_base.h"

#include "modules/common/log.h"
#include "modules/common/vehicle_state/vehicle_state.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file,
              "modules/planning/testdata/garage_routing.pb.txt",
              "The routing file used in test");
DEFINE_string(test_localization_file,
              "modules/planning/testdata/garage_localization.pb.txt",
              "The localization test file");
DEFINE_string(test_chassis_file,
              "modules/planning/testdata/garage_chassis.pb.txt",
              "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_planning_config_file =
      "modules/planning/testdata/conf/planning_config.pb.txt";
  FLAGS_adapter_config_path = "modules/planning/testdata/conf/adapter.conf";
  FLAGS_map_file_path = "modules/planning/testdata/base_map.txt";
  FLAGS_test_localization_file =
      "modules/planning/testdata/garage_localization.pb.txt";
  FLAGS_test_chassis_file = "modules/planning/testdata/garage_chassis.pb.txt",
  FLAGS_test_prediction_file =
      "modules/planning/testdata/garage_prediction.pb.txt",
  FLAGS_v = 4;
}

bool PlanningTestBase::SetUpAdapters() {
  if (!AdapterManager::Initialized()) {
    AdapterManager::Init(FLAGS_adapter_config_path);
  }
  if (!AdapterManager::GetRoutingResponse()) {
    AERROR << "routing is not registered in adapter manager, check adapter "
              "config file."
           << FLAGS_adapter_config_path;
    return false;
  }
  if (!AdapterManager::FeedRoutingResponseFile(
          FLAGS_test_routing_response_file)) {
    AERROR << "failed to routing file: " << FLAGS_test_routing_response_file;
    return false;
  }
  AINFO << "Using Routing " << FLAGS_test_routing_response_file;
  if (!AdapterManager::FeedLocalizationFile(FLAGS_test_localization_file)) {
    AERROR << "Failed to load localization file: "
           << FLAGS_test_localization_file;
    return false;
  }
  AINFO << "Using Localization file: " << FLAGS_test_localization_file;
  if (!AdapterManager::FeedChassisFile(FLAGS_test_chassis_file)) {
    AERROR << "Failed to load chassis file: " << FLAGS_test_chassis_file;
    return false;
  }
  AINFO << "Using Chassis file: " << FLAGS_test_chassis_file;
  if (!FLAGS_test_prediction_file.empty() &&
      !AdapterManager::FeedPredictionFile(FLAGS_test_prediction_file)) {
    AERROR << "Failed to load prediction file: " << FLAGS_test_prediction_file;
    return false;
  }
  AINFO << "Using Prediction file: " << FLAGS_test_prediction_file;
  return true;
}

void PlanningTestBase::SetUp() {
  adc_trajectory_ = nullptr;
  CHECK(SetUpAdapters()) << "Failed to setup adapters";
  planning_.Init();
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");
  std::string tmp_golden_path = "/tmp/" + golden_result_file;
  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;
  planning_.RunOnce();
  adc_trajectory_ = AdapterManager::GetPlanning()->GetLatestPublished();
  if (!adc_trajectory_) {
    AERROR << " did not get latest adc trajectory";
    return false;
  }
  TrimPlanning(adc_trajectory_);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is " << tmp_golden_path << " Remember to:\n"
          << "mv " << tmp_golden_path << " " << FLAGS_test_data_dir << "\n"
          << "git add " << FLAGS_test_data_dir << "/" << golden_result_file;
    ::apollo::common::util::SetProtoToASCIIFile(*adc_trajectory_,
                                                golden_result_file);
  } else {
    ADCTrajectory golden_result;
    bool load_success = ::apollo::common::util::GetProtoFromASCIIFile(
        full_golden_path, &golden_result);
    if (!load_success) {
      AERROR << "Failed to load golden file: " << full_golden_path;
      ::apollo::common::util::SetProtoToASCIIFile(*adc_trajectory_,
                                                  tmp_golden_path);
      AINFO << "Current result is written to " << tmp_golden_path;
      return false;
    }
    bool same_result =
        ::apollo::common::util::IsProtoEqual(golden_result, *adc_trajectory_);
    if (!same_result) {
      std::string tmp_planning_file = tmp_golden_path + ".tmp";
      ::apollo::common::util::SetProtoToASCIIFile(*adc_trajectory_,
                                                  tmp_planning_file);
      AERROR << "found diff " << tmp_planning_file << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

void PlanningTestBase::export_sl_points(
    const std::vector<std::vector<common::SLPoint>>& points,
    const std::string& filename) {
  AINFO << "Write sl_points to file " << filename;
  std::ofstream ofs(filename);
  ofs << "level, s, l" << std::endl;
  int level = 0;
  for (const auto& level_points : points) {
    for (const auto& point : level_points) {
      ofs << level << ", " << point.s() << ", " << point.l() << std::endl;
    }
    ++level;
  }
  ofs.close();
}

void PlanningTestBase::export_path_data(const PathData& path_data,
                                        const std::string& filename) {
  AINFO << "Write path_data to file " << filename;
  std::ofstream ofs(filename);
  ofs << "s, l, dl, ddl, x, y, z" << std::endl;
  const auto& frenet_path = path_data.frenet_frame_path();
  const auto& discrete_path = path_data.discretized_path();
  if (frenet_path.NumOfPoints() != discrete_path.NumOfPoints()) {
    AERROR << "frenet_path and discrete path have different number of points";
    return;
  }
  for (uint32_t i = 0; i < frenet_path.NumOfPoints(); ++i) {
    const auto& frenet_point = frenet_path.PointAt(i);
    const auto& discrete_point = discrete_path.PathPointAt(i);
    ofs << frenet_point.s() << ", " << frenet_point.l() << ", "
        << frenet_point.dl() << ", " << frenet_point.ddl() << discrete_point.x()
        << ", " << discrete_point.y() << ", " << discrete_point.z()
        << std::endl;
  }
  ofs.close();
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: Avoid verbose output to terminal.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. 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.
 *****************************************************************************/

#include "modules/planning/integration_tests/planning_test_base.h"

#include "modules/common/log.h"
#include "modules/common/vehicle_state/vehicle_state.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file,
              "modules/planning/testdata/garage_routing.pb.txt",
              "The routing file used in test");
DEFINE_string(test_localization_file,
              "modules/planning/testdata/garage_localization.pb.txt",
              "The localization test file");
DEFINE_string(test_chassis_file,
              "modules/planning/testdata/garage_chassis.pb.txt",
              "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_planning_config_file =
      "modules/planning/testdata/conf/planning_config.pb.txt";
  FLAGS_adapter_config_path = "modules/planning/testdata/conf/adapter.conf";
  FLAGS_map_file_path = "modules/planning/testdata/base_map.txt";
  FLAGS_test_localization_file =
      "modules/planning/testdata/garage_localization.pb.txt";
  FLAGS_test_chassis_file = "modules/planning/testdata/garage_chassis.pb.txt";
  FLAGS_test_prediction_file =
      "modules/planning/testdata/garage_prediction.pb.txt";
}

bool PlanningTestBase::SetUpAdapters() {
  if (!AdapterManager::Initialized()) {
    AdapterManager::Init(FLAGS_adapter_config_path);
  }
  if (!AdapterManager::GetRoutingResponse()) {
    AERROR << "routing is not registered in adapter manager, check adapter "
              "config file."
           << FLAGS_adapter_config_path;
    return false;
  }
  if (!AdapterManager::FeedRoutingResponseFile(
          FLAGS_test_routing_response_file)) {
    AERROR << "failed to routing file: " << FLAGS_test_routing_response_file;
    return false;
  }
  AINFO << "Using Routing " << FLAGS_test_routing_response_file;
  if (!AdapterManager::FeedLocalizationFile(FLAGS_test_localization_file)) {
    AERROR << "Failed to load localization file: "
           << FLAGS_test_localization_file;
    return false;
  }
  AINFO << "Using Localization file: " << FLAGS_test_localization_file;
  if (!AdapterManager::FeedChassisFile(FLAGS_test_chassis_file)) {
    AERROR << "Failed to load chassis file: " << FLAGS_test_chassis_file;
    return false;
  }
  AINFO << "Using Chassis file: " << FLAGS_test_chassis_file;
  if (!FLAGS_test_prediction_file.empty() &&
      !AdapterManager::FeedPredictionFile(FLAGS_test_prediction_file)) {
    AERROR << "Failed to load prediction file: " << FLAGS_test_prediction_file;
    return false;
  }
  AINFO << "Using Prediction file: " << FLAGS_test_prediction_file;
  return true;
}

void PlanningTestBase::SetUp() {
  adc_trajectory_ = nullptr;
  CHECK(SetUpAdapters()) << "Failed to setup adapters";
  planning_.Init();
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");
  std::string tmp_golden_path = "/tmp/" + golden_result_file;
  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;
  planning_.RunOnce();
  adc_trajectory_ = AdapterManager::GetPlanning()->GetLatestPublished();
  if (!adc_trajectory_) {
    AERROR << " did not get latest adc trajectory";
    return false;
  }
  TrimPlanning(adc_trajectory_);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is " << tmp_golden_path << " Remember to:\n"
          << "mv " << tmp_golden_path << " " << FLAGS_test_data_dir << "\n"
          << "git add " << FLAGS_test_data_dir << "/" << golden_result_file;
    ::apollo::common::util::SetProtoToASCIIFile(*adc_trajectory_,
                                                golden_result_file);
  } else {
    ADCTrajectory golden_result;
    bool load_success = ::apollo::common::util::GetProtoFromASCIIFile(
        full_golden_path, &golden_result);
    if (!load_success) {
      AERROR << "Failed to load golden file: " << full_golden_path;
      ::apollo::common::util::SetProtoToASCIIFile(*adc_trajectory_,
                                                  tmp_golden_path);
      AINFO << "Current result is written to " << tmp_golden_path;
      return false;
    }
    bool same_result =
        ::apollo::common::util::IsProtoEqual(golden_result, *adc_trajectory_);
    if (!same_result) {
      std::string tmp_planning_file = tmp_golden_path + ".tmp";
      ::apollo::common::util::SetProtoToASCIIFile(*adc_trajectory_,
                                                  tmp_planning_file);
      AERROR << "found diff " << tmp_planning_file << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

void PlanningTestBase::export_sl_points(
    const std::vector<std::vector<common::SLPoint>>& points,
    const std::string& filename) {
  AINFO << "Write sl_points to file " << filename;
  std::ofstream ofs(filename);
  ofs << "level, s, l" << std::endl;
  int level = 0;
  for (const auto& level_points : points) {
    for (const auto& point : level_points) {
      ofs << level << ", " << point.s() << ", " << point.l() << std::endl;
    }
    ++level;
  }
  ofs.close();
}

void PlanningTestBase::export_path_data(const PathData& path_data,
                                        const std::string& filename) {
  AINFO << "Write path_data to file " << filename;
  std::ofstream ofs(filename);
  ofs << "s, l, dl, ddl, x, y, z" << std::endl;
  const auto& frenet_path = path_data.frenet_frame_path();
  const auto& discrete_path = path_data.discretized_path();
  if (frenet_path.NumOfPoints() != discrete_path.NumOfPoints()) {
    AERROR << "frenet_path and discrete path have different number of points";
    return;
  }
  for (uint32_t i = 0; i < frenet_path.NumOfPoints(); ++i) {
    const auto& frenet_point = frenet_path.PointAt(i);
    const auto& discrete_point = discrete_path.PathPointAt(i);
    ofs << frenet_point.s() << ", " << frenet_point.l() << ", "
        << frenet_point.dl() << ", " << frenet_point.ddl() << discrete_point.x()
        << ", " << discrete_point.y() << ", " << discrete_point.z()
        << std::endl;
  }
  ofs.close();
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>#include <v8.h>
#include <sys/stat.h>
#include <common.h>

v8::Handle<v8::Value> _file(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {
	return v8::ThrowException(v8::String::New("Invalid call format. Use 'new File(name)'"));
    }

    args.This()->SetInternalField(0, args[0]);
    args.This()->SetInternalField(1, v8::Boolean::New(false));
    return args.This();
}

v8::Handle<v8::Value> _open(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    if (args.Length() < 1) {
	return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.open(mode)'"));
    }
    v8::String::Utf8Value mode(args[0]);
    v8::String::Utf8Value name(args.This()->GetInternalField(0));
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
    if (!file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File already opened"));
    }

    FILE * f;
    f = fopen(*name, *mode);

    if (!f) {
	return v8::ThrowException(v8::String::New("Cannot open file"));
    }

    struct stat st;
    if (stat(*name, &st) == 0) {
	args.This()->SetInternalField(2, v8::Integer::New(st.st_size));
    }
    args.This()->SetInternalField(1, v8::External::New((void *)f));
    args.This()->SetInternalField(3, v8::Integer::New(0));

    return args.This();
}

v8::Handle<v8::Value> _close(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("Cannot close non-opened file"));
    }

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
    fclose(f);
    args.This()->SetInternalField(1, v8::Boolean::New(false));
    return args.This();
}

v8::Handle<v8::Value> _read(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be opened before reading"));
    }

    long size = args.This()->GetInternalField(2)->IntegerValue();
    long pos = args.This()->GetInternalField(3)->IntegerValue();

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());

    long avail = size-pos;
    if (!avail) { return v8::Boolean::New(false); }

    if (args.Length() && args[0]->IsNumber()) {
        int len = args[0]->IntegerValue();
	if (len < avail) { avail = len; }
    }
    char buf[avail];
    fread(buf, sizeof(char), avail, f);
    pos += avail;

    args.This()->SetInternalField(3, v8::Integer::New(pos));

   if (args.Length() > 1 && args[1]->IsTrue()) {
       return char2array(buf, avail);
   } else {
       return char2string(buf, avail);
    }
}

v8::Handle<v8::Value> _rewind(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be opened before rewinding"));
    }

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
    rewind(f);

    args.This()->SetInternalField(3, v8::Integer::New(0));
    return args.This();
}

v8::Handle<v8::Value> _write(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be opened before writing"));
    }

    if (args.Length() < 1) {
	return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.write(data)'"));
    }

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());

    if (args[0]->IsArray()) {
	v8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);
	int len = arr->Length();

	int max = 4096;
	int current = 0;
	char buf[max];
	for (int i=0;i<len;i++) {
    	    v8::Handle<v8::Integer> a = v8::Integer::New(arr->Get(v8::Integer::New(i))->IntegerValue());
	    buf[current++] = (char) a->Int32Value();
	    if (current == max) {
    		fwrite(buf, sizeof(char), current, f);
		current = 0;
	    }
	}
	if (current) { fwrite(buf, sizeof(char), current, f); }

    } else {
	v8::String::Utf8Value data(args[0]);

	fwrite(*data, sizeof(char), args[0]->ToString()->Utf8Length(), f);
    }

    return args.This();
}

v8::Handle<v8::Value> _remove(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::String::Utf8Value name(args.This()->GetInternalField(0));
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (!file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be closed before deleting"));
    }

    if (!remove(*name)) {
	return v8::ThrowException(v8::String::New("Cannot remove file"));
    }

    return args.This();
}

v8::Handle<v8::Value> _getsize(const v8::Arguments& args) {
    v8::HandleScope handle_scope;

    v8::String::Utf8Value name(args.This()->GetInternalField(0));
    struct stat st;
    if (stat(*name, &st) == 0) {
	return v8::Integer::New(st.st_size);
    } else {
	return v8::Boolean::New(false);
    }
}

v8::Handle<v8::Value> _tostring(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    return args.This()->GetInternalField(0);

}

void SetupIo(v8::Handle<v8::Object> target) {
  v8::HandleScope handle_scope;
  v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_file);
  ft->SetClassName(v8::String::New("File"));
  v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
  ot->SetInternalFieldCount(4); /* filename, handle, size, position */

  v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
  pt->Set("open", v8::FunctionTemplate::New(_open));
  pt->Set("read", v8::FunctionTemplate::New(_read));
  pt->Set("rewind", v8::FunctionTemplate::New(_rewind));
  pt->Set("close", v8::FunctionTemplate::New(_close));
  pt->Set("write", v8::FunctionTemplate::New(_write));
  pt->Set("remove", v8::FunctionTemplate::New(_remove));
  pt->Set("getSize", v8::FunctionTemplate::New(_getsize));
  pt->Set("toString", v8::FunctionTemplate::New(_tostring));

  target->Set(v8::String::New("File"), ft->GetFunction());
}
<commit_msg>Basic directory support<commit_after>#include <v8.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <common.h>
#include <dirent.h>
#include <string.h>

v8::Handle<v8::Value> _directory(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {
	return v8::ThrowException(v8::String::New("Invalid call format. Use 'new Directory(name)'"));
    }

    args.This()->SetInternalField(0, args[0]);
    return args.This();
}

v8::Handle<v8::Value> _create(const v8::Arguments& args) {
    v8::HandleScope handle_scope;

    v8::String::Utf8Value name(args.This()->GetInternalField(0));
    int mode;
    if (args.Length() == 0) {
	mode = 0777;
    } else {
	mode = args[0]->Int32Value();
    }

    int result = mkdir(*name, mode);
    if (result != 0) {
	return v8::ThrowException(v8::String::New("Cannot create directory'"));
    }

    return args.This();
}

v8::Handle<v8::Value> _listfiles(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::String::Utf8Value name(args.This()->GetInternalField(0));

    DIR * dp;
    struct dirent * ep;

    v8::Handle<v8::Array> result = v8::Array::New();

    dp = opendir(*name);
    if (dp == NULL) { return v8::ThrowException(v8::String::New("Directory cannot be opened")); }
    int cnt = 0;
    while ((ep = readdir(dp))) {
	if (ep->d_type == DT_REG) {
	    result->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));
	}
    }
    closedir(dp);
    return result;
}

v8::Handle<v8::Value> _listdirectories(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::String::Utf8Value name(args.This()->GetInternalField(0));

    DIR * dp;
    struct dirent * ep;

    v8::Handle<v8::Array> result = v8::Array::New();

    dp = opendir(*name);
    if (dp == NULL) { return v8::ThrowException(v8::String::New("Directory cannot be opened")); }
    int cnt = 0;
    while ((ep = readdir(dp))) {
	if (ep->d_type == DT_DIR) {
	    if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0) {
		result->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));
	    }
	}
    }
    closedir(dp);
    return result;
}

v8::Handle<v8::Value> _file(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {
	return v8::ThrowException(v8::String::New("Invalid call format. Use 'new File(name)'"));
    }

    args.This()->SetInternalField(0, args[0]);
    args.This()->SetInternalField(1, v8::Boolean::New(false));
    return args.This();
}

v8::Handle<v8::Value> _open(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    if (args.Length() < 1) {
	return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.open(mode)'"));
    }
    v8::String::Utf8Value mode(args[0]);
    v8::String::Utf8Value name(args.This()->GetInternalField(0));
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
    if (!file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File already opened"));
    }

    FILE * f;
    f = fopen(*name, *mode);

    if (!f) {
	return v8::ThrowException(v8::String::New("Cannot open file"));
    }

    struct stat st;
    if (stat(*name, &st) == 0) {
	args.This()->SetInternalField(2, v8::Integer::New(st.st_size));
    }
    args.This()->SetInternalField(1, v8::External::New((void *)f));
    args.This()->SetInternalField(3, v8::Integer::New(0));

    return args.This();
}

v8::Handle<v8::Value> _close(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("Cannot close non-opened file"));
    }

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
    fclose(f);
    args.This()->SetInternalField(1, v8::Boolean::New(false));
    return args.This();
}

v8::Handle<v8::Value> _read(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be opened before reading"));
    }

    long size = args.This()->GetInternalField(2)->IntegerValue();
    long pos = args.This()->GetInternalField(3)->IntegerValue();

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());

    long avail = size-pos;
    if (!avail) { return v8::Boolean::New(false); }

    if (args.Length() && args[0]->IsNumber()) {
        int len = args[0]->IntegerValue();
	if (len < avail) { avail = len; }
    }
    char buf[avail];
    fread(buf, sizeof(char), avail, f);
    pos += avail;

    args.This()->SetInternalField(3, v8::Integer::New(pos));

   if (args.Length() > 1 && args[1]->IsTrue()) {
       return char2array(buf, avail);
   } else {
       return char2string(buf, avail);
    }
}

v8::Handle<v8::Value> _rewind(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be opened before rewinding"));
    }

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
    rewind(f);

    args.This()->SetInternalField(3, v8::Integer::New(0));
    return args.This();
}

v8::Handle<v8::Value> _write(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be opened before writing"));
    }

    if (args.Length() < 1) {
	return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.write(data)'"));
    }

    FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());

    if (args[0]->IsArray()) {
	v8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);
	int len = arr->Length();

	int max = 4096;
	int current = 0;
	char buf[max];
	for (int i=0;i<len;i++) {
    	    v8::Handle<v8::Integer> a = v8::Integer::New(arr->Get(v8::Integer::New(i))->IntegerValue());
	    buf[current++] = (char) a->Int32Value();
	    if (current == max) {
    		fwrite(buf, sizeof(char), current, f);
		current = 0;
	    }
	}
	if (current) { fwrite(buf, sizeof(char), current, f); }

    } else {
	v8::String::Utf8Value data(args[0]);

	fwrite(*data, sizeof(char), args[0]->ToString()->Utf8Length(), f);
    }

    return args.This();
}

v8::Handle<v8::Value> _remove(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    v8::String::Utf8Value name(args.This()->GetInternalField(0));
    v8::Handle<v8::Value> file = args.This()->GetInternalField(1);

    if (!file->IsFalse()) {
	return v8::ThrowException(v8::String::New("File must be closed before deleting"));
    }

    if (!remove(*name)) {
	return v8::ThrowException(v8::String::New("Cannot remove file"));
    }

    return args.This();
}

v8::Handle<v8::Value> _getsize(const v8::Arguments& args) {
    v8::HandleScope handle_scope;

    v8::String::Utf8Value name(args.This()->GetInternalField(0));
    struct stat st;
    if (stat(*name, &st) == 0) {
	return v8::Integer::New(st.st_size);
    } else {
	return v8::Boolean::New(false);
    }
}

v8::Handle<v8::Value> _tostring(const v8::Arguments& args) {
    v8::HandleScope handle_scope;
    return args.This()->GetInternalField(0);

}

void SetupIo(v8::Handle<v8::Object> target) {
  v8::HandleScope handle_scope;

  v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_file);
  ft->SetClassName(v8::String::New("File"));
  v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
  ot->SetInternalFieldCount(4); /* filename, handle, size, position */

  v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
  pt->Set("open", v8::FunctionTemplate::New(_open));
  pt->Set("read", v8::FunctionTemplate::New(_read));
  pt->Set("rewind", v8::FunctionTemplate::New(_rewind));
  pt->Set("close", v8::FunctionTemplate::New(_close));
  pt->Set("write", v8::FunctionTemplate::New(_write));
  pt->Set("remove", v8::FunctionTemplate::New(_remove));
  pt->Set("getSize", v8::FunctionTemplate::New(_getsize));
  pt->Set("toString", v8::FunctionTemplate::New(_tostring));

  target->Set(v8::String::New("File"), ft->GetFunction());

  ft = v8::FunctionTemplate::New(_directory);
  ft->SetClassName(v8::String::New("Directory"));
  ot = ft->InstanceTemplate();
  ot->SetInternalFieldCount(1); /* dirname */

  pt = ft->PrototypeTemplate();
  pt->Set("create", v8::FunctionTemplate::New(_create));
  pt->Set("listFiles", v8::FunctionTemplate::New(_listfiles));
  pt->Set("listDirectories", v8::FunctionTemplate::New(_listdirectories));
  pt->Set("toString", v8::FunctionTemplate::New(_tostring));

  target->Set(v8::String::New("Directory"), ft->GetFunction());

}
<|endoftext|>


<commit_before>//===-- NativeThreadLinux.cpp --------------------------------- -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "NativeThreadLinux.h"

#include <signal.h>

#include "NativeProcessLinux.h"
#include "NativeRegisterContextLinux_x86_64.h"

#include "lldb/Core/Log.h"
#include "lldb/Core/State.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/lldb-enumerations.h"
#include "lldb/lldb-private-log.h"
#include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
#include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
#include "Plugins/Process/Utility/RegisterInfoInterface.h"

using namespace lldb;
using namespace lldb_private;

namespace
{
    void LogThreadStopInfo (Log &log, const ThreadStopInfo &stop_info, const char *const header)
    {
        switch (stop_info.reason)
        {
            case eStopReasonSignal:
                log.Printf ("%s: %s: signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
                return;
            case eStopReasonException:
                log.Printf ("%s: %s: exception type 0x%" PRIx64, __FUNCTION__, header, stop_info.details.exception.type);
                return;
            default:
                log.Printf ("%s: %s: invalid stop reason %" PRIu32, __FUNCTION__, header, static_cast<uint32_t> (stop_info.reason));
        }
    }
}

NativeThreadLinux::NativeThreadLinux (NativeProcessLinux *process, lldb::tid_t tid) :
    NativeThreadProtocol (process, tid),
    m_state (StateType::eStateInvalid),
    m_stop_info (),
    m_reg_context_sp ()
{
}

const char *
NativeThreadLinux::GetName()
{
    NativeProcessProtocolSP process_sp = m_process_wp.lock ();
    if (!process_sp)
        return "<unknown: no process>";

    // const NativeProcessLinux *const process = reinterpret_cast<NativeProcessLinux*> (process_sp->get ());
    return Host::GetThreadName (process_sp->GetID (), GetID ()).c_str ();
}

lldb::StateType
NativeThreadLinux::GetState ()
{
    return m_state;
}

bool
NativeThreadLinux::GetStopReason (ThreadStopInfo &stop_info)
{
    Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
    switch (m_state)
    {
    case eStateStopped:
    case eStateCrashed:
    case eStateExited:
    case eStateSuspended:
    case eStateUnloaded:
        if (log)
            LogThreadStopInfo (*log, m_stop_info, "m_stop_info in thread: ");
        stop_info = m_stop_info;
        if (log)
            LogThreadStopInfo (*log, stop_info, "returned stop_info: ");
        return true;

    case eStateInvalid:
    case eStateConnected:
    case eStateAttaching:
    case eStateLaunching:
    case eStateRunning:
    case eStateStepping:
    case eStateDetached:
    default:
        if (log)
        {
            log->Printf ("NativeThreadLinux::%s tid %" PRIu64 " in state %s cannot answer stop reason",
                    __FUNCTION__, GetID (), StateAsCString (m_state));
        }
        return false;
    }
}

lldb_private::NativeRegisterContextSP
NativeThreadLinux::GetRegisterContext ()
{
    // Return the register context if we already created it.
    if (m_reg_context_sp)
        return m_reg_context_sp;

    // First select the appropriate RegisterInfoInterface.
    RegisterInfoInterface *reg_interface = nullptr;
    NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
    if (!m_process_sp)
        return NativeRegisterContextSP ();

    ArchSpec target_arch;
    if (!m_process_sp->GetArchitecture (target_arch))
        return NativeRegisterContextSP ();

    switch (target_arch.GetTriple().getOS())
    {
        case llvm::Triple::Linux:
            switch (target_arch.GetMachine())
            {
            case llvm::Triple::x86:
            case llvm::Triple::x86_64:
                if (HostInfo::GetArchitecture().GetAddressByteSize() == 4)
                {
                    // 32-bit hosts run with a RegisterContextLinux_i386 context.
                    reg_interface = static_cast<RegisterInfoInterface*>(new RegisterContextLinux_i386(target_arch));
                }
                else
                {
                    assert((HostInfo::GetArchitecture().GetAddressByteSize() == 8) &&
                           "Register setting path assumes this is a 64-bit host");
                    // X86_64 hosts know how to work with 64-bit and 32-bit EXEs using the x86_64 register context.
                    reg_interface = static_cast<RegisterInfoInterface*> (new RegisterContextLinux_x86_64 (target_arch));
                }
                break;
            default:
                break;
            }
            break;
        default:
            break;
    }

    assert(reg_interface && "OS or CPU not supported!");
    if (!reg_interface)
        return NativeRegisterContextSP ();

    // Now create the register context.
    switch (target_arch.GetMachine())
    {
#if 0
        case llvm::Triple::mips64:
        {
            RegisterContextPOSIXProcessMonitor_mips64 *reg_ctx = new RegisterContextPOSIXProcessMonitor_mips64(*this, 0, reg_interface);
            m_posix_thread = reg_ctx;
            m_reg_context_sp.reset(reg_ctx);
            break;
        }
#endif
#if 0
        case llvm::Triple::x86:
#endif
        case llvm::Triple::x86_64:
        {
            const uint32_t concrete_frame_idx = 0;
            m_reg_context_sp.reset (new NativeRegisterContextLinux_x86_64(*this, concrete_frame_idx, reg_interface));
            break;
        }
        default:
            break;
    }

    return m_reg_context_sp;
}

Error
NativeThreadLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
{
    // TODO implement
    return Error ("not implemented");
}

Error
NativeThreadLinux::RemoveWatchpoint (lldb::addr_t addr)
{
    // TODO implement
    return Error ("not implemented");
}

void
NativeThreadLinux::SetLaunching ()
{
    const StateType new_state = StateType::eStateLaunching;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    // Also mark it as stopped since launching temporarily stops the newly created thread
    // in the ptrace machinery.
    m_stop_info.reason = StopReason::eStopReasonSignal;
    m_stop_info.details.signal.signo = SIGSTOP;
}

void
NativeThreadLinux::SetRunning ()
{
    const StateType new_state = StateType::eStateRunning;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonNone;
}

void
NativeThreadLinux::SetStepping ()
{
    const StateType new_state = StateType::eStateStepping;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonNone;
}

void
NativeThreadLinux::SetStoppedBySignal (uint32_t signo)
{
    Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
    if (log)
        log->Printf ("NativeThreadLinux::%s called with signal 0x%" PRIx32, __FUNCTION__, signo);

    const StateType new_state = StateType::eStateStopped;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonSignal;
    m_stop_info.details.signal.signo = signo;
}

void
NativeThreadLinux::SetStoppedByBreakpoint ()
{
    const StateType new_state = StateType::eStateStopped;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonSignal;
    m_stop_info.details.signal.signo = SIGTRAP;
}

bool
NativeThreadLinux::IsStoppedAtBreakpoint ()
{
    // Are we stopped? If not, this can't be a breakpoint.
    if (GetState () != StateType::eStateStopped)
        return false;

    // Was the stop reason a signal with signal number SIGTRAP? If not, not a breakpoint.
    return (m_stop_info.reason == StopReason::eStopReasonSignal) &&
            (m_stop_info.details.signal.signo == SIGTRAP);
}

void
NativeThreadLinux::SetCrashedWithException (uint64_t exception_type, lldb::addr_t exception_addr)
{
    const StateType new_state = StateType::eStateCrashed;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonException;
    m_stop_info.details.exception.type = exception_type;
    m_stop_info.details.exception.data_count = 1;
    m_stop_info.details.exception.data[0] = exception_addr;
}

void
NativeThreadLinux::SetSuspended ()
{
    const StateType new_state = StateType::eStateSuspended;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    // FIXME what makes sense here? Do we need a suspended StopReason?
    m_stop_info.reason = StopReason::eStopReasonNone;
}

void
NativeThreadLinux::SetExited ()
{
    const StateType new_state = StateType::eStateExited;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonThreadExiting;
}

void
NativeThreadLinux::MaybeLogStateChange (lldb::StateType new_state)
{
    Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
    // If we're not logging, we're done.
    if (!log)
        return;

    // If this is a state change to the same state, we're done.
    lldb::StateType old_state = m_state;
    if (new_state == old_state)
        return;

    NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
    lldb::pid_t pid = m_process_sp ? m_process_sp->GetID () : LLDB_INVALID_PROCESS_ID;

    // Log it.
    log->Printf ("NativeThreadLinux: thread (pid=%" PRIu64 ", tid=%" PRIu64 ") changing from state %s to %s", pid, GetID (), StateAsCString (old_state), StateAsCString (new_state));
}

static
uint32_t MaybeTranslateHostSignoToGdbSigno (uint32_t host_signo)
{
    switch (host_signo)
    {
        case SIGSEGV: return eGdbSignalBadAccess;
        case SIGILL:  return eGdbSignalBadInstruction;
        case SIGFPE:  return eGdbSignalArithmetic;
        // NOTE: debugserver sends SIGTRAP through unmodified.  Do the same here.
        // case SIGTRAP: return eGdbSignalBreakpoint;

        // Nothing for eGdbSignalSoftware (0x95).
        // Nothing for eGdbSignalEmulation (0x94).

        default:
            // No translations.
            return host_signo;
    }
}

uint32_t
NativeThreadLinux::TranslateStopInfoToGdbSignal (const ThreadStopInfo &stop_info) const
{
    switch (stop_info.reason)
    {
        case eStopReasonSignal:
            return MaybeTranslateHostSignoToGdbSigno (stop_info.details.signal.signo);
            break;

        case eStopReasonException:
            // FIXME verify how we handle exception type.
            return MaybeTranslateHostSignoToGdbSigno (static_cast<uint32_t> (stop_info.details.exception.type));
            break;

        default:
            assert (0 && "unexpected stop_info.reason found");
            return 0;
    }
}

<commit_msg>NativeThreadLinux: remove translation of some Linux signals to gdb signals.<commit_after>//===-- NativeThreadLinux.cpp --------------------------------- -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "NativeThreadLinux.h"

#include <signal.h>

#include "NativeProcessLinux.h"
#include "NativeRegisterContextLinux_x86_64.h"

#include "lldb/Core/Log.h"
#include "lldb/Core/State.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/lldb-enumerations.h"
#include "lldb/lldb-private-log.h"
#include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
#include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
#include "Plugins/Process/Utility/RegisterInfoInterface.h"

using namespace lldb;
using namespace lldb_private;

namespace
{
    void LogThreadStopInfo (Log &log, const ThreadStopInfo &stop_info, const char *const header)
    {
        switch (stop_info.reason)
        {
            case eStopReasonSignal:
                log.Printf ("%s: %s: signal 0x%" PRIx32, __FUNCTION__, header, stop_info.details.signal.signo);
                return;
            case eStopReasonException:
                log.Printf ("%s: %s: exception type 0x%" PRIx64, __FUNCTION__, header, stop_info.details.exception.type);
                return;
            default:
                log.Printf ("%s: %s: invalid stop reason %" PRIu32, __FUNCTION__, header, static_cast<uint32_t> (stop_info.reason));
        }
    }
}

NativeThreadLinux::NativeThreadLinux (NativeProcessLinux *process, lldb::tid_t tid) :
    NativeThreadProtocol (process, tid),
    m_state (StateType::eStateInvalid),
    m_stop_info (),
    m_reg_context_sp ()
{
}

const char *
NativeThreadLinux::GetName()
{
    NativeProcessProtocolSP process_sp = m_process_wp.lock ();
    if (!process_sp)
        return "<unknown: no process>";

    // const NativeProcessLinux *const process = reinterpret_cast<NativeProcessLinux*> (process_sp->get ());
    return Host::GetThreadName (process_sp->GetID (), GetID ()).c_str ();
}

lldb::StateType
NativeThreadLinux::GetState ()
{
    return m_state;
}

bool
NativeThreadLinux::GetStopReason (ThreadStopInfo &stop_info)
{
    Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
    switch (m_state)
    {
    case eStateStopped:
    case eStateCrashed:
    case eStateExited:
    case eStateSuspended:
    case eStateUnloaded:
        if (log)
            LogThreadStopInfo (*log, m_stop_info, "m_stop_info in thread: ");
        stop_info = m_stop_info;
        if (log)
            LogThreadStopInfo (*log, stop_info, "returned stop_info: ");
        return true;

    case eStateInvalid:
    case eStateConnected:
    case eStateAttaching:
    case eStateLaunching:
    case eStateRunning:
    case eStateStepping:
    case eStateDetached:
        if (log)
        {
            log->Printf ("NativeThreadLinux::%s tid %" PRIu64 " in state %s cannot answer stop reason",
                    __FUNCTION__, GetID (), StateAsCString (m_state));
        }
        return false;
    }
}

lldb_private::NativeRegisterContextSP
NativeThreadLinux::GetRegisterContext ()
{
    // Return the register context if we already created it.
    if (m_reg_context_sp)
        return m_reg_context_sp;

    // First select the appropriate RegisterInfoInterface.
    RegisterInfoInterface *reg_interface = nullptr;
    NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
    if (!m_process_sp)
        return NativeRegisterContextSP ();

    ArchSpec target_arch;
    if (!m_process_sp->GetArchitecture (target_arch))
        return NativeRegisterContextSP ();

    switch (target_arch.GetTriple().getOS())
    {
        case llvm::Triple::Linux:
            switch (target_arch.GetMachine())
            {
            case llvm::Triple::x86:
            case llvm::Triple::x86_64:
                if (HostInfo::GetArchitecture().GetAddressByteSize() == 4)
                {
                    // 32-bit hosts run with a RegisterContextLinux_i386 context.
                    reg_interface = static_cast<RegisterInfoInterface*>(new RegisterContextLinux_i386(target_arch));
                }
                else
                {
                    assert((HostInfo::GetArchitecture().GetAddressByteSize() == 8) &&
                           "Register setting path assumes this is a 64-bit host");
                    // X86_64 hosts know how to work with 64-bit and 32-bit EXEs using the x86_64 register context.
                    reg_interface = static_cast<RegisterInfoInterface*> (new RegisterContextLinux_x86_64 (target_arch));
                }
                break;
            default:
                break;
            }
            break;
        default:
            break;
    }

    assert(reg_interface && "OS or CPU not supported!");
    if (!reg_interface)
        return NativeRegisterContextSP ();

    // Now create the register context.
    switch (target_arch.GetMachine())
    {
#if 0
        case llvm::Triple::mips64:
        {
            RegisterContextPOSIXProcessMonitor_mips64 *reg_ctx = new RegisterContextPOSIXProcessMonitor_mips64(*this, 0, reg_interface);
            m_posix_thread = reg_ctx;
            m_reg_context_sp.reset(reg_ctx);
            break;
        }
#endif
#if 0
        case llvm::Triple::x86:
#endif
        case llvm::Triple::x86_64:
        {
            const uint32_t concrete_frame_idx = 0;
            m_reg_context_sp.reset (new NativeRegisterContextLinux_x86_64(*this, concrete_frame_idx, reg_interface));
            break;
        }
        default:
            break;
    }

    return m_reg_context_sp;
}

Error
NativeThreadLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
{
    // TODO implement
    return Error ("not implemented");
}

Error
NativeThreadLinux::RemoveWatchpoint (lldb::addr_t addr)
{
    // TODO implement
    return Error ("not implemented");
}

void
NativeThreadLinux::SetLaunching ()
{
    const StateType new_state = StateType::eStateLaunching;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    // Also mark it as stopped since launching temporarily stops the newly created thread
    // in the ptrace machinery.
    m_stop_info.reason = StopReason::eStopReasonSignal;
    m_stop_info.details.signal.signo = SIGSTOP;
}

void
NativeThreadLinux::SetRunning ()
{
    const StateType new_state = StateType::eStateRunning;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonNone;
}

void
NativeThreadLinux::SetStepping ()
{
    const StateType new_state = StateType::eStateStepping;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonNone;
}

void
NativeThreadLinux::SetStoppedBySignal (uint32_t signo)
{
    Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
    if (log)
        log->Printf ("NativeThreadLinux::%s called with signal 0x%" PRIx32, __FUNCTION__, signo);

    const StateType new_state = StateType::eStateStopped;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonSignal;
    m_stop_info.details.signal.signo = signo;
}

void
NativeThreadLinux::SetStoppedByBreakpoint ()
{
    const StateType new_state = StateType::eStateStopped;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonSignal;
    m_stop_info.details.signal.signo = SIGTRAP;
}

bool
NativeThreadLinux::IsStoppedAtBreakpoint ()
{
    // Are we stopped? If not, this can't be a breakpoint.
    if (GetState () != StateType::eStateStopped)
        return false;

    // Was the stop reason a signal with signal number SIGTRAP? If not, not a breakpoint.
    return (m_stop_info.reason == StopReason::eStopReasonSignal) &&
            (m_stop_info.details.signal.signo == SIGTRAP);
}

void
NativeThreadLinux::SetCrashedWithException (uint64_t exception_type, lldb::addr_t exception_addr)
{
    const StateType new_state = StateType::eStateCrashed;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonException;
    m_stop_info.details.exception.type = exception_type;
    m_stop_info.details.exception.data_count = 1;
    m_stop_info.details.exception.data[0] = exception_addr;
}

void
NativeThreadLinux::SetSuspended ()
{
    const StateType new_state = StateType::eStateSuspended;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    // FIXME what makes sense here? Do we need a suspended StopReason?
    m_stop_info.reason = StopReason::eStopReasonNone;
}

void
NativeThreadLinux::SetExited ()
{
    const StateType new_state = StateType::eStateExited;
    MaybeLogStateChange (new_state);
    m_state = new_state;

    m_stop_info.reason = StopReason::eStopReasonThreadExiting;
}

void
NativeThreadLinux::MaybeLogStateChange (lldb::StateType new_state)
{
    Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
    // If we're not logging, we're done.
    if (!log)
        return;

    // If this is a state change to the same state, we're done.
    lldb::StateType old_state = m_state;
    if (new_state == old_state)
        return;

    NativeProcessProtocolSP m_process_sp = m_process_wp.lock ();
    lldb::pid_t pid = m_process_sp ? m_process_sp->GetID () : LLDB_INVALID_PROCESS_ID;

    // Log it.
    log->Printf ("NativeThreadLinux: thread (pid=%" PRIu64 ", tid=%" PRIu64 ") changing from state %s to %s", pid, GetID (), StateAsCString (old_state), StateAsCString (new_state));
}

uint32_t
NativeThreadLinux::TranslateStopInfoToGdbSignal (const ThreadStopInfo &stop_info) const
{
    switch (stop_info.reason)
    {
        case eStopReasonSignal:
            // No translation.
            return stop_info.details.signal.signo;

        case eStopReasonException:
            {
                Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
                // FIXME I think the eStopReasonException is a xnu/Mach exception, which we
                // shouldn't see on Linux.
                // No translation.
                if (log)
                    log->Printf ("NativeThreadLinux::%s saw an exception stop type (signo %"
                                 PRIu64 "), not expecting to see exceptions on Linux",
                                 __FUNCTION__,
                                 stop_info.details.exception.type);
                return static_cast<uint32_t> (stop_info.details.exception.type);
            }

        default:
            assert (0 && "unexpected stop_info.reason found");
            return 0;
    }
}

<|endoftext|>


<commit_before><commit_msg>Password Update bubble combobox left alignment<commit_after><|endoftext|>


<commit_before>/**
 * @file llchatentry.cpp
 * @brief LLChatEntry implementation
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "linden_common.h"

#include "llchatentry.h"

static LLDefaultChildRegistry::Register<LLChatEntry> r("chat_editor");

LLChatEntry::Params::Params()
:	has_history("has_history", true),
 	is_expandable("is_expandable", false),
 	expand_lines_count("expand_lines_count", 1)
{}

LLChatEntry::LLChatEntry(const Params& p)
:	LLTextEditor(p),
 	mTextExpandedSignal(NULL),
 	mHasHistory(p.has_history),
 	mIsExpandable(p.is_expandable),
 	mExpandLinesCount(p.expand_lines_count),
 	mPrevLinesCount(0)
{
	// Initialize current history line iterator
	mCurrentHistoryLine = mLineHistory.begin();

	mAutoIndent = false;
}

LLChatEntry::~LLChatEntry()
{
	delete mTextExpandedSignal;
}

void LLChatEntry::draw()
{
	LLTextEditor::draw();

	if(mIsExpandable)
	{
		expandText();
	}
}

void LLChatEntry::onCommit()
{
	updateHistory();
	LLTextEditor::onCommit();
}

boost::signals2::connection LLChatEntry::setTextExpandedCallback(const commit_signal_t::slot_type& cb)
{
	if (!mTextExpandedSignal)
	{
		mTextExpandedSignal = new commit_signal_t();
	}
	return mTextExpandedSignal->connect(cb);
}

void LLChatEntry::expandText()
{
	int visible_lines_count = llabs(getVisibleLines(true).first - getVisibleLines(true).second);
	bool can_expand = getLineCount() <= mExpandLinesCount;

	// true if pasted text has more lines than expand height limit and expand limit is not reached yet
	bool text_pasted = (getLineCount() > mExpandLinesCount) && (visible_lines_count < mExpandLinesCount);

	if (mIsExpandable && (can_expand || text_pasted) && getLineCount() != mPrevLinesCount)
	{
		int lines_height = 0;
		if (text_pasted)
		{
			// text is pasted and now mLineInfoList.size() > mExpandLineCounts and mLineInfoList is not empty,
			// so lines_height is the sum of the last 'mExpandLinesCount' lines height
			lines_height = (mLineInfoList.end() - mExpandLinesCount)->mRect.mTop - mLineInfoList.back().mRect.mBottom;
		}
		else
		{
			lines_height = mLineInfoList.begin()->mRect.mTop - mLineInfoList.back().mRect.mBottom;
		}

		int height = mVPad * 2 +  lines_height;

		LLRect doc_rect = getRect();
		doc_rect.setOriginAndSize(doc_rect.mLeft, doc_rect.mBottom, doc_rect.getWidth(), height);
		setShape(doc_rect);

		mPrevLinesCount = getLineCount();

		if (mTextExpandedSignal)
		{
			(*mTextExpandedSignal)(this, LLSD() );
		}
	}
}

// line history support
void LLChatEntry::updateHistory()
{
	// On history enabled, remember committed line and
	// reset current history line number.
	// Be sure only to remember lines that are not empty and that are
	// different from the last on the list.
	if (mHasHistory && getLength())
	{
		// Add text to history, ignoring duplicates
		if (mLineHistory.empty() || getText() != mLineHistory.back())
		{
			mLineHistory.push_back(getText());
		}

		mCurrentHistoryLine = mLineHistory.end();
	}
}

BOOL LLChatEntry::handleSpecialKey(const KEY key, const MASK mask)
{
	BOOL handled = FALSE;

	LLTextEditor::handleSpecialKey(key, mask);

	switch(key)
	{
	case KEY_RETURN:
		if (MASK_NONE == mask)
		{
			needsReflow();
		}
		break;

	case KEY_UP:
		if (mHasHistory && MASK_CONTROL == mask)
		{
			if (!mLineHistory.empty() && mCurrentHistoryLine > mLineHistory.begin())
			{
				setText(*(--mCurrentHistoryLine));
				endOfDoc();
			}
			else
			{
				LLUI::reportBadKeystroke();
			}
			handled = TRUE;
		}
		break;

	case KEY_DOWN:
		if (mHasHistory && MASK_CONTROL == mask)
		{
			if (!mLineHistory.empty() && ++mCurrentHistoryLine < mLineHistory.end())
			{
				setText(*mCurrentHistoryLine);
				endOfDoc();
			}
			else if (!mLineHistory.empty() && mCurrentHistoryLine == mLineHistory.end())
			{
				std::string empty("");
				setText(empty);
				needsReflow();
				endOfDoc();
			}
			else
			{
				LLUI::reportBadKeystroke();
			}
			handled = TRUE;
		}
		break;

	default:
		break;
	}

	return handled;
}
<commit_msg>CHUI-127 ADDITIONAL FIX (Make chat field auto resizable)<commit_after>/**
 * @file llchatentry.cpp
 * @brief LLChatEntry implementation
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "linden_common.h"

#include "llchatentry.h"

static LLDefaultChildRegistry::Register<LLChatEntry> r("chat_editor");

LLChatEntry::Params::Params()
:	has_history("has_history", true),
 	is_expandable("is_expandable", false),
 	expand_lines_count("expand_lines_count", 1)
{}

LLChatEntry::LLChatEntry(const Params& p)
:	LLTextEditor(p),
 	mTextExpandedSignal(NULL),
 	mHasHistory(p.has_history),
 	mIsExpandable(p.is_expandable),
 	mExpandLinesCount(p.expand_lines_count),
 	mPrevLinesCount(0)
{
	// Initialize current history line iterator
	mCurrentHistoryLine = mLineHistory.begin();

	mAutoIndent = false;
}

LLChatEntry::~LLChatEntry()
{
	delete mTextExpandedSignal;
}

void LLChatEntry::draw()
{
	LLTextEditor::draw();

	if(mIsExpandable)
	{
		expandText();
	}
}

void LLChatEntry::onCommit()
{
	updateHistory();
	LLTextEditor::onCommit();
}

boost::signals2::connection LLChatEntry::setTextExpandedCallback(const commit_signal_t::slot_type& cb)
{
	if (!mTextExpandedSignal)
	{
		mTextExpandedSignal = new commit_signal_t();
	}
	return mTextExpandedSignal->connect(cb);
}

void LLChatEntry::expandText()
{
	int visible_lines_count = llabs(getVisibleLines(true).first - getVisibleLines(true).second);
	bool can_expand = getLineCount() <= mExpandLinesCount;

	// true if pasted text has more lines than expand height limit and expand limit is not reached yet
	bool text_pasted = (getLineCount() > mExpandLinesCount) && (visible_lines_count < mExpandLinesCount);

	if (mIsExpandable && (can_expand || text_pasted) && getLineCount() != mPrevLinesCount)
	{
		int lines_height = 0;
		if (text_pasted)
		{
			// text is pasted and now mLineInfoList.size() > mExpandLineCounts and mLineInfoList is not empty,
			// so lines_height is the sum of the last 'mExpandLinesCount' lines height
			lines_height = (mLineInfoList.end() - mExpandLinesCount)->mRect.mTop - mLineInfoList.back().mRect.mBottom;
		}
		else
		{
			lines_height = mLineInfoList.begin()->mRect.mTop - mLineInfoList.back().mRect.mBottom;
		}

		int height = mVPad * 2 +  lines_height;

		LLRect doc_rect = getRect();
		doc_rect.setOriginAndSize(doc_rect.mLeft, doc_rect.mBottom, doc_rect.getWidth(), height);
		setShape(doc_rect);

		mPrevLinesCount = getLineCount();

		if (mTextExpandedSignal)
		{
			(*mTextExpandedSignal)(this, LLSD() );
		}
	}
}

// line history support
void LLChatEntry::updateHistory()
{
	// On history enabled, remember committed line and
	// reset current history line number.
	// Be sure only to remember lines that are not empty and that are
	// different from the last on the list.
	if (mHasHistory && getLength())
	{
		// Add text to history, ignoring duplicates
		if (mLineHistory.empty() || getText() != mLineHistory.back())
		{
			mLineHistory.push_back(getText());
		}

		mCurrentHistoryLine = mLineHistory.end();
	}
}

BOOL LLChatEntry::handleSpecialKey(const KEY key, const MASK mask)
{
	BOOL handled = FALSE;

	LLTextEditor::handleSpecialKey(key, mask);

	switch(key)
	{
	case KEY_RETURN:
		if (MASK_NONE == mask)
		{
			needsReflow();
		}
		break;

	case KEY_UP:
		if (mHasHistory && MASK_CONTROL == mask)
		{
			if (!mLineHistory.empty() && mCurrentHistoryLine > mLineHistory.begin())
			{
				setText(*(--mCurrentHistoryLine));
				endOfDoc();
			}
			else
			{
				LLUI::reportBadKeystroke();
			}
			handled = TRUE;
		}
		break;

	case KEY_DOWN:
		if (mHasHistory && MASK_CONTROL == mask)
		{
			if (!mLineHistory.empty() && mCurrentHistoryLine < (mLineHistory.end() - 1) )
			{
				setText(*(++mCurrentHistoryLine));
				endOfDoc();
			}
			else if (!mLineHistory.empty() && mCurrentHistoryLine == (mLineHistory.end() - 1) )
			{
				mCurrentHistoryLine++;
				std::string empty("");
				setText(empty);
				needsReflow();
				endOfDoc();
			}
			else
			{
				LLUI::reportBadKeystroke();
			}
			handled = TRUE;
		}
		break;

	default:
		break;
	}

	return handled;
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/providers/cpu/tensor/space_depth_ops.h"
#include "core/util/eigen_common_wrapper.h"
#include <array>

namespace onnxruntime {

ONNX_CPU_OPERATOR_KERNEL(
    SpaceToDepth,
    1,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    SpaceToDepth<float>);

ONNX_CPU_OPERATOR_VERSIONED_KERNEL(
    DepthToSpace,
    1, 10,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    DepthToSpace<float>);

ONNX_CPU_OPERATOR_KERNEL(
    DepthToSpace,
    11,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    DepthToSpace<float>);

// intermediate tensor shapes are:
// (batch, blocksize, blocksize, input_depth / (blocksize * blocksize), input_height, input_width) for DepthToSpace
// (batch, input_depth, input_height / blocksize, blocksize, input_width / blocksize, blocksize) for SpaceToDepth
const int IntermediateTensorRank = 6;
typedef Eigen::TensorMap<Eigen::Tensor<float, IntermediateTensorRank, Eigen::RowMajor, Eigen::DenseIndex>,
                         Eigen::Aligned>
    EigenTensorMap;

typedef Eigen::TensorMap<Eigen::Tensor<const float, IntermediateTensorRank, Eigen::RowMajor, Eigen::DenseIndex>,
                         Eigen::Aligned>
    ConstEigenTensorMap;

// helper to create output to minimize binary size
static void CreateOutput(const Tensor& input, Tensor& output,
                         const std::array<Eigen::DenseIndex, IntermediateTensorRank>& permutation,
                         const Eigen::DenseIndex batch_size,  // dim0 in both input and output
                         const Eigen::DenseIndex in_dim1, const Eigen::DenseIndex in_dim2, const Eigen::DenseIndex in_dim3,
                         const Eigen::DenseIndex in_dim4, const Eigen::DenseIndex in_dim5,
                         const Eigen::DenseIndex out_dim1, const Eigen::DenseIndex out_dim2, const Eigen::DenseIndex out_dim3,
                         const Eigen::DenseIndex out_dim4, const Eigen::DenseIndex out_dim5) {
  EigenTensorMap(output.template MutableData<float>(), batch_size, out_dim1, out_dim2, out_dim3, out_dim4, out_dim5) =
      ConstEigenTensorMap(input.template Data<float>(), batch_size,
                          in_dim1, in_dim2, in_dim3, in_dim4, in_dim5)
          .shuffle(permutation);
}

template <>
Status SpaceToDepth<float>::Compute(OpKernelContext* context) const {
  const auto* tensor_pointer = context->Input<Tensor>(0);
  if (tensor_pointer == nullptr) return Status(common::ONNXRUNTIME, common::FAIL, "input count mismatch");
  const Tensor& input = *tensor_pointer;
  const TensorShape& input_shape = input.Shape();
  ORT_ENFORCE(input_shape.NumDimensions() == 4);
  const int64_t batch = input_shape[0];
  const int64_t input_depth = input_shape[1];
  const int64_t input_height = input_shape[2];
  const int64_t input_width = input_shape[3];
  ORT_ENFORCE(input_height % this->blocksize_ == 0);
  ORT_ENFORCE(input_width % this->blocksize_ == 0);

  const Eigen::DenseIndex output_depth = input_depth * blocksize_ * blocksize_;
  const Eigen::DenseIndex output_height = input_height / blocksize_;
  const Eigen::DenseIndex output_width = input_width / blocksize_;
  Tensor& output = *context->Output(0, {batch, output_depth, output_height, output_width});

  std::array<Eigen::DenseIndex, IntermediateTensorRank> permutation{{0, 3, 5, 1, 2, 4}};
  CreateOutput(input, output, permutation, batch,
               input_depth, input_height / blocksize_, blocksize_, input_width / blocksize_, blocksize_,
               blocksize_, blocksize_, input_depth, input_height / blocksize_, input_width / blocksize_);

  return Status::OK();
}

template <>
Status DepthToSpace<float>::Compute(OpKernelContext* context) const {
  const auto* tensor_pointer = context->Input<Tensor>(0);
  if (tensor_pointer == nullptr) return Status(common::ONNXRUNTIME, common::FAIL, "input count mismatch");
  const Tensor& input = *tensor_pointer;
  ORT_ENFORCE(input.Shape().NumDimensions() == 4);

  const int64_t batch = input.Shape().GetDims().at(0);
  const int64_t input_depth = input.Shape().GetDims().at(1);
  const int64_t input_height = input.Shape().GetDims().at(2);
  const int64_t input_width = input.Shape().GetDims().at(3);
  ORT_ENFORCE(input_depth % (blocksize_ * blocksize_) == 0);

  const int64_t output_depth = input_depth / blocksize_ / blocksize_;
  const int64_t output_height = input_height * blocksize_;
  const int64_t output_width = input_width * blocksize_;

  Tensor& output = *context->Output(0, {batch, output_depth, output_height, output_width});

  // handle DCR and CRD format
  auto dim1 = is_dcr_ ? blocksize_ : input_depth / blocksize_ / blocksize_;
  auto dim3 = is_dcr_ ? input_depth / blocksize_ / blocksize_ : blocksize_;

  auto permutation = is_dcr_ ? std::array<Eigen::DenseIndex, IntermediateTensorRank>{{0, 3, 4, 1, 5, 2}}
                             : std::array<Eigen::DenseIndex, IntermediateTensorRank>{{0, 1, 4, 2, 5, 3}};

  CreateOutput(input, output, permutation, batch,
               dim1, blocksize_, dim3, input_height, input_width,
               input_depth / blocksize_ / blocksize_, input_height, blocksize_, input_width, blocksize_);

  return Status::OK();
}

}  // namespace onnxruntime
<commit_msg>Disable erroneous compiler warning in space_depth_ops.cc<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

// TODO: x86 release builds produce warning C4723: potential divide by 0
#ifdef _MSC_VER
#pragma warning(disable : 4723)
#endif

#include "core/providers/cpu/tensor/space_depth_ops.h"
#include "core/util/eigen_common_wrapper.h"
#include <array>

namespace onnxruntime {

ONNX_CPU_OPERATOR_KERNEL(
    SpaceToDepth,
    1,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    SpaceToDepth<float>);

ONNX_CPU_OPERATOR_VERSIONED_KERNEL(
    DepthToSpace,
    1, 10,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    DepthToSpace<float>);

ONNX_CPU_OPERATOR_KERNEL(
    DepthToSpace,
    11,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    DepthToSpace<float>);

// intermediate tensor shapes are:
// (batch, blocksize, blocksize, input_depth / (blocksize * blocksize), input_height, input_width) for DepthToSpace
// (batch, input_depth, input_height / blocksize, blocksize, input_width / blocksize, blocksize) for SpaceToDepth
const int IntermediateTensorRank = 6;
typedef Eigen::TensorMap<Eigen::Tensor<float, IntermediateTensorRank, Eigen::RowMajor, Eigen::DenseIndex>,
                         Eigen::Aligned>
    EigenTensorMap;

typedef Eigen::TensorMap<Eigen::Tensor<const float, IntermediateTensorRank, Eigen::RowMajor, Eigen::DenseIndex>,
                         Eigen::Aligned>
    ConstEigenTensorMap;

// helper to create output to minimize binary size
static void CreateOutput(const Tensor& input, Tensor& output,
                         const std::array<Eigen::DenseIndex, IntermediateTensorRank>& permutation,
                         const Eigen::DenseIndex batch_size,  // dim0 in both input and output
                         const Eigen::DenseIndex in_dim1, const Eigen::DenseIndex in_dim2, const Eigen::DenseIndex in_dim3,
                         const Eigen::DenseIndex in_dim4, const Eigen::DenseIndex in_dim5,
                         const Eigen::DenseIndex out_dim1, const Eigen::DenseIndex out_dim2, const Eigen::DenseIndex out_dim3,
                         const Eigen::DenseIndex out_dim4, const Eigen::DenseIndex out_dim5) {
  EigenTensorMap(output.template MutableData<float>(), batch_size, out_dim1, out_dim2, out_dim3, out_dim4, out_dim5) =
      ConstEigenTensorMap(input.template Data<float>(), batch_size,
                          in_dim1, in_dim2, in_dim3, in_dim4, in_dim5)
          .shuffle(permutation);
}

template <>
Status SpaceToDepth<float>::Compute(OpKernelContext* context) const {
  const auto* tensor_pointer = context->Input<Tensor>(0);
  if (tensor_pointer == nullptr) return Status(common::ONNXRUNTIME, common::FAIL, "input count mismatch");
  const Tensor& input = *tensor_pointer;
  const TensorShape& input_shape = input.Shape();
  ORT_ENFORCE(input_shape.NumDimensions() == 4);
  const int64_t batch = input_shape[0];
  const int64_t input_depth = input_shape[1];
  const int64_t input_height = input_shape[2];
  const int64_t input_width = input_shape[3];
  ORT_ENFORCE(input_height % this->blocksize_ == 0);
  ORT_ENFORCE(input_width % this->blocksize_ == 0);

  const Eigen::DenseIndex output_depth = input_depth * blocksize_ * blocksize_;
  const Eigen::DenseIndex output_height = input_height / blocksize_;
  const Eigen::DenseIndex output_width = input_width / blocksize_;
  Tensor& output = *context->Output(0, {batch, output_depth, output_height, output_width});

  std::array<Eigen::DenseIndex, IntermediateTensorRank> permutation{{0, 3, 5, 1, 2, 4}};
  CreateOutput(input, output, permutation, batch,
               input_depth, input_height / blocksize_, blocksize_, input_width / blocksize_, blocksize_,
               blocksize_, blocksize_, input_depth, input_height / blocksize_, input_width / blocksize_);

  return Status::OK();
}

template <>
Status DepthToSpace<float>::Compute(OpKernelContext* context) const {
  const auto* tensor_pointer = context->Input<Tensor>(0);
  if (tensor_pointer == nullptr) return Status(common::ONNXRUNTIME, common::FAIL, "input count mismatch");
  const Tensor& input = *tensor_pointer;
  ORT_ENFORCE(input.Shape().NumDimensions() == 4);

  const int64_t batch = input.Shape().GetDims().at(0);
  const int64_t input_depth = input.Shape().GetDims().at(1);
  const int64_t input_height = input.Shape().GetDims().at(2);
  const int64_t input_width = input.Shape().GetDims().at(3);
  ORT_ENFORCE(input_depth % (blocksize_ * blocksize_) == 0);

  const int64_t output_depth = input_depth / blocksize_ / blocksize_;
  const int64_t output_height = input_height * blocksize_;
  const int64_t output_width = input_width * blocksize_;

  Tensor& output = *context->Output(0, {batch, output_depth, output_height, output_width});

  // handle DCR and CRD format
  auto dim1 = is_dcr_ ? blocksize_ : input_depth / blocksize_ / blocksize_;
  auto dim3 = is_dcr_ ? input_depth / blocksize_ / blocksize_ : blocksize_;

  auto permutation = is_dcr_ ? std::array<Eigen::DenseIndex, IntermediateTensorRank>{{0, 3, 4, 1, 5, 2}}
                             : std::array<Eigen::DenseIndex, IntermediateTensorRank>{{0, 1, 4, 2, 5, 3}};

  CreateOutput(input, output, permutation, batch,
               dim1, blocksize_, dim3, input_height, input_width,
               input_depth / blocksize_ / blocksize_, input_height, blocksize_, input_width, blocksize_);

  return Status::OK();
}

}  // namespace onnxruntime
<|endoftext|>