<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "OSPCommon.h"
#if defined(OSPRAY_TASKING_TBB)
# include <tbb/task_scheduler_init.h>
#elif defined(OSPRAY_TASKING_CILK)
# include <cilk/cilk_api.h>
#elif defined(OSPRAY_TASKING_OMP)
# include <omp.h>
#elif defined(OSPRAY_TASKING_INTERNAL)
# include "common/tasking/TaskSys.h"
#endif
// embree
#include "embree2/rtcore.h"
#include "ospcommon/sysinfo.h"

namespace ospray {

  RTCDevice g_embreeDevice = nullptr;

  /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */
  extern "C" void *malloc64(size_t size)
  {
    return ospcommon::alignedMalloc(size);
  }

  /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */
  extern "C" void free64(void *ptr)
  {
    return ospcommon::alignedFree(ptr);
  }

  /*! logging level - '0' means 'no logging at all', increasing
      numbers mean increasing verbosity of log messages */
  uint32_t logLevel = 0;
  bool debugMode = false;
  int numThreads = -1;

  WarnOnce::WarnOnce(const std::string &s)
    : s(s)
  {
    std::cout << "Warning: " << s << " (only reporting first occurrence)"
              << std::endl;
  }

  /*! for debugging. compute a checksum for given area range... */
  void *computeCheckSum(const void *ptr, size_t numBytes)
  {
    long *end = (long *)((char *)ptr + (numBytes - (numBytes%8)));
    long *mem = (long *)ptr;
    long sum = 0;
    long i = 0;

    while (mem < end) {
      sum += (i+13) * *mem;
      ++i;
      ++mem;
    }
    return (void *)sum;
  }

  void doAssertion(const char *file, int line,
                   const char *expr, const char *expl) {
    if (expl)
      fprintf(stderr,"%s:%i: Assertion failed: \"%s\":\nAdditional Info: %s\n",
              file, line, expr, expl);
    else
      fprintf(stderr,"%s:%i: Assertion failed: \"%s\".\n", file, line, expr);
    abort();
  }

  void removeArgs(int &ac, char **&av, int where, int howMany)
  {
    for (int i=where+howMany;i<ac;i++)
      av[i-howMany] = av[i];
    ac -= howMany;
  }

  void init(int *_ac, const char ***_av)
  {
#ifndef OSPRAY_TARGET_MIC
    // If we're not on a MIC, check for SSE4.1 as minimum supported ISA. Will
    // be increased to SSE4.2 in future.
    int cpuFeatures = ospcommon::getCPUFeatures();
    if ((cpuFeatures & ospcommon::CPU_FEATURE_SSE41) == 0)
      throw std::runtime_error("Error. OSPRay only runs on CPUs that support"
                               " at least SSE4.1.");
#endif

    if (_ac && _av) {
      int &ac = *_ac;
      char ** &av = *(char ***)_av;
      for (int i=1;i<ac;) {
        std::string parm = av[i];
        if (parm == "--osp:debug") {
          debugMode = true;
          numThreads = 1;
          removeArgs(ac,av,i,1);
        } else if (parm == "--osp:verbose") {
          logLevel = 1;
          removeArgs(ac,av,i,1);
        } else if (parm == "--osp:vv") {
          logLevel = 2;
          removeArgs(ac,av,i,1);
        } else if (parm == "--osp:loglevel") {
          logLevel = atoi(av[i+1]);
          removeArgs(ac,av,i,2);
        } else if (parm == "--osp:numthreads" || parm == "--osp:num-threads") {
          numThreads = atoi(av[i+1]);
          removeArgs(ac,av,i,2);
        } else {
          ++i;
        }
      }
    }

#if defined(OSPRAY_TASKING_TBB)
    static tbb::task_scheduler_init tbb_init(numThreads);
    UNUSED(tbb_init);
#elif defined(OSPRAY_TASKING_CILK)
    __cilkrts_set_param("nworkers", std::to_string(numThreads).c_str());
#elif defined(OSPRAY_TASKING_OMP)
    if (numThreads > 0) {
      omp_set_num_threads(numThreads);
    }
#elif defined(OSPRAY_TASKING_INTERNAL)
    try {
      ospray::Task::initTaskSystem(debugMode ? 0 : numThreads);
    } catch (const std::runtime_error &e) {
      std::cerr << "WARNING: " << e.what() << std::endl;
    }
#endif
  }

  void error_handler(const RTCError code, const char *str)
  {
    printf("Embree: ");
    switch (code) {
      case RTC_UNKNOWN_ERROR    : printf("RTC_UNKNOWN_ERROR"); break;
      case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break;
      case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break;
      case RTC_OUT_OF_MEMORY    : printf("RTC_OUT_OF_MEMORY"); break;
      case RTC_UNSUPPORTED_CPU  : printf("RTC_UNSUPPORTED_CPU"); break;
      default                   : printf("invalid error code"); break;
    }
    if (str) {
      printf(" (");
      while (*str) putchar(*str++);
      printf(")\n");
    }
    abort();
  }

  size_t sizeOf(const OSPDataType type) {
    switch (type) {
    case OSP_VOID_PTR:  return sizeof(void *);
    case OSP_OBJECT:    return sizeof(void *);
    case OSP_DATA:      return sizeof(void *);
    case OSP_CHAR:      return sizeof(int8);
    case OSP_UCHAR:     return sizeof(uint8);
    case OSP_UCHAR2:    return sizeof(vec2uc);
    case OSP_UCHAR3:    return sizeof(vec3uc);
    case OSP_UCHAR4:    return sizeof(vec4uc);
    case OSP_USHORT:    return sizeof(uint16);
    case OSP_INT:       return sizeof(int32);
    case OSP_INT2:      return sizeof(vec2i);
    case OSP_INT3:      return sizeof(vec3i);
    case OSP_INT4:      return sizeof(vec4i);
    case OSP_UINT:      return sizeof(uint32);
    case OSP_UINT2:     return sizeof(vec2ui);
    case OSP_UINT3:     return sizeof(vec3ui);
    case OSP_UINT4:     return sizeof(vec4ui);
    case OSP_LONG:      return sizeof(int64);
    case OSP_LONG2:     return sizeof(vec2l);
    case OSP_LONG3:     return sizeof(vec3l);
    case OSP_LONG4:     return sizeof(vec4l);
    case OSP_ULONG:     return sizeof(uint64);
    case OSP_ULONG2:    return sizeof(vec2ul);
    case OSP_ULONG3:    return sizeof(vec3ul);
    case OSP_ULONG4:    return sizeof(vec4ul);
    case OSP_FLOAT:     return sizeof(float);
    case OSP_FLOAT2:    return sizeof(vec2f);
    case OSP_FLOAT3:    return sizeof(vec3f);
    case OSP_FLOAT4:    return sizeof(vec4f);
    case OSP_FLOAT3A:   return sizeof(vec3fa);
    case OSP_DOUBLE:    return sizeof(double);
    default: break;
    };

    std::stringstream error;
    error << __FILE__ << ":" << __LINE__ << ": unknown OSPDataType "
          << (int)type;
    throw std::runtime_error(error.str());
  }

  OSPDataType typeForString(const char *string) {
    if (string == NULL)                return(OSP_UNKNOWN);
    if (strcmp(string, "char"  ) == 0) return(OSP_CHAR);
    if (strcmp(string, "double") == 0) return(OSP_DOUBLE);
    if (strcmp(string, "float" ) == 0) return(OSP_FLOAT);
    if (strcmp(string, "float2") == 0) return(OSP_FLOAT2);
    if (strcmp(string, "float3") == 0) return(OSP_FLOAT2);
    if (strcmp(string, "float4") == 0) return(OSP_FLOAT2);
    if (strcmp(string, "int"   ) == 0) return(OSP_INT);
    if (strcmp(string, "int2"  ) == 0) return(OSP_INT2);
    if (strcmp(string, "int3"  ) == 0) return(OSP_INT3);
    if (strcmp(string, "int4"  ) == 0) return(OSP_INT4);
    if (strcmp(string, "uchar" ) == 0) return(OSP_UCHAR);
    if (strcmp(string, "uchar2") == 0) return(OSP_UCHAR2);
    if (strcmp(string, "uchar3") == 0) return(OSP_UCHAR3);
    if (strcmp(string, "uchar4") == 0) return(OSP_UCHAR4);
    if (strcmp(string, "ushort") == 0) return(OSP_USHORT);
    if (strcmp(string, "uint"  ) == 0) return(OSP_UINT);
    if (strcmp(string, "uint2" ) == 0) return(OSP_UINT2);
    if (strcmp(string, "uint3" ) == 0) return(OSP_UINT3);
    if (strcmp(string, "uint4" ) == 0) return(OSP_UINT4);
    return(OSP_UNKNOWN);
  }

  size_t sizeOf(const OSPTextureFormat type) {
    switch (type) {
      case OSP_TEXTURE_RGBA8:
      case OSP_TEXTURE_SRGBA:   return sizeof(uint32);
      case OSP_TEXTURE_RGBA32F: return sizeof(vec4f);
      case OSP_TEXTURE_RGB8:
      case OSP_TEXTURE_SRGB:    return sizeof(vec3uc);
      case OSP_TEXTURE_RGB32F:  return sizeof(vec3f);
      case OSP_TEXTURE_R8:      return sizeof(uint8);
      case OSP_TEXTURE_R32F:    return sizeof(float);
    }

    std::stringstream error;
    error << __FILE__ << ":" << __LINE__ << ": unknown OSPTextureFormat "
          << (int)type;
    throw std::runtime_error(error.str());
  }

} // ::ospray

<commit_msg>Fix and complete OSPDataType functions<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "OSPCommon.h"
#if defined(OSPRAY_TASKING_TBB)
# include <tbb/task_scheduler_init.h>
#elif defined(OSPRAY_TASKING_CILK)
# include <cilk/cilk_api.h>
#elif defined(OSPRAY_TASKING_OMP)
# include <omp.h>
#elif defined(OSPRAY_TASKING_INTERNAL)
# include "common/tasking/TaskSys.h"
#endif
// embree
#include "embree2/rtcore.h"
#include "ospcommon/sysinfo.h"

namespace ospray {

  RTCDevice g_embreeDevice = nullptr;

  /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */
  extern "C" void *malloc64(size_t size)
  {
    return ospcommon::alignedMalloc(size);
  }

  /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */
  extern "C" void free64(void *ptr)
  {
    return ospcommon::alignedFree(ptr);
  }

  /*! logging level - '0' means 'no logging at all', increasing
      numbers mean increasing verbosity of log messages */
  uint32_t logLevel = 0;
  bool debugMode = false;
  int numThreads = -1;

  WarnOnce::WarnOnce(const std::string &s)
    : s(s)
  {
    std::cout << "Warning: " << s << " (only reporting first occurrence)"
              << std::endl;
  }

  /*! for debugging. compute a checksum for given area range... */
  void *computeCheckSum(const void *ptr, size_t numBytes)
  {
    long *end = (long *)((char *)ptr + (numBytes - (numBytes%8)));
    long *mem = (long *)ptr;
    long sum = 0;
    long i = 0;

    while (mem < end) {
      sum += (i+13) * *mem;
      ++i;
      ++mem;
    }
    return (void *)sum;
  }

  void doAssertion(const char *file, int line,
                   const char *expr, const char *expl) {
    if (expl)
      fprintf(stderr,"%s:%i: Assertion failed: \"%s\":\nAdditional Info: %s\n",
              file, line, expr, expl);
    else
      fprintf(stderr,"%s:%i: Assertion failed: \"%s\".\n", file, line, expr);
    abort();
  }

  void removeArgs(int &ac, char **&av, int where, int howMany)
  {
    for (int i=where+howMany;i<ac;i++)
      av[i-howMany] = av[i];
    ac -= howMany;
  }

  void init(int *_ac, const char ***_av)
  {
#ifndef OSPRAY_TARGET_MIC
    // If we're not on a MIC, check for SSE4.1 as minimum supported ISA. Will
    // be increased to SSE4.2 in future.
    int cpuFeatures = ospcommon::getCPUFeatures();
    if ((cpuFeatures & ospcommon::CPU_FEATURE_SSE41) == 0)
      throw std::runtime_error("Error. OSPRay only runs on CPUs that support"
                               " at least SSE4.1.");
#endif

    if (_ac && _av) {
      int &ac = *_ac;
      char ** &av = *(char ***)_av;
      for (int i=1;i<ac;) {
        std::string parm = av[i];
        if (parm == "--osp:debug") {
          debugMode = true;
          numThreads = 1;
          removeArgs(ac,av,i,1);
        } else if (parm == "--osp:verbose") {
          logLevel = 1;
          removeArgs(ac,av,i,1);
        } else if (parm == "--osp:vv") {
          logLevel = 2;
          removeArgs(ac,av,i,1);
        } else if (parm == "--osp:loglevel") {
          logLevel = atoi(av[i+1]);
          removeArgs(ac,av,i,2);
        } else if (parm == "--osp:numthreads" || parm == "--osp:num-threads") {
          numThreads = atoi(av[i+1]);
          removeArgs(ac,av,i,2);
        } else {
          ++i;
        }
      }
    }

#if defined(OSPRAY_TASKING_TBB)
    static tbb::task_scheduler_init tbb_init(numThreads);
    UNUSED(tbb_init);
#elif defined(OSPRAY_TASKING_CILK)
    __cilkrts_set_param("nworkers", std::to_string(numThreads).c_str());
#elif defined(OSPRAY_TASKING_OMP)
    if (numThreads > 0) {
      omp_set_num_threads(numThreads);
    }
#elif defined(OSPRAY_TASKING_INTERNAL)
    try {
      ospray::Task::initTaskSystem(debugMode ? 0 : numThreads);
    } catch (const std::runtime_error &e) {
      std::cerr << "WARNING: " << e.what() << std::endl;
    }
#endif
  }

  void error_handler(const RTCError code, const char *str)
  {
    printf("Embree: ");
    switch (code) {
      case RTC_UNKNOWN_ERROR    : printf("RTC_UNKNOWN_ERROR"); break;
      case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break;
      case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break;
      case RTC_OUT_OF_MEMORY    : printf("RTC_OUT_OF_MEMORY"); break;
      case RTC_UNSUPPORTED_CPU  : printf("RTC_UNSUPPORTED_CPU"); break;
      default                   : printf("invalid error code"); break;
    }
    if (str) {
      printf(" (");
      while (*str) putchar(*str++);
      printf(")\n");
    }
    abort();
  }

  size_t sizeOf(const OSPDataType type) {
    switch (type) {
    case OSP_VOID_PTR:
    case OSP_OBJECT:
    case OSP_CAMERA:
    case OSP_DATA:
    case OSP_FRAMEBUFFER:
    case OSP_GEOMETRY:
    case OSP_LIGHT:
    case OSP_MATERIAL:
    case OSP_MODEL:
    case OSP_RENDERER:
    case OSP_TEXTURE:
    case OSP_TRANSFER_FUNCTION:
    case OSP_VOLUME:
    case OSP_PIXEL_OP:
    case OSP_STRING:    return sizeof(void *);
    case OSP_CHAR:      return sizeof(int8);
    case OSP_UCHAR:     return sizeof(uint8);
    case OSP_UCHAR2:    return sizeof(vec2uc);
    case OSP_UCHAR3:    return sizeof(vec3uc);
    case OSP_UCHAR4:    return sizeof(vec4uc);
    case OSP_USHORT:    return sizeof(uint16);
    case OSP_INT:       return sizeof(int32);
    case OSP_INT2:      return sizeof(vec2i);
    case OSP_INT3:      return sizeof(vec3i);
    case OSP_INT4:      return sizeof(vec4i);
    case OSP_UINT:      return sizeof(uint32);
    case OSP_UINT2:     return sizeof(vec2ui);
    case OSP_UINT3:     return sizeof(vec3ui);
    case OSP_UINT4:     return sizeof(vec4ui);
    case OSP_LONG:      return sizeof(int64);
    case OSP_LONG2:     return sizeof(vec2l);
    case OSP_LONG3:     return sizeof(vec3l);
    case OSP_LONG4:     return sizeof(vec4l);
    case OSP_ULONG:     return sizeof(uint64);
    case OSP_ULONG2:    return sizeof(vec2ul);
    case OSP_ULONG3:    return sizeof(vec3ul);
    case OSP_ULONG4:    return sizeof(vec4ul);
    case OSP_FLOAT:     return sizeof(float);
    case OSP_FLOAT2:    return sizeof(vec2f);
    case OSP_FLOAT3:    return sizeof(vec3f);
    case OSP_FLOAT4:    return sizeof(vec4f);
    case OSP_FLOAT3A:   return sizeof(vec3fa);
    case OSP_DOUBLE:    return sizeof(double);
    };

    std::stringstream error;
    error << __FILE__ << ":" << __LINE__ << ": unknown OSPDataType "
          << (int)type;
    throw std::runtime_error(error.str());
  }

  OSPDataType typeForString(const char *string) {
    if (string == NULL)                return(OSP_UNKNOWN);
    if (strcmp(string, "char"  ) == 0) return(OSP_CHAR);
    if (strcmp(string, "double") == 0) return(OSP_DOUBLE);
    if (strcmp(string, "float" ) == 0) return(OSP_FLOAT);
    if (strcmp(string, "float2") == 0) return(OSP_FLOAT2);
    if (strcmp(string, "float3") == 0) return(OSP_FLOAT3);
    if (strcmp(string, "float4") == 0) return(OSP_FLOAT4);
    if (strcmp(string, "int"   ) == 0) return(OSP_INT);
    if (strcmp(string, "int2"  ) == 0) return(OSP_INT2);
    if (strcmp(string, "int3"  ) == 0) return(OSP_INT3);
    if (strcmp(string, "int4"  ) == 0) return(OSP_INT4);
    if (strcmp(string, "uchar" ) == 0) return(OSP_UCHAR);
    if (strcmp(string, "uchar2") == 0) return(OSP_UCHAR2);
    if (strcmp(string, "uchar3") == 0) return(OSP_UCHAR3);
    if (strcmp(string, "uchar4") == 0) return(OSP_UCHAR4);
    if (strcmp(string, "ushort") == 0) return(OSP_USHORT);
    if (strcmp(string, "uint"  ) == 0) return(OSP_UINT);
    if (strcmp(string, "uint2" ) == 0) return(OSP_UINT2);
    if (strcmp(string, "uint3" ) == 0) return(OSP_UINT3);
    if (strcmp(string, "uint4" ) == 0) return(OSP_UINT4);
    return(OSP_UNKNOWN);
  }

  size_t sizeOf(const OSPTextureFormat type) {
    switch (type) {
      case OSP_TEXTURE_RGBA8:
      case OSP_TEXTURE_SRGBA:   return sizeof(uint32);
      case OSP_TEXTURE_RGBA32F: return sizeof(vec4f);
      case OSP_TEXTURE_RGB8:
      case OSP_TEXTURE_SRGB:    return sizeof(vec3uc);
      case OSP_TEXTURE_RGB32F:  return sizeof(vec3f);
      case OSP_TEXTURE_R8:      return sizeof(uint8);
      case OSP_TEXTURE_R32F:    return sizeof(float);
    }

    std::stringstream error;
    error << __FILE__ << ":" << __LINE__ << ": unknown OSPTextureFormat "
          << (int)type;
    throw std::runtime_error(error.str());
  }

} // ::ospray

<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2003 by krecipes.sourceforge.net authors                *
 *                                                                         *
 *                                                                         *
 *   This program 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.                                   *
 ***************************************************************************/
#include "kreexport.h"

KreExporter::KreExporter( RecipeDB *db, const QString& filename = QString::null, const QString format = QString::null )
{
  database = db;
  if(filename != QString::null){
    if(filename.right(4) == ".kre" || filename.right(6) == ".kreml"){
      file = new QFile(filename);
    }
    else{
      QString form = format;
      form = form.remove('*');
      if(form != ".kre" && form != ".kreml"){
        form = ".kre";
      }
      file = new QFile(filename+form);
    }
    QFileInfo fi(*file);
    type = fi.extension();
    name = (fi.fileName()).remove("."+type);
    exportEnable = true;
  }
  else{
    exportEnable = false;
  }
}

KreExporter::~KreExporter()
{
}

/*!
    \fn KreExporter::export()
 * export recipe to XML and save it to a file
 */
void KreExporter::exporter(const int recipeId)
{
  recipe = new Recipe();
  recipe->recipeID = -1;
  database->loadRecipe( recipe, recipeId );
  if(exportEnable){
    bool fileExists = file->exists();
    int overwrite;
    if(fileExists){
      overwrite = KMessageBox::questionYesNo( 0,i18n("File ")+file->name()+i18n(" exists. Would you like to overwrite it?"),i18n("Saving recipe") );
    }
    if(!fileExists || overwrite == KMessageBox::Yes){
      if(type == "kreml"){
        if ( file->open( IO_WriteOnly ) ) {
          QTextStream stream( file );
          stream << "<krecipes version=\"0.1\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
          stream << createKRE();
          stream << "</krecipes>";
          file->close();
        }
      }
      else{
        // create a temporary .kre file
        QString kreml = "<krecipes version=\"0.1\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
        kreml += createKRE();
        kreml += "</krecipes>";
        int size = kreml.length();
        // compress and save file
        KTar* kre = new KTar(file->name(), "application/x-gzip");
        kre->open( IO_WriteOnly );
        kre->writeFile(name+".kreml",getenv( "LOGNAME" ), "", size, kreml);
        kre->close();
      }
    }
  }
  else{
    qDebug("no output file have been selected for export.");
  }
}

void KreExporter::categoryExporter(QValueList<int>* l){
  recipe = new Recipe();
  recipe->recipeID = -1;
  QString kreml;
  QValueList<int>::iterator it;
  if(exportEnable){
    bool fileExists = file->exists();
    int overwrite;
    if(fileExists){
      overwrite = KMessageBox::questionYesNo( 0,i18n("File ")+file->name()+i18n(" exists. Would you like to overwrite it?"),i18n("Saving recipe") );
    }
    if(!fileExists || overwrite == KMessageBox::Yes){
      kreml = "<krecipes version=\"0.1\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
      for ( it = l->begin(); it != l->end(); ++it ){
        database->loadRecipe( recipe, *it );
        kreml += createKRE();
      }
      kreml += "</krecipes>\n";
      if(type == "kreml"){
        if ( file->open( IO_WriteOnly ) ) {
          QTextStream stream( file );
          stream << kreml;
          file->close();
        }
      }
      else{
        int size = kreml.length();
        // compress and save file
        KTar* kre = new KTar(file->name(), "application/x-gzip");
        kre->open( IO_WriteOnly );
        kre->writeFile(name+".kreml",getenv( "LOGNAME" ), "", size, kreml);
        kre->close();
      }
    }
  }
  else{
    qDebug("no output file have been selected for export.");
  }
}

/*!
    \fn KreManager::createKRE()
 * return a QString containing XML encoded recipe
 */
QString KreExporter::createKRE(const int recipeId)
{
    QString xml;
    if(recipeId != -1){
      recipe = new Recipe();
      recipe->recipeID = -1;
      database->loadRecipe( recipe, recipeId );
      xml = "<krecipes version=\"0.1\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
    }
    else{
      xml = "";
    }
    xml +="<krecipes-recipe>";
    xml += "<krecipes-description>\n";
    xml += "<title>"+recipe->title.utf8()+"</title>\n";
    for (Element *el = (recipe->authorList).getFirst(); el; el= (recipe->authorList).getNext()){
      xml += "<author>"+el->name.utf8()+"</author>\n";
    }
    xml += "<pictures>\n";
    xml += "<pic format=\"JPEG\" id=\"1\"><![CDATA["; //fixed id until we implement multiple photos ability
    KTempFile* fn = new KTempFile (locateLocal("tmp", "kre"), ".jpg", 0600);
    recipe->photo.save(fn->name(), "JPEG");
    QByteArray data;
    if( fn ){
      data = (fn->file())->readAll();
      fn->close();
      xml += KCodecs::base64Encode(data, true);
    }
    xml += "]]></pic>\n";
    xml += "</pictures>\n";
    xml += "<category>\n";
    for (Element *ct = (recipe->categoryList).getFirst(); ct; ct= (recipe->categoryList).getNext()){
      xml += "<cat>"+ct->name.utf8()+"</cat>\n";
    }
    xml += "</category>\n";
    xml += "<serving>";
    xml += QString::number(recipe->persons);
    xml += "</serving>\n";
    xml += "</krecipes-description>\n";
    xml += "<krecipes-ingredients>\n";
    for (Ingredient* in = (recipe->ingList).getFirst(); in; in= (recipe->ingList).getNext()){
      xml += "<ingredient>\n";
      xml += "<name>"+in->name.utf8()+"</name>\n";
      xml += "<amount>";
      xml += QString::number(in->amount);
      xml += "</amount>\n";
      xml += "<unit>"+in->units.utf8()+"</unit>\n";
      xml += "</ingredient>\n";
      /// @todo add ingredient properties
    }
    xml += "</krecipes-ingredients>\n";
    xml += "<krecipes-instructions>\n";
    xml += recipe->instructions.utf8();
    xml += "</krecipes-instructions>\n";
    xml += "</krecipes-recipe>\n";
    if(recipeId != -1){
      xml += "</krecipes>\n";
    }
    return xml;
}
<commit_msg>change kreml version to 0.4<commit_after>/***************************************************************************
 *   Copyright (C) 2003 by krecipes.sourceforge.net authors                *
 *                                                                         *
 *                                                                         *
 *   This program 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.                                   *
 ***************************************************************************/
#include "kreexport.h"

KreExporter::KreExporter( RecipeDB *db, const QString& filename = QString::null, const QString format = QString::null )
{
  database = db;
  if(filename != QString::null){
    if(filename.right(4) == ".kre" || filename.right(6) == ".kreml"){
      file = new QFile(filename);
    }
    else{
      QString form = format;
      form = form.remove('*');
      if(form != ".kre" && form != ".kreml"){
        form = ".kre";
      }
      file = new QFile(filename+form);
    }
    QFileInfo fi(*file);
    type = fi.extension();
    name = (fi.fileName()).remove("."+type);
    exportEnable = true;
  }
  else{
    exportEnable = false;
  }
}

KreExporter::~KreExporter()
{
}

/*!
    \fn KreExporter::export()
 * export recipe to XML and save it to a file
 */
void KreExporter::exporter(const int recipeId)
{
  recipe = new Recipe();
  recipe->recipeID = -1;
  database->loadRecipe( recipe, recipeId );
  if(exportEnable){
    bool fileExists = file->exists();
    int overwrite;
    if(fileExists){
      overwrite = KMessageBox::questionYesNo( 0,i18n("File ")+file->name()+i18n(" exists. Would you like to overwrite it?"),i18n("Saving recipe") );
    }
    if(!fileExists || overwrite == KMessageBox::Yes){
      if(type == "kreml"){
        if ( file->open( IO_WriteOnly ) ) {
          QTextStream stream( file );
          stream << "<krecipes version=\"0.4\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
          stream << createKRE();
          stream << "</krecipes>";
          file->close();
        }
      }
      else{
        // create a temporary .kre file
        QString kreml = "<krecipes version=\"0.4\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
        kreml += createKRE();
        kreml += "</krecipes>";
        int size = kreml.length();
        // compress and save file
        KTar* kre = new KTar(file->name(), "application/x-gzip");
        kre->open( IO_WriteOnly );
        kre->writeFile(name+".kreml",getenv( "LOGNAME" ), "", size, kreml);
        kre->close();
      }
    }
  }
  else{
    qDebug("no output file have been selected for export.");
  }
}

void KreExporter::categoryExporter(QValueList<int>* l){
  recipe = new Recipe();
  recipe->recipeID = -1;
  QString kreml;
  QValueList<int>::iterator it;
  if(exportEnable){
    bool fileExists = file->exists();
    int overwrite;
    if(fileExists){
      overwrite = KMessageBox::questionYesNo( 0,i18n("File ")+file->name()+i18n(" exists. Would you like to overwrite it?"),i18n("Saving recipe") );
    }
    if(!fileExists || overwrite == KMessageBox::Yes){
      kreml = "<krecipes version=\"0.4\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
      for ( it = l->begin(); it != l->end(); ++it ){
        database->loadRecipe( recipe, *it );
        kreml += createKRE();
      }
      kreml += "</krecipes>\n";
      if(type == "kreml"){
        if ( file->open( IO_WriteOnly ) ) {
          QTextStream stream( file );
          stream << kreml;
          file->close();
        }
      }
      else{
        int size = kreml.length();
        // compress and save file
        KTar* kre = new KTar(file->name(), "application/x-gzip");
        kre->open( IO_WriteOnly );
        kre->writeFile(name+".kreml",getenv( "LOGNAME" ), "", size, kreml);
        kre->close();
      }
    }
  }
  else{
    qDebug("no output file have been selected for export.");
  }
}

/*!
    \fn KreManager::createKRE()
 * return a QString containing XML encoded recipe
 */
QString KreExporter::createKRE(const int recipeId)
{
    QString xml;
    if(recipeId != -1){
      recipe = new Recipe();
      recipe->recipeID = -1;
      database->loadRecipe( recipe, recipeId );
      xml = "<krecipes version=\"0.4\" lang=\""+(KGlobal::locale())->country()+"\" >\n";
    }
    else{
      xml = "";
    }
    xml +="<krecipes-recipe>";
    xml += "<krecipes-description>\n";
    xml += "<title>"+recipe->title.utf8()+"</title>\n";
    for (Element *el = (recipe->authorList).getFirst(); el; el= (recipe->authorList).getNext()){
      xml += "<author>"+el->name.utf8()+"</author>\n";
    }
    xml += "<pictures>\n";
    xml += "<pic format=\"JPEG\" id=\"1\"><![CDATA["; //fixed id until we implement multiple photos ability
    KTempFile* fn = new KTempFile (locateLocal("tmp", "kre"), ".jpg", 0600);
    recipe->photo.save(fn->name(), "JPEG");
    QByteArray data;
    if( fn ){
      data = (fn->file())->readAll();
      fn->close();
      xml += KCodecs::base64Encode(data, true);
    }
    xml += "]]></pic>\n";
    xml += "</pictures>\n";
    xml += "<category>\n";
    for (Element *ct = (recipe->categoryList).getFirst(); ct; ct= (recipe->categoryList).getNext()){
      xml += "<cat>"+ct->name.utf8()+"</cat>\n";
    }
    xml += "</category>\n";
    xml += "<serving>";
    xml += QString::number(recipe->persons);
    xml += "</serving>\n";
    xml += "</krecipes-description>\n";
    xml += "<krecipes-ingredients>\n";
    for (Ingredient* in = (recipe->ingList).getFirst(); in; in= (recipe->ingList).getNext()){
      xml += "<ingredient>\n";
      xml += "<name>"+in->name.utf8()+"</name>\n";
      xml += "<amount>";
      xml += QString::number(in->amount);
      xml += "</amount>\n";
      xml += "<unit>"+in->units.utf8()+"</unit>\n";
      xml += "</ingredient>\n";
      /// @todo add ingredient properties
    }
    xml += "</krecipes-ingredients>\n";
    xml += "<krecipes-instructions>\n";
    xml += recipe->instructions.utf8();
    xml += "</krecipes-instructions>\n";
    xml += "</krecipes-recipe>\n";
    if(recipeId != -1){
      xml += "</krecipes>\n";
    }
    return xml;
}
<|endoftext|>


<commit_before>#pragma once
/*
**  Copyright (C) 2013 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_TYPE_PROXYPROPERTY_HPP_
#define _QI_TYPE_PROXYPROPERTY_HPP_

#include <qi/log.hpp>
#include <qi/property.hpp>
#include <qi/anyfunction.hpp>

namespace qi
{
  /** Property proxy using AnyObject as backend
  * @warning reading and writing the property are synchronous operations
  * and might take time if backend object is a remote proxy.
  */
  template < typename T, template< class...> class PropertyType = Property >
  class ProxyProperty: public PropertyType<T>
  {
  public:
    using SignalType = SignalF<void (const T&)>;
    using ThisProxyType = ProxyProperty;
    ProxyProperty() {}
    /* The signal bounce code is completely duplicated from SignalProxy.
     * Unfortunately factoring this is not trivial:
     * onSubscribe needs to be passed to Signal constructor, and we want to keep
     * it that way.
    */
    ProxyProperty(AnyObject object, const std::string& propertyName)
    {
      setup(object, propertyName);
    }
    void setup(AnyObject object, const std::string& propertyName);
    ~ProxyProperty();
    Future<void> onSubscribe(bool enable, GenericObject* object, const std::string& propertyName, SignalLink link);
    AnyReference bounceEvent(const AnyReferenceVector args);
    void triggerOverride(const GenericFunctionParameters& params, MetaCallType, GenericObject* object, const std::string& propertyName);
  private:
    T getter(GenericObject* object, const std::string& propertyName);
    bool setter(T&, const T&, GenericObject* object, const std::string& propertyName);
  };

  template<typename T, template< class...> class PropertyType>
  void makeProxyProperty(PropertyType<T>& target, AnyObject object, const std::string& signalName)
  {
    ProxyProperty<T, PropertyType>& proxy = static_cast<ProxyProperty<T, PropertyType> &>(target);
    proxy.setup(object, signalName);
  }
  template<typename T, template< class...> class PropertyType>
  void makeProxyProperty(ProxyProperty<T, PropertyType>& target, AnyObject object, const std::string& signalName)
  {
    target.setup(object, signalName);
  }

  template<typename T, template< class...> class PropertyType>
  ProxyProperty<T, PropertyType>::~ProxyProperty()
  {
    SignalType::disconnectAll();
  }

  template<typename T, template< class...> class PropertyType>
  void ProxyProperty<T, PropertyType>::setup(AnyObject object, const std::string& propertyName)
  {
    // signal part
    SignalBase::setOnSubscribers(boost::bind(&ThisProxyType::onSubscribe, this, _1,
      object.asGenericObject(), propertyName, SignalBase::invalidSignalLink));
    SignalBase::setTriggerOverride(boost::bind(&ThisProxyType::triggerOverride, this, _1, _2,
      object.asGenericObject(), propertyName));

    // property part
    this->_getter = boost::bind(&ThisProxyType::getter, this, object.asGenericObject(), propertyName);
    this->_setter = boost::bind(&ThisProxyType::setter, this, _1, _2, object.asGenericObject(), propertyName);
  }

  template<typename T, template< class...> class PropertyType>
  Future<void> ProxyProperty<T, PropertyType>::onSubscribe(bool enable, GenericObject* object, const std::string& propertyName, SignalLink link)
  {
    if (enable)
    {
      link = object->connect(propertyName,
          SignalSubscriber(
            AnyFunction::fromDynamicFunction(boost::bind(&ThisProxyType::bounceEvent, this, _1))
            )).value();
    }
    else
    {
      bool ok = !object->disconnect(link).hasError();
      if (!ok)
        qiLogError("qitype.proxysignal") << "Failed to disconnect from parent signal";
      link = SignalBase::invalidSignalLink;
    }
    // rebind onSubscribe since link changed
    SignalBase::setOnSubscribers(boost::bind(&ThisProxyType::onSubscribe, this, _1,
      object, propertyName, link));
    return Future<void>{0};
  }

  template<typename T, template< class...> class PropertyType>
  AnyReference ProxyProperty<T, PropertyType>::bounceEvent(const AnyReferenceVector args)
  {
    // Receive notify from backend, trigger on our signal, bypassing our trigger overload
    SignalType::callSubscribers(args);
    return AnyReference(typeOf<void>());
  }

  template<typename T, template< class...> class PropertyType>
  void ProxyProperty<T, PropertyType>::triggerOverride(const GenericFunctionParameters& params, MetaCallType,
    GenericObject* object, const std::string& propertyName)
  {
    // Just forward to backend, which will notify us in bouceEvent(),
    // and then we will notify our local Subscribers
    object->metaPost(propertyName, params);
  }
  template<typename T, template< class...> class PropertyType>
  T ProxyProperty<T, PropertyType>::getter(GenericObject* object, const std::string& propertyName)
  {
    return object->property<T>(propertyName);
  }
  template<typename T, template< class...> class PropertyType>
  bool ProxyProperty<T, PropertyType>::setter(T& target, const T& v, GenericObject* object, const std::string& propertyName)
  {
    // no need to fill target it's never used since we have a getter
    object->setProperty(propertyName, v).value(); // throw on remote error
    // Prevent local subscribers from being called
    return false;
  }
}
#endif  // _QITYPE_PROXYPROPERTY_HPP_
<commit_msg>Proxy Property: fix implicit cast warning<commit_after>#pragma once
/*
**  Copyright (C) 2013 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QI_TYPE_PROXYPROPERTY_HPP_
#define _QI_TYPE_PROXYPROPERTY_HPP_

#include <qi/log.hpp>
#include <qi/property.hpp>
#include <qi/anyfunction.hpp>

namespace qi
{
  /** Property proxy using AnyObject as backend
  * @warning reading and writing the property are synchronous operations
  * and might take time if backend object is a remote proxy.
  */
  template < typename T, template< class...> class PropertyType = Property >
  class ProxyProperty: public PropertyType<T>
  {
  public:
    using SignalType = SignalF<void (const T&)>;
    using ThisProxyType = ProxyProperty;
    ProxyProperty() {}
    /* The signal bounce code is completely duplicated from SignalProxy.
     * Unfortunately factoring this is not trivial:
     * onSubscribe needs to be passed to Signal constructor, and we want to keep
     * it that way.
    */
    ProxyProperty(AnyObject object, const std::string& propertyName)
    {
      setup(object, propertyName);
    }
    void setup(AnyObject object, const std::string& propertyName);
    ~ProxyProperty();
    Future<void> onSubscribe(bool enable, GenericObject* object, const std::string& propertyName, SignalLink link);
    AnyReference bounceEvent(const AnyReferenceVector args);
    void triggerOverride(const GenericFunctionParameters& params, MetaCallType, GenericObject* object, const std::string& propertyName);
  private:
    T getter(GenericObject* object, const std::string& propertyName);
    bool setter(T&, const T&, GenericObject* object, const std::string& propertyName);
  };

  template<typename T, template< class...> class PropertyType>
  void makeProxyProperty(PropertyType<T>& target, AnyObject object, const std::string& signalName)
  {
    ProxyProperty<T, PropertyType>& proxy = static_cast<ProxyProperty<T, PropertyType> &>(target);
    proxy.setup(object, signalName);
  }
  template<typename T, template< class...> class PropertyType>
  void makeProxyProperty(ProxyProperty<T, PropertyType>& target, AnyObject object, const std::string& signalName)
  {
    target.setup(object, signalName);
  }

  template<typename T, template< class...> class PropertyType>
  ProxyProperty<T, PropertyType>::~ProxyProperty()
  {
    SignalType::disconnectAll();
  }

  template<typename T, template< class...> class PropertyType>
  void ProxyProperty<T, PropertyType>::setup(AnyObject object, const std::string& propertyName)
  {
    // signal part
    SignalBase::setOnSubscribers(boost::bind(&ThisProxyType::onSubscribe, this, _1,
      object.asGenericObject(), propertyName, SignalBase::invalidSignalLink));
    SignalBase::setTriggerOverride(boost::bind(&ThisProxyType::triggerOverride, this, _1, _2,
      object.asGenericObject(), propertyName));

    // property part
    this->_getter = boost::bind(&ThisProxyType::getter, this, object.asGenericObject(), propertyName);
    this->_setter = boost::bind(&ThisProxyType::setter, this, _1, _2, object.asGenericObject(), propertyName);
  }

  template<typename T, template< class...> class PropertyType>
  Future<void> ProxyProperty<T, PropertyType>::onSubscribe(bool enable, GenericObject* object, const std::string& propertyName, SignalLink link)
  {
    if (enable)
    {
      link = object->connect(propertyName,
          SignalSubscriber(
            AnyFunction::fromDynamicFunction(boost::bind(&ThisProxyType::bounceEvent, this, _1))
            )).value();
    }
    else
    {
      bool ok = !object->disconnect(link).hasError();
      if (!ok)
        qiLogError("qitype.proxysignal") << "Failed to disconnect from parent signal";
      link = SignalBase::invalidSignalLink;
    }
    // rebind onSubscribe since link changed
    SignalBase::setOnSubscribers(boost::bind(&ThisProxyType::onSubscribe, this, _1,
      object, propertyName, link));
    return Future<void>{nullptr};
  }

  template<typename T, template< class...> class PropertyType>
  AnyReference ProxyProperty<T, PropertyType>::bounceEvent(const AnyReferenceVector args)
  {
    // Receive notify from backend, trigger on our signal, bypassing our trigger overload
    SignalType::callSubscribers(args);
    return AnyReference(typeOf<void>());
  }

  template<typename T, template< class...> class PropertyType>
  void ProxyProperty<T, PropertyType>::triggerOverride(const GenericFunctionParameters& params, MetaCallType,
    GenericObject* object, const std::string& propertyName)
  {
    // Just forward to backend, which will notify us in bouceEvent(),
    // and then we will notify our local Subscribers
    object->metaPost(propertyName, params);
  }
  template<typename T, template< class...> class PropertyType>
  T ProxyProperty<T, PropertyType>::getter(GenericObject* object, const std::string& propertyName)
  {
    return object->property<T>(propertyName);
  }
  template<typename T, template< class...> class PropertyType>
  bool ProxyProperty<T, PropertyType>::setter(T& target, const T& v, GenericObject* object, const std::string& propertyName)
  {
    // no need to fill target it's never used since we have a getter
    object->setProperty(propertyName, v).value(); // throw on remote error
    // Prevent local subscribers from being called
    return false;
  }
}
#endif  // _QITYPE_PROXYPROPERTY_HPP_
<|endoftext|>


<commit_before>//  A C++ I/O streams interface to the zlib gz* functions
//
// Written by Bernie Bright, 1998
// Based on zlib/contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
//
// Copyright (C) 1998  Bernie Bright - bbright@c031.aone.net.au
//
// This program 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.
//
// This program 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 more 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$

#ifndef _zfstream_hxx
#define _zfstream_hxx

#include <simgear/compiler.h>

#ifdef HAVE_ZLIB
#  include <zlib.h>
#else
#  include <simgear/zlib/zlib.h>
#endif

#ifdef FG_HAVE_STD_INCLUDES

#  include <streambuf>
#  include <istream>

#  define ios_openmode ios_base::openmode
#  define ios_in       ios_base::in
#  define ios_out      ios_base::out
#  define ios_app      ios_base::app
#  define ios_binary   ios_base::binary

#  define ios_seekdir  ios_base::seekdir

#  define ios_badbit   ios_base::badbit
#  define ios_failbit  ios_base::failbit

FG_USING_STD(streambuf);
FG_USING_STD(ios_base);
FG_USING_STD(streampos);
FG_USING_STD(streamoff);

#else

#  ifdef FG_HAVE_STREAMBUF
#    include <streambuf.h>
#    include <istream.h>
#  else
#    include <iostream.h>
#  endif

//#  define ios_openmode ios::open_mode
#  define ios_openmode int
#  define ios_in       ios::in
#  define ios_out      ios::out
#  define ios_app      ios::app

#if defined(__GNUC__) && __GNUC_MINOR__ < 8
#  define ios_binary   ios::bin
#elif defined( FG_HAVE_NATIVE_SGI_COMPILERS )
#  define ios_binary   0
#else
#  define ios_binary   ios::binary
#endif

#  define ios_seekdir  ios::seek_dir

#  define ios_badbit   ios::badbit
#  define ios_failbit  ios::failbit

#  include <simgear/fg_traits.hxx>

#endif // FG_HAVE_STD_INCLUDES

//-----------------------------------------------------------------------------
//
//
//
class gzfilebuf : public streambuf
{
public:

#ifndef FG_HAVE_STD_INCLUDES
    typedef char_traits<char>           traits_type;
    typedef char_traits<char>::int_type int_type;
    typedef char_traits<char>::pos_type pos_type;
    typedef char_traits<char>::off_type off_type;
#endif

    gzfilebuf();
    virtual ~gzfilebuf();

    gzfilebuf* open( const char* name, ios_openmode io_mode );
    gzfilebuf* attach( int file_descriptor, ios_openmode io_mode );
    gzfilebuf* close();

//     int setcompressionlevel( int comp_level );
//     int setcompressionstrategy( int comp_strategy );
    bool is_open() const { return (file != NULL); }
    virtual streampos seekoff( streamoff off, ios_seekdir way, int which );
    virtual int sync();

protected:

    virtual int_type underflow();
    virtual int_type overflow( int_type c = traits_type::eof() );

private:

    int_type flushbuf();
    int fillbuf();

    // Convert io_mode to "rwab" string.
    void cvt_iomode( char* mode_str, ios_openmode io_mode );

private:

    gzFile file;
    ios_openmode mode;
    bool own_file_descriptor;

    // Get (input) buffer.
    int ibuf_size;
    char* ibuffer;

    enum { page_size = 4096 };

private:
    // Not defined
    gzfilebuf( const gzfilebuf& );
    void operator= ( const gzfilebuf& );
};

//-----------------------------------------------------------------------------
//
//
//
struct gzifstream_base
{
    gzifstream_base() {}

    gzfilebuf gzbuf;
};

#endif // _zfstream_hxx

<commit_msg>#include "config.h"<commit_after>//  A C++ I/O streams interface to the zlib gz* functions
//
// Written by Bernie Bright, 1998
// Based on zlib/contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
//
// Copyright (C) 1998  Bernie Bright - bbright@c031.aone.net.au
//
// This program 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.
//
// This program 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 more 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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$

#ifndef _zfstream_hxx
#define _zfstream_hxx

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <simgear/compiler.h>

#ifdef HAVE_ZLIB
#  include <zlib.h>
#else
#  include <simgear/zlib/zlib.h>
#endif

#ifdef FG_HAVE_STD_INCLUDES

#  include <streambuf>
#  include <istream>

#  define ios_openmode ios_base::openmode
#  define ios_in       ios_base::in
#  define ios_out      ios_base::out
#  define ios_app      ios_base::app
#  define ios_binary   ios_base::binary

#  define ios_seekdir  ios_base::seekdir

#  define ios_badbit   ios_base::badbit
#  define ios_failbit  ios_base::failbit

FG_USING_STD(streambuf);
FG_USING_STD(ios_base);
FG_USING_STD(streampos);
FG_USING_STD(streamoff);

#else

#  ifdef FG_HAVE_STREAMBUF
#    include <streambuf.h>
#    include <istream.h>
#  else
#    include <iostream.h>
#  endif

//#  define ios_openmode ios::open_mode
#  define ios_openmode int
#  define ios_in       ios::in
#  define ios_out      ios::out
#  define ios_app      ios::app

#if defined(__GNUC__) && __GNUC_MINOR__ < 8
#  define ios_binary   ios::bin
#elif defined( FG_HAVE_NATIVE_SGI_COMPILERS )
#  define ios_binary   0
#else
#  define ios_binary   ios::binary
#endif

#  define ios_seekdir  ios::seek_dir

#  define ios_badbit   ios::badbit
#  define ios_failbit  ios::failbit

#  include <simgear/fg_traits.hxx>

#endif // FG_HAVE_STD_INCLUDES

//-----------------------------------------------------------------------------
//
//
//
class gzfilebuf : public streambuf
{
public:

#ifndef FG_HAVE_STD_INCLUDES
    typedef char_traits<char>           traits_type;
    typedef char_traits<char>::int_type int_type;
    typedef char_traits<char>::pos_type pos_type;
    typedef char_traits<char>::off_type off_type;
#endif

    gzfilebuf();
    virtual ~gzfilebuf();

    gzfilebuf* open( const char* name, ios_openmode io_mode );
    gzfilebuf* attach( int file_descriptor, ios_openmode io_mode );
    gzfilebuf* close();

//     int setcompressionlevel( int comp_level );
//     int setcompressionstrategy( int comp_strategy );
    bool is_open() const { return (file != NULL); }
    virtual streampos seekoff( streamoff off, ios_seekdir way, int which );
    virtual int sync();

protected:

    virtual int_type underflow();
    virtual int_type overflow( int_type c = traits_type::eof() );

private:

    int_type flushbuf();
    int fillbuf();

    // Convert io_mode to "rwab" string.
    void cvt_iomode( char* mode_str, ios_openmode io_mode );

private:

    gzFile file;
    ios_openmode mode;
    bool own_file_descriptor;

    // Get (input) buffer.
    int ibuf_size;
    char* ibuffer;

    enum { page_size = 4096 };

private:
    // Not defined
    gzfilebuf( const gzfilebuf& );
    void operator= ( const gzfilebuf& );
};

//-----------------------------------------------------------------------------
//
//
//
struct gzifstream_base
{
    gzifstream_base() {}

    gzfilebuf gzbuf;
};

#endif // _zfstream_hxx

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DirectoryNames.h"

/* implementation system headers */
#ifndef _WIN32
#  include <stdlib.h>
#  include <unistd.h>
#  include <sys/types.h>
#  include <pwd.h>
#else   // _WIN32
#  include <sys/types.h>
#  include <sys/stat.h>
#  include <stdio.h>
#  include <direct.h>
#  include <shlobj.h>
#endif  // _WIN32
#if defined(__APPLE__)
#  include <CoreServices/CoreServices.h>
#endif

// NOTE: terminate all strings with '/' or '\\'

static std::string		setupString(std::string dir)
{
  std::string name = getConfigDirName();
  name += dir;
  name += DirectorySeparator;
  return name;
}

std::string		getConfigDirName( const char* versionName )
{
#if defined(_WIN32)
  std::string name("C:");
  char dir[MAX_PATH];
  ITEMIDLIST* idl;
  if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &idl))) {
    if (SHGetPathFromIDList(idl, dir)) {
      struct stat statbuf;
      if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)
	name = dir;
    }

    IMalloc* shalloc;
    if (SUCCEEDED(SHGetMalloc(&shalloc))) {
      shalloc->Free(idl);
      shalloc->Release();
    }
  }

  // yes your suposed to have the "my" in front of it. I know it's silly, but it's the MS way.
  name += "\\My BZFlag Files\\";
	if (versionName)
	{
		name += versionName;
		name += "\\";
	}
  return name;

#elif defined(__APPLE__)
  std::string name;
  ::FSRef libraryFolder;
  ::OSErr err;
  err = ::FSFindFolder(::kUserDomain, ::kApplicationSupportFolderType, true, &libraryFolder);
  if(err == ::noErr) {
    char buff[1024];
    err = ::FSRefMakePath(&libraryFolder, (UInt8*)buff, sizeof(buff));
    if(err == ::noErr) {
      std::strcat(buff, "/BZFlag/");
			if (versionName)
			{
				std::strcat(buff, versionName);
				std::strcat(buff,"/");
			}
     name = buff;
    }
  }
  return name;
#else
  std::string name;
  struct passwd *pwent = getpwuid(getuid());
  if (pwent && pwent->pw_dir) {
    name += std::string(pwent->pw_dir);
    name += "/";
  }
  name += ".bzf/";
	if (versionName)
	{
		name+= versionName;
		name+="/";
	}
  return name;
#endif
}

extern std::string		getCacheDirName()
{
  std::string name = getConfigDirName();
  name += "cache";
#if !defined (_WIN32) && !defined (__APPLE__)
  // add in hostname on UNIX
  if (getenv("HOST")) {
    name += ".";
    name += getenv("HOST");
  }
#endif
  name += DirectorySeparator;
  return name;
}

extern std::string		getRecordDirName()
{
  return setupString("recordings");
}

extern std::string		getScreenShotDirName()
{
  return setupString("screenshots");
}

extern std::string		getTempDirName()
{
// FIXME: needs something for Windows and maybe other platforms
#if defined(_WIN32)
	std::string name = getConfigDirName();
	name += "temp";
#else
  std::string name;
  if (getenv("TMPDIR")) {
    name = getenv("TMPDIR");
  } else {
    name = "/tmp";
  }
#endif
  name += DirectorySeparator;
  return name;
}

extern std::string		getWorldDirName()
{
  return setupString("worlds");
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>FIXME should be able to share the cache tween HOSTs<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DirectoryNames.h"

/* implementation system headers */
#ifndef _WIN32
#  include <stdlib.h>
#  include <unistd.h>
#  include <sys/types.h>
#  include <pwd.h>
#else   // _WIN32
#  include <sys/types.h>
#  include <sys/stat.h>
#  include <stdio.h>
#  include <direct.h>
#  include <shlobj.h>
#endif  // _WIN32
#if defined(__APPLE__)
#  include <CoreServices/CoreServices.h>
#endif

// NOTE: terminate all strings with '/' or '\\'

static std::string		setupString(std::string dir)
{
  std::string name = getConfigDirName();
  name += dir;
  name += DirectorySeparator;
  return name;
}

std::string		getConfigDirName( const char* versionName )
{
#if defined(_WIN32)
  std::string name("C:");
  char dir[MAX_PATH];
  ITEMIDLIST* idl;
  if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &idl))) {
    if (SHGetPathFromIDList(idl, dir)) {
      struct stat statbuf;
      if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)
	name = dir;
    }

    IMalloc* shalloc;
    if (SUCCEEDED(SHGetMalloc(&shalloc))) {
      shalloc->Free(idl);
      shalloc->Release();
    }
  }

  // yes your suposed to have the "my" in front of it. I know it's silly, but it's the MS way.
  name += "\\My BZFlag Files\\";
	if (versionName)
	{
		name += versionName;
		name += "\\";
	}
  return name;

#elif defined(__APPLE__)
  std::string name;
  ::FSRef libraryFolder;
  ::OSErr err;
  err = ::FSFindFolder(::kUserDomain, ::kApplicationSupportFolderType, true, &libraryFolder);
  if(err == ::noErr) {
    char buff[1024];
    err = ::FSRefMakePath(&libraryFolder, (UInt8*)buff, sizeof(buff));
    if(err == ::noErr) {
      std::strcat(buff, "/BZFlag/");
			if (versionName)
			{
				std::strcat(buff, versionName);
				std::strcat(buff,"/");
			}
     name = buff;
    }
  }
  return name;
#else
  std::string name;
  struct passwd *pwent = getpwuid(getuid());
  if (pwent && pwent->pw_dir) {
    name += std::string(pwent->pw_dir);
    name += "/";
  }
  name += ".bzf/";
	if (versionName)
	{
		name+= versionName;
		name+="/";
	}
  return name;
#endif
}

extern std::string		getCacheDirName()
{
  std::string name = getConfigDirName();
  name += "cache";
#if !defined (_WIN32) && !defined (__APPLE__)
  // add in hostname on UNIX
  // FIXME should be able to share the cache
  if (getenv("HOST")) {
    name += ".";
    name += getenv("HOST");
  }
#endif
  name += DirectorySeparator;
  return name;
}

extern std::string		getRecordDirName()
{
  return setupString("recordings");
}

extern std::string		getScreenShotDirName()
{
  return setupString("screenshots");
}

extern std::string		getTempDirName()
{
// FIXME: needs something for Windows and maybe other platforms
#if defined(_WIN32)
	std::string name = getConfigDirName();
	name += "temp";
#else
  std::string name;
  if (getenv("TMPDIR")) {
    name = getenv("TMPDIR");
  } else {
    name = "/tmp";
  }
#endif
  name += DirectorySeparator;
  return name;
}

extern std::string		getWorldDirName()
{
  return setupString("worlds");
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include <QtWidgets>

#ifdef QT_OPENGL_LIB
#include <QtOpenGL/QGLWidget>
#endif

#include "editorView.h"

using namespace qReal;

EditorView::EditorView(QWidget *parent)
	: QGraphicsView(parent)
	, mMouseOldPosition()
	, mWheelPressed(false)
	, mZoom(0)
	, mTouchManager(this)
{
	setRenderHint(QPainter::Antialiasing, true);

	mScene = new EditorViewScene(this);
	connect(mScene, SIGNAL(zoomIn()), this, SLOT(zoomIn()));
	connect(mScene, SIGNAL(zoomOut()), this, SLOT(zoomOut()));

	setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
	setResizeAnchor(QGraphicsView::AnchorUnderMouse);

	mMVIface = new EditorViewMViface(this, mScene);
	setScene(mScene);

	setAcceptDrops(true);
	setDragMode(RubberBandDrag);
	setEnabled(false);

	setMouseTracking(true);

	setAlignment(Qt::AlignCenter);

	connect(&mTouchManager, SIGNAL(gestureStarted()), mScene, SLOT(deleteGesture()));
}

EditorView::~EditorView()
{
	delete mMVIface;
	delete mScene;
}

EditorViewMViface *EditorView::mvIface() const
{
	return mMVIface;
}

EditorViewScene *EditorView::editorViewScene() const
{
	return mScene;
}

void EditorView::toggleAntialiasing(bool checked)
{
	setRenderHint(QPainter::Antialiasing, checked);
	setRenderHint(QPainter::SmoothPixmapTransform, checked);
}

void EditorView::toggleOpenGL(bool checked)
{
	Q_UNUSED(checked)
#ifdef QT_OPENGL_LIB
			setViewport(checked ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget);
#endif
}

void EditorView::zoomIn()
{
	if (mWheelPressed || mZoom >= SettingsManager::value("maxZoom").toInt()) {
		return;
	}

	QTimeLine *animation = new QTimeLine(300, this);
	animation->setUpdateInterval(20);
	connect(animation, SIGNAL(valueChanged(qreal)), this, SLOT(zoomInTime()));
	connect(animation, SIGNAL(finished()), this, SLOT(animFinished()));
	animation->start();

	++mZoom;
}

void EditorView::zoomOut()
{
	if (mWheelPressed || mZoom <= SettingsManager::value("minZoom").toInt()) {
		return;
	}

	QTimeLine *anim = new QTimeLine(300, this);
	anim->setUpdateInterval(20);

	connect(anim, SIGNAL(valueChanged(qreal)), this, SLOT(zoomOutTime()));
	connect(anim, SIGNAL(finished()), this, SLOT(animFinished()));
	anim->start();

	--mZoom;
}

void EditorView::checkGrid()
{
	if (SettingsManager::value("ShowGrid").toBool()) {
		mScene->setNeedDrawGrid(mScene->realIndexGrid() >= 2 && mScene->realIndexGrid() <= 380);
	}
}

void EditorView::setMainWindow(qReal::MainWindow *mainWindow)
{
	mMVIface->scene()->setMainWindow(mainWindow);
}

void EditorView::setDrawSceneGrid(bool show)
{
	mScene->setNeedDrawGrid(show);
	mScene->invalidate();
}

void EditorView::mouseMoveEvent(QMouseEvent *event)
{
	if (mWheelPressed) {
		if (mMouseOldPosition != QPointF()) {
			QRectF rect = sceneRect();
			qreal dx = (event->localPos().x() - mMouseOldPosition.x());
			qreal dy = (event->localPos().y() - mMouseOldPosition.y());
			rect.moveLeft(rect.left() - dx);
			rect.moveTop(rect.top() - dy);
			setSceneRect(rect);
			translate(dx, dy);
		}
		mMouseOldPosition = event->localPos();
	}
	QGraphicsView::mouseMoveEvent(event);
	if (event->buttons() & Qt::RightButton) {
		setDragMode(NoDrag);
	} else {
		if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ControlModifier)) {
			setDragMode(RubberBandDrag);
			mScene->itemSelectUpdate();
		/*} else 	if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ShiftModifier)) {
			setDragMode(ScrollHandDrag); //  (see #615)
			mScene->itemSelectUpdate();*/
		} else if (event->buttons() & Qt::LeftButton ) {
			EdgeElement *newEdgeEl = dynamic_cast<EdgeElement *>(itemAt(event->pos()));
			if (newEdgeEl && newEdgeEl->isBreakPointPressed()) {
				newEdgeEl->breakPointUnpressed();
				setDragMode(NoDrag);
			}
		}
	}
	if (mScene->getNeedDrawGrid())
		mScene->invalidate();
}

void EditorView::mouseReleaseEvent(QMouseEvent *event)
{
	if (!(event->buttons() & Qt::MidButton)) {
		mWheelPressed = false;
		mMouseOldPosition = QPointF();
	}
	QGraphicsView::mouseReleaseEvent(event);
	if (mScene->getNeedDrawGrid()) {
		mScene->invalidate();
	}
}

void EditorView::mousePressEvent(QMouseEvent *event)
{
	mWheelPressed  = (event->buttons() & Qt::MidButton);
	mMouseOldPosition = QPointF();
	if (!mWheelPressed) {
		QGraphicsView::mousePressEvent(event);
	}
	if (event->buttons() & Qt::LeftButton) {
		if (!(event->buttons() & Qt::RightButton) && !mTouchManager.isGestureRunning()) {
			setDragMode(RubberBandDrag);
		}
		if (event->modifiers() & Qt::ControlModifier) {
			mScene->itemSelectUpdate();
		}
	}
}

void EditorView::scrollContentsBy(int dx, int dy)
{
	QGraphicsView::scrollContentsBy(dx, dy);
	if (mScene->getNeedDrawGrid()) {
		mScene->invalidate();
	}
}

void EditorView::keyPressEvent(QKeyEvent *event)
{
	QGraphicsView::keyPressEvent(event);
	if (event->key() == Qt::Key_Space) {
		setDragMode(QGraphicsView::ScrollHandDrag);
		event->accept();
	}
}

void EditorView::keyReleaseEvent(QKeyEvent *event)
{
	if (event->key() == Qt::Key_Space) {
		setDragMode(QGraphicsView::RubberBandDrag);
	} else {
		QGraphicsView::keyPressEvent(event);
	}
}

bool EditorView::viewportEvent(QEvent *event)
{
	switch (event->type()) {
	case QEvent::TouchBegin:
	case QEvent::TouchUpdate:
	case QEvent::TouchEnd:
		// For some reason touch viewport events can`t be processed in manual event
		// filters, so catching them here
		return mTouchManager.processTouchEvent(static_cast<QTouchEvent *>(event));
	default:
		break;
	}
	return QGraphicsView::viewportEvent(event);
}

void EditorView::invalidateScene()
{
	scene()->invalidate();
}

void EditorView::ensureElementVisible(Element const * const element)
{
	if (element) {
		qreal const widgetWidth = size().width();
		qreal const widgetHeight = size().height();
		qreal const elementWidth = element->boundingRect().width();
		qreal const elementHeight = element->boundingRect().height();
		ensureVisible(element, (widgetWidth - elementWidth) / 2, (widgetHeight - elementHeight) / 2);
	}
}

void EditorView::ensureElementVisible(Element const * const element
		, int xMargin, int yMargin)
{
	if (element) {
		ensureVisible(element, xMargin, yMargin);
	}
}

void EditorView::setTitlesVisible(bool visible)
{
	mScene->setTitlesVisible(visible);
}

void EditorView::zoomInTime()
{
	qreal const zoomFactor = static_cast<qreal>(SettingsManager::value("zoomFactor").toInt()) / (10 + 15) + 1;
	zoom(zoomFactor);
}

void EditorView::zoomOutTime()
{
	qreal const zoomFactor = 1 / (static_cast<qreal>(SettingsManager::value("zoomFactor").toInt()) / (10 + 15) + 1);
	zoom(zoomFactor);
}

void EditorView::animFinished()
{
	delete sender();
}

void EditorView::zoom(qreal const zoomFactor)
{
	setSceneRect(mScene->sceneRect());
	scale(zoomFactor, zoomFactor);

	if (SettingsManager::value("ShowGrid").toBool()) {
		mScene->setRealIndexGrid(mScene->realIndexGrid() * zoomFactor);
	}
	checkGrid();
}
<commit_msg>Fixed rubber band when moving elements after gestures<commit_after>#include <QtWidgets>

#ifdef QT_OPENGL_LIB
#include <QtOpenGL/QGLWidget>
#endif

#include "editorView.h"

using namespace qReal;

EditorView::EditorView(QWidget *parent)
	: QGraphicsView(parent)
	, mMouseOldPosition()
	, mWheelPressed(false)
	, mZoom(0)
	, mTouchManager(this)
{
	setRenderHint(QPainter::Antialiasing, true);

	mScene = new EditorViewScene(this);
	connect(mScene, SIGNAL(zoomIn()), this, SLOT(zoomIn()));
	connect(mScene, SIGNAL(zoomOut()), this, SLOT(zoomOut()));

	setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
	setResizeAnchor(QGraphicsView::AnchorUnderMouse);

	mMVIface = new EditorViewMViface(this, mScene);
	setScene(mScene);

	setAcceptDrops(true);
	setDragMode(RubberBandDrag);
	setEnabled(false);

	setMouseTracking(true);

	setAlignment(Qt::AlignCenter);

	connect(&mTouchManager, SIGNAL(gestureStarted()), mScene, SLOT(deleteGesture()));
}

EditorView::~EditorView()
{
	delete mMVIface;
	delete mScene;
}

EditorViewMViface *EditorView::mvIface() const
{
	return mMVIface;
}

EditorViewScene *EditorView::editorViewScene() const
{
	return mScene;
}

void EditorView::toggleAntialiasing(bool checked)
{
	setRenderHint(QPainter::Antialiasing, checked);
	setRenderHint(QPainter::SmoothPixmapTransform, checked);
}

void EditorView::toggleOpenGL(bool checked)
{
	Q_UNUSED(checked)
#ifdef QT_OPENGL_LIB
			setViewport(checked ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget);
#endif
}

void EditorView::zoomIn()
{
	if (mWheelPressed || mZoom >= SettingsManager::value("maxZoom").toInt()) {
		return;
	}

	QTimeLine *animation = new QTimeLine(300, this);
	animation->setUpdateInterval(20);
	connect(animation, SIGNAL(valueChanged(qreal)), this, SLOT(zoomInTime()));
	connect(animation, SIGNAL(finished()), this, SLOT(animFinished()));
	animation->start();

	++mZoom;
}

void EditorView::zoomOut()
{
	if (mWheelPressed || mZoom <= SettingsManager::value("minZoom").toInt()) {
		return;
	}

	QTimeLine *anim = new QTimeLine(300, this);
	anim->setUpdateInterval(20);

	connect(anim, SIGNAL(valueChanged(qreal)), this, SLOT(zoomOutTime()));
	connect(anim, SIGNAL(finished()), this, SLOT(animFinished()));
	anim->start();

	--mZoom;
}

void EditorView::checkGrid()
{
	if (SettingsManager::value("ShowGrid").toBool()) {
		mScene->setNeedDrawGrid(mScene->realIndexGrid() >= 2 && mScene->realIndexGrid() <= 380);
	}
}

void EditorView::setMainWindow(qReal::MainWindow *mainWindow)
{
	mMVIface->scene()->setMainWindow(mainWindow);
}

void EditorView::setDrawSceneGrid(bool show)
{
	mScene->setNeedDrawGrid(show);
	mScene->invalidate();
}

void EditorView::mouseMoveEvent(QMouseEvent *event)
{
	if (mWheelPressed) {
		if (mMouseOldPosition != QPointF()) {
			QRectF rect = sceneRect();
			qreal dx = (event->localPos().x() - mMouseOldPosition.x());
			qreal dy = (event->localPos().y() - mMouseOldPosition.y());
			rect.moveLeft(rect.left() - dx);
			rect.moveTop(rect.top() - dy);
			setSceneRect(rect);
			translate(dx, dy);
		}
		mMouseOldPosition = event->localPos();
	}
	QGraphicsView::mouseMoveEvent(event);
	if (event->buttons() & Qt::RightButton) {
		setDragMode(NoDrag);
	} else {
		if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ControlModifier)) {
			setDragMode(RubberBandDrag);
			mScene->itemSelectUpdate();
		/*} else 	if ((event->buttons() & Qt::LeftButton) && (event->modifiers() & Qt::ShiftModifier)) {
			setDragMode(ScrollHandDrag); //  (see #615)
			mScene->itemSelectUpdate();*/
		} else if (event->buttons() & Qt::LeftButton ) {
			EdgeElement *newEdgeEl = dynamic_cast<EdgeElement *>(itemAt(event->pos()));
			if (newEdgeEl && newEdgeEl->isBreakPointPressed()) {
				newEdgeEl->breakPointUnpressed();
				setDragMode(NoDrag);
			}
		}
	}
	if (mScene->getNeedDrawGrid())
		mScene->invalidate();
}

void EditorView::mouseReleaseEvent(QMouseEvent *event)
{
	if (!(event->buttons() & Qt::MidButton)) {
		mWheelPressed = false;
		mMouseOldPosition = QPointF();
	}
	QGraphicsView::mouseReleaseEvent(event);
	if (mScene->getNeedDrawGrid()) {
		mScene->invalidate();
	}
}

void EditorView::mousePressEvent(QMouseEvent *event)
{
	mWheelPressed  = (event->buttons() & Qt::MidButton);
	mMouseOldPosition = QPointF();
	if (!mWheelPressed) {
		QGraphicsView::mousePressEvent(event);
	}
	if (event->buttons() & Qt::LeftButton) {
		if (!(event->buttons() & Qt::RightButton) && !mTouchManager.isGestureRunning()
				&& !itemAt(event->pos())) {
			setDragMode(RubberBandDrag);
		}
		if (event->modifiers() & Qt::ControlModifier) {
			mScene->itemSelectUpdate();
		}
	}
}

void EditorView::scrollContentsBy(int dx, int dy)
{
	QGraphicsView::scrollContentsBy(dx, dy);
	if (mScene->getNeedDrawGrid()) {
		mScene->invalidate();
	}
}

void EditorView::keyPressEvent(QKeyEvent *event)
{
	QGraphicsView::keyPressEvent(event);
	if (event->key() == Qt::Key_Space) {
		setDragMode(QGraphicsView::ScrollHandDrag);
		event->accept();
	}
}

void EditorView::keyReleaseEvent(QKeyEvent *event)
{
	if (event->key() == Qt::Key_Space) {
		setDragMode(QGraphicsView::RubberBandDrag);
	} else {
		QGraphicsView::keyPressEvent(event);
	}
}

bool EditorView::viewportEvent(QEvent *event)
{
	switch (event->type()) {
	case QEvent::TouchBegin:
	case QEvent::TouchUpdate:
	case QEvent::TouchEnd:
		// For some reason touch viewport events can`t be processed in manual event
		// filters, so catching them here
		return mTouchManager.processTouchEvent(static_cast<QTouchEvent *>(event));
	default:
		break;
	}
	return QGraphicsView::viewportEvent(event);
}

void EditorView::invalidateScene()
{
	scene()->invalidate();
}

void EditorView::ensureElementVisible(Element const * const element)
{
	if (element) {
		qreal const widgetWidth = size().width();
		qreal const widgetHeight = size().height();
		qreal const elementWidth = element->boundingRect().width();
		qreal const elementHeight = element->boundingRect().height();
		ensureVisible(element, (widgetWidth - elementWidth) / 2, (widgetHeight - elementHeight) / 2);
	}
}

void EditorView::ensureElementVisible(Element const * const element
		, int xMargin, int yMargin)
{
	if (element) {
		ensureVisible(element, xMargin, yMargin);
	}
}

void EditorView::setTitlesVisible(bool visible)
{
	mScene->setTitlesVisible(visible);
}

void EditorView::zoomInTime()
{
	qreal const zoomFactor = static_cast<qreal>(SettingsManager::value("zoomFactor").toInt()) / (10 + 15) + 1;
	zoom(zoomFactor);
}

void EditorView::zoomOutTime()
{
	qreal const zoomFactor = 1 / (static_cast<qreal>(SettingsManager::value("zoomFactor").toInt()) / (10 + 15) + 1);
	zoom(zoomFactor);
}

void EditorView::animFinished()
{
	delete sender();
}

void EditorView::zoom(qreal const zoomFactor)
{
	setSceneRect(mScene->sceneRect());
	scale(zoomFactor, zoomFactor);

	if (SettingsManager::value("ShowGrid").toBool()) {
		mScene->setRealIndexGrid(mScene->realIndexGrid() * zoomFactor);
	}
	checkGrid();
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993-2010 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DirectoryNames.h"

/* implementation system headers */
#ifndef _WIN32
#  include <stdlib.h>
#  include <unistd.h>
#  include <sys/types.h>
#  include <pwd.h>
#else   // _WIN32
#  include <sys/types.h>
#  include <sys/stat.h>
#  include <stdio.h>
#  include <direct.h>
#  include <shlobj.h>
#endif  // _WIN32
#if defined(__APPLE__)
#  include <CoreServices/CoreServices.h>
#endif

// NOTE: terminate all strings with '/' or '\\'

std::string configDir(bool set, const char *str)
{
  static std::string customConfigDir = std::string("");
  if (set) {
    customConfigDir = std::string(str);
  }
  return customConfigDir;
}

void			setCustomConfigDir(const char *str)
{
	std::string dir = str;
	if (dir.size() > 2)
	{
		if (*dir.begin() == '"')
			dir.erase(dir.begin());

		if (*(dir.end()-1) == '"')
			dir.erase(dir.end()-1);

	}
  configDir(1, dir.c_str());
}

std::string		getConfigDirName( const char* versionName )
{
  std::string customConfigDir = configDir(0, NULL);

  if (customConfigDir.size() > 0)
    return customConfigDir;

#if defined(_WIN32)
  std::string name("C:");
  char dir[MAX_PATH];
  ITEMIDLIST* idl;
  if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &idl))) {
    if (SHGetPathFromIDList(idl, dir)) {
      struct stat statbuf;
      if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)
	name = dir;
    }

    IMalloc* shalloc;
    if (SUCCEEDED(SHGetMalloc(&shalloc))) {
      shalloc->Free(idl);
      shalloc->Release();
    }
  }

  // yes your suposed to have the "my" in front of it. I know it's silly, but it's the MS way.
  name += "\\My BZFlag Files\\";
  if (versionName) {
    name += versionName;
    name += "\\";
  }
  customConfigDir = name;
  return name;

#elif defined(__APPLE__)
  std::string name;
  ::FSRef libraryFolder;
  ::OSErr err;
  err = ::FSFindFolder(::kUserDomain, ::kApplicationSupportFolderType, true, &libraryFolder);
  if(err == ::noErr) {
    char buff[1024];
    err = ::FSRefMakePath(&libraryFolder, (UInt8*)buff, sizeof(buff));
    if(err == ::noErr) {
      std::strcat(buff, "/BZFlag/");
      if (versionName) {
	std::strcat(buff, versionName);
	std::strcat(buff, "/");
      }
     name = buff;
    }
  }
  customConfigDir = name;
  return name;
#else
  std::string name;
  struct passwd *pwent = getpwuid(getuid());
  if (pwent && pwent->pw_dir) {
    name += std::string(pwent->pw_dir);
    name += "/";
  }
  name += ".bzf/";
  if (versionName) {
    name += versionName;
    name += "/";
  }
  customConfigDir = name;
  return name;
#endif
}

static std::string		setupString(std::string dir)
{
  std::string name = getConfigDirName();
  name += dir;
  name += DirectorySeparator;
  return name;
}

std::string getCacheDirName()
{
  std::string name = getConfigDirName();
  name += "cache";
#if !defined (_WIN32) && !defined (__APPLE__)
  // add in hostname on UNIX
  // FIXME should be able to share the cache
  if (getenv("HOST")) {
    name += ".";
    name += getenv("HOST");
  }
#endif
  name += DirectorySeparator;
  return name;
}

std::string getRecordDirName()
{
  return setupString("recordings");
}

std::string getScreenShotDirName()
{
  return setupString("screenshots");
}

std::string getTempDirName()
{
// FIXME: needs something for Windows and maybe other platforms
#if defined(_WIN32)
  std::string name = getConfigDirName();
  name += "temp";
#else
  std::string name;
  if (getenv("TMPDIR")) {
    name = getenv("TMPDIR");
  } else {
    name = "/tmp";
  }
#endif
  name += DirectorySeparator;
  return name;
}

std::string getWorldDirName()
{
  return setupString("worlds");
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>move bzflag config on windows to local application data for the user<commit_after>/* bzflag
 * Copyright (c) 1993-2010 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "DirectoryNames.h"

/* implementation system headers */
#ifndef _WIN32
#  include <stdlib.h>
#  include <unistd.h>
#  include <sys/types.h>
#  include <pwd.h>
#else   // _WIN32
#  include <sys/types.h>
#  include <sys/stat.h>
#  include <stdio.h>
#  include <direct.h>
#  include <shlobj.h>
#endif  // _WIN32
#if defined(__APPLE__)
#  include <CoreServices/CoreServices.h>
#endif

// NOTE: terminate all strings with '/' or '\\'

std::string configDir(bool set, const char *str)
{
  static std::string customConfigDir = std::string("");
  if (set) {
    customConfigDir = std::string(str);
  }
  return customConfigDir;
}

void			setCustomConfigDir(const char *str)
{
	std::string dir = str;
	if (dir.size() > 2)
	{
		if (*dir.begin() == '"')
			dir.erase(dir.begin());

		if (*(dir.end()-1) == '"')
			dir.erase(dir.end()-1);

	}
  configDir(1, dir.c_str());
}

std::string		getConfigDirName( const char* versionName )
{
  std::string customConfigDir = configDir(0, NULL);

  if (customConfigDir.size() > 0)
    return customConfigDir;

#if defined(_WIN32)
  std::string name("C:");
  char dir[MAX_PATH];
  ITEMIDLIST* idl;
  if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_LOCAL_APPDATA , &idl))) {
    if (SHGetPathFromIDList(idl, dir)) {
      struct stat statbuf;
      if (stat(dir, &statbuf) == 0 && (statbuf.st_mode & _S_IFDIR) != 0)
	name = dir;
    }

    IMalloc* shalloc;
    if (SUCCEEDED(SHGetMalloc(&shalloc))) {
      shalloc->Free(idl);
      shalloc->Release();
    }
  }

  // yes your suposed to have the "my" in front of it. I know it's silly, but it's the MS way.
  name += "\\BZFlag\\";
  if (versionName) {
    name += versionName;
    name += "\\";
  }
  customConfigDir = name;
  return name;

#elif defined(__APPLE__)
  std::string name;
  ::FSRef libraryFolder;
  ::OSErr err;
  err = ::FSFindFolder(::kUserDomain, ::kApplicationSupportFolderType, true, &libraryFolder);
  if(err == ::noErr) {
    char buff[1024];
    err = ::FSRefMakePath(&libraryFolder, (UInt8*)buff, sizeof(buff));
    if(err == ::noErr) {
      std::strcat(buff, "/BZFlag/");
      if (versionName) {
	std::strcat(buff, versionName);
	std::strcat(buff, "/");
      }
     name = buff;
    }
  }
  customConfigDir = name;
  return name;
#else
  std::string name;
  struct passwd *pwent = getpwuid(getuid());
  if (pwent && pwent->pw_dir) {
    name += std::string(pwent->pw_dir);
    name += "/";
  }
  name += ".bzf/";
  if (versionName) {
    name += versionName;
    name += "/";
  }
  customConfigDir = name;
  return name;
#endif
}

static std::string		setupString(std::string dir)
{
  std::string name = getConfigDirName();
  name += dir;
  name += DirectorySeparator;
  return name;
}

std::string getCacheDirName()
{
  std::string name = getConfigDirName();
  name += "cache";
#if !defined (_WIN32) && !defined (__APPLE__)
  // add in hostname on UNIX
  // FIXME should be able to share the cache
  if (getenv("HOST")) {
    name += ".";
    name += getenv("HOST");
  }
#endif
  name += DirectorySeparator;
  return name;
}

std::string getRecordDirName()
{
  return setupString("recordings");
}

std::string getScreenShotDirName()
{
  return setupString("screenshots");
}

std::string getTempDirName()
{
// FIXME: needs something for Windows and maybe other platforms
#if defined(_WIN32)
  std::string name = getConfigDirName();
  name += "temp";
#else
  std::string name;
  if (getenv("TMPDIR")) {
    name = getenv("TMPDIR");
  } else {
    name = "/tmp";
  }
#endif
  name += DirectorySeparator;
  return name;
}

std::string getWorldDirName()
{
  return setupString("worlds");
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include "armnnOnnxParser/IOnnxParser.hpp"
#include "google/protobuf/repeated_field.h"
#include <unordered_map>

#include <onnx/onnx.pb.h>

namespace armnn
{
class TensorInfo;
enum class ActivationFunction;
}

namespace armnnOnnxParser
{

using ModelPtr = std::unique_ptr<onnx::ModelProto>;

class OnnxParserImpl
{

using OperationParsingFunction = void(OnnxParserImpl::*)(const onnx::NodeProto& NodeProto);

public:

    using GraphPtr = std::unique_ptr<onnx::GraphProto>;

    /// Create the network from a protobuf binary file on disk
    armnn::INetworkPtr CreateNetworkFromBinaryFile(const char* graphFile);

    /// Create the network from a protobuf binary file on disk, with inputShapes specified
    armnn::INetworkPtr CreateNetworkFromBinaryFile(const char* graphFile,
                                                   const std::map<std::string, armnn::TensorShape>& inputShapes);

    /// Create the network from a protobuf text file on disk
    armnn::INetworkPtr CreateNetworkFromTextFile(const char* graphFile);

    /// Create the network from a protobuf text file on disk, with inputShapes specified
    armnn::INetworkPtr CreateNetworkFromTextFile(const char* graphFile,
                                                 const std::map<std::string, armnn::TensorShape>& inputShapes);

    /// Create the network directly from protobuf text in a string. Useful for debugging/testing
    armnn::INetworkPtr CreateNetworkFromString(const std::string& protoText);

     /// Create the network directly from protobuf text in a string, with inputShapes specified.
     /// Useful for debugging/testing
    armnn::INetworkPtr CreateNetworkFromString(const std::string& protoText,
                                               const std::map<std::string, armnn::TensorShape>& inputShapes);

    /// Retrieve binding info (layer id and tensor info) for the network input identified by the given layer name
    BindingPointInfo GetNetworkInputBindingInfo(const std::string& name) const;

    /// Retrieve binding info (layer id and tensor info) for the network output identified by the given layer name
    BindingPointInfo GetNetworkOutputBindingInfo(const std::string& name) const;

public:

    OnnxParserImpl();
    ~OnnxParserImpl() = default;

    static ModelPtr LoadModelFromBinaryFile(const char * fileName);
    static ModelPtr LoadModelFromTextFile(const char * fileName);
    static ModelPtr LoadModelFromString(const std::string& inputString);

    /// Retrieve inputs names
    static std::vector<std::string> GetInputs(ModelPtr& model);

    /// Retrieve outputs names
    static std::vector<std::string> GetOutputs(ModelPtr& model);

    /// Retrieve version in X.Y.Z form
    static const std::string GetVersion();

private:

    /// Parses a ModelProto loaded into memory from one of the other CreateNetwork*
    armnn::INetworkPtr CreateNetworkFromModel(onnx::ModelProto& model);

    /// Parse every node and make the connection between the resulting tensors
    void LoadGraph();

    void SetupInfo(const google::protobuf::RepeatedPtrField<onnx::ValueInfoProto >* list);

    std::vector<armnn::TensorInfo> ComputeOutputInfo(
        std::vector<std::string> outNames,
        const armnn::IConnectableLayer* layer,
        std::vector<armnn::TensorShape> inputShapes,
        const onnx::TensorProto::DataType& type = onnx::TensorProto::FLOAT);

    void DetectFullyConnected();

    template <typename Location>
    void GetInputAndParam(const onnx::NodeProto& node,
                          std::string* inputName,
                          std::string* constName,
                          const Location& location);

    template <typename Location>
    void To1DTensor(const std::string &name, const Location& location);

    //Broadcast Preparation functions
    std::pair<std::string, std::string> AddPrepareBroadcast(const std::string& input0, const std::string& input1);
    void PrependForBroadcast(const std::string& outputName, const std::string& input0, const std::string& input1);

    void AddConvLayerWithDepthwiseConv(const onnx::NodeProto& node, const armnn::Convolution2dDescriptor& convDesc);
    void AddFullyConnected(const onnx::NodeProto& matmulNode, const onnx::NodeProto* addNode = nullptr);
    void AddPoolingLayer(const onnx::NodeProto& nodeProto, armnn::Pooling2dDescriptor& desc);

    void CreateConstantLayer(const std::string& tensorName, const std::string& layerName);
    void CreateInt64ConstantLayer(const std::string& tensorName, const std::string& layerName);
    void CreateReshapeLayer(const std::string& inputName,
                            const std::string& outputName,
                            const std::string& layerName);

    void ParseActivation(const onnx::NodeProto& nodeProto, const armnn::ActivationFunction func);
    void ParseClip(const onnx::NodeProto& nodeProto);
    void ParseSigmoid(const onnx::NodeProto& nodeProto);
    void ParseTanh(const onnx::NodeProto& nodeProto);
    void ParseRelu(const onnx::NodeProto& nodeProto);
    void ParseLeakyRelu(const onnx::NodeProto& nodeProto);

    void ParseAdd(const onnx::NodeProto& nodeProto);
    void ParseAveragePool(const onnx::NodeProto& nodeProto);
    void ParseBatchNormalization(const onnx::NodeProto& node);
    void ParseConcat(const onnx::NodeProto& nodeProto);
    void ParseConstant(const onnx::NodeProto& nodeProto);
    void ParseConv(const onnx::NodeProto& nodeProto);
    void ParseFlatten(const onnx::NodeProto& node);
    void ParseGather(const onnx::NodeProto& node);
    void ParseGemm(const onnx::NodeProto& node);
    void ParseGlobalAveragePool(const onnx::NodeProto& node);
    void ParseMaxPool(const onnx::NodeProto& nodeProto);
    void ParseShape(const onnx::NodeProto& node);
    void ParseReshape(const onnx::NodeProto& nodeProto);
    void ParseUnsqueeze(const onnx::NodeProto& nodeProto);

    void RegisterInputSlot(armnn::IConnectableLayer* layer,
                           const std::string& tensorId,
                           unsigned int slotIndex);
    void RegisterInputSlots(armnn::IConnectableLayer* layer, const std::vector<std::string>& tensorIndexes);
    void RegisterOutputSlots(armnn::IConnectableLayer* layer, const std::vector<std::string>& tensorIndexes);

    void SetupInputLayers();
    void SetupOutputLayers();

    void ResetParser();
    void Cleanup();

    std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
    CreateConstTensor(const std::string name,
                      armnn::Optional<armnn::PermutationVector&> permutationVector = armnn::EmptyOptional());

    std::pair<armnn::ConstTensor, std::unique_ptr<int32_t[]>>
    CreateInt64ConstTensor(const std::string name,
                           armnn::Optional<armnn::PermutationVector&> permutationVector = armnn::EmptyOptional());

    template <typename TypeList, typename Location>
    void ValidateInputs(const onnx::NodeProto& node,
                        TypeList validInputs,
                        const Location& location);

    /// The network we're building. Gets cleared after it is passed to the user
    armnn::INetworkPtr m_Network;

    /// Ptr to the graph we're building the network from
    GraphPtr m_Graph;

    /// Map of the information for every tensor
    struct OnnxTensor
    {
        std::unique_ptr<armnn::TensorInfo>          m_info;
        std::unique_ptr<const onnx::TensorProto>    m_tensor;
        onnx::TensorProto::DataType                 m_dtype;

        OnnxTensor() : m_info(nullptr), m_tensor(nullptr), m_dtype(onnx::TensorProto::FLOAT) { }
        bool isConstant() { return m_tensor != nullptr; }
    };

    std::unordered_map<std::string, OnnxTensor> m_TensorsInfo;

    /// map of onnx operation names to parsing member functions
    static const std::map<std::string, OperationParsingFunction> m_ParserFunctions;

    /// A mapping of an output slot to each of the input slots it should be connected to
    /// The outputSlot is from the layer that creates this tensor as one of its ouputs
    /// The inputSlots are from the layers that use this tensor as one of their inputs
    struct TensorSlots
    {
        armnn::IOutputSlot* outputSlot;
        std::vector<armnn::IInputSlot*> inputSlots;

        TensorSlots() : outputSlot(nullptr) { }
    };
    /// Map of the tensor names to their connections for the connections of the layers of the graph
    std::unordered_map<std::string, TensorSlots> m_TensorConnections;

    /// Map of the tensor names to their node and index in graph.node()
    std::unordered_map<std::string, std::pair<const onnx::NodeProto*, int>> m_OutputsMap;

    /// Number of times a specific node (identified by his index number) was used as input
    /// and list of the nodes it was fused with
    struct UsageSummary
    {
        std::vector<size_t> fusedWithNodes;
        size_t inputForNodes;

        UsageSummary() : fusedWithNodes({}), inputForNodes(0) { }

    };

    std::vector<UsageSummary> m_OutputsFusedAndUsed;

    std::map<std::string, armnn::TensorShape> m_InputShapes;

    std::unordered_map<std::string, armnn::TensorInfo> m_InputInfos;

    std::unordered_map<std::string, armnn::TensorInfo> m_OutputInfos;

};
}
<commit_msg>IVGCVSW-6581 Inclusive language changes on the OnnxParser.hpp file<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include "armnnOnnxParser/IOnnxParser.hpp"
#include "google/protobuf/repeated_field.h"
#include <unordered_map>

#include <onnx/onnx.pb.h>

namespace armnn
{
class TensorInfo;
enum class ActivationFunction;
}

namespace armnnOnnxParser
{

using ModelPtr = std::unique_ptr<onnx::ModelProto>;

class OnnxParserImpl
{

using OperationParsingFunction = void(OnnxParserImpl::*)(const onnx::NodeProto& NodeProto);

public:

    using GraphPtr = std::unique_ptr<onnx::GraphProto>;

    /// Create the network from a protobuf binary file on disk
    armnn::INetworkPtr CreateNetworkFromBinaryFile(const char* graphFile);

    /// Create the network from a protobuf binary file on disk, with inputShapes specified
    armnn::INetworkPtr CreateNetworkFromBinaryFile(const char* graphFile,
                                                   const std::map<std::string, armnn::TensorShape>& inputShapes);

    /// Create the network from a protobuf text file on disk
    armnn::INetworkPtr CreateNetworkFromTextFile(const char* graphFile);

    /// Create the network from a protobuf text file on disk, with inputShapes specified
    armnn::INetworkPtr CreateNetworkFromTextFile(const char* graphFile,
                                                 const std::map<std::string, armnn::TensorShape>& inputShapes);

    /// Create the network directly from protobuf text in a string. Useful for debugging/testing
    armnn::INetworkPtr CreateNetworkFromString(const std::string& protoText);

     /// Create the network directly from protobuf text in a string, with inputShapes specified.
     /// Useful for debugging/testing
    armnn::INetworkPtr CreateNetworkFromString(const std::string& protoText,
                                               const std::map<std::string, armnn::TensorShape>& inputShapes);

    /// Retrieve binding info (layer id and tensor info) for the network input identified by the given layer name
    BindingPointInfo GetNetworkInputBindingInfo(const std::string& name) const;

    /// Retrieve binding info (layer id and tensor info) for the network output identified by the given layer name
    BindingPointInfo GetNetworkOutputBindingInfo(const std::string& name) const;

public:

    OnnxParserImpl();
    ~OnnxParserImpl() = default;

    static ModelPtr LoadModelFromBinaryFile(const char * fileName);
    static ModelPtr LoadModelFromTextFile(const char * fileName);
    static ModelPtr LoadModelFromString(const std::string& inputString);

    /// Retrieve inputs names
    static std::vector<std::string> GetInputs(ModelPtr& model);

    /// Retrieve outputs names
    static std::vector<std::string> GetOutputs(ModelPtr& model);

    /// Retrieve version in X.Y.Z form
    static const std::string GetVersion();

private:

    /// Parses a ModelProto loaded into memory from one of the other CreateNetwork*
    armnn::INetworkPtr CreateNetworkFromModel(onnx::ModelProto& model);

    /// Parse every node and make the connection between the resulting tensors
    void LoadGraph();

    void SetupInfo(const google::protobuf::RepeatedPtrField<onnx::ValueInfoProto >* list);

    std::vector<armnn::TensorInfo> ComputeOutputInfo(
        std::vector<std::string> outNames,
        const armnn::IConnectableLayer* layer,
        std::vector<armnn::TensorShape> inputShapes,
        const onnx::TensorProto::DataType& type = onnx::TensorProto::FLOAT);

    void DetectFullyConnected();

    template <typename Location>
    void GetInputAndParam(const onnx::NodeProto& node,
                          std::string* inputName,
                          std::string* constName,
                          const Location& location);

    template <typename Location>
    void To1DTensor(const std::string &name, const Location& location);

    //Broadcast Preparation functions
    std::pair<std::string, std::string> AddPrepareBroadcast(const std::string& input0, const std::string& input1);
    void PrependForBroadcast(const std::string& outputName, const std::string& input0, const std::string& input1);

    void AddConvLayerWithDepthwiseConv(const onnx::NodeProto& node, const armnn::Convolution2dDescriptor& convDesc);
    void AddFullyConnected(const onnx::NodeProto& matmulNode, const onnx::NodeProto* addNode = nullptr);
    void AddPoolingLayer(const onnx::NodeProto& nodeProto, armnn::Pooling2dDescriptor& desc);

    void CreateConstantLayer(const std::string& tensorName, const std::string& layerName);
    void CreateInt64ConstantLayer(const std::string& tensorName, const std::string& layerName);
    void CreateReshapeLayer(const std::string& inputName,
                            const std::string& outputName,
                            const std::string& layerName);

    void ParseActivation(const onnx::NodeProto& nodeProto, const armnn::ActivationFunction func);
    void ParseClip(const onnx::NodeProto& nodeProto);
    void ParseSigmoid(const onnx::NodeProto& nodeProto);
    void ParseTanh(const onnx::NodeProto& nodeProto);
    void ParseRelu(const onnx::NodeProto& nodeProto);
    void ParseLeakyRelu(const onnx::NodeProto& nodeProto);

    void ParseAdd(const onnx::NodeProto& nodeProto);
    void ParseAveragePool(const onnx::NodeProto& nodeProto);
    void ParseBatchNormalization(const onnx::NodeProto& node);
    void ParseConcat(const onnx::NodeProto& nodeProto);
    void ParseConstant(const onnx::NodeProto& nodeProto);
    void ParseConv(const onnx::NodeProto& nodeProto);
    void ParseFlatten(const onnx::NodeProto& node);
    void ParseGather(const onnx::NodeProto& node);
    void ParseGemm(const onnx::NodeProto& node);
    void ParseGlobalAveragePool(const onnx::NodeProto& node);
    void ParseMaxPool(const onnx::NodeProto& nodeProto);
    void ParseShape(const onnx::NodeProto& node);
    void ParseReshape(const onnx::NodeProto& nodeProto);
    void ParseUnsqueeze(const onnx::NodeProto& nodeProto);

    void RegisterInputSlot(armnn::IConnectableLayer* layer,
                           const std::string& tensorId,
                           unsigned int slotIndex);
    void RegisterInputSlots(armnn::IConnectableLayer* layer, const std::vector<std::string>& tensorIndexes);
    void RegisterOutputSlots(armnn::IConnectableLayer* layer, const std::vector<std::string>& tensorIndexes);

    void SetupInputLayers();
    void SetupOutputLayers();

    void ResetParser();
    void Cleanup();

    std::pair<armnn::ConstTensor, std::unique_ptr<float[]>>
    CreateConstTensor(const std::string name,
                      armnn::Optional<armnn::PermutationVector&> permutationVector = armnn::EmptyOptional());

    std::pair<armnn::ConstTensor, std::unique_ptr<int32_t[]>>
    CreateInt64ConstTensor(const std::string name,
                           armnn::Optional<armnn::PermutationVector&> permutationVector = armnn::EmptyOptional());

    template <typename TypeList, typename Location>
    void ValidateInputs(const onnx::NodeProto& node,
                        TypeList validInputs,
                        const Location& location);

    /// The network we're building. Gets cleared after it is passed to the user
    armnn::INetworkPtr m_Network;

    /// Ptr to the graph we're building the network from
    GraphPtr m_Graph;

    /// Map of the information for every tensor
    struct OnnxTensor
    {
        std::unique_ptr<armnn::TensorInfo>          m_info;
        std::unique_ptr<const onnx::TensorProto>    m_tensor;
        onnx::TensorProto::DataType                 m_dtype;

        OnnxTensor() : m_info(nullptr), m_tensor(nullptr), m_dtype(onnx::TensorProto::FLOAT) { }
        bool isConstant() { return m_tensor != nullptr; }
    };

    std::unordered_map<std::string, OnnxTensor> m_TensorsInfo;

    /// map of onnx operation names to parsing member functions
    static const std::map<std::string, OperationParsingFunction> m_ParserFunctions;

    /// A mapping of an output slot to each of the input slots it should be connected to
    /// The outputSlot is from the layer that creates this tensor as one of its ouputs
    /// The inputSlots are from the layers that use this tensor as one of their inputs
    struct TensorSlots
    {
        armnn::IOutputSlot* outputSlot;
        std::vector<armnn::IInputSlot*> inputSlots;

        TensorSlots() : outputSlot(nullptr) { }
    };
    /// Map of the tensor names to their connections for the connections of the layers of the graph
    std::unordered_map<std::string, TensorSlots> m_TensorConnections;

    /// Map of the tensor names to their node and index in graph.node()
    std::unordered_map<std::string, std::pair<const onnx::NodeProto*, int>> m_OutputsMap;

    /// Number of times a specific node (identified by its index number) was used as input
    /// and list of the nodes it was fused with
    struct UsageSummary
    {
        std::vector<size_t> fusedWithNodes;
        size_t inputForNodes;

        UsageSummary() : fusedWithNodes({}), inputForNodes(0) { }

    };

    std::vector<UsageSummary> m_OutputsFusedAndUsed;

    std::map<std::string, armnn::TensorShape> m_InputShapes;

    std::unordered_map<std::string, armnn::TensorInfo> m_InputInfos;

    std::unordered_map<std::string, armnn::TensorInfo> m_OutputInfos;

};
}
<|endoftext|>


<commit_before>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//

#define NUMPY_IMPORT_ARRAY
#include "numpy_interop.hpp"

#include "assign.hpp"
#include "init.hpp"
#include "copy_from_numpy_arrfunc.hpp"
#include "array_from_py.hpp"
#include "array_from_py_typededuction.hpp"
#include "type_functions.hpp"

static void pydynd_cleanup() { dynd::libdynd_cleanup(); }

void pydynd::pydynd_init()
{
  import_numpy();
  dynd::libdynd_init();
  atexit(pydynd_cleanup);
  pydynd::init_type_functions();
  pydynd::init_array_from_py_typededuction();
  pydynd::init_array_from_py();
}
<commit_msg>Clear out empty initialization routines.<commit_after>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//

#define NUMPY_IMPORT_ARRAY
#include "numpy_interop.hpp"

#include "assign.hpp"
#include "init.hpp"
#include "copy_from_numpy_arrfunc.hpp"
#include "array_from_py.hpp"
#include "array_from_py_typededuction.hpp"
#include "type_functions.hpp"

void pydynd::pydynd_init()
{
  import_numpy();
  pydynd::init_type_functions();
  pydynd::init_array_from_py_typededuction();
  pydynd::init_array_from_py();
}
<|endoftext|>