<commit_before>// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>

// language.cc: Subclasses and singletons for google_breakpad::Language.
// See language.h for details.

#include "common/language.h"

#include <stdlib.h>

#if !defined(__ANDROID__)
#include <cxxabi.h>
#endif

#if defined(HAVE_RUST_DEMANGLE)
#include <rust_demangle.h>
#endif

#include <limits>

namespace {

string MakeQualifiedNameWithSeparator(const string& parent_name,
                                      const char* separator,
                                      const string& name) {
  if (parent_name.empty()) {
    return name;
  }

  return parent_name + separator + name;
}

}  // namespace

namespace google_breakpad {

// C++ language-specific operations.
class CPPLanguage: public Language {
 public:
  CPPLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, "::", name);
  }

  virtual DemangleResult DemangleName(const string& mangled,
                                      string* demangled) const {
#if defined(__ANDROID__)
    // Android NDK doesn't provide abi::__cxa_demangle.
    demangled->clear();
    return kDontDemangle;
#else
    int status;
    char* demangled_c =
        abi::__cxa_demangle(mangled.c_str(), NULL, NULL, &status);

    DemangleResult result;
    if (status == 0) {
      result = kDemangleSuccess;
      demangled->assign(demangled_c);
    } else {
      result = kDemangleFailure;
      demangled->clear();
    }

    if (demangled_c) {
      free(reinterpret_cast<void*>(demangled_c));
    }

    return result;
#endif
  }
};

CPPLanguage CPPLanguageSingleton;

// Java language-specific operations.
class JavaLanguage: public Language {
 public:
  JavaLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, ".", name);
  }
};

JavaLanguage JavaLanguageSingleton;

// Swift language-specific operations.
class SwiftLanguage: public Language {
 public:
  SwiftLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, ".", name);
  }

  virtual DemangleResult DemangleName(const string& mangled,
                                      string* demangled) const {
    // There is no programmatic interface to a Swift demangler. Pass through the
    // mangled form because it encodes more information than the qualified name
    // that would have been built by MakeQualifiedName(). The output can be
    // post-processed by xcrun swift-demangle to transform mangled Swift names
    // into something more readable.
    demangled->assign(mangled);
    return kDemangleSuccess;
  }
};

SwiftLanguage SwiftLanguageSingleton;

// Rust language-specific operations.
class RustLanguage: public Language {
 public:
  RustLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, ".", name);
  }

  virtual DemangleResult DemangleName(const string& mangled,
                                      std::string* demangled) const {
    // Rust names use GCC C++ name mangling, but demangling them with
    // abi_demangle doesn't produce stellar results due to them having
    // another layer of encoding.
    // If callers provide rustc-demangle, use that.
#if defined(HAVE_RUST_DEMANGLE)
    char* rust_demangled = rust_demangle(mangled.c_str());
    if (rust_demangled == nullptr) {
      return kDemangleFailure;
    }
    demangled->assign(rust_demangled);
    free_rust_demangled_name(rust_demangled);
#else
    // Otherwise, pass through the mangled name so callers can demangle
    // after the fact.
    demangled->assign(mangled);
#endif
    return kDemangleSuccess;
  }
};

RustLanguage RustLanguageSingleton;

// Assembler language-specific operations.
class AssemblerLanguage: public Language {
 public:
  AssemblerLanguage() {}

  bool HasFunctions() const { return false; }
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return name;
  }
};

AssemblerLanguage AssemblerLanguageSingleton;

const Language * const Language::CPlusPlus = &CPPLanguageSingleton;
const Language * const Language::Java = &JavaLanguageSingleton;
const Language * const Language::Swift = &SwiftLanguageSingleton;
const Language * const Language::Rust = &RustLanguageSingleton;
const Language * const Language::Assembler = &AssemblerLanguageSingleton;

} // namespace google_breakpad
<commit_msg>Use string instead of std::string<commit_after>// Copyright (c) 2010 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>

// language.cc: Subclasses and singletons for google_breakpad::Language.
// See language.h for details.

#include "common/language.h"

#include <stdlib.h>

#if !defined(__ANDROID__)
#include <cxxabi.h>
#endif

#if defined(HAVE_RUST_DEMANGLE)
#include <rust_demangle.h>
#endif

#include <limits>

namespace {

string MakeQualifiedNameWithSeparator(const string& parent_name,
                                      const char* separator,
                                      const string& name) {
  if (parent_name.empty()) {
    return name;
  }

  return parent_name + separator + name;
}

}  // namespace

namespace google_breakpad {

// C++ language-specific operations.
class CPPLanguage: public Language {
 public:
  CPPLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, "::", name);
  }

  virtual DemangleResult DemangleName(const string& mangled,
                                      string* demangled) const {
#if defined(__ANDROID__)
    // Android NDK doesn't provide abi::__cxa_demangle.
    demangled->clear();
    return kDontDemangle;
#else
    int status;
    char* demangled_c =
        abi::__cxa_demangle(mangled.c_str(), NULL, NULL, &status);

    DemangleResult result;
    if (status == 0) {
      result = kDemangleSuccess;
      demangled->assign(demangled_c);
    } else {
      result = kDemangleFailure;
      demangled->clear();
    }

    if (demangled_c) {
      free(reinterpret_cast<void*>(demangled_c));
    }

    return result;
#endif
  }
};

CPPLanguage CPPLanguageSingleton;

// Java language-specific operations.
class JavaLanguage: public Language {
 public:
  JavaLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, ".", name);
  }
};

JavaLanguage JavaLanguageSingleton;

// Swift language-specific operations.
class SwiftLanguage: public Language {
 public:
  SwiftLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, ".", name);
  }

  virtual DemangleResult DemangleName(const string& mangled,
                                      string* demangled) const {
    // There is no programmatic interface to a Swift demangler. Pass through the
    // mangled form because it encodes more information than the qualified name
    // that would have been built by MakeQualifiedName(). The output can be
    // post-processed by xcrun swift-demangle to transform mangled Swift names
    // into something more readable.
    demangled->assign(mangled);
    return kDemangleSuccess;
  }
};

SwiftLanguage SwiftLanguageSingleton;

// Rust language-specific operations.
class RustLanguage: public Language {
 public:
  RustLanguage() {}

  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return MakeQualifiedNameWithSeparator(parent_name, ".", name);
  }

  virtual DemangleResult DemangleName(const string& mangled,
                                      string* demangled) const {
    // Rust names use GCC C++ name mangling, but demangling them with
    // abi_demangle doesn't produce stellar results due to them having
    // another layer of encoding.
    // If callers provide rustc-demangle, use that.
#if defined(HAVE_RUST_DEMANGLE)
    char* rust_demangled = rust_demangle(mangled.c_str());
    if (rust_demangled == nullptr) {
      return kDemangleFailure;
    }
    demangled->assign(rust_demangled);
    free_rust_demangled_name(rust_demangled);
#else
    // Otherwise, pass through the mangled name so callers can demangle
    // after the fact.
    demangled->assign(mangled);
#endif
    return kDemangleSuccess;
  }
};

RustLanguage RustLanguageSingleton;

// Assembler language-specific operations.
class AssemblerLanguage: public Language {
 public:
  AssemblerLanguage() {}

  bool HasFunctions() const { return false; }
  string MakeQualifiedName(const string &parent_name,
                           const string &name) const {
    return name;
  }
};

AssemblerLanguage AssemblerLanguageSingleton;

const Language * const Language::CPlusPlus = &CPPLanguageSingleton;
const Language * const Language::Java = &JavaLanguageSingleton;
const Language * const Language::Swift = &SwiftLanguageSingleton;
const Language * const Language::Rust = &RustLanguageSingleton;
const Language * const Language::Assembler = &AssemblerLanguageSingleton;

} // namespace google_breakpad
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestHigherOrderCell.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkGenericCell.h"
#include "vtkPoints.h"

static const unsigned int depth = 5;
static unsigned char HigherOrderCell[][depth] = {
    { VTK_LINE, VTK_QUADRATIC_EDGE, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_TRIANGLE, VTK_QUADRATIC_TRIANGLE, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_QUAD, VTK_QUADRATIC_QUAD, VTK_QUADRATIC_LINEAR_QUAD,
      VTK_BIQUADRATIC_QUAD, VTK_NUMBER_OF_CELL_TYPES},
    { VTK_TETRA, VTK_QUADRATIC_TETRA, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_HEXAHEDRON, VTK_QUADRATIC_HEXAHEDRON,
      VTK_BIQUADRATIC_QUADRATIC_HEXAHEDRON, VTK_TRIQUADRATIC_HEXAHEDRON, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_WEDGE, VTK_QUADRATIC_WEDGE, VTK_QUADRATIC_LINEAR_WEDGE,
      VTK_BIQUADRATIC_QUADRATIC_WEDGE, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_PYRAMID, VTK_QUADRATIC_PYRAMID, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES }
    };

//----------------------------------------------------------------------------
// Simply set the points to the pcoords coordinate
// and the point id to the natural order
void InitializeACell(vtkCell *cell)
{
  if( cell )
    {
    double *pcoords = cell->GetParametricCoords();
    int numPts = cell->GetNumberOfPoints();
    for(int i = 0; i < numPts; ++i)
      {
      double *point = pcoords + 3*i;
      cell->GetPointIds()->SetId(i,i);
      //cerr << point[0] << "," << point[1] << "," << point[2] << endl;
      cell->GetPoints()->SetPoint(i, point);
      }
    }
}

//----------------------------------------------------------------------------
// c1 is the reference cell. In the test this is the linear cell
// and thus c2 is the higher order one. We need to check that result on c1
// are consistant with result on c2 (but we cannot say anything after that)
int CompareHigherOrderCell(vtkCell *c1, vtkCell *c2)
{
  int rval = 0;
  //c1->Print( cout );
  //c2->Print( cout );
  int c1numPts = c1->GetNumberOfPoints();
  int c2numPts = c2->GetNumberOfPoints();
  int numPts = c1numPts < c2numPts ? c1numPts : c2numPts;
  for( int p = 0; p < numPts; ++p)
    {
    vtkIdType pid1 = c1->GetPointId(p);
    vtkIdType pid2 = c2->GetPointId(p);
    if( pid1 != pid2 )
      {
      cerr << "Problem with pid:" << pid1 << " != " << pid2 << " in cell #" <<
        c1->GetCellType() << " and #" << c2->GetCellType() << endl;
      ++rval;
      }
    double *pt1 = c1->Points->GetPoint(p);
    double *pt2 = c2->Points->GetPoint(p);
    if( pt1[0] != pt2[0]
     || pt1[1] != pt2[1]
     || pt1[2] != pt2[2])
      {
      cerr << "Problem with points coord:" <<
        pt1[0] << "," << pt1[1] << "," << pt1[2]
        << " != " <<
        pt2[0] << "," << pt2[1] << "," << pt2[2]
        << " in cell #" <<
        c1->GetCellType() << " and #" << c2->GetCellType() << endl;
      ++rval;
      }
    }
  return rval;
}

//----------------------------------------------------------------------------
int TestHigherOrderCell(int , char *[])
{
  int rval = 0;
  if( sizeof(HigherOrderCell[0]) != depth )
    {
    cerr << sizeof(HigherOrderCell[0]) << endl;
    cerr << "Problem in the test" << endl;
    return 1;
    }

  const unsigned char *orderCell;
  const unsigned int nCells = sizeof(HigherOrderCell)/depth;
  vtkCell* cellArray[depth];
  for( unsigned int i = 0; i < nCells; ++i)
    {
    orderCell = HigherOrderCell[i];
    //cerr << "Higher : " << (int)orderCell[0] << "," << (int)orderCell[1] << ","
    //  << (int)orderCell[2] << "," << (int)orderCell[3] << "," << (int)orderCell[4] << endl;
    for( unsigned int c = 0; c < depth; ++c)
      {
      const int cellType = orderCell[c];
      cellArray[c] = vtkGenericCell::InstantiateCell(cellType);
      InitializeACell( cellArray[c] );
      }
    vtkCell *linCell = cellArray[0]; // this is the reference linear cell
    vtkCell *quadCell = cellArray[1]; // this is the reference quadratic cell (serendipity)
    //const int numPts   = linCell->GetNumberOfPoints();
    const int numEdges = linCell->GetNumberOfEdges();
    const int numFaces = linCell->GetNumberOfFaces();
    const int dim      = linCell->GetCellDimension();
    // First check consistancy across cell of higher dimension:
    // Technically doing the loop from 1 to depth will be redundant when doing the
    // CompareHigherOrderCell on the quadratic cell since we will compare the exactly
    // same cell...
    for( unsigned int c = 1; c < depth; ++c)
      {
      vtkCell *cell = cellArray[c];
      if( cell )
        {
        if( cell->GetCellType() != (int)orderCell[c] )
          {
          cerr << "Problem in the test" << endl;
          ++rval;
          }
        if( cell->GetCellDimension() != dim )
          {
          cerr << "Wrong dim for cellId #" << cell->GetCellType() << endl;
          ++rval;
          }
        if( cell->GetNumberOfEdges() != numEdges)
          {
          cerr << "Wrong numEdges for cellId #" << cell->GetCellType() << endl;
          ++rval;
          }
        if( cell->GetNumberOfFaces() != numFaces )
          {
          cerr << "Wrong numFace for cellId #" << cell->GetCellType() << endl;
          ++rval;
          }
        // Make sure that edge across all different cell are identical
        for(int e=0; e<numEdges; ++e)
          {
          vtkCell *c1 = linCell->GetEdge(e);
          vtkCell *c2 = cell->GetEdge(e);
          cerr << "Doing Edge: #" << e << " comp:" << linCell->GetCellType() << " vs "
            << cell->GetCellType() << endl;
          rval += CompareHigherOrderCell(c1, c2);
          //vtkCell *qc1 = quadCell->GetEdge(e);
          //cerr << "Doing Edge: #" << e << " comp:" << quadCell->GetCellType() << " vs "
          //  << cell->GetCellType() << endl;
          //rval += CompareHigherOrderCell(qc1, c2);
          }
        // Make sure that face across all different cell are identical
        for(int f=0; f<numFaces; ++f)
          {
          vtkCell *f1 = linCell->GetFace(f);
          vtkCell *f2 = cell->GetFace(f);
          cerr << "Doing Face: #" << f << " comp:" << linCell->GetCellType() << " vs "
            << cell->GetCellType() << endl;
          rval += CompareHigherOrderCell(f1, f2);
          //vtkCell *qf1 = quadCell->GetFace(f);
          //cerr << "Doing Face: #" << f << " comp:" << quadCell->GetCellType() << " vs "
          //  << cell->GetCellType() << endl;
          //rval += CompareHigherOrderCell(qf1, f2);
          }
        }
      }
    // Cleanup
    for( unsigned int c = 0; c < depth; ++c)
      {
      vtkCell *cell = cellArray[c];
      if( cell )
        {
        cell->Delete();
        }
      }
    }

  return rval;
}

<commit_msg>COMP: Remove warning<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestHigherOrderCell.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkGenericCell.h"
#include "vtkPoints.h"

static const unsigned int depth = 5;
static unsigned char HigherOrderCell[][depth] = {
    { VTK_LINE, VTK_QUADRATIC_EDGE, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_TRIANGLE, VTK_QUADRATIC_TRIANGLE, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_QUAD, VTK_QUADRATIC_QUAD, VTK_QUADRATIC_LINEAR_QUAD,
      VTK_BIQUADRATIC_QUAD, VTK_NUMBER_OF_CELL_TYPES},
    { VTK_TETRA, VTK_QUADRATIC_TETRA, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_HEXAHEDRON, VTK_QUADRATIC_HEXAHEDRON,
      VTK_BIQUADRATIC_QUADRATIC_HEXAHEDRON, VTK_TRIQUADRATIC_HEXAHEDRON, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_WEDGE, VTK_QUADRATIC_WEDGE, VTK_QUADRATIC_LINEAR_WEDGE,
      VTK_BIQUADRATIC_QUADRATIC_WEDGE, VTK_NUMBER_OF_CELL_TYPES },
    { VTK_PYRAMID, VTK_QUADRATIC_PYRAMID, VTK_NUMBER_OF_CELL_TYPES,
      VTK_NUMBER_OF_CELL_TYPES, VTK_NUMBER_OF_CELL_TYPES }
    };

//----------------------------------------------------------------------------
// Simply set the points to the pcoords coordinate
// and the point id to the natural order
void InitializeACell(vtkCell *cell)
{
  if( cell )
    {
    double *pcoords = cell->GetParametricCoords();
    int numPts = cell->GetNumberOfPoints();
    for(int i = 0; i < numPts; ++i)
      {
      double *point = pcoords + 3*i;
      cell->GetPointIds()->SetId(i,i);
      //cerr << point[0] << "," << point[1] << "," << point[2] << endl;
      cell->GetPoints()->SetPoint(i, point);
      }
    }
}

//----------------------------------------------------------------------------
// c1 is the reference cell. In the test this is the linear cell
// and thus c2 is the higher order one. We need to check that result on c1
// are consistant with result on c2 (but we cannot say anything after that)
int CompareHigherOrderCell(vtkCell *c1, vtkCell *c2)
{
  int rval = 0;
  //c1->Print( cout );
  //c2->Print( cout );
  int c1numPts = c1->GetNumberOfPoints();
  int c2numPts = c2->GetNumberOfPoints();
  int numPts = c1numPts < c2numPts ? c1numPts : c2numPts;
  for( int p = 0; p < numPts; ++p)
    {
    vtkIdType pid1 = c1->GetPointId(p);
    vtkIdType pid2 = c2->GetPointId(p);
    if( pid1 != pid2 )
      {
      cerr << "Problem with pid:" << pid1 << " != " << pid2 << " in cell #" <<
        c1->GetCellType() << " and #" << c2->GetCellType() << endl;
      ++rval;
      }
    double *pt1 = c1->Points->GetPoint(p);
    double *pt2 = c2->Points->GetPoint(p);
    if( pt1[0] != pt2[0]
     || pt1[1] != pt2[1]
     || pt1[2] != pt2[2])
      {
      cerr << "Problem with points coord:" <<
        pt1[0] << "," << pt1[1] << "," << pt1[2]
        << " != " <<
        pt2[0] << "," << pt2[1] << "," << pt2[2]
        << " in cell #" <<
        c1->GetCellType() << " and #" << c2->GetCellType() << endl;
      ++rval;
      }
    }
  return rval;
}

//----------------------------------------------------------------------------
int TestHigherOrderCell(int , char *[])
{
  int rval = 0;
  if( sizeof(HigherOrderCell[0]) != depth )
    {
    cerr << sizeof(HigherOrderCell[0]) << endl;
    cerr << "Problem in the test" << endl;
    return 1;
    }

  const unsigned char *orderCell;
  const unsigned int nCells = sizeof(HigherOrderCell)/depth;
  vtkCell* cellArray[depth];
  for( unsigned int i = 0; i < nCells; ++i)
    {
    orderCell = HigherOrderCell[i];
    //cerr << "Higher : " << (int)orderCell[0] << "," << (int)orderCell[1] << ","
    //  << (int)orderCell[2] << "," << (int)orderCell[3] << "," << (int)orderCell[4] << endl;
    for( unsigned int c = 0; c < depth; ++c)
      {
      const int cellType = orderCell[c];
      cellArray[c] = vtkGenericCell::InstantiateCell(cellType);
      InitializeACell( cellArray[c] );
      }
    vtkCell *linCell = cellArray[0]; // this is the reference linear cell
    //vtkCell *quadCell = cellArray[1]; // this is the reference quadratic cell (serendipity)
    //const int numPts   = linCell->GetNumberOfPoints();
    const int numEdges = linCell->GetNumberOfEdges();
    const int numFaces = linCell->GetNumberOfFaces();
    const int dim      = linCell->GetCellDimension();
    // First check consistancy across cell of higher dimension:
    // Technically doing the loop from 1 to depth will be redundant when doing the
    // CompareHigherOrderCell on the quadratic cell since we will compare the exactly
    // same cell...
    for( unsigned int c = 1; c < depth; ++c)
      {
      vtkCell *cell = cellArray[c];
      if( cell )
        {
        if( cell->GetCellType() != (int)orderCell[c] )
          {
          cerr << "Problem in the test" << endl;
          ++rval;
          }
        if( cell->GetCellDimension() != dim )
          {
          cerr << "Wrong dim for cellId #" << cell->GetCellType() << endl;
          ++rval;
          }
        if( cell->GetNumberOfEdges() != numEdges)
          {
          cerr << "Wrong numEdges for cellId #" << cell->GetCellType() << endl;
          ++rval;
          }
        if( cell->GetNumberOfFaces() != numFaces )
          {
          cerr << "Wrong numFace for cellId #" << cell->GetCellType() << endl;
          ++rval;
          }
        // Make sure that edge across all different cell are identical
        for(int e=0; e<numEdges; ++e)
          {
          vtkCell *c1 = linCell->GetEdge(e);
          vtkCell *c2 = cell->GetEdge(e);
          cerr << "Doing Edge: #" << e << " comp:" << linCell->GetCellType() << " vs "
            << cell->GetCellType() << endl;
          rval += CompareHigherOrderCell(c1, c2);
          //vtkCell *qc1 = quadCell->GetEdge(e);
          //cerr << "Doing Edge: #" << e << " comp:" << quadCell->GetCellType() << " vs "
          //  << cell->GetCellType() << endl;
          //rval += CompareHigherOrderCell(qc1, c2);
          }
        // Make sure that face across all different cell are identical
        for(int f=0; f<numFaces; ++f)
          {
          vtkCell *f1 = linCell->GetFace(f);
          vtkCell *f2 = cell->GetFace(f);
          cerr << "Doing Face: #" << f << " comp:" << linCell->GetCellType() << " vs "
            << cell->GetCellType() << endl;
          rval += CompareHigherOrderCell(f1, f2);
          //vtkCell *qf1 = quadCell->GetFace(f);
          //cerr << "Doing Face: #" << f << " comp:" << quadCell->GetCellType() << " vs "
          //  << cell->GetCellType() << endl;
          //rval += CompareHigherOrderCell(qf1, f2);
          }
        }
      }
    // Cleanup
    for( unsigned int c = 0; c < depth; ++c)
      {
      vtkCell *cell = cellArray[c];
      if( cell )
        {
        cell->Delete();
        }
      }
    }

  return rval;
}

<|endoftext|>


<commit_before>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Southwest Research Institute® (SwRI®) nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

#include <swri_yaml_util/yaml_util.h>

#include <stdio.h>
// C++ standard libraries
#include <sstream>
#include <iomanip>
#ifdef YAMLCPP_OLD_API
#include <fstream>
#endif  // YAMLCPP_OLD_API

#ifndef YAMLCPP_OLD_API
namespace YAML
{
  void operator >> (const YAML::Node& node, float& value)
  {
    value = node.as<float>();
  }

  void operator >> (const YAML::Node& node, double& value)
  {
    value = node.as<double>();
  }

  void operator >> (const YAML::Node& node, bool& value)
  {
    value = node.as<bool>();
  }

  void operator >> (const YAML::Node& node, int16_t& value)
  {
    value = node.as<int16_t>();
  }

  void operator >> (const YAML::Node& node, uint16_t& value)
  {
    value = node.as<uint16_t>();
  }

  void operator >> (const YAML::Node& node, int32_t& value)
  {
    value = node.as<int32_t>();
  }

  void operator >> (const YAML::Node& node, uint32_t& value)
  {
    value = node.as<uint32_t>();
  }

  void operator >> (const YAML::Node& node, int64_t& value)
  {
    value = node.as<int64_t>();
  }

  void operator >> (const YAML::Node& node, uint64_t& value)
  {
    value = node.as<uint64_t>();
  }

  void operator >> (const YAML::Node& node, std::string& value)
  {
    value = node.as<std::string>();
  }
}
#endif  // YAMLCPP_OLD_API

namespace swri_yaml_util
{
  bool LoadFile(const std::string& path, YAML::Node& yaml)
  {
    try
    {
      #ifndef YAMLCPP_OLD_API
      yaml = YAML::LoadFile(path);
      #else
      std::ifstream fin(path.c_str());
      if (fin.fail())
      {
        return false;
      }

      YAML::Parser parser(fin);
      parser.GetNextDocument(yaml);
      #endif  // YAMLCPP_OLD_API
    }
    catch (...)
    {
      return false;
    }

    return true;
  }

  bool LoadString(const std::string& input, YAML::Node& yaml)
  {
    try
    {
#ifndef YAMLCPP_OLD_API
      yaml = YAML::Load(input);
#else
      std::stringstream stream(input);
      YAML::Parser parser(stream);
      parser.GetNextDocument(yaml);
#endif  // YAMLCPP_OLD_API
    }
    catch (...)
    {
      return false;
    }

    return true;
  }

  bool LoadMap(const std::map<std::string,std::string>& dict, YAML::Node& yaml)
  {
    std::vector<std::string> items;

    for (std::map<std::string,std::string>::const_iterator iter = dict.begin();
         iter != dict.end();
         ++iter)
    {
      if (!iter->first.empty()) {
        items.push_back("\"" + iter->first + "\": \"" + iter->second + "\"");
      }
    }

    std::string input = "{ ";
    for (size_t i = 0; i < items.size(); ++i) {
      input += items[i];
      if (i+1 < items.size()) {
        input += ", ";
      }
    }
    input += "}";

    printf("stringified: %s", input.c_str());

    return LoadString(input, yaml);
  }

  bool FindValue(const YAML::Node& node, const std::string& name)
  {
    #ifndef YAMLCPP_OLD_API
      return node[name];
    #else
      return node.FindValue(name);
    #endif  // YAMLCPP_OLD_API
  }

  std::auto_ptr<YAML::Node> Clone(const YAML::Node& node)
  {
    #ifndef YAMLCPP_OLD_API
      return std::auto_ptr<YAML::Node>(new YAML::Node(YAML::Clone(node)));
    #else
      return node.Clone();
    #endif  // YAMLCPP_OLD_API
  }

  std::string ToString(double value, int32_t precision)
  {
    std::stringstream ss;
    ss << std::setprecision(precision) << value;

    return ss.str();
  }
}
<commit_msg>swri_yaml_util: fix compatibility with yaml-cpp 0.7.0<commit_after>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Southwest Research Institute® (SwRI®) nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

#include <swri_yaml_util/yaml_util.h>

#include <stdio.h>
// C++ standard libraries
#include <sstream>
#include <iomanip>
#ifdef YAMLCPP_OLD_API
#include <fstream>
#endif  // YAMLCPP_OLD_API

#ifndef YAMLCPP_OLD_API
namespace YAML
{
  void operator >> (const YAML::Node& node, float& value)
  {
    value = node.as<float>();
  }

  void operator >> (const YAML::Node& node, double& value)
  {
    value = node.as<double>();
  }

  void operator >> (const YAML::Node& node, bool& value)
  {
    value = node.as<bool>();
  }

  void operator >> (const YAML::Node& node, int16_t& value)
  {
    value = node.as<int16_t>();
  }

  void operator >> (const YAML::Node& node, uint16_t& value)
  {
    value = node.as<uint16_t>();
  }

  void operator >> (const YAML::Node& node, int32_t& value)
  {
    value = node.as<int32_t>();
  }

  void operator >> (const YAML::Node& node, uint32_t& value)
  {
    value = node.as<uint32_t>();
  }

  void operator >> (const YAML::Node& node, int64_t& value)
  {
    value = node.as<int64_t>();
  }

  void operator >> (const YAML::Node& node, uint64_t& value)
  {
    value = node.as<uint64_t>();
  }

  void operator >> (const YAML::Node& node, std::string& value)
  {
    value = node.as<std::string>();
  }
}
#endif  // YAMLCPP_OLD_API

namespace swri_yaml_util
{
  bool LoadFile(const std::string& path, YAML::Node& yaml)
  {
    try
    {
      #ifndef YAMLCPP_OLD_API
      yaml = YAML::LoadFile(path);
      #else
      std::ifstream fin(path.c_str());
      if (fin.fail())
      {
        return false;
      }

      YAML::Parser parser(fin);
      parser.GetNextDocument(yaml);
      #endif  // YAMLCPP_OLD_API
    }
    catch (...)
    {
      return false;
    }

    return true;
  }

  bool LoadString(const std::string& input, YAML::Node& yaml)
  {
    try
    {
#ifndef YAMLCPP_OLD_API
      yaml = YAML::Load(input);
#else
      std::stringstream stream(input);
      YAML::Parser parser(stream);
      parser.GetNextDocument(yaml);
#endif  // YAMLCPP_OLD_API
    }
    catch (...)
    {
      return false;
    }

    return true;
  }

  bool LoadMap(const std::map<std::string,std::string>& dict, YAML::Node& yaml)
  {
    std::vector<std::string> items;

    for (std::map<std::string,std::string>::const_iterator iter = dict.begin();
         iter != dict.end();
         ++iter)
    {
      if (!iter->first.empty()) {
        items.push_back("\"" + iter->first + "\": \"" + iter->second + "\"");
      }
    }

    std::string input = "{ ";
    for (size_t i = 0; i < items.size(); ++i) {
      input += items[i];
      if (i+1 < items.size()) {
        input += ", ";
      }
    }
    input += "}";

    printf("stringified: %s", input.c_str());

    return LoadString(input, yaml);
  }

  bool FindValue(const YAML::Node& node, const std::string& name)
  {
    #ifndef YAMLCPP_OLD_API
      return static_cast<bool>(node[name]);
    #else
      return node.FindValue(name);
    #endif  // YAMLCPP_OLD_API
  }

  std::auto_ptr<YAML::Node> Clone(const YAML::Node& node)
  {
    #ifndef YAMLCPP_OLD_API
      return std::auto_ptr<YAML::Node>(new YAML::Node(YAML::Clone(node)));
    #else
      return node.Clone();
    #endif  // YAMLCPP_OLD_API
  }

  std::string ToString(double value, int32_t precision)
  {
    std::stringstream ss;
    ss << std::setprecision(precision) << value;

    return ss.str();
  }
}
<|endoftext|>


<commit_before>#include "common/platform.h"

std::wstring WinNTStringToWideString( const std::string& str )
{
    size_t slen = str.length();
    int len     = MultiByteToWideChar( CP_ACP, 0,
                                       input.c_str(),
                                       static_cast<int>(slen) + 1,
                                       0,
                                       0 );

    // Allocate space for the new wstring
    wchar_t *buffer = new wchar_t[len];

    MultiByteToWideChar( CP_ACP, 0,
                         str.c_str(),
                         static_cast<int>(slen) + 1,
                         buffer,
                         len );

    std::wstring result( buffer );
    delete[] buffer;

    return result;
}

<commit_msg>removing now defunct windows file. all code belongs in platform_vista.cpp<commit_after><|endoftext|>


<commit_before>/* This file is part of Ingen.
 * Copyright 2007-2011 David Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "Connection.hpp"
#include "Port.hpp"

#include "ingen/client/ConnectionModel.hpp"

using namespace std;

namespace Ingen {
namespace GUI {

Connection::Connection(FlowCanvas::Canvas&                      canvas,
                       boost::shared_ptr<const ConnectionModel> model,
                       FlowCanvas::Connectable*                 src,
                       FlowCanvas::Connectable*                 dst,
                       uint32_t                                 color)
	: FlowCanvas::Connection(canvas, src, dst, color)
	, _connection_model(model)
{
	Port* const src_port = dynamic_cast<Port*>(src);
	if (src_port)
		_bpath->property_dash() = src_port->dash();
}

}   // namespace GUI
}   // namespace Ingen
<commit_msg>Implement connections as a custom gnomecanvas C widget. Hide all gnomecanvas API completely from Connection.hpp.<commit_after>/* This file is part of Ingen.
 * Copyright 2007-2011 David Robillard <http://drobilla.net>
 *
 * Ingen is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "Connection.hpp"
#include "Port.hpp"

#include "ingen/client/ConnectionModel.hpp"

using namespace std;

namespace Ingen {
namespace GUI {

Connection::Connection(FlowCanvas::Canvas&                      canvas,
                       boost::shared_ptr<const ConnectionModel> model,
                       FlowCanvas::Connectable*                 src,
                       FlowCanvas::Connectable*                 dst,
                       uint32_t                                 color)
	: FlowCanvas::Connection(canvas, src, dst, color)
	, _connection_model(model)
{
}

}   // namespace GUI
}   // namespace Ingen
<|endoftext|>


<commit_before>/* QuickCross Project
 * License: APACHE-2.0
 * Author: Ben Lau
 * Project Site: https://github.com/benlau/quickcross
 *
 */

#include <QSysInfo>
#include <QtGlobal>
#include "qcdevice.h"

#ifdef Q_OS_ANDROID
#include <QAndroidJniEnvironment>
#include <QAndroidJniObject>
#endif

static qreal m_dp = 1;

/*!
 * \qmltype Device
 * \instantiates QCDevice
 * \inqmlmodule QuickCross
 * \inherits QObject
 *
 * \brief Provider of device related information
 * It is a singleton component
 *
 */

QCDevice::QCDevice(QObject *parent) : QObject(parent)
{

#ifdef Q_OS_ANDROID
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
    QAndroidJniObject resource = activity.callObjectMethod("getResources","()Landroid/content/res/Resources;");
    QAndroidJniObject metrics = resource.callObjectMethod("getDisplayMetrics","()Landroid/util/DisplayMetrics;");
    m_dp = metrics.getField<float>("density");
#endif
}

/*!
 * \qmlproperty string Device::os
 * This property hold the product name of the operating system this application is running in.
 * It is equivalent to QSysInfo::productType()
 *
 */

QString QCDevice::os() const
{
    QString res = "unknown";

#ifdef Q_OS_LINUX
    // Don't return a distribution name
    res = "linux"
#else
    res = QSysInfo::productType();
#endif

    return res;
}

/*!
 * \qmlproperty bool Device::isAndroid
 */

bool QCDevice::isAndroid() const
{
#ifdef Q_OS_ANDROID
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty bool Device::isLinux
 */

bool QCDevice::isLinux() const
{
#ifdef Q_OS_LINUX
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty bool Device::isIOS
 */

bool QCDevice::isIOS() const
{
#ifdef Q_OS_IOS
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty bool Device::isMac
 */

bool QCDevice::isMac() const
{
#ifdef Q_OS_MAC
    return true;
#else
    return false;
#endif

}

/*!
 * \qmlproperty bool Device::isWindows
 */

bool QCDevice::isWindows() const
{
#ifdef Q_OS_WIN32
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty real Device::dp
 *
 * This property hold the density independent pixel (DP) of the Android device this application is running.
 *
 * It is valid only in Android system. In other system, the default value is 1.
 *
 */

qreal QCDevice::dp() const
{
    return m_dp;
}

<commit_msg>Fix build problem<commit_after>/* QuickCross Project
 * License: APACHE-2.0
 * Author: Ben Lau
 * Project Site: https://github.com/benlau/quickcross
 *
 */

#include <QSysInfo>
#include <QtGlobal>
#include "qcdevice.h"

#ifdef Q_OS_ANDROID
#include <QAndroidJniEnvironment>
#include <QAndroidJniObject>
#endif

static qreal m_dp = 1;

/*!
 * \qmltype Device
 * \instantiates QCDevice
 * \inqmlmodule QuickCross
 * \inherits QObject
 *
 * \brief Provider of device related information
 * It is a singleton component
 *
 */

QCDevice::QCDevice(QObject *parent) : QObject(parent)
{

#ifdef Q_OS_ANDROID
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");
    QAndroidJniObject resource = activity.callObjectMethod("getResources","()Landroid/content/res/Resources;");
    QAndroidJniObject metrics = resource.callObjectMethod("getDisplayMetrics","()Landroid/util/DisplayMetrics;");
    m_dp = metrics.getField<float>("density");
#endif
}

/*!
 * \qmlproperty string Device::os
 * This property hold the product name of the operating system this application is running in.
 * It is equivalent to QSysInfo::productType()
 *
 */

QString QCDevice::os() const
{
    QString res = "unknown";

#ifdef Q_OS_LINUX
    // Don't return a distribution name
    res = "linux";
#else
    res = QSysInfo::productType();
#endif

    return res;
}

/*!
 * \qmlproperty bool Device::isAndroid
 */

bool QCDevice::isAndroid() const
{
#ifdef Q_OS_ANDROID
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty bool Device::isLinux
 */

bool QCDevice::isLinux() const
{
#ifdef Q_OS_LINUX
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty bool Device::isIOS
 */

bool QCDevice::isIOS() const
{
#ifdef Q_OS_IOS
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty bool Device::isMac
 */

bool QCDevice::isMac() const
{
#ifdef Q_OS_MAC
    return true;
#else
    return false;
#endif

}

/*!
 * \qmlproperty bool Device::isWindows
 */

bool QCDevice::isWindows() const
{
#ifdef Q_OS_WIN32
    return true;
#else
    return false;
#endif
}

/*!
 * \qmlproperty real Device::dp
 *
 * This property hold the density independent pixel (DP) of the Android device this application is running.
 *
 * It is valid only in Android system. In other system, the default value is 1.
 *
 */

qreal QCDevice::dp() const
{
    return m_dp;
}

<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File NodalTetElec.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: 3D Nodal Tet Electrostatic Point Definitions
//
///////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <algorithm>
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/Foundations.hpp>

#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/Polylib/Polylib.h>
#include <LibUtilities/Foundations/NodalTetElec.h>
#include <LibUtilities/Foundations/NodalTetElecData.h>

namespace Nektar
{
    namespace LibUtilities
    {
        void NodalTetElec::CalculatePoints()
        {
            // Allocate the storage for points
            Points<double>::CalculatePoints();
            ASSERTL0(false, "3D Point Expansion Not Implemented Yet");
        }

        void NodalTetElec::CalculateWeights()
        {
            // No weights computed
        }

        void NodalTetElec::CalculateDerivMatrix()
        {
            // No derivative matrix computed
        }

        boost::shared_ptr<NodalTetElec::PointsBaseType> NodalTetElec::Create(const PointsKey &key)
        {
            boost::shared_ptr<PointsBaseType> returnval(MemoryManager<NodalTetElec>::AllocateSharedPtr(key));
            returnval->Initialize();
            return returnval;
        }

        void NodalTetElec::NodalPointReorder3d()
        {
        }

    } // end of namespace stdregion
} // end of namespace stdregion

/**
* $Log: NodalTetElec.cpp,v $
* Revision 1.8  2007/07/20 00:28:26  bnelson
* Replaced boost::shared_ptr with Nektar::ptr
*
* Revision 1.7  2007/05/15 03:37:24  bnelson
* Updated to use the new Array object.
*
* Revision 1.6  2007/04/30 23:29:09  jfrazier
* More conversion to multi_array.
*
* Revision 1.5  2007/04/29 00:31:57  jfrazier
* Updated to use multi_arrays.
*
*/
<commit_msg>Updated Tetrahedron symmetry and calculate points<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File NodalTetElec.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: 3D Nodal Tet Electrostatic Point Definitions
//
///////////////////////////////////////////////////////////////////////////////

#include <iostream>
#include <algorithm>
#include <LibUtilities/Foundations/Points.h>
#include <LibUtilities/Foundations/Foundations.hpp>

#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/Polylib/Polylib.h>
#include <LibUtilities/Foundations/NodalTetElec.h>
#include <LibUtilities/Foundations/NodalTetElecData.h>

namespace Nektar
{
    namespace LibUtilities
    {
        void NodalTetElec::CalculatePoints()
        {
            // Allocate the storage for points
            Points<double>::CalculatePoints();

            int index=0,isum=0;
            const int offset = 5; //offset to match Datafile
            NekDouble a,b,c,d;
            unsigned int numPoints = GetNumPoints();

            // initialize values
            for(unsigned int i=0; i < numPoints-2; ++i)
            {
                index += NodalTetElecNPTS[i];
            }

            for(unsigned int i=0; i < NodalTetElecNPTS[numPoints-2]; ++i, ++index)
            {
                // 1 Point Symmetry: aaaa
                if(int(NodalTetElecData[index][0]))
                {
                    a = NodalTetElecData[index][5];
                    b = NodalTetElecData[index][6];
                    c = NodalTetElecData[index][7];
                    d = NodalTetElecData[index][8];

                    m_points[0][isum] = 2.0*b - 1.0;
                    m_points[1][isum] = 2.0*c - 1.0;
                    m_points[2][isum] = 2.0*d - 1.0;
                    isum++;
                    continue;
                }//end symmetry 1

                // 4 Point symmetry: aaab or abbb
                if(int(NodalTetElecData[index][1]))
                {
                    for(unsigned int j=0; j < 4; ++j)
                    {
                        a = NodalTetElecData[index][offset + perm4_3d[j][0]];
                        b = NodalTetElecData[index][offset + perm4_3d[j][1]];
                        c = NodalTetElecData[index][offset + perm4_3d[j][2]];
                        d = NodalTetElecData[index][offset + perm4_3d[j][3]];

                        m_points[0][isum] = 2.0*b - 1.0;
                        m_points[1][isum] = 2.0*c - 1.0;
                        m_points[2][isum] = 2.0*d - 1.0;
                        isum++;
                    }//end j
                    continue;
                }//end symmetry 4

                // 6 Point symmetry: aabb
                if(int(NodalTetElecData[index][2]))
                {
                    for(unsigned int j=0; j < 6; ++j)
                    {
                        a = NodalTetElecData[index][offset + perm6_3d[j][0]];
                        b = NodalTetElecData[index][offset + perm6_3d[j][1]];
                        c = NodalTetElecData[index][offset + perm6_3d[j][2]];
                        d = NodalTetElecData[index][offset + perm6_3d[j][3]];

                        m_points[0][isum] = 2.0*b - 1.0;
                        m_points[1][isum] = 2.0*c - 1.0;
                        m_points[2][isum] = 2.0*d - 1.0;
                        isum++;
                    }//end j
                    continue;
                }//end symmetry6

                // 12 Point symmetry: case aabc
                if(int(NodalTetElecData[index][3]) == 1)
                {
                    for(unsigned int j=0; j < 12; ++j)
                    {
                        a = NodalTetElecData[index][offset + perm12A_3d[j][0]];
                        b = NodalTetElecData[index][offset + perm12A_3d[j][1]];
                        c = NodalTetElecData[index][offset + perm12A_3d[j][2]];
                        d = NodalTetElecData[index][offset + perm12A_3d[j][3]];

                        m_points[0][isum] = 2.0*b - 1.0;
                        m_points[1][isum] = 2.0*c - 1.0;
                        m_points[2][isum] = 2.0*d - 1.0;
                        isum++;
                    }//end j
                    continue;
                }//end symmetry 12 aabc

                // 12 Point symmetry: case abcc
                if(int(NodalTetElecData[index][3]) == 2)
                {
                    for(unsigned int j=0; j < 12; ++j)
                    {
                        a = NodalTetElecData[index][offset + perm12B_3d[j][0]];
                        b = NodalTetElecData[index][offset + perm12B_3d[j][1]];
                        c = NodalTetElecData[index][offset + perm12B_3d[j][2]];
                        d = NodalTetElecData[index][offset + perm12B_3d[j][3]];

                        m_points[0][isum] = 2.0*b - 1.0;
                        m_points[1][isum] = 2.0*c - 1.0;
                        m_points[2][isum] = 2.0*d - 1.0;
                        isum++;
                    }//end j
                    continue;
                }//end symmetry 12 abcc

                // 12 Point symmetry: case abbc
                if(int(NodalTetElecData[index][3]) == 3)
                {
                    for(unsigned int j=0; j < 12; ++j)
                    {
                        a = NodalTetElecData[index][offset + perm12C_3d[j][0]];
                        b = NodalTetElecData[index][offset + perm12C_3d[j][1]];
                        c = NodalTetElecData[index][offset + perm12C_3d[j][2]];
                        d = NodalTetElecData[index][offset + perm12C_3d[j][3]];

                        m_points[0][isum] = 2.0*b - 1.0;
                        m_points[1][isum] = 2.0*c - 1.0;
                        m_points[2][isum] = 2.0*d - 1.0;
                        isum++;
                    }//end j
                    continue;
                }//end symmetry 12 abbc

                // 24 Point symmetry: case abcd
                if(int(NodalTetElecData[index][4]))
                {
                    for(unsigned int j=0; j < 24; ++j)
                    {
                        a = NodalTetElecData[index][offset + perm24_3d[j][0]];
                        b = NodalTetElecData[index][offset + perm24_3d[j][1]];
                        c = NodalTetElecData[index][offset + perm24_3d[j][2]];
                        d = NodalTetElecData[index][offset + perm24_3d[j][3]];

                        m_points[0][isum] = 2.0*b - 1.0;
                        m_points[1][isum] = 2.0*c - 1.0;
                        m_points[2][isum] = 2.0*d - 1.0;
                        isum++;
                    }//end j
                    continue;
                }//end symmetry24abcd

            }//end npts

            NodalPointReorder3d();

            ASSERTL1((isum==m_pointsKey.GetTotNumPoints()),"sum not equal to npts");
        }

        void NodalTetElec::CalculateWeights()
        {
            // No weights computed
        }

        void NodalTetElec::CalculateDerivMatrix()
        {
            // No derivative matrix computed
        }

        boost::shared_ptr<NodalTetElec::PointsBaseType> NodalTetElec::Create(const PointsKey &key)
        {
            boost::shared_ptr<PointsBaseType> returnval(MemoryManager<NodalTetElec>::AllocateSharedPtr(key));
            returnval->Initialize();
            return returnval;
        }

        void NodalTetElec::NodalPointReorder3d()
        {
        }

    } // end of namespace stdregion
} // end of namespace stdregion

/**
* $Log: NodalTetElec.cpp,v $
* Revision 1.9  2007/07/22 23:03:26  bnelson
* Backed out Nektar::ptr.
*
* Revision 1.8  2007/07/20 00:28:26  bnelson
* Replaced boost::shared_ptr with Nektar::ptr
*
* Revision 1.7  2007/05/15 03:37:24  bnelson
* Updated to use the new Array object.
*
* Revision 1.6  2007/04/30 23:29:09  jfrazier
* More conversion to multi_array.
*
* Revision 1.5  2007/04/29 00:31:57  jfrazier
* Updated to use multi_arrays.
*
*/
<|endoftext|>


<commit_before>#include "SUIT_FileDlg.h"

#include "SUIT_Tools.h"
#include "SUIT_Session.h"
#include "SUIT_Desktop.h"
#include "SUIT_MessageBox.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_FileValidator.h"

#include <qdir.h>
#include <qlabel.h>
#include <qregexp.h>
#include <qpalette.h>
#include <qobjectlist.h>
#include <qpushbutton.h>
#include <qapplication.h>

#define MIN_COMBO_SIZE 100

QString SUIT_FileDlg::myLastVisitedPath;

/*!
Constructor
*/
SUIT_FileDlg::SUIT_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal ) :
QFileDialog( parent, 0, modal ),
myValidator( 0 ),
myQuickCombo( 0 ),
myOpen( open )
{
  if ( parent->icon() )
    setIcon( *parent->icon() );
  setSizeGripEnabled( true );

  if (showQuickDir) {
    // inserting quick dir combo box
    QLabel* lab  = new QLabel(tr("Quick path:"), this);
    myQuickCombo = new QComboBox(false, this);
    myQuickCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
    myQuickCombo->setMinimumSize(MIN_COMBO_SIZE, 0);

    // the following is a workaround for proper layouting of custom widgets ===========
    QPushButton* btn = new QPushButton(this);
    btn->setEnabled(false);
    QPalette pal = btn->palette();
    QColorGroup ca = pal.active();
    ca.setColor(QColorGroup::Light,    palette().active().background());
    ca.setColor(QColorGroup::Midlight, palette().active().background());
    ca.setColor(QColorGroup::Dark,     palette().active().background());
    ca.setColor(QColorGroup::Mid,      palette().active().background());
    ca.setColor(QColorGroup::Shadow,   palette().active().background());
    QColorGroup ci = pal.inactive();
    ci.setColor(QColorGroup::Light,    palette().inactive().background());
    ci.setColor(QColorGroup::Midlight, palette().inactive().background());
    ci.setColor(QColorGroup::Dark,     palette().inactive().background());
    ci.setColor(QColorGroup::Mid,      palette().inactive().background());
    ci.setColor(QColorGroup::Shadow,   palette().inactive().background());
    QColorGroup cd = pal.disabled();
    cd.setColor(QColorGroup::Light,    palette().disabled().background());
    cd.setColor(QColorGroup::Midlight, palette().disabled().background());
    cd.setColor(QColorGroup::Dark,     palette().disabled().background());
    cd.setColor(QColorGroup::Mid,      palette().disabled().background());
    cd.setColor(QColorGroup::Shadow,   palette().disabled().background());
    pal.setActive(ca); pal.setInactive(ci); pal.setDisabled(cd);
    btn->setPalette(pal);
    // ================================================================================

    connect(myQuickCombo, SIGNAL(activated(const QString&)), this, SLOT(quickDir(const QString&)));
    addWidgets(lab, myQuickCombo, btn);

    // getting dir list from settings
    QString dirs;
    SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
    if ( resMgr )
      dirs = resMgr->stringValue( "FileDlg", "QuickDirList" );

    QStringList dirList = QStringList::split(';', dirs, false);
    if (dirList.count() > 0) {
      for (unsigned i = 0; i < dirList.count(); i++)
	      myQuickCombo->insertItem(dirList[i]);
    }
    else {
      myQuickCombo->insertItem(QDir::homeDirPath());
    }

    // the following is a workaround for proper layouting of custom widgets ===========
    QValueList<QPushButton*> buttonList;
    QValueList<QLabel*> labelList;
    const QObjectList *list = children();
    QObjectListIt it(*list);
    int maxButWidth = lab->sizeHint().width();
    int maxLabWidth = btn->sizeHint().width();

    for (; it.current() ; ++it) {
      if ( it.current()->isA( "QLabel" ) ) {
	int tempW = ((QLabel*)it.current())->minimumWidth();
	if ( maxLabWidth < tempW ) maxLabWidth = tempW;
	labelList.append( (QLabel*)it.current() );
      }
      else if( it.current()->isA("QPushButton") ) {
	int tempW = ((QPushButton*)it.current())->minimumWidth();
	if ( maxButWidth < tempW ) maxButWidth = tempW;
	buttonList.append( (QPushButton*)it.current() );
      }
    }
    if (maxButWidth > 0) {
      QValueList<QPushButton*>::Iterator bListIt;
      for ( bListIt = buttonList.begin(); bListIt != buttonList.end(); ++bListIt )
	(*bListIt)->setFixedWidth( maxButWidth );
    }
    if (maxLabWidth > 0) {
      QValueList<QLabel*>::Iterator lListIt;
      for ( lListIt = labelList.begin(); lListIt != labelList.end(); ++lListIt )
	(*lListIt)->setFixedWidth( maxLabWidth );
    }
    // ================================================================================
  }
  setMode( myOpen ? ExistingFile : AnyFile );
  setCaption( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );
  if (myLastVisitedPath.isNull() || myLastVisitedPath.isEmpty()) {
    // If no last visited path exists -> switch to the first preferred path
    processPath(myQuickCombo->text(0));
  }
  else if ( !processPath(myLastVisitedPath) ) {
    // If last visited path doesn't exist -> switch to the first preferred path
    processPath(myQuickCombo->text(0));
  }
  myValidator = new SUIT_FileValidator(this);

}

/*!
Destructor
*/
SUIT_FileDlg::~SUIT_FileDlg()
{
}

/*!
Sets validator for file names to open/save
Deletes previous validator
*/
void SUIT_FileDlg::setValidator( SUIT_FileValidator* v )
{
  if (myValidator)
    delete myValidator;
  myValidator = v;
}

/*!
Returns the selected file
*/
QString SUIT_FileDlg::selectedFile() const
{
  return mySelectedFile;
}

/*!
Returns 'true' if this is 'Open File' dialog
and 'false' if 'Save File' dialog
*/
bool SUIT_FileDlg::isOpenDlg() const
{
  return myOpen;
}

/*!
Closes this dialog and sets the return code to 'Accepted'
if the selected name is valid ( see 'acceptData()' )
*/
void SUIT_FileDlg::accept()
{
//  mySelectedFile = QFileDialog::selectedFile().simplifyWhiteSpace(); //VSR- 06/12/02
  mySelectedFile = QFileDialog::selectedFile(); //VSR+ 06/12/02
  addExtension();
//  mySelectedFile = mySelectedFile.simplifyWhiteSpace(); //VSR- 06/12/02

  /* Qt 2.2.2 BUG: accept() is called twice if you validate
  the selected file name by pressing 'Return' key in file
  name editor but this name is not acceptable for acceptData()
  */
  if ( acceptData() ) {
    myLastVisitedPath = dirPath();
    QFileDialog::accept();
  }
}

/*!
Closes this dialog and sets the return code to 'Rejected'
*/
void SUIT_FileDlg::reject()
{
  mySelectedFile = QString::null;
  QFileDialog::reject();
}

/*!
Returns 'true' if selected file is valid.
The validity is checked by a file validator,
if there is no validator the file is always
considered as valid
*/
bool SUIT_FileDlg::acceptData()
{
  if ( myValidator )
  {
    if ( isOpenDlg() )
      return myValidator->canOpen( selectedFile() );
    else
      return myValidator->canSave( selectedFile() );
  }
  return true;
}

/*!
Adds an extension to the selected file name
if the file has not it.
The extension is extracted from the active filter.
*/
void SUIT_FileDlg::addExtension()
{
//  mySelectedFile.stripWhiteSpace();//VSR- 06/12/02
//  if ( mySelectedFile.isEmpty() )//VSR- 06/12/02
  if ( mySelectedFile.stripWhiteSpace().isEmpty() )//VSR+ 06/12/02
    return;

//  if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR- 06/12/02
//ota :   16/12/03  if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR+ 06/12/02
//  {

#if QT_VERSION < 0x030000
    QRegExp r( QString::fromLatin1("([a-zA-Z0-9.*? +;#]*)$") );
    int len, index = r.match( selectedFilter(), 0, &len );
#else
    QRegExp r( QString::fromLatin1("\\([a-zA-Z0-9.*? +;#]*\\)$") );
    int index = r.search(selectedFilter());
#endif
    if ( index >= 0 )
    {
#if QT_VERSION < 0x030000
//      QString wildcard = selectedFilter().mid( index + 1, len-2 ); //VSR- 06/12/02
      QString wildcard = selectedFilter().mid( index + 1, len-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#else
//      QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ); //VSR- 06/12/02
      QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#endif
    int aLen = mySelectedFile.length();
    if ( mySelectedFile[aLen - 1] == '.')
	  //if the file name ends with the point remove it
	    mySelectedFile.truncate(aLen - 1);
    QString anExt = "." + SUIT_Tools::extension( mySelectedFile ).stripWhiteSpace();
      // From the filters list make a pattern to validate a file extension
      // Due to transformations from the filter list (*.txt *.*xx *.c++ SUIT*.* ) we
      // will have the pattern (\.txt|\..*xx|\.c\+\+|\..*) (as we validate extension only we remove
      // stay extension mask only in the pattern
      QString aPattern(wildcard);
      QRegExp anExtRExp("("+aPattern.replace(QRegExp("(^| )[0-9a-zA-Z*_?]*\\."), " \\.").
			stripWhiteSpace().replace(QRegExp("\\s+"), "|").
			replace(QRegExp("[*]"),".*").replace(QRegExp("[+]"),"\\+") + ")");

      if ( anExtRExp.match(anExt) == -1 ) //if a selected file extension does not match to filter's list
	{ //remove a point if it is at the word end
    int aExtLen = anExt.length();
	  if (anExt[ aExtLen - 1 ] == '.')  anExt.truncate( aExtLen - 1 );
	  index = wildcard.findRev( '.' );
	  if ( index >= 0 )
	    mySelectedFile += wildcard.mid( index ); //add the extension
	}
    }
  //  }
}

/*!
  Processes selection : tries to set given path or filename as selection
*/
bool SUIT_FileDlg::processPath( const QString& path )
{
  if ( !path.isNull() ) {
    QFileInfo fi( path );
    if ( fi.exists() ) {
      if ( fi.isFile() )
	setSelection( path );
      else if ( fi.isDir() )
	setDir( path );
      return true;
    }
    else {
      if ( QFileInfo( fi.dirPath() ).exists() ) {
	setDir( fi.dirPath() );
	return true;
      }
    }
  }
  return false;
}
/*!
  Called when user selects item from "Quick Dir" combo box
*/
void SUIT_FileDlg::quickDir(const QString& dirPath)
{
  if ( !QDir(dirPath).exists() ) {
    SUIT_MessageBox::error1(this,
			   tr("ERR_ERROR"),
			   tr("ERR_DIR_NOT_EXIST").arg(dirPath),
			   tr("BUT_OK"));

  }
  else {
    processPath(dirPath);
  }
}

/*!
  Returns the file name for Open/Save [ static ]
*/
QString SUIT_FileDlg::getFileName( QWidget*           parent,
				  const QString&     initial,
                                  const QStringList& filters,
                                  const QString&     caption,
                                  bool               open,
				  bool               showQuickDir,
				  SUIT_FileValidator* validator )
{
  SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, showQuickDir, true );
  if ( !caption.isEmpty() )
    fd->setCaption( caption );
  if ( !initial.isEmpty() ) {
    fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
  }
  fd->setFilters( filters );
  if ( validator )
    fd->setValidator( validator );
  fd->exec();
  QString filename = fd->selectedFile();
  delete fd;
  qApp->processEvents();
  return filename;
}

/*!
  Existing directory selection dialog [ static ]
*/
QString SUIT_FileDlg::getExistingDirectory ( QWidget*       parent,
					    const QString& initial,
					    const QString& caption,
					    bool           showQuickDir )
{
  SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true);
  if ( !caption.isEmpty() )
    fd->setCaption( caption );
  if ( !initial.isEmpty() ) {
    fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
  }
  fd->setMode( DirectoryOnly );
  fd->setFilters(tr("DIRECTORIES_FILTER"));
  fd->exec();
  QString dirname = fd->selectedFile();
  delete fd;
  qApp->processEvents();
  return dirname;

}
<commit_msg>Correction.<commit_after>#include "SUIT_FileDlg.h"

#include "SUIT_Tools.h"
#include "SUIT_Session.h"
#include "SUIT_Desktop.h"
#include "SUIT_MessageBox.h"
#include "SUIT_ResourceMgr.h"
#include "SUIT_FileValidator.h"

#include <qdir.h>
#include <qlabel.h>
#include <qregexp.h>
#include <qpalette.h>
#include <qobjectlist.h>
#include <qpushbutton.h>
#include <qapplication.h>

#define MIN_COMBO_SIZE 100

QString SUIT_FileDlg::myLastVisitedPath;

/*!
Constructor
*/
SUIT_FileDlg::SUIT_FileDlg( QWidget* parent, bool open, bool showQuickDir, bool modal ) :
QFileDialog( parent, 0, modal ),
myValidator( 0 ),
myQuickCombo( 0 ),
myOpen( open )
{
  if ( parent->icon() )
    setIcon( *parent->icon() );
  setSizeGripEnabled( true );

  if (showQuickDir) {
    // inserting quick dir combo box
    QLabel* lab  = new QLabel(tr("Quick path:"), this);
    myQuickCombo = new QComboBox(false, this);
    myQuickCombo->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed));
    myQuickCombo->setMinimumSize(MIN_COMBO_SIZE, 0);

    // the following is a workaround for proper layouting of custom widgets ===========
    QPushButton* btn = new QPushButton(this);
    btn->setEnabled(false);
    QPalette pal = btn->palette();
    QColorGroup ca = pal.active();
    ca.setColor(QColorGroup::Light,    palette().active().background());
    ca.setColor(QColorGroup::Midlight, palette().active().background());
    ca.setColor(QColorGroup::Dark,     palette().active().background());
    ca.setColor(QColorGroup::Mid,      palette().active().background());
    ca.setColor(QColorGroup::Shadow,   palette().active().background());
    QColorGroup ci = pal.inactive();
    ci.setColor(QColorGroup::Light,    palette().inactive().background());
    ci.setColor(QColorGroup::Midlight, palette().inactive().background());
    ci.setColor(QColorGroup::Dark,     palette().inactive().background());
    ci.setColor(QColorGroup::Mid,      palette().inactive().background());
    ci.setColor(QColorGroup::Shadow,   palette().inactive().background());
    QColorGroup cd = pal.disabled();
    cd.setColor(QColorGroup::Light,    palette().disabled().background());
    cd.setColor(QColorGroup::Midlight, palette().disabled().background());
    cd.setColor(QColorGroup::Dark,     palette().disabled().background());
    cd.setColor(QColorGroup::Mid,      palette().disabled().background());
    cd.setColor(QColorGroup::Shadow,   palette().disabled().background());
    pal.setActive(ca); pal.setInactive(ci); pal.setDisabled(cd);
    btn->setPalette(pal);
    // ================================================================================

    connect(myQuickCombo, SIGNAL(activated(const QString&)), this, SLOT(quickDir(const QString&)));
    addWidgets(lab, myQuickCombo, btn);

    // getting dir list from settings
    QString dirs;
    SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
    if ( resMgr )
      dirs = resMgr->stringValue( "FileDlg", "QuickDirList" );

    QStringList dirList = QStringList::split(';', dirs, false);
    if (dirList.count() > 0) {
      for (unsigned i = 0; i < dirList.count(); i++)
	      myQuickCombo->insertItem(dirList[i]);
    }
    else {
      myQuickCombo->insertItem(QDir::homeDirPath());
    }

    // the following is a workaround for proper layouting of custom widgets ===========
    QValueList<QPushButton*> buttonList;
    QValueList<QLabel*> labelList;
    const QObjectList *list = children();
    QObjectListIt it(*list);
    int maxButWidth = lab->sizeHint().width();
    int maxLabWidth = btn->sizeHint().width();

    for (; it.current() ; ++it) {
      if ( it.current()->isA( "QLabel" ) ) {
	int tempW = ((QLabel*)it.current())->minimumWidth();
	if ( maxLabWidth < tempW ) maxLabWidth = tempW;
	labelList.append( (QLabel*)it.current() );
      }
      else if( it.current()->isA("QPushButton") ) {
	int tempW = ((QPushButton*)it.current())->minimumWidth();
	if ( maxButWidth < tempW ) maxButWidth = tempW;
	buttonList.append( (QPushButton*)it.current() );
      }
    }
    if (maxButWidth > 0) {
      QValueList<QPushButton*>::Iterator bListIt;
      for ( bListIt = buttonList.begin(); bListIt != buttonList.end(); ++bListIt )
	(*bListIt)->setFixedWidth( maxButWidth );
    }
    if (maxLabWidth > 0) {
      QValueList<QLabel*>::Iterator lListIt;
      for ( lListIt = labelList.begin(); lListIt != labelList.end(); ++lListIt )
	(*lListIt)->setFixedWidth( maxLabWidth );
    }
    // ================================================================================
  }
  setMode( myOpen ? ExistingFile : AnyFile );
  setCaption( myOpen ? tr( "INF_DESK_DOC_OPEN" ) : tr( "INF_DESK_DOC_SAVE" ) );

  if (showQuickDir) {
    if (myLastVisitedPath.isNull() || myLastVisitedPath.isEmpty()) {
      // If no last visited path exists -> switch to the first preferred path
      processPath(myQuickCombo->text(0));
    }
    else if ( !processPath(myLastVisitedPath) ) {
      // If last visited path doesn't exist -> switch to the first preferred path
      processPath(myQuickCombo->text(0));
    }
  }

  myValidator = new SUIT_FileValidator(this);

}

/*!
Destructor
*/
SUIT_FileDlg::~SUIT_FileDlg()
{
}

/*!
Sets validator for file names to open/save
Deletes previous validator
*/
void SUIT_FileDlg::setValidator( SUIT_FileValidator* v )
{
  if (myValidator)
    delete myValidator;
  myValidator = v;
}

/*!
Returns the selected file
*/
QString SUIT_FileDlg::selectedFile() const
{
  return mySelectedFile;
}

/*!
Returns 'true' if this is 'Open File' dialog
and 'false' if 'Save File' dialog
*/
bool SUIT_FileDlg::isOpenDlg() const
{
  return myOpen;
}

/*!
Closes this dialog and sets the return code to 'Accepted'
if the selected name is valid ( see 'acceptData()' )
*/
void SUIT_FileDlg::accept()
{
//  mySelectedFile = QFileDialog::selectedFile().simplifyWhiteSpace(); //VSR- 06/12/02
  mySelectedFile = QFileDialog::selectedFile(); //VSR+ 06/12/02
  addExtension();
//  mySelectedFile = mySelectedFile.simplifyWhiteSpace(); //VSR- 06/12/02

  /* Qt 2.2.2 BUG: accept() is called twice if you validate
  the selected file name by pressing 'Return' key in file
  name editor but this name is not acceptable for acceptData()
  */
  if ( acceptData() ) {
    myLastVisitedPath = dirPath();
    QFileDialog::accept();
  }
}

/*!
Closes this dialog and sets the return code to 'Rejected'
*/
void SUIT_FileDlg::reject()
{
  mySelectedFile = QString::null;
  QFileDialog::reject();
}

/*!
Returns 'true' if selected file is valid.
The validity is checked by a file validator,
if there is no validator the file is always
considered as valid
*/
bool SUIT_FileDlg::acceptData()
{
  if ( myValidator )
  {
    if ( isOpenDlg() )
      return myValidator->canOpen( selectedFile() );
    else
      return myValidator->canSave( selectedFile() );
  }
  return true;
}

/*!
Adds an extension to the selected file name
if the file has not it.
The extension is extracted from the active filter.
*/
void SUIT_FileDlg::addExtension()
{
//  mySelectedFile.stripWhiteSpace();//VSR- 06/12/02
//  if ( mySelectedFile.isEmpty() )//VSR- 06/12/02
  if ( mySelectedFile.stripWhiteSpace().isEmpty() )//VSR+ 06/12/02
    return;

//  if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR- 06/12/02
//ota :   16/12/03  if ( SUIT_Tools::getFileExtensionFromPath( mySelectedFile ).isEmpty() ) //VSR+ 06/12/02
//  {

#if QT_VERSION < 0x030000
    QRegExp r( QString::fromLatin1("([a-zA-Z0-9.*? +;#]*)$") );
    int len, index = r.match( selectedFilter(), 0, &len );
#else
    QRegExp r( QString::fromLatin1("\\([a-zA-Z0-9.*? +;#]*\\)$") );
    int index = r.search(selectedFilter());
#endif
    if ( index >= 0 )
    {
#if QT_VERSION < 0x030000
//      QString wildcard = selectedFilter().mid( index + 1, len-2 ); //VSR- 06/12/02
      QString wildcard = selectedFilter().mid( index + 1, len-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#else
//      QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ); //VSR- 06/12/02
      QString wildcard = selectedFilter().mid( index + 1, r.matchedLength()-2 ).stripWhiteSpace(); //VSR+ 06/12/02
#endif
    int aLen = mySelectedFile.length();
    if ( mySelectedFile[aLen - 1] == '.')
	  //if the file name ends with the point remove it
	    mySelectedFile.truncate(aLen - 1);
    QString anExt = "." + SUIT_Tools::extension( mySelectedFile ).stripWhiteSpace();
      // From the filters list make a pattern to validate a file extension
      // Due to transformations from the filter list (*.txt *.*xx *.c++ SUIT*.* ) we
      // will have the pattern (\.txt|\..*xx|\.c\+\+|\..*) (as we validate extension only we remove
      // stay extension mask only in the pattern
      QString aPattern(wildcard);
      QRegExp anExtRExp("("+aPattern.replace(QRegExp("(^| )[0-9a-zA-Z*_?]*\\."), " \\.").
			stripWhiteSpace().replace(QRegExp("\\s+"), "|").
			replace(QRegExp("[*]"),".*").replace(QRegExp("[+]"),"\\+") + ")");

      if ( anExtRExp.match(anExt) == -1 ) //if a selected file extension does not match to filter's list
	{ //remove a point if it is at the word end
    int aExtLen = anExt.length();
	  if (anExt[ aExtLen - 1 ] == '.')  anExt.truncate( aExtLen - 1 );
	  index = wildcard.findRev( '.' );
	  if ( index >= 0 )
	    mySelectedFile += wildcard.mid( index ); //add the extension
	}
    }
  //  }
}

/*!
  Processes selection : tries to set given path or filename as selection
*/
bool SUIT_FileDlg::processPath( const QString& path )
{
  if ( !path.isNull() ) {
    QFileInfo fi( path );
    if ( fi.exists() ) {
      if ( fi.isFile() )
	setSelection( path );
      else if ( fi.isDir() )
	setDir( path );
      return true;
    }
    else {
      if ( QFileInfo( fi.dirPath() ).exists() ) {
	setDir( fi.dirPath() );
	return true;
      }
    }
  }
  return false;
}
/*!
  Called when user selects item from "Quick Dir" combo box
*/
void SUIT_FileDlg::quickDir(const QString& dirPath)
{
  if ( !QDir(dirPath).exists() ) {
    SUIT_MessageBox::error1(this,
			   tr("ERR_ERROR"),
			   tr("ERR_DIR_NOT_EXIST").arg(dirPath),
			   tr("BUT_OK"));

  }
  else {
    processPath(dirPath);
  }
}

/*!
  Returns the file name for Open/Save [ static ]
*/
QString SUIT_FileDlg::getFileName( QWidget*           parent,
				  const QString&     initial,
                                  const QStringList& filters,
                                  const QString&     caption,
                                  bool               open,
				  bool               showQuickDir,
				  SUIT_FileValidator* validator )
{
  SUIT_FileDlg* fd = new SUIT_FileDlg( parent, open, showQuickDir, true );
  if ( !caption.isEmpty() )
    fd->setCaption( caption );
  if ( !initial.isEmpty() ) {
    fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
  }
  fd->setFilters( filters );
  if ( validator )
    fd->setValidator( validator );
  fd->exec();
  QString filename = fd->selectedFile();
  delete fd;
  qApp->processEvents();
  return filename;
}

/*!
  Existing directory selection dialog [ static ]
*/
QString SUIT_FileDlg::getExistingDirectory ( QWidget*       parent,
					    const QString& initial,
					    const QString& caption,
					    bool           showQuickDir )
{
  SUIT_FileDlg* fd = new SUIT_FileDlg( parent, true, showQuickDir, true);
  if ( !caption.isEmpty() )
    fd->setCaption( caption );
  if ( !initial.isEmpty() ) {
    fd->processPath( initial ); // VSR 24/03/03 check for existing of directory has been added to avoid QFileDialog's bug
  }
  fd->setMode( DirectoryOnly );
  fd->setFilters(tr("DIRECTORIES_FILTER"));
  fd->exec();
  QString dirname = fd->selectedFile();
  delete fd;
  qApp->processEvents();
  return dirname;

}
<|endoftext|>