<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tp_LegendPosition.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 00:15:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _CHART2_TP_LEGENDPOSITION_HXX
#define _CHART2_TP_LEGENDPOSITION_HXX

// header for SfxTabPage
#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
// header for FixedText
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif

//.............................................................................
namespace chart
{
//.............................................................................

/*************************************************************************
|*
|* Legenden-Anordnungs-Tab-Page
|*
\************************************************************************/
class SchLegendPosTabPage : public SfxTabPage
{
private:
    FixedLine   aGrpLegend;
    RadioButton aRbtLeft;
    RadioButton aRbtTop;
    RadioButton aRbtBottom;
    RadioButton aRbtRight;

public:
    SchLegendPosTabPage(Window* pParent, const SfxItemSet& rInAttrs);
    virtual ~SchLegendPosTabPage();

    static SfxTabPage* Create(Window* pParent, const SfxItemSet& rInAttrs);
    virtual BOOL FillItemSet(SfxItemSet& rOutAttrs);
    virtual void Reset(const SfxItemSet& rInAttrs);
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif

<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2006/01/06 20:27:26 iha 1.2.4.3: added legendposition to wizard and restructured legend postiion control classes 2005/10/07 11:19:59 bm 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2004/09/07 10:04:06 bm 1.2.4.1: fixed order of members to fit order in dialog<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tp_LegendPosition.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 17:46:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _CHART2_TP_LEGENDPOSITION_HXX
#define _CHART2_TP_LEGENDPOSITION_HXX

// header for SfxTabPage
#ifndef _SFXTABDLG_HXX
#include <sfx2/tabdlg.hxx>
#endif
// header for FixedText
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
//for auto_ptr
#include <memory>

//.............................................................................
namespace chart
{
//.............................................................................

class LegendPositionResources;
class SchLegendPosTabPage : public SfxTabPage
{
private:
    FixedLine   aGrpLegend;

    ::std::auto_ptr< LegendPositionResources >   m_apLegendPositionResources;

public:
    SchLegendPosTabPage(Window* pParent, const SfxItemSet& rInAttrs);
    virtual ~SchLegendPosTabPage();

    static SfxTabPage* Create(Window* pParent, const SfxItemSet& rInAttrs);
    virtual BOOL FillItemSet(SfxItemSet& rOutAttrs);
    virtual void Reset(const SfxItemSet& rInAttrs);
};

//.............................................................................
} //namespace chart
//.............................................................................

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NumberFormatterWrapper.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:26:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/
#ifndef _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX
#define _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX

#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/
class FixedNumberFormatter;

class NumberFormatterWrapper
{
public:
    NumberFormatterWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier );
    virtual ~NumberFormatterWrapper();

    SvNumberFormatter* getSvNumberFormatter() const;
    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >
                getNumberFormatsSupplier() { return m_xNumberFormatsSupplier; };

    rtl::OUString getFormattedString( sal_Int32 nNumberFormatKey, double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;

private: //private member
    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >
                        m_xNumberFormatsSupplier;

    SvNumberFormatter* m_pNumberFormatter;
};

class FixedNumberFormatter
{
public:
    FixedNumberFormatter( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier
        , sal_Int32 nNumberFormatKey );
    virtual ~FixedNumberFormatter();

    rtl::OUString getFormattedString( double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;

private:
    NumberFormatterWrapper      m_aNumberFormatterWrapper;
    ULONG                       m_nNumberFormatKey;
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.126); FILE MERGED 2008/04/01 15:04:15 thb 1.4.126.3: #i85898# Stripping all external header guards 2008/04/01 10:50:30 thb 1.4.126.2: #i85898# Stripping all external header guards 2008/03/28 16:44:01 rt 1.4.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: NumberFormatterWrapper.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX
#define _CHART2_VIEW_NUMBERFORMATTERWRAPPER_HXX

#include <svtools/zforlist.hxx>
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/
class FixedNumberFormatter;

class NumberFormatterWrapper
{
public:
    NumberFormatterWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier );
    virtual ~NumberFormatterWrapper();

    SvNumberFormatter* getSvNumberFormatter() const;
    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >
                getNumberFormatsSupplier() { return m_xNumberFormatsSupplier; };

    rtl::OUString getFormattedString( sal_Int32 nNumberFormatKey, double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;

private: //private member
    ::com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier >
                        m_xNumberFormatsSupplier;

    SvNumberFormatter* m_pNumberFormatter;
};

class FixedNumberFormatter
{
public:
    FixedNumberFormatter( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >& xSupplier
        , sal_Int32 nNumberFormatKey );
    virtual ~FixedNumberFormatter();

    rtl::OUString getFormattedString( double fValue, sal_Int32& rLabelColor, bool& rbColorChanged ) const;

private:
    NumberFormatterWrapper      m_aNumberFormatterWrapper;
    ULONG                       m_nNumberFormatKey;
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>


<commit_before>#include "h5test.h"
#include "parallel_io.h"
#include "comm.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"

struct Var_t
{
  const char * name;
  const char * descript;
};

Var_t varT[] =
  {
    {"T", "Temp in K"},
    {"p", "Pressure in N/m^2"},
    {"u", "X Velocity in m/s"},
    {"v", "Y Velocity in m/s"},
    {"w", "Z Velocity in m/s"},
    {"a", "A Velocity in m/s"},
    {"b", "B Velocity in m/s"},
    {"c", "C Velocity in m/s"},
    {"d", "D Velocity in m/s"},
    {"e", "E Velocity in m/s"},
  };

ParallelIO::ParallelIO()
  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
    m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0),
    m_dne_stripes(-1), m_auto_max_stripes(-1), m_stripesT3(-1)
{}

#ifndef USE_HDF5
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
  if (P.myProc == 0)
    printf("This program requires HDF5 which is not available => quitting\n");
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
}

#else
void ParallelIO::h5writer(CmdLineOptions& cmd)
{

  hid_t   file_id;       //file      identifier
  hid_t   group_id;      //group     identifier
  hid_t   dset_id;       //Dataset   identifier
  hid_t   filespace;     //Dataspace id in file
  hid_t   memspace;      //Dataspace id in memory.
  hid_t   plist_id;      //Property List id
  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;
  hsize_t is, num;
  int     ierr;
  MPI_Comm commF;
  H5FD_mpio_xfer_t  xfer_mode;   // HDF5 transfer mode (indep or collective)
  const char * fn = "UNSTRUCT.h5";

  // compute size info

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  double lSz     = 1.0;

  m_numvar    = cmd.nvar;
  num         = cmd.localSz;
  lSz         = num;
  count[0]    = 1;
  h5stride[0] = 1;
  starts[0]   = is;
  sz[0]       = num;
  gsz[0]      = cmd.globalSz;
  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);

  int iTotalSz = m_totalSz/(1024*1024);

  // Initialize data buffer
  double xk = num*P.myProc;

  double *data = new double[num];
  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;

  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
      m_nIOUnits         = results.numIO;
      m_dne_stripes      = results.S_dne_stripes;
      m_auto_max_stripes = results.S_auto_max_stripes;
      m_nStripesT3       = results.nStripesT3;
    }

  xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;

  t0 = walltime();

  plist_id = H5Pcreate(H5P_FILE_ACCESS);
  H5Pset_fapl_mpio(plist_id, P.comm, info);

  // Create file collectively
  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);

  MPI_File* pFH = NULL;
  ierr    = H5Fget_vfd_handle(file_id, H5P_DEFAULT, (void **) &pFH);
  ierr    = MPI_File_get_info(*pFH, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_aggregators = results.numIO;
  m_nStripes    = results.numStripes;
  m_stripeSz    = results.stripeSize;
  H5Pclose(plist_id);

  // Create Group
  group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

  std::string timeZ, timeL;
  dateZ(timeZ);
  add_attribute(group_id,"Zulu Time", timeZ.c_str());

  dateL(timeL);
  add_attribute(group_id,"Local Time", timeL.c_str());

  for (int ivar = 0; ivar < m_numvar; ++ivar)
    {

      // Create the dataspace for the dataset
      filespace = H5Screate_simple(1, &gsz[0], NULL);
      memspace  = H5Screate_simple(1, sz,      NULL);

      if (cmd.h5chunk)
        {
          plist_id = H5Pcreate(H5P_DATASET_CREATE);
          H5Pset_chunk(plist_id,1, sz);

          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, plist_id, H5P_DEFAULT);
          H5Pclose(plist_id);
          H5Sclose(filespace);

          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
        }
      else if (cmd.h5slab)
        {
          // Create the dataset w/ default properties and close filespace
          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
          H5Sclose(filespace);

          // Select hyperslab in the file.
          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
        }

      plist_id = H5Pcreate(H5P_DATASET_XFER);
      H5Pset_dxpl_mpio(plist_id, xfer_mode);

      add_attribute(dset_id, "Variable Description", varT[ivar].descript);

      t1   = walltime();

      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
                               plist_id, data);
      t2   = walltime();
      m_t += (t2 - t1);

      H5Dclose(dset_id);
      H5Sclose(filespace);
      H5Sclose(memspace);
      H5Pclose(plist_id);
    }

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz /(m_totalTime * 1024.0 * 1024.0);
  free(data);
  H5Gclose(group_id);
  H5Fclose(file_id);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
  hid_t attr_id, aspace_id, atype_id;
  hsize_t attrlen, num[1];

  attrlen = strlen(value);
  num[0]  = 1;

  atype_id = H5Tcopy(H5T_C_S1);
  H5Tset_size(atype_id, attrlen);

  aspace_id = H5Screate_simple(1,num, NULL);

  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite(attr_id, atype_id, value);
  H5Aclose(attr_id);
  H5Sclose(aspace_id);
}
#endif

void ParallelIO::MPIIOwriter(CmdLineOptions& cmd)
{

  MPI_File     fh;
  MPI_Offset   is, rem, offset;
  MPI_Datatype coreData, gblData, my_vector;
  MPI_Status   status;
  int          iTotalSz, ierr, nDim;
  int          sz[2], gsz[2], starts[2];
  const char*  fn = "UNSTRUCT.mpiio";

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  m_numvar      = 1;
  m_totalSz     = cmd.globalSz*m_numvar*sizeof(double);
  iTotalSz      = m_totalSz/(1024*1024);
  int    num    = cmd.localSz;
  double *data  = new double[num];
  double xk     = is;

  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;
  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
      m_nIOUnits = results.numIO;
    }

  //nDim = 1;
  //offset = is*sizeof(double);
  //ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);
  //ierr = MPI_Type_commit(&my_vector);
  //ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, "native", info);

  offset    = 0;
  nDim      = 2;
  sz[0]     = cmd.localSz/cmd.xwidth;
  sz[1]     = cmd.xwidth;
  gsz[0]    = cmd.globalSz/cmd.xwidth;
  gsz[1]    = cmd.xwidth;
  starts[0] = 0;
  starts[1] = 0;

  ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &coreData);
  ierr = MPI_Type_commit(&coreData);
  starts[0] = sz[0]*P.myProc;
  ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &gblData);
  ierr = MPI_Type_commit(&gblData);

  t0 = walltime();

  ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);
  if (ierr)
    MPI_Abort(P.comm, -1);

  ierr = MPI_File_get_info(fh, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_aggregators = results.numIO;
  m_nStripes    = results.numStripes;
  m_stripeSz    = results.stripeSize;

  ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, "native", info);

  ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);
  ierr = MPI_File_close(&fh);

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz/(m_totalTime * 1024.0 * 1024.0);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

<commit_msg>yet another typo<commit_after>#include "h5test.h"
#include "parallel_io.h"
#include "comm.h"
#include "cmdLineOptions.h"
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include "measure.h"
#include "t3pio.h"

struct Var_t
{
  const char * name;
  const char * descript;
};

Var_t varT[] =
  {
    {"T", "Temp in K"},
    {"p", "Pressure in N/m^2"},
    {"u", "X Velocity in m/s"},
    {"v", "Y Velocity in m/s"},
    {"w", "Z Velocity in m/s"},
    {"a", "A Velocity in m/s"},
    {"b", "B Velocity in m/s"},
    {"c", "C Velocity in m/s"},
    {"d", "D Velocity in m/s"},
    {"e", "E Velocity in m/s"},
  };

ParallelIO::ParallelIO()
  : m_t(0.0), m_rate(0.0), m_totalSz(1.0), m_nStripes(1),
    m_nIOUnits(1), m_stripeSz(-1), m_numvar(1), m_aggregators(0),
    m_dne_stripes(-1), m_auto_max_stripes(-1), m_nStripesT3(-1)
{}

#ifndef USE_HDF5
void ParallelIO::h5writer(CmdLineOptions& cmd)
{
  if (P.myProc == 0)
    printf("This program requires HDF5 which is not available => quitting\n");
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
}

#else
void ParallelIO::h5writer(CmdLineOptions& cmd)
{

  hid_t   file_id;       //file      identifier
  hid_t   group_id;      //group     identifier
  hid_t   dset_id;       //Dataset   identifier
  hid_t   filespace;     //Dataspace id in file
  hid_t   memspace;      //Dataspace id in memory.
  hid_t   plist_id;      //Property List id
  hsize_t sz[1], gsz[1], starts[1], count[1], block[1], h5stride[1], rem;
  hsize_t is, num;
  int     ierr;
  MPI_Comm commF;
  H5FD_mpio_xfer_t  xfer_mode;   // HDF5 transfer mode (indep or collective)
  const char * fn = "UNSTRUCT.h5";

  // compute size info

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  double lSz     = 1.0;

  m_numvar    = cmd.nvar;
  num         = cmd.localSz;
  lSz         = num;
  count[0]    = 1;
  h5stride[0] = 1;
  starts[0]   = is;
  sz[0]       = num;
  gsz[0]      = cmd.globalSz;
  m_totalSz   = cmd.globalSz*m_numvar*sizeof(double);

  int iTotalSz = m_totalSz/(1024*1024);

  // Initialize data buffer
  double xk = num*P.myProc;

  double *data = new double[num];
  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;

  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
      m_nIOUnits         = results.numIO;
      m_dne_stripes      = results.S_dne_stripes;
      m_auto_max_stripes = results.S_auto_max_stripes;
      m_nStripesT3       = results.nStripesT3;
    }

  xfer_mode = (cmd.collective) ? H5FD_MPIO_COLLECTIVE : H5FD_MPIO_INDEPENDENT;

  t0 = walltime();

  plist_id = H5Pcreate(H5P_FILE_ACCESS);
  H5Pset_fapl_mpio(plist_id, P.comm, info);

  // Create file collectively
  file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id);

  MPI_File* pFH = NULL;
  ierr    = H5Fget_vfd_handle(file_id, H5P_DEFAULT, (void **) &pFH);
  ierr    = MPI_File_get_info(*pFH, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_aggregators = results.numIO;
  m_nStripes    = results.numStripes;
  m_stripeSz    = results.stripeSize;
  H5Pclose(plist_id);

  // Create Group
  group_id = H5Gcreate(file_id, "Solution", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

  std::string timeZ, timeL;
  dateZ(timeZ);
  add_attribute(group_id,"Zulu Time", timeZ.c_str());

  dateL(timeL);
  add_attribute(group_id,"Local Time", timeL.c_str());

  for (int ivar = 0; ivar < m_numvar; ++ivar)
    {

      // Create the dataspace for the dataset
      filespace = H5Screate_simple(1, &gsz[0], NULL);
      memspace  = H5Screate_simple(1, sz,      NULL);

      if (cmd.h5chunk)
        {
          plist_id = H5Pcreate(H5P_DATASET_CREATE);
          H5Pset_chunk(plist_id,1, sz);

          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, plist_id, H5P_DEFAULT);
          H5Pclose(plist_id);
          H5Sclose(filespace);

          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, h5stride, count, sz);
        }
      else if (cmd.h5slab)
        {
          // Create the dataset w/ default properties and close filespace
          dset_id = H5Dcreate(group_id, varT[ivar].name, H5T_NATIVE_DOUBLE, filespace,
                              H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
          H5Sclose(filespace);

          // Select hyperslab in the file.
          filespace = H5Dget_space(dset_id);
          H5Sselect_hyperslab(filespace, H5S_SELECT_SET, starts, NULL, sz , NULL);
        }

      plist_id = H5Pcreate(H5P_DATASET_XFER);
      H5Pset_dxpl_mpio(plist_id, xfer_mode);

      add_attribute(dset_id, "Variable Description", varT[ivar].descript);

      t1   = walltime();

      herr_t status = H5Dwrite(dset_id, H5T_NATIVE_DOUBLE, memspace, filespace,
                               plist_id, data);
      t2   = walltime();
      m_t += (t2 - t1);

      H5Dclose(dset_id);
      H5Sclose(filespace);
      H5Sclose(memspace);
      H5Pclose(plist_id);
    }

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz /(m_totalTime * 1024.0 * 1024.0);
  free(data);
  H5Gclose(group_id);
  H5Fclose(file_id);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

void ParallelIO::add_attribute(hid_t id, const char* descript, const char* value)
{
  hid_t attr_id, aspace_id, atype_id;
  hsize_t attrlen, num[1];

  attrlen = strlen(value);
  num[0]  = 1;

  atype_id = H5Tcopy(H5T_C_S1);
  H5Tset_size(atype_id, attrlen);

  aspace_id = H5Screate_simple(1,num, NULL);

  attr_id   = H5Acreate(id, descript, atype_id, aspace_id, H5P_DEFAULT, H5P_DEFAULT);
  H5Awrite(attr_id, atype_id, value);
  H5Aclose(attr_id);
  H5Sclose(aspace_id);
}
#endif

void ParallelIO::MPIIOwriter(CmdLineOptions& cmd)
{

  MPI_File     fh;
  MPI_Offset   is, rem, offset;
  MPI_Datatype coreData, gblData, my_vector;
  MPI_Status   status;
  int          iTotalSz, ierr, nDim;
  int          sz[2], gsz[2], starts[2];
  const char*  fn = "UNSTRUCT.mpiio";

  rem = cmd.globalSz % P.nProcs;
  if (P.myProc < rem)
    is = P.myProc * cmd.localSz;
  else
    is = (cmd.localSz + 1)*rem + cmd.localSz*(P.myProc - rem);

  m_numvar      = 1;
  m_totalSz     = cmd.globalSz*m_numvar*sizeof(double);
  iTotalSz      = m_totalSz/(1024*1024);
  int    num    = cmd.localSz;
  double *data  = new double[num];
  double xk     = is;

  for (int i = 0; i < num; ++i)
    data[i] = xk++;

  double t0, t1, t2;

  // Delete old file
  if (P.myProc == 0)
    MPI_File_delete((char * )fn, MPI_INFO_NULL);
  MPI_Barrier(P.comm);

  // Build MPI info;
  MPI_Info info  = MPI_INFO_NULL;
  MPI_Info infoF = MPI_INFO_NULL;
  MPI_Info_create(&info);
  MPI_Info_create(&infoF);

  T3PIO_results_t results;

  if (cmd.useT3PIO)
    {
      int ierr = t3pio_set_info(P.comm, info, "./",
                                T3PIO_GLOBAL_SIZE,         iTotalSz,
                                T3PIO_STRIPE_COUNT,        cmd.stripes,
                                T3PIO_STRIPE_SIZE_MB,      cmd.stripeSz,
                                T3PIO_MAX_AGGREGATORS,     cmd.maxWriters,
                                T3PIO_RESULTS,             &results);
      m_nIOUnits = results.numIO;
    }

  //nDim = 1;
  //offset = is*sizeof(double);
  //ierr = MPI_Type_contiguous(num, MPI_DOUBLE, &my_vector);
  //ierr = MPI_Type_commit(&my_vector);
  //ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, my_vector, "native", info);

  offset    = 0;
  nDim      = 2;
  sz[0]     = cmd.localSz/cmd.xwidth;
  sz[1]     = cmd.xwidth;
  gsz[0]    = cmd.globalSz/cmd.xwidth;
  gsz[1]    = cmd.xwidth;
  starts[0] = 0;
  starts[1] = 0;

  ierr = MPI_Type_create_subarray(nDim, sz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &coreData);
  ierr = MPI_Type_commit(&coreData);
  starts[0] = sz[0]*P.myProc;
  ierr = MPI_Type_create_subarray(nDim, gsz, sz, starts, MPI_ORDER_C, MPI_DOUBLE,
                                  &gblData);
  ierr = MPI_Type_commit(&gblData);

  t0 = walltime();

  ierr = MPI_File_open(P.comm, (char *) fn, MPI_MODE_WRONLY | MPI_MODE_CREATE, info, &fh);
  if (ierr)
    MPI_Abort(P.comm, -1);

  ierr = MPI_File_get_info(fh, &infoF);

  t3pio_extract_key_values(infoF, &results);
  m_aggregators = results.numIO;
  m_nStripes    = results.numStripes;
  m_stripeSz    = results.stripeSize;

  ierr = MPI_File_set_view(fh, offset, MPI_DOUBLE, gblData, "native", info);

  ierr = MPI_File_write_all(fh, &data[0], 1, coreData, &status);
  ierr = MPI_File_close(&fh);

  m_totalTime = walltime() - t0;
  m_rate      = m_totalSz/(m_totalTime * 1024.0 * 1024.0);
  MPI_Info_free(&info);
  MPI_Info_free(&infoF);
}

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/status/language_menu_button.h"

#include <string>

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// The language menu consists of 3 parts (in this order):
//
//   (1) XKB layout names and IME languages names. The size of the list is
//       always >= 1.
//   (2) IME properties. This list might be empty.
//   (3) "Configure IME..." button.
//
// Example of the menu (Japanese):
//
// ============================== (border of the popup window)
// [ ] US                         (|index| in the following functions is 0)
// [*] Anthy
// [ ] PinYin
// ------------------------------ (separator)
// [*] Hiragana                   (index = 5, The property has 2 radio groups)
// [ ] Katakana
// [ ] HalfWidthKatakana
// [*] Roman
// [ ] Kana
// ------------------------------ (separator)
// Configure IME...               (index = 11)
// ============================== (border of the popup window)
//
// Example of the menu (Simplified Chinese):
//
// ============================== (border of the popup window)
// [ ] US
// [ ] Anthy
// [*] PinYin
// ------------------------------ (separator)
// Switch to full letter mode     (The property has 2 command buttons)
// Switch to half punctuation mode
// ------------------------------ (separator)
// Configure IME...
// ============================== (border of the popup window)
//

namespace {

// Constants to specify the type of items in |model_|.
enum {
  COMMAND_ID_LANGUAGES = 0,  // US, Anthy, PinYin, ...
  COMMAND_ID_IME_PROPERTIES,  // Hiragana, Katakana, ...
  COMMAND_ID_CONFIGURE_IME,  // The "Configure IME..." button.
};

// A group ID for IME properties starts from 0. We use the huge value for the
// XKB/IME language list to avoid conflict.
const int kRadioGroupLanguage = 1 << 16;
const int kRadioGroupNone = -1;
const size_t kMaxLanguageNameLen = 7;
const wchar_t kSpacer[] = L"MMMMMMM";

// Returns the language name for the given |language|. Instead of input
// method names like "Pinyin" and "Anthy", we'll show language names like
// "Chinese (Simplified)" and "Japanese".
std::string GetLanguageName(const chromeos::InputLanguage& language) {
  std::string language_code = language.language_code;
  if (language.id == "pinyin") {
    // The pinyin input method returns "zh_CN" as language_code, but
    // l10n_util expects "zh-CN".
    language_code = "zh-CN";
  } else if (language.id == "chewing") {
    // Likewise, the chewing input method returns "zh" as language_code,
    // which is ambiguous. We use zh-TW instead.
    language_code = "zh-TW";
  } else if (language_code == "t") {
    // "t" is used by input methods that do not associate with a
    // particular language. Returns the display name as-is.
    return language.display_name;
  }
  const string16 language_name = l10n_util::GetDisplayNameForLocale(
      language_code,
      g_browser_process->GetApplicationLocale(),
      true);
  // TODO(satorux): We should add input method names if multiple input
  // methods are available for one input language.
  return UTF16ToUTF8(language_name);
}

// Converts chromeos::InputLanguage object into human readable string. Returns
// a string for the drop-down menu if |for_menu| is true. Otherwise, returns a
// string for the status area.
std::string FormatInputLanguage(
    const chromeos::InputLanguage& language, bool for_menu) {
  std::string formatted = GetLanguageName(language);
  if (formatted.empty()) {
    formatted = language.id;
  }
  if (for_menu) {
    switch (language.category) {
      case chromeos::LANGUAGE_CATEGORY_XKB:
        // TODO(yusukes): Use message catalog.
        formatted += " (Layout)";
        break;
      case chromeos::LANGUAGE_CATEGORY_IME:
        // TODO(yusukes): Use message catalog.
        formatted += " (IME)";
        break;
    }
  } else {
    // For status area. Trim the string.
    formatted = formatted.substr(0, kMaxLanguageNameLen);
    // TODO(yusukes): Simple substr() does not work for non-ASCII string.
    // TODO(yusukes): How can we ensure that the trimmed string does not
    // overflow the area?
  }
  return formatted;
}

}  // namespace

namespace chromeos {

////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton

LanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)
    : MenuButton(NULL, std::wstring(), this, false),
      language_list_(LanguageLibrary::Get()->GetActiveLanguages()),
      model_(NULL),
      // Be aware that the constructor of |language_menu_| calls GetItemCount()
      // in this class. Therefore, GetItemCount() have to return 0 when
      // |model_| is NULL.
      ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),
      host_(host) {
  DCHECK(language_list_.get() && !language_list_->empty());
  // Update the model
  RebuildModel();
  // Grab the real estate.
  UpdateIcon(kSpacer);
  // Display the default XKB name (usually "US").
  const std::string name = FormatInputLanguage(language_list_->at(0), false);
  UpdateIcon(UTF8ToWide(name));
  LanguageLibrary::Get()->AddObserver(this);
}

LanguageMenuButton::~LanguageMenuButton() {
  LanguageLibrary::Get()->RemoveObserver(this);
}

////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, menus::MenuModel implementation:

int LanguageMenuButton::GetCommandIdAt(int index) const {
  return 0;  // dummy
}

bool LanguageMenuButton::IsLabelDynamicAt(int index) const {
  // Menu content for the language button could change time by time.
  return true;
}

bool LanguageMenuButton::GetAcceleratorAt(
    int index, menus::Accelerator* accelerator) const {
  // Views for Chromium OS does not support accelerators yet.
  return false;
}

bool LanguageMenuButton::IsItemCheckedAt(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(language_list_.get());

  if (IndexIsInLanguageList(index)) {
    const InputLanguage& language = language_list_->at(index);
    return language == LanguageLibrary::Get()->current_language();
  }

  if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    return property_list.at(index).is_selection_item_checked;
  }

  // Separator(s) or the "Configure IME" button.
  return false;
}

int LanguageMenuButton::GetGroupIdAt(int index) const {
  DCHECK_GE(index, 0);

  if (IndexIsInLanguageList(index)) {
    return kRadioGroupLanguage;
  }

  if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    return property_list.at(index).selection_item_id;
  }

  return kRadioGroupNone;
}

bool LanguageMenuButton::HasIcons() const  {
  // We don't support IME nor keyboard icons on Chrome OS.
  return false;
}

bool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {
  return false;
}

bool LanguageMenuButton::IsEnabledAt(int index) const {
  // Just return true so all IMEs, XKB layouts, and IME properties could be
  // clicked.
  return true;
}

menus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {
  // We don't use nested menus.
  return NULL;
}

void LanguageMenuButton::HighlightChangedTo(int index) {
  // Views for Chromium OS does not support this interface yet.
}

void LanguageMenuButton::MenuWillShow() {
  // Views for Chromium OS does not support this interface yet.
}

int LanguageMenuButton::GetItemCount() const {
  if (!model_.get()) {
    // Model is not constructed yet. This means that LanguageMenuButton is
    // being constructed. Return zero.
    return 0;
  }
  return model_->GetItemCount();
}

menus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {
  DCHECK_GE(index, 0);

  if (IndexPointsToConfigureImeMenuItem(index)) {
    return menus::MenuModel::TYPE_COMMAND;  // "Configure IME"
  }

  if (IndexIsInLanguageList(index)) {
    return menus::MenuModel::TYPE_RADIO;
  }

  if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    if (property_list.at(index).is_selection_item) {
      return menus::MenuModel::TYPE_RADIO;
    }
    return menus::MenuModel::TYPE_COMMAND;
  }

  return menus::MenuModel::TYPE_SEPARATOR;
}

string16 LanguageMenuButton::GetLabelAt(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(language_list_.get());

  if (IndexPointsToConfigureImeMenuItem(index)) {
    return l10n_util::GetStringUTF16(IDS_STATUSBAR_IME_CONFIGURE);
  }

  std::string name;
  if (IndexIsInLanguageList(index)) {
    name = FormatInputLanguage(language_list_->at(index), true);
  } else if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    name = property_list.at(index).label;
  }

  return UTF8ToUTF16(name);
}

void LanguageMenuButton::ActivatedAt(int index) {
  DCHECK_GE(index, 0);
  DCHECK(language_list_.get());

  if (IndexPointsToConfigureImeMenuItem(index)) {
    host_->OpenButtonOptions(this);
    return;
  }

  if (IndexIsInLanguageList(index)) {
    // Inter-IME switching or IME-XKB switching.
    const InputLanguage& language = language_list_->at(index);
    LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);
    return;
  }

  if (GetPropertyIndex(index, &index)) {
    // Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    const std::string key = property_list.at(index).key;
    if (property_list.at(index).is_selection_item) {
      // Radio button is clicked.
      const int id = property_list.at(index).selection_item_id;
      // First, deactivate all other properties in the same radio group.
      for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {
        if (i != index && id == property_list.at(i).selection_item_id) {
          LanguageLibrary::Get()->DeactivateImeProperty(
              property_list.at(i).key);
        }
      }
      // Then, activate the property clicked.
      LanguageLibrary::Get()->ActivateImeProperty(key);
    } else {
      // Command button like "Switch to half punctuation mode" is clicked.
      // We can always use "Deactivate" for command buttons.
      LanguageLibrary::Get()->DeactivateImeProperty(key);
    }
    return;
  }

  // Separators are not clickable.
  NOTREACHED();
}

////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, views::ViewMenuDelegate implementation:

void LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
  language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());
  RebuildModel();
  language_menu_.Rebuild();
  language_menu_.UpdateStates();
  language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}

////////////////////////////////////////////////////////////////////////////////
// LanguageLibrary::Observer implementation:

void LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {
  const std::string name = FormatInputLanguage(obj->current_language(), false);
  UpdateIcon(UTF8ToWide(name));

  // This is necessary to remove IME properties when the current language is
  // switched to XKB.
  RebuildModel();
}

void LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {
  RebuildModel();
}

void LanguageMenuButton::UpdateIcon(const std::wstring& name) {
  set_border(NULL);
  SetFont(ResourceBundle::GetSharedInstance().GetFont(
      ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
  SetEnabledColor(SK_ColorWHITE);
  SetShowHighlighted(false);
  SetText(name);
  set_alignment(TextButton::ALIGN_RIGHT);
  SchedulePaint();
}

void LanguageMenuButton::RebuildModel() {
  model_.reset(new menus::SimpleMenuModel(NULL));
  string16 dummy_label = UTF8ToUTF16("");
  // Indicates if separator's needed before each section.
  bool need_separator = false;

  if (!language_list_->empty()) {
    // We "abuse" the command_id and group_id arguments of AddRadioItem method.
    // A COMMAND_ID_XXX enum value is passed as command_id, and array index of
    // |language_list_| or |property_list| is passed as group_id.
    for (size_t i = 0; i < language_list_->size(); ++i) {
      model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);
    }
    need_separator = true;
  }

  const ImePropertyList& property_list
      = LanguageLibrary::Get()->current_ime_properties();
  const InputLanguage& current_language
      = LanguageLibrary::Get()->current_language();
  if ((!property_list.empty()) &&
      (current_language.category == chromeos::LANGUAGE_CATEGORY_IME)) {
    if (need_separator)
      model_->AddSeparator();
    for (size_t i = 0; i < property_list.size(); ++i) {
      model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);
    }
    need_separator = true;
  }

  if (host_->ShouldOpenButtonOptions(this)) {
    // Note: We use AddSeparator() for separators, and AddRadioItem() for all
    // other items even if an item is not actually a radio item.
    if (need_separator)
      model_->AddSeparator();
    model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 /* dummy */);
  }
}

bool LanguageMenuButton::IndexIsInLanguageList(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(model_.get());

  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
          (model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));
}

bool LanguageMenuButton::GetPropertyIndex(
    int index, int* property_index) const {
  DCHECK_GE(index, 0);
  DCHECK(property_index);
  DCHECK(model_.get());

  if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
      (model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {
    *property_index = model_->GetGroupIdAt(index);
    return true;
  }
  return false;
}

bool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(model_.get());

  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
          (model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));
}

// TODO(yusukes): Register and handle hotkeys for IME and XKB switching?

}  // namespace chromeos
<commit_msg>Remove "(IME)" and "(Layout)" strings from the language status menu. I think we no longer need these debug print strings.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/status/language_menu_button.h"

#include <string>

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/status/status_area_host.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// The language menu consists of 3 parts (in this order):
//
//   (1) XKB layout names and IME languages names. The size of the list is
//       always >= 1.
//   (2) IME properties. This list might be empty.
//   (3) "Configure IME..." button.
//
// Example of the menu (Japanese):
//
// ============================== (border of the popup window)
// [ ] US                         (|index| in the following functions is 0)
// [*] Anthy
// [ ] PinYin
// ------------------------------ (separator)
// [*] Hiragana                   (index = 5, The property has 2 radio groups)
// [ ] Katakana
// [ ] HalfWidthKatakana
// [*] Roman
// [ ] Kana
// ------------------------------ (separator)
// Configure IME...               (index = 11)
// ============================== (border of the popup window)
//
// Example of the menu (Simplified Chinese):
//
// ============================== (border of the popup window)
// [ ] US
// [ ] Anthy
// [*] PinYin
// ------------------------------ (separator)
// Switch to full letter mode     (The property has 2 command buttons)
// Switch to half punctuation mode
// ------------------------------ (separator)
// Configure IME...
// ============================== (border of the popup window)
//

namespace {

// Constants to specify the type of items in |model_|.
enum {
  COMMAND_ID_LANGUAGES = 0,  // US, Anthy, PinYin, ...
  COMMAND_ID_IME_PROPERTIES,  // Hiragana, Katakana, ...
  COMMAND_ID_CONFIGURE_IME,  // The "Configure IME..." button.
};

// A group ID for IME properties starts from 0. We use the huge value for the
// XKB/IME language list to avoid conflict.
const int kRadioGroupLanguage = 1 << 16;
const int kRadioGroupNone = -1;
const size_t kMaxLanguageNameLen = 7;
const wchar_t kSpacer[] = L"MMMMMMM";

// Returns the language name for the given |language|. Instead of input
// method names like "Pinyin" and "Anthy", we'll show language names like
// "Chinese (Simplified)" and "Japanese".
std::string GetLanguageName(const chromeos::InputLanguage& language) {
  std::string language_code = language.language_code;
  if (language.id == "pinyin") {
    // The pinyin input method returns "zh_CN" as language_code, but
    // l10n_util expects "zh-CN".
    language_code = "zh-CN";
  } else if (language.id == "chewing") {
    // Likewise, the chewing input method returns "zh" as language_code,
    // which is ambiguous. We use zh-TW instead.
    language_code = "zh-TW";
  } else if (language_code == "t") {
    // "t" is used by input methods that do not associate with a
    // particular language. Returns the display name as-is.
    return language.display_name;
  }
  const string16 language_name = l10n_util::GetDisplayNameForLocale(
      language_code,
      g_browser_process->GetApplicationLocale(),
      true);
  // TODO(satorux): We should add input method names if multiple input
  // methods are available for one input language.
  return UTF16ToUTF8(language_name);
}

// Converts chromeos::InputLanguage object into human readable string. Returns
// a string for the drop-down menu if |for_menu| is true. Otherwise, returns a
// string for the status area.
std::string FormatInputLanguage(
    const chromeos::InputLanguage& language, bool for_menu) {
  std::string formatted = GetLanguageName(language);
  if (formatted.empty()) {
    formatted = language.id;
  }
  if (!for_menu) {
    // For status area. Trim the string.
    formatted = formatted.substr(0, kMaxLanguageNameLen);
    // TODO(yusukes): Simple substr() does not work for non-ASCII string.
    // TODO(yusukes): How can we ensure that the trimmed string does not
    // overflow the area?
  }
  return formatted;
}

}  // namespace

namespace chromeos {

////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton

LanguageMenuButton::LanguageMenuButton(StatusAreaHost* host)
    : MenuButton(NULL, std::wstring(), this, false),
      language_list_(LanguageLibrary::Get()->GetActiveLanguages()),
      model_(NULL),
      // Be aware that the constructor of |language_menu_| calls GetItemCount()
      // in this class. Therefore, GetItemCount() have to return 0 when
      // |model_| is NULL.
      ALLOW_THIS_IN_INITIALIZER_LIST(language_menu_(this)),
      host_(host) {
  DCHECK(language_list_.get() && !language_list_->empty());
  // Update the model
  RebuildModel();
  // Grab the real estate.
  UpdateIcon(kSpacer);
  // Display the default XKB name (usually "US").
  const std::string name = FormatInputLanguage(language_list_->at(0), false);
  UpdateIcon(UTF8ToWide(name));
  LanguageLibrary::Get()->AddObserver(this);
}

LanguageMenuButton::~LanguageMenuButton() {
  LanguageLibrary::Get()->RemoveObserver(this);
}

////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, menus::MenuModel implementation:

int LanguageMenuButton::GetCommandIdAt(int index) const {
  return 0;  // dummy
}

bool LanguageMenuButton::IsLabelDynamicAt(int index) const {
  // Menu content for the language button could change time by time.
  return true;
}

bool LanguageMenuButton::GetAcceleratorAt(
    int index, menus::Accelerator* accelerator) const {
  // Views for Chromium OS does not support accelerators yet.
  return false;
}

bool LanguageMenuButton::IsItemCheckedAt(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(language_list_.get());

  if (IndexIsInLanguageList(index)) {
    const InputLanguage& language = language_list_->at(index);
    return language == LanguageLibrary::Get()->current_language();
  }

  if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    return property_list.at(index).is_selection_item_checked;
  }

  // Separator(s) or the "Configure IME" button.
  return false;
}

int LanguageMenuButton::GetGroupIdAt(int index) const {
  DCHECK_GE(index, 0);

  if (IndexIsInLanguageList(index)) {
    return kRadioGroupLanguage;
  }

  if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    return property_list.at(index).selection_item_id;
  }

  return kRadioGroupNone;
}

bool LanguageMenuButton::HasIcons() const  {
  // We don't support IME nor keyboard icons on Chrome OS.
  return false;
}

bool LanguageMenuButton::GetIconAt(int index, SkBitmap* icon) const {
  return false;
}

bool LanguageMenuButton::IsEnabledAt(int index) const {
  // Just return true so all IMEs, XKB layouts, and IME properties could be
  // clicked.
  return true;
}

menus::MenuModel* LanguageMenuButton::GetSubmenuModelAt(int index) const {
  // We don't use nested menus.
  return NULL;
}

void LanguageMenuButton::HighlightChangedTo(int index) {
  // Views for Chromium OS does not support this interface yet.
}

void LanguageMenuButton::MenuWillShow() {
  // Views for Chromium OS does not support this interface yet.
}

int LanguageMenuButton::GetItemCount() const {
  if (!model_.get()) {
    // Model is not constructed yet. This means that LanguageMenuButton is
    // being constructed. Return zero.
    return 0;
  }
  return model_->GetItemCount();
}

menus::MenuModel::ItemType LanguageMenuButton::GetTypeAt(int index) const {
  DCHECK_GE(index, 0);

  if (IndexPointsToConfigureImeMenuItem(index)) {
    return menus::MenuModel::TYPE_COMMAND;  // "Configure IME"
  }

  if (IndexIsInLanguageList(index)) {
    return menus::MenuModel::TYPE_RADIO;
  }

  if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    if (property_list.at(index).is_selection_item) {
      return menus::MenuModel::TYPE_RADIO;
    }
    return menus::MenuModel::TYPE_COMMAND;
  }

  return menus::MenuModel::TYPE_SEPARATOR;
}

string16 LanguageMenuButton::GetLabelAt(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(language_list_.get());

  if (IndexPointsToConfigureImeMenuItem(index)) {
    return l10n_util::GetStringUTF16(IDS_STATUSBAR_IME_CONFIGURE);
  }

  std::string name;
  if (IndexIsInLanguageList(index)) {
    name = FormatInputLanguage(language_list_->at(index), true);
  } else if (GetPropertyIndex(index, &index)) {
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    name = property_list.at(index).label;
  }

  return UTF8ToUTF16(name);
}

void LanguageMenuButton::ActivatedAt(int index) {
  DCHECK_GE(index, 0);
  DCHECK(language_list_.get());

  if (IndexPointsToConfigureImeMenuItem(index)) {
    host_->OpenButtonOptions(this);
    return;
  }

  if (IndexIsInLanguageList(index)) {
    // Inter-IME switching or IME-XKB switching.
    const InputLanguage& language = language_list_->at(index);
    LanguageLibrary::Get()->ChangeLanguage(language.category, language.id);
    return;
  }

  if (GetPropertyIndex(index, &index)) {
    // Intra-IME switching (e.g. Japanese-Hiragana to Japanese-Katakana).
    const ImePropertyList& property_list
        = LanguageLibrary::Get()->current_ime_properties();
    const std::string key = property_list.at(index).key;
    if (property_list.at(index).is_selection_item) {
      // Radio button is clicked.
      const int id = property_list.at(index).selection_item_id;
      // First, deactivate all other properties in the same radio group.
      for (int i = 0; i < static_cast<int>(property_list.size()); ++i) {
        if (i != index && id == property_list.at(i).selection_item_id) {
          LanguageLibrary::Get()->DeactivateImeProperty(
              property_list.at(i).key);
        }
      }
      // Then, activate the property clicked.
      LanguageLibrary::Get()->ActivateImeProperty(key);
    } else {
      // Command button like "Switch to half punctuation mode" is clicked.
      // We can always use "Deactivate" for command buttons.
      LanguageLibrary::Get()->DeactivateImeProperty(key);
    }
    return;
  }

  // Separators are not clickable.
  NOTREACHED();
}

////////////////////////////////////////////////////////////////////////////////
// LanguageMenuButton, views::ViewMenuDelegate implementation:

void LanguageMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {
  language_list_.reset(LanguageLibrary::Get()->GetActiveLanguages());
  RebuildModel();
  language_menu_.Rebuild();
  language_menu_.UpdateStates();
  language_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}

////////////////////////////////////////////////////////////////////////////////
// LanguageLibrary::Observer implementation:

void LanguageMenuButton::LanguageChanged(LanguageLibrary* obj) {
  const std::string name = FormatInputLanguage(obj->current_language(), false);
  UpdateIcon(UTF8ToWide(name));

  // This is necessary to remove IME properties when the current language is
  // switched to XKB.
  RebuildModel();
}

void LanguageMenuButton::ImePropertiesChanged(LanguageLibrary* obj) {
  RebuildModel();
}

void LanguageMenuButton::UpdateIcon(const std::wstring& name) {
  set_border(NULL);
  SetFont(ResourceBundle::GetSharedInstance().GetFont(
      ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
  SetEnabledColor(SK_ColorWHITE);
  SetShowHighlighted(false);
  SetText(name);
  set_alignment(TextButton::ALIGN_RIGHT);
  SchedulePaint();
}

void LanguageMenuButton::RebuildModel() {
  model_.reset(new menus::SimpleMenuModel(NULL));
  string16 dummy_label = UTF8ToUTF16("");
  // Indicates if separator's needed before each section.
  bool need_separator = false;

  if (!language_list_->empty()) {
    // We "abuse" the command_id and group_id arguments of AddRadioItem method.
    // A COMMAND_ID_XXX enum value is passed as command_id, and array index of
    // |language_list_| or |property_list| is passed as group_id.
    for (size_t i = 0; i < language_list_->size(); ++i) {
      model_->AddRadioItem(COMMAND_ID_LANGUAGES, dummy_label, i);
    }
    need_separator = true;
  }

  const ImePropertyList& property_list
      = LanguageLibrary::Get()->current_ime_properties();
  const InputLanguage& current_language
      = LanguageLibrary::Get()->current_language();
  if ((!property_list.empty()) &&
      (current_language.category == chromeos::LANGUAGE_CATEGORY_IME)) {
    if (need_separator)
      model_->AddSeparator();
    for (size_t i = 0; i < property_list.size(); ++i) {
      model_->AddRadioItem(COMMAND_ID_IME_PROPERTIES, dummy_label, i);
    }
    need_separator = true;
  }

  if (host_->ShouldOpenButtonOptions(this)) {
    // Note: We use AddSeparator() for separators, and AddRadioItem() for all
    // other items even if an item is not actually a radio item.
    if (need_separator)
      model_->AddSeparator();
    model_->AddRadioItem(COMMAND_ID_CONFIGURE_IME, dummy_label, 0 /* dummy */);
  }
}

bool LanguageMenuButton::IndexIsInLanguageList(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(model_.get());

  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
          (model_->GetCommandIdAt(index) == COMMAND_ID_LANGUAGES));
}

bool LanguageMenuButton::GetPropertyIndex(
    int index, int* property_index) const {
  DCHECK_GE(index, 0);
  DCHECK(property_index);
  DCHECK(model_.get());

  if ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
      (model_->GetCommandIdAt(index) == COMMAND_ID_IME_PROPERTIES)) {
    *property_index = model_->GetGroupIdAt(index);
    return true;
  }
  return false;
}

bool LanguageMenuButton::IndexPointsToConfigureImeMenuItem(int index) const {
  DCHECK_GE(index, 0);
  DCHECK(model_.get());

  return ((model_->GetTypeAt(index) == menus::MenuModel::TYPE_RADIO) &&
          (model_->GetCommandIdAt(index) == COMMAND_ID_CONFIGURE_IME));
}

// TODO(yusukes): Register and handle hotkeys for IME and XKB switching?

}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "base/stringprintf.h"
#include "chrome/browser/extensions/api/socket/socket_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/test/test_server.h"

using namespace extension_function_test_utils;

namespace {

const std::string kHostname = "127.0.0.1";
const int kPort = 8888;

class SocketApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
    command_line->AppendSwitch(switches::kEnablePlatformApps);
  }

  static std::string GenerateCreateFunctionArgs(const std::string& protocol,
                                                const std::string& address,
                                                int port) {
    return base::StringPrintf("[\"%s\", \"%s\", %d]", protocol.c_str(),
                              address.c_str(), port);
  }
};

}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketUDPCreateGood) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
      socket_create_function,
      GenerateCreateFunctionArgs("udp", kHostname, kPort),
      browser(), NONE));
  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());
  int socketId = -1;
  EXPECT_TRUE(value->GetInteger("socketId", &socketId));
  EXPECT_TRUE(socketId > 0);
}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketTCPCreateGood) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
      socket_create_function,
      GenerateCreateFunctionArgs("udp", kHostname, kPort),
      browser(), NONE));
  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());
  int socketId = -1;
  EXPECT_TRUE(value->GetInteger("socketId", &socketId));
  ASSERT_TRUE(socketId > 0);
}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  // TODO(miket): this test currently passes only because of artificial code
  // that doesn't run in production. Fix this when we're able to.
  RunFunctionAndReturnError(
      socket_create_function,
      GenerateCreateFunctionArgs("xxxx", kHostname, kPort),
      browser(), NONE);
}

// http://crbug.com/111572
IN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketUDPExtension) {
  scoped_ptr<net::TestServer> test_server(
      new net::TestServer(net::TestServer::TYPE_UDP_ECHO,
                          FilePath(FILE_PATH_LITERAL("net/data"))));
  EXPECT_TRUE(test_server->Start());

  net::HostPortPair host_port_pair = test_server->host_port_pair();
  int port = host_port_pair.port();
  ASSERT_TRUE(port > 0);

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());

  ExtensionTestMessageListener listener("info_please", true);

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("socket/api")));
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  listener.Reply(
      base::StringPrintf("udp:%s:%d", host_port_pair.host().c_str(), port));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/111572
IN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketTCPExtension) {
  scoped_ptr<net::TestServer> test_server(
      new net::TestServer(net::TestServer::TYPE_TCP_ECHO,
                          FilePath(FILE_PATH_LITERAL("net/data"))));
  EXPECT_TRUE(test_server->Start());

  net::HostPortPair host_port_pair = test_server->host_port_pair();
  int port = host_port_pair.port();
  ASSERT_TRUE(port > 0);

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());

  ExtensionTestMessageListener listener("info_please", true);

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("socket/api")));
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  listener.Reply(
      base::StringPrintf("tcp:%s:%d", host_port_pair.host().c_str(), port));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Disable SocketApiTest.SocketTCPExtension. Timing out on Win and Mac.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "base/stringprintf.h"
#include "chrome/browser/extensions/api/socket/socket_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "net/test/test_server.h"

using namespace extension_function_test_utils;

namespace {

const std::string kHostname = "127.0.0.1";
const int kPort = 8888;

class SocketApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
    command_line->AppendSwitch(switches::kEnablePlatformApps);
  }

  static std::string GenerateCreateFunctionArgs(const std::string& protocol,
                                                const std::string& address,
                                                int port) {
    return base::StringPrintf("[\"%s\", \"%s\", %d]", protocol.c_str(),
                              address.c_str(), port);
  }
};

}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketUDPCreateGood) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
      socket_create_function,
      GenerateCreateFunctionArgs("udp", kHostname, kPort),
      browser(), NONE));
  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());
  int socketId = -1;
  EXPECT_TRUE(value->GetInteger("socketId", &socketId));
  EXPECT_TRUE(socketId > 0);
}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketTCPCreateGood) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
      socket_create_function,
      GenerateCreateFunctionArgs("udp", kHostname, kPort),
      browser(), NONE));
  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());
  int socketId = -1;
  EXPECT_TRUE(value->GetInteger("socketId", &socketId));
  ASSERT_TRUE(socketId > 0);
}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  // TODO(miket): this test currently passes only because of artificial code
  // that doesn't run in production. Fix this when we're able to.
  RunFunctionAndReturnError(
      socket_create_function,
      GenerateCreateFunctionArgs("xxxx", kHostname, kPort),
      browser(), NONE);
}

// http://crbug.com/111572
IN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketUDPExtension) {
  scoped_ptr<net::TestServer> test_server(
      new net::TestServer(net::TestServer::TYPE_UDP_ECHO,
                          FilePath(FILE_PATH_LITERAL("net/data"))));
  EXPECT_TRUE(test_server->Start());

  net::HostPortPair host_port_pair = test_server->host_port_pair();
  int port = host_port_pair.port();
  ASSERT_TRUE(port > 0);

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());

  ExtensionTestMessageListener listener("info_please", true);

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("socket/api")));
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  listener.Reply(
      base::StringPrintf("udp:%s:%d", host_port_pair.host().c_str(), port));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/111572
IN_PROC_BROWSER_TEST_F(SocketApiTest, DISABLED_SocketTCPExtension) {
  scoped_ptr<net::TestServer> test_server(
      new net::TestServer(net::TestServer::TYPE_TCP_ECHO,
                          FilePath(FILE_PATH_LITERAL("net/data"))));
  EXPECT_TRUE(test_server->Start());

  net::HostPortPair host_port_pair = test_server->host_port_pair();
  int port = host_port_pair.port();
  ASSERT_TRUE(port > 0);

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());

  ExtensionTestMessageListener listener("info_please", true);

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("socket/api")));
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  listener.Reply(
      base::StringPrintf("tcp:%s:%d", host_port_pair.host().c_str(), port));

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS) || defined(OS_MACOSX)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<commit_msg>Marking ExtensionApiTest.Infobars as FAILS on MACOSX due to recent buildbot test failures. BUG=60990 TBR=vangelis@chromium.org TEST=bots Review URL: http://codereview.chromium.org/4152008<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
#define MAYBE_Infobars Infobars
#elif defined(OS_MACOSX)
// Temporarily marked as FAILS on OSX. See http://crbug.com/60990 for details.
#define MAYBE_Infobars FAILS_Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<|endoftext|>