<commit_before>#include "rampancy/Cortex.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CallGraphSCCPass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include <memory>
#include <algorithm>
#include "rampancy/Compiler.h"
#include "rampancy/CompilerManager.h"
#include "rampancy/CompilerRegistry.h"

extern "C" {
#include "clips.h"
}
namespace rampancy {
   static llvm::ManagedStatic<Cortex> rampantCortexObject;

   Cortex* Cortex::getRampantCortex() {
      return &*rampantCortexObject;
   }
   Cortex::Cortex(void* theEnv) {
      if(theEnv) {
         env = new CLIPSEnvironment(theEnv);
      } else {
         env = new CLIPSEnvironment();
      }
      context = new llvm::LLVMContext();
      manager = new CompilerManager();
      manager->setContext(context);
      manager->setEnvironment(env);
   }
   Cortex::~Cortex() {
      delete manager;
      delete context;
      delete env;
   }

   llvm::LLVMContext* Cortex::getContext() {
      return context;
   }

   void Cortex::setContext(llvm::LLVMContext* llvmContext) {
      context = llvmContext;
      manager->setContext(context);
   }

   CLIPSEnvironment* Cortex::getEnvironment() {
      return env;
   }
   void Cortex::setEnvironment(CLIPSEnvironment* theEnv) {
      env = theEnv;
      manager->setEnvironment(env);
   }

   void Cortex::compileToKnowledge(void* theEnv) {
      //we need to get the first argument from theEnv to find out where to
      //route it to
      DATA_OBJECT arg0;
      char* copy;
      copy = CharBuffer(512);
      if((EnvArgCountCheck(theEnv, (char*)"compile", AT_LEAST, 1) == -1)) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nNo compiler provided to use!\n");
         return;
      }

      if((EnvArgTypeCheck(theEnv, (char*)"compile", 1, SYMBOL, &arg0) == 0)) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\ncompiler name must be a symbol!\n");
         return;
      }
      std::string tmp (DOToString(arg0));
      //we need some indirection to prevent the CLIPS garbage collector from
      //coming down like a fucking hammer on what we're doing here. Awesomely,
      //this will all be cleaned up at the end of the function :D.
      llvm::StringRef logicalName(tmp);
      llvm::Module* module = compile(logicalName, theEnv);
      if(!module) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nThe compiler failed to compile the target file\n");
         return;
      }
      convertToKnowledge(logicalName, module, theEnv);
   }
   void Cortex::interpretToKnowledge(void* theEnv) {
      //we need to get the first argument from theEnv to find out where to
      //route it to
      DATA_OBJECT arg0;
      char* copy;
      copy = CharBuffer(512);
      if((EnvArgCountCheck(theEnv, (char*)"interpret", AT_LEAST, 1) == -1)) {
         EnvPrintRouter(theEnv, (char*)"werror",
              (char*) "\nNo compiler provided to use!\n");
         return;
      }

      if((EnvArgTypeCheck(theEnv, (char*)"interpret", 1, SYMBOL, &arg0) == 0)) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nCompiler name must be a symbol!\n");
         return;
      }
      std::string tmp (DOToString(arg0));
      //we need some indirection to prevent the CLIPS garbage collector from
      //coming down like a fucking hammer on what we're doing here. Awesomely,
      //this will all be cleaned up at the end of the function :D.
      llvm::StringRef logicalName(tmp);
      llvm::Module* module = interpret(logicalName, theEnv);
      if(!module) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nThe compiler failed to interpret the target file\n");
         return;
      }
      convertToKnowledge(logicalName, module, theEnv);
   }
   llvm::Module* Cortex::compile(llvm::StringRef logicalName, void* theEnv) {
      return manager->compile(logicalName, theEnv);
   }
   llvm::Module* Cortex::interpret(llvm::StringRef logicalName, void* theEnv) {
      return manager->interpret(logicalName, theEnv);
   }
   llvm::Module* Cortex::compile(char* logicalName, int argc, char** argv) {
      return manager->compile(logicalName, argc, argv);
   }
   llvm::Module* Cortex::compile(llvm::StringRef logicalName, int argc, char** argv) {
      return manager->compile(logicalName, argc, argv);
   }

   llvm::Module* Cortex::interpret(llvm::StringRef logicalName,
         llvm::StringRef input) {
      return manager->interpret(logicalName, input);
   }
   llvm::Module* Cortex::interpret(char* logicalName, llvm::StringRef input) {
      return manager->interpret(logicalName, input);
   }

   void Cortex::convertToKnowledge(llvm::StringRef logicalName,
         llvm::Module* module, void* theEnv) {
      CompilerRegistry* compilers = CompilerRegistry::getCompilerRegistry();
      Compiler* target = compilers->getCompiler(logicalName);
      if(!target) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nProvided logical name does not exist\n");
         return;
      } else {
         llvm::PassManager tmpPassManager;
         CLIPSEnvironment* tEnv = new CLIPSEnvironment(theEnv);
         //taken from opt
         llvm::TargetLibraryInfo *tli =
            new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
         tmpPassManager.add(tli);
         llvm::TargetData *td = 0;
         const std::string &moduleDataLayout = module->getDataLayout();
         if(!moduleDataLayout.empty())
            td = new llvm::TargetData(moduleDataLayout);
         if(td)
            tmpPassManager.add(td);
         target->setEnvironment(tEnv);
         target->setContext(context);
         tmpPassManager.add(target);
         tmpPassManager.run(*module);
      }
   }
   void Cortex::convertToKnowledge(llvm::StringRef logicalName,
         llvm::Module* module) {
      CompilerRegistry* compilers = CompilerRegistry::getCompilerRegistry();
      Compiler* target = compilers->getCompiler(logicalName);
      if(!target) {
         EnvPrintRouter(env->getEnvironment(), (char*)"werror",
               (char*)"\nProvided logical name does not exist\n");
         return;
      } else {
         llvm::PassManager tmpPassManager;
         //taken from opt
         llvm::TargetLibraryInfo *tli =
            new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
         tmpPassManager.add(tli);
         llvm::TargetData *td = 0;
         const std::string &moduleDataLayout = module->getDataLayout();
         if(!moduleDataLayout.empty())
            td = new llvm::TargetData(moduleDataLayout);
         if(td)
            tmpPassManager.add(td);
         target->setEnvironment(env);
         target->setContext(context);
         tmpPassManager.add(target);
         tmpPassManager.run(*module);
      }
   }

}
<commit_msg>Modified the printout statement for interpret and compile<commit_after>#include "rampancy/Cortex.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CallGraphSCCPass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include <memory>
#include <algorithm>
#include "rampancy/Compiler.h"
#include "rampancy/CompilerManager.h"
#include "rampancy/CompilerRegistry.h"

extern "C" {
#include "clips.h"
}
namespace rampancy {
   static llvm::ManagedStatic<Cortex> rampantCortexObject;

   Cortex* Cortex::getRampantCortex() {
      return &*rampantCortexObject;
   }
   Cortex::Cortex(void* theEnv) {
      if(theEnv) {
         env = new CLIPSEnvironment(theEnv);
      } else {
         env = new CLIPSEnvironment();
      }
      context = new llvm::LLVMContext();
      manager = new CompilerManager();
      manager->setContext(context);
      manager->setEnvironment(env);
   }
   Cortex::~Cortex() {
      delete manager;
      delete context;
      delete env;
   }

   llvm::LLVMContext* Cortex::getContext() {
      return context;
   }

   void Cortex::setContext(llvm::LLVMContext* llvmContext) {
      context = llvmContext;
      manager->setContext(context);
   }

   CLIPSEnvironment* Cortex::getEnvironment() {
      return env;
   }
   void Cortex::setEnvironment(CLIPSEnvironment* theEnv) {
      env = theEnv;
      manager->setEnvironment(env);
   }

   void Cortex::compileToKnowledge(void* theEnv) {
      //we need to get the first argument from theEnv to find out where to
      //route it to
      DATA_OBJECT arg0;
      char* copy;
      copy = CharBuffer(512);
      if((EnvArgCountCheck(theEnv, (char*)"compile", EXACTLY, 2) == -1)) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nCompile arguments are <compiler> <multifield>\n"
                      "It may be necessary to wrap your input arguments in"
                      "a create$ call.\n");
         return;
      }

      if((EnvArgTypeCheck(theEnv, (char*)"compile", 1, SYMBOL, &arg0) == 0)) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\ncompiler name must be a symbol!\n");
         return;
      }
      std::string tmp (DOToString(arg0));
      //we need some indirection to prevent the CLIPS garbage collector from
      //coming down like a fucking hammer on what we're doing here. Awesomely,
      //this will all be cleaned up at the end of the function :D.
      llvm::StringRef logicalName(tmp);
      llvm::Module* module = compile(logicalName, theEnv);
      if(!module) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nThe compiler failed to compile the target file\n");
         return;
      }
      convertToKnowledge(logicalName, module, theEnv);
   }
   void Cortex::interpretToKnowledge(void* theEnv) {
      //we need to get the first argument from theEnv to find out where to
      //route it to
      DATA_OBJECT arg0;
      char* copy;
      copy = CharBuffer(512);
      if((EnvArgCountCheck(theEnv, (char*)"interpret", EXACTLY, 2) == -1)) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nInterpret arguments are <compiler> <multifield>\n"
                      "It may be necessary to wrap your input arguments in"
                      "a create$ call.\n");
         return;
      }

      if((EnvArgTypeCheck(theEnv, (char*)"interpret", 1, SYMBOL, &arg0) == 0)) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nCompiler name must be a symbol!\n");
         return;
      }
      std::string tmp (DOToString(arg0));
      //we need some indirection to prevent the CLIPS garbage collector from
      //coming down like a fucking hammer on what we're doing here. Awesomely,
      //this will all be cleaned up at the end of the function :D.
      llvm::StringRef logicalName(tmp);
      llvm::Module* module = interpret(logicalName, theEnv);
      if(!module) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nThe compiler failed to interpret the target file\n");
         return;
      }
      convertToKnowledge(logicalName, module, theEnv);
   }
   llvm::Module* Cortex::compile(llvm::StringRef logicalName, void* theEnv) {
      return manager->compile(logicalName, theEnv);
   }
   llvm::Module* Cortex::interpret(llvm::StringRef logicalName, void* theEnv) {
      return manager->interpret(logicalName, theEnv);
   }
   llvm::Module* Cortex::compile(char* logicalName, int argc, char** argv) {
      return manager->compile(logicalName, argc, argv);
   }
   llvm::Module* Cortex::compile(llvm::StringRef logicalName, int argc, char** argv) {
      return manager->compile(logicalName, argc, argv);
   }

   llvm::Module* Cortex::interpret(llvm::StringRef logicalName,
         llvm::StringRef input) {
      return manager->interpret(logicalName, input);
   }
   llvm::Module* Cortex::interpret(char* logicalName, llvm::StringRef input) {
      return manager->interpret(logicalName, input);
   }

   void Cortex::convertToKnowledge(llvm::StringRef logicalName,
         llvm::Module* module, void* theEnv) {
      CompilerRegistry* compilers = CompilerRegistry::getCompilerRegistry();
      Compiler* target = compilers->getCompiler(logicalName);
      if(!target) {
         EnvPrintRouter(theEnv, (char*)"werror",
               (char*)"\nProvided logical name does not exist\n");
         return;
      } else {
         llvm::PassManager tmpPassManager;
         CLIPSEnvironment* tEnv = new CLIPSEnvironment(theEnv);
         //taken from opt
         llvm::TargetLibraryInfo *tli =
            new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
         tmpPassManager.add(tli);
         llvm::TargetData *td = 0;
         const std::string &moduleDataLayout = module->getDataLayout();
         if(!moduleDataLayout.empty())
            td = new llvm::TargetData(moduleDataLayout);
         if(td)
            tmpPassManager.add(td);
         target->setEnvironment(tEnv);
         target->setContext(context);
         tmpPassManager.add(target);
         tmpPassManager.run(*module);
      }
   }
   void Cortex::convertToKnowledge(llvm::StringRef logicalName,
         llvm::Module* module) {
      CompilerRegistry* compilers = CompilerRegistry::getCompilerRegistry();
      Compiler* target = compilers->getCompiler(logicalName);
      if(!target) {
         EnvPrintRouter(env->getEnvironment(), (char*)"werror",
               (char*)"\nProvided logical name does not exist\n");
         return;
      } else {
         llvm::PassManager tmpPassManager;
         //taken from opt
         llvm::TargetLibraryInfo *tli =
            new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
         tmpPassManager.add(tli);
         llvm::TargetData *td = 0;
         const std::string &moduleDataLayout = module->getDataLayout();
         if(!moduleDataLayout.empty())
            td = new llvm::TargetData(moduleDataLayout);
         if(td)
            tmpPassManager.add(td);
         target->setEnvironment(env);
         target->setContext(context);
         tmpPassManager.add(target);
         tmpPassManager.run(*module);
      }
   }

}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project.

    Copyright (C) 2011 Harald Sitter <sitter@kde.org>
    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "streamreader.h"

QT_BEGIN_NAMESPACE
#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM
namespace Phonon
{
namespace Gstreamer
{

StreamReader::StreamReader(const Phonon::MediaSource &source, MediaObject *parent)
    : m_pos(0)
    , m_size(0)
    , m_eos(false)
    , m_locked(false)
    , m_seekable(false)
    , m_mediaObject(parent)
{
    connectToSource(source);
}

int StreamReader::currentBufferSize() const
{
    return m_buffer.size();
}

void StreamReader::writeData(const QByteArray &data) {
    QMutexLocker locker(&m_mutex);

    m_buffer.append(data);
    m_waitingForData.wakeAll();
}

void StreamReader::setCurrentPos(qint64 pos)
{
    QMutexLocker locker(&m_mutex);

    m_pos = pos;
    seekStream(pos);
    m_buffer.clear();
}

quint64 StreamReader::currentPos() const
{
    return m_pos;
}

GstFlowReturn StreamReader::read(quint64 pos, int length, char *buffer)
{
    QMutexLocker locker(&m_mutex);

    if (currentPos() != pos) {
        if (!streamSeekable()) {
            return GST_FLOW_NOT_SUPPORTED;
        }
        // TODO: technically an error can occur here, however the abstractstream
        // API does not consider this, so we must assume that everything always goes
        // alright and continue processing.
        setCurrentPos(pos);
    }

    while (currentBufferSize() < length) {
        int oldSize = currentBufferSize();
        needData();

        m_waitingForData.wait(&m_mutex);

        // Abort instantly if we got unlocked, whether we got sufficient data or not
        // is absolutely unimportant at this point.
        if (!m_locked) {
            break;
        }

        if (oldSize == currentBufferSize()) {
            // We didn't get any data, check if we are at the end of stream already.
            if (m_eos) {
                return GST_FLOW_UNEXPECTED;
        }
    }
    if (m_mediaObject->state() != Phonon::BufferingState &&
        m_mediaObject->state() != Phonon::LoadingState) {
        enoughData();
    }

    qMemCopy(buffer, m_buffer.data(), length);
    m_pos += length;
    //truncate the buffer
    m_buffer = m_buffer.mid(length);
    return GST_FLOW_OK;
}

void StreamReader::endOfData()
{
    QMutexLocker locker(&m_mutex);
    m_eos = true;
    m_waitingForData.wakeAll();
}

void StreamReader::start()
{
    QMutexLocker locker(&m_mutex);
    m_buffer.clear();
    m_eos = false;
    m_locked = true;
    m_pos = 0;
    m_seekable = false;
    m_size = 0;
    reset();
}

void StreamReader::stop()
{
    enoughData();
    m_waitingForData.wakeAll();
}

void StreamReader::unlock()
{
    QMutexLocker locker(&m_mutex);
    enoughData();
    m_locked = false;
    m_waitingForData.wakeAll();
}

void StreamReader::setStreamSize(qint64 newSize)
{
    m_size = newSize;
}

qint64 StreamReader::streamSize() const
{
    return m_size;
}

void StreamReader::setStreamSeekable(bool seekable)
{
//    if (seekable) {
//        // The initial stream size of a seekable stream *must* not be 0 or
//        // GStreamer will refuse to typefind.
//        m_size = 1;
//    }
    m_seekable = seekable;
}

bool StreamReader::streamSeekable() const
{
    // TODO - problems with pull seeking and the way our current stack works.
    return false;
//    return m_seekable;
}

}
}
#endif //QT_NO_PHONON_ABSTRACTMEDIASTREAM

QT_END_NAMESPACE
<commit_msg>Missing curly brace. compile++<commit_after>/*  This file is part of the KDE project.

    Copyright (C) 2011 Harald Sitter <sitter@kde.org>
    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "streamreader.h"

QT_BEGIN_NAMESPACE
#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM
namespace Phonon
{
namespace Gstreamer
{

StreamReader::StreamReader(const Phonon::MediaSource &source, MediaObject *parent)
    : m_pos(0)
    , m_size(0)
    , m_eos(false)
    , m_locked(false)
    , m_seekable(false)
    , m_mediaObject(parent)
{
    connectToSource(source);
}

int StreamReader::currentBufferSize() const
{
    return m_buffer.size();
}

void StreamReader::writeData(const QByteArray &data) {
    QMutexLocker locker(&m_mutex);

    m_buffer.append(data);
    m_waitingForData.wakeAll();
}

void StreamReader::setCurrentPos(qint64 pos)
{
    QMutexLocker locker(&m_mutex);

    m_pos = pos;
    seekStream(pos);
    m_buffer.clear();
}

quint64 StreamReader::currentPos() const
{
    return m_pos;
}

GstFlowReturn StreamReader::read(quint64 pos, int length, char *buffer)
{
    QMutexLocker locker(&m_mutex);

    if (currentPos() != pos) {
        if (!streamSeekable()) {
            return GST_FLOW_NOT_SUPPORTED;
        }
        // TODO: technically an error can occur here, however the abstractstream
        // API does not consider this, so we must assume that everything always goes
        // alright and continue processing.
        setCurrentPos(pos);
    }

    while (currentBufferSize() < length) {
        int oldSize = currentBufferSize();
        needData();

        m_waitingForData.wait(&m_mutex);

        // Abort instantly if we got unlocked, whether we got sufficient data or not
        // is absolutely unimportant at this point.
        if (!m_locked) {
            break;
        }

        if (oldSize == currentBufferSize()) {
            // We didn't get any data, check if we are at the end of stream already.
            if (m_eos) {
                return GST_FLOW_UNEXPECTED;
            }
        }
    }
    if (m_mediaObject->state() != Phonon::BufferingState &&
        m_mediaObject->state() != Phonon::LoadingState) {
        enoughData();
    }

    qMemCopy(buffer, m_buffer.data(), length);
    m_pos += length;
    //truncate the buffer
    m_buffer = m_buffer.mid(length);
    return GST_FLOW_OK;
}

void StreamReader::endOfData()
{
    QMutexLocker locker(&m_mutex);
    m_eos = true;
    m_waitingForData.wakeAll();
}

void StreamReader::start()
{
    QMutexLocker locker(&m_mutex);
    m_buffer.clear();
    m_eos = false;
    m_locked = true;
    m_pos = 0;
    m_seekable = false;
    m_size = 0;
    reset();
}

void StreamReader::stop()
{
    enoughData();
    m_waitingForData.wakeAll();
}

void StreamReader::unlock()
{
    QMutexLocker locker(&m_mutex);
    enoughData();
    m_locked = false;
    m_waitingForData.wakeAll();
}

void StreamReader::setStreamSize(qint64 newSize)
{
    m_size = newSize;
}

qint64 StreamReader::streamSize() const
{
    return m_size;
}

void StreamReader::setStreamSeekable(bool seekable)
{
//    if (seekable) {
//        // The initial stream size of a seekable stream *must* not be 0 or
//        // GStreamer will refuse to typefind.
//        m_size = 1;
//    }
    m_seekable = seekable;
}

bool StreamReader::streamSeekable() const
{
    // TODO - problems with pull seeking and the way our current stack works.
    return false;
//    return m_seekable;
}

}
}
#endif //QT_NO_PHONON_ABSTRACTMEDIASTREAM

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/image_reader.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/factory.hpp>

namespace mapnik
{

inline boost::optional<std::string> type_from_bytes(char const* data, size_t size)
{
    using result_type = boost::optional<std::string>;
    if (size >= 4)
    {
        unsigned int magic = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
        if (magic == 0x89504E47U)
        {
            return result_type("png");
        }
        else if (magic == 0x49492A00 || magic == 0x4D4D002A)
        {
            return result_type("tiff");
        }
    }
    if (size>=2)
    {
        unsigned int magic = ((data[0] << 8) | data[1]) & 0xffff;
        if (magic == 0xffd8)
        {
            return result_type("jpeg");
        }
    }

    if (size>=12)
    {
        if (data[0] == 'R' && data[1] == 'I' && data[2] == 'F' && data[3] == 'F' &&
            data[8] == 'W' && data[9] == 'E' && data[10] == 'B' && data[11] == 'P')
        {
            return result_type("webp");
        }
    }
    return result_type();
}

image_reader* get_image_reader(char const* data, size_t size)
{
    boost::optional<std::string> type = type_from_bytes(data,size);
    if (type)
        return factory<image_reader,std::string,char const*,size_t>::instance().create_object(*type, data,size);
    else
        throw image_reader_exception("image_reader: can't determine type from input data");
}

image_reader* get_image_reader(std::string const& filename,std::string const& type)
{
    return factory<image_reader,std::string,std::string const&>::instance().create_object(type,filename);
}

image_reader* get_image_reader(std::string const& filename)
{
    boost::optional<std::string> type = type_from_filename(filename);
    if (type)
    {
        return factory<image_reader,std::string,std::string const&>::instance().create_object(*type,filename);
    }
    return 0;
}

}
<commit_msg>Updated image reader so that it would throw an exception rather then returning a 0 pointer.<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2014 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

// mapnik
#include <mapnik/image_reader.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/factory.hpp>

namespace mapnik
{

inline boost::optional<std::string> type_from_bytes(char const* data, size_t size)
{
    using result_type = boost::optional<std::string>;
    if (size >= 4)
    {
        unsigned int magic = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3];
        if (magic == 0x89504E47U)
        {
            return result_type("png");
        }
        else if (magic == 0x49492A00 || magic == 0x4D4D002A)
        {
            return result_type("tiff");
        }
    }
    if (size>=2)
    {
        unsigned int magic = ((data[0] << 8) | data[1]) & 0xffff;
        if (magic == 0xffd8)
        {
            return result_type("jpeg");
        }
    }

    if (size>=12)
    {
        if (data[0] == 'R' && data[1] == 'I' && data[2] == 'F' && data[3] == 'F' &&
            data[8] == 'W' && data[9] == 'E' && data[10] == 'B' && data[11] == 'P')
        {
            return result_type("webp");
        }
    }
    return result_type();
}

image_reader* get_image_reader(char const* data, size_t size)
{
    boost::optional<std::string> type = type_from_bytes(data,size);
    if (type)
        return factory<image_reader,std::string,char const*,size_t>::instance().create_object(*type, data,size);
    else
        throw image_reader_exception("image_reader: can't determine type from input data");
}

image_reader* get_image_reader(std::string const& filename,std::string const& type)
{
    return factory<image_reader,std::string,std::string const&>::instance().create_object(type,filename);
}

image_reader* get_image_reader(std::string const& filename)
{
    boost::optional<std::string> type = type_from_filename(filename);
    if (type)
    {
        return factory<image_reader,std::string,std::string const&>::instance().create_object(*type,filename);
    }
    else
    {
        throw image_reader_exception("image_reader: can't determine type from input data");
    }
}

}
<|endoftext|>


<commit_before>#include <QPen>
#include <QLineF>
#include <QGraphicsItem>
#include <QPolygonF>
#include <QPainter>
#include <QDebug>
#include <QSize>
#include <QGraphicsDropShadowEffect>

#include <cmath>

#include "gui/edge_graphics_item.h"
#include "gui/edge_weight_text.h"
#include "gui/vertex_graphics_item.h"

static int center_ = VertexGraphicsItem::GraphicSize / 2;

EdgeGraphicsItem::EdgeGraphicsItem(VertexGraphicsItem* from, VertexGraphicsItem* to, Edge* edge): from(from), to(to), edge(edge)
{
    setFlag(GraphicsItemFlag::ItemIsSelectable);
    weightText_ = new EdgeWeightText(this);

    // Pro zlepseni citelnosti textu
//    auto shadow = new QGraphicsDropShadowEffect();
//    shadow->setOffset(0, 0);
//    shadow->setBlurRadius(10);
//    shadow->setColor(QColor(255, 255, 255));
//    weightText_->setGraphicsEffect(shadow);
    weightText_->setFlag(QGraphicsItem::ItemIsSelectable);
    weightText_->setHtml(QString::number(edge->weight));
    weightText_->setHtml(QString("%1").arg(edge->weight));
    weightText_->edge = edge;
}

void EdgeGraphicsItem::updatePosition() {
    QRectF rect(line().p1(), line().p2());
    auto s = rect.size();
    s.scale(150, 150, Qt::IgnoreAspectRatio);
    rect.setSize(s);

    scene()->invalidate(rect);
}

double deg(double x) {
    return 360 * x / (2 * M_PI);
}

void EdgeGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QPen pen;
    pen.setWidth(3);
    if (edge->bridge) {
        pen.setColor(QColor(230, 230, 230));
    } else {
        // TODO - handle bridges
        pen.setColor(QColor(180, 180, 180));
    }
    setPen(pen);

    QLineF line(this->mapFromItem(from, center_, center_), this->mapFromItem(to, center_, center_));
    setZValue(-1);
    double angle = std::acos(line.dx() / line.length());

    double dx = line.dx();
    /// Protoze QT je hloupe a ma obracene osu Y
    double dy = -line.dy();

    double radius = VertexGraphicsItem::GraphicSize / 2;
    QPointF v1 = line.p1() - line.p2();
    double ratio1 = radius / sqrt(v1.x() * v1.x() + v1.y() * v1.y());
    QPointF moved1 = line.p1() - v1*ratio1;
    line.setP1(moved1);

    QPointF v2 = line.p2() - line.p1();
    double ratio2 = radius / sqrt(v2.x() * v2.x() + v2.y() * v2.y());
    QPointF moved2 = line.p2() - v2*ratio2;
    line.setP2(moved2);

    if (dy <= 0) {
        angle = -angle;
    }

    setLine(line);

    QPolygonF arrowHead;
    arrowHead.clear();

    /// Pro zjednoduseni abychom nemuseli resit otaceni uhlu
    float arrowSize = -15;

    double arrowAngle = 1 * M_PI / 3;

    QPointF arrowP1 = line.p2() + QPointF(sin(angle + arrowAngle) * arrowSize, cos(angle + arrowAngle) * arrowSize);
    QPointF arrowP2 = line.p2() + QPointF(sin(angle + M_PI - arrowAngle) * arrowSize, cos(angle + M_PI - arrowAngle) * arrowSize);
    arrowHead << line.p2() << arrowP1 << arrowP2;

    pen.setWidth(1);
    painter->setPen(pen);
    painter->setBrush(QColor(180, 180, 180));
    painter->drawPolygon(arrowHead);

    double weightRadius = -25;
    double x_offset = std::abs(M_PI - std::abs(angle));

    QPointF offset{x_offset * 4, 10};
//    QPointF offset = QPointF(x_shift / log(x_shift), y_shift / log(y_shift));

//    qDebug() << QString("%1\t%2\t%3\t%4").arg(x_offset).arg(M_PI/2.0 - angle).arg(dx).arg(dy);

    QPointF textPoint = line.p2() + QPointF(sin(angle + arrowAngle) * weightRadius, cos(angle + arrowAngle) * weightRadius) - offset;
    weightText_->setPos(textPoint);

    QGraphicsLineItem::paint(painter, option, widget);
}
<commit_msg>Minor cleanup<commit_after>#include <QPen>
#include <QLineF>
#include <QGraphicsItem>
#include <QPolygonF>
#include <QPainter>
#include <QDebug>
#include <QSize>
#include <QGraphicsDropShadowEffect>

#include <cmath>

#include "gui/edge_graphics_item.h"
#include "gui/edge_weight_text.h"
#include "gui/vertex_graphics_item.h"

static int center_ = VertexGraphicsItem::GraphicSize / 2;

EdgeGraphicsItem::EdgeGraphicsItem(VertexGraphicsItem* from, VertexGraphicsItem* to, Edge* edge): from(from), to(to), edge(edge)
{
    setFlag(GraphicsItemFlag::ItemIsSelectable);
    weightText_ = new EdgeWeightText(this);

    // Pro zlepseni citelnosti textu
//    auto shadow = new QGraphicsDropShadowEffect();
//    shadow->setOffset(0, 0);
//    shadow->setBlurRadius(10);
//    shadow->setColor(QColor(255, 255, 255));
//    weightText_->setGraphicsEffect(shadow);
    weightText_->setFlag(QGraphicsItem::ItemIsSelectable);
    weightText_->setHtml(QString::number(edge->weight));
    weightText_->setHtml(QString("%1").arg(edge->weight));
    weightText_->edge = edge;
}

void EdgeGraphicsItem::updatePosition() {
    QRectF rect(line().p1(), line().p2());
    auto s = rect.size();
    s.scale(150, 150, Qt::IgnoreAspectRatio);
    rect.setSize(s);

    scene()->invalidate(rect);
}

double deg(double x) {
    return 360 * x / (2 * M_PI);
}

void EdgeGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QPen pen;
    pen.setWidth(3);
    if (edge->bridge) {
        pen.setColor(QColor(230, 230, 230));
    } else {
        // TODO - handle bridges
        pen.setColor(QColor(180, 180, 180));
    }
    setPen(pen);

    QLineF line(this->mapFromItem(from, center_, center_), this->mapFromItem(to, center_, center_));
    setZValue(-1);
    double angle = std::acos(line.dx() / line.length());

    double dx = line.dx();
    /// Protoze QT je hloupe a ma obracene osu Y
    double dy = -line.dy();

    double radius = VertexGraphicsItem::GraphicSize / 2;
    QPointF v1 = line.p1() - line.p2();
    double ratio1 = radius / sqrt(v1.x() * v1.x() + v1.y() * v1.y());
    QPointF moved1 = line.p1() - v1*ratio1;
    line.setP1(moved1);

    QPointF v2 = line.p2() - line.p1();
    double ratio2 = radius / sqrt(v2.x() * v2.x() + v2.y() * v2.y());
    QPointF moved2 = line.p2() - v2*ratio2;
    line.setP2(moved2);

    if (dy <= 0) {
        angle = -angle;
    }

    setLine(line);

    QPolygonF arrowHead;
    arrowHead.clear();

    /// Pro zjednoduseni abychom nemuseli resit otaceni uhlu
    float arrowSize = -15;

    double arrowAngle = 1 * M_PI / 3;

    QPointF arrowP1 = line.p2() + QPointF(sin(angle + arrowAngle) * arrowSize, cos(angle + arrowAngle) * arrowSize);
    QPointF arrowP2 = line.p2() + QPointF(sin(angle + M_PI - arrowAngle) * arrowSize, cos(angle + M_PI - arrowAngle) * arrowSize);
    arrowHead << line.p2() << arrowP1 << arrowP2;

    pen.setWidth(1);
    painter->setPen(pen);
    painter->setBrush(QColor(180, 180, 180));
    painter->drawPolygon(arrowHead);

    double weightRadius = -25;
    double x_offset = std::abs(M_PI - std::abs(angle));

    QPointF offset{x_offset * 4, 10};
//    QPointF offset = QPointF(x_shift / log(x_shift), y_shift / log(y_shift));

//    qDebug() << QString("%1\t%2\t%3\t%4").arg(x_offset).arg(M_PI/2.0 - angle).arg(dx).arg(dy);

    QPointF textPoint = line.p2() + QPointF(sin(angle + arrowAngle) * weightRadius, cos(angle + arrowAngle) * weightRadius) - offset;
    weightText_->setPos(textPoint);

    QGraphicsLineItem::paint(painter, option, widget);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "shell_main_delegate.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "content/shell/shell_browser_main.h"
#include "content/shell/shell_content_browser_client.h"
#include "content/shell/shell_content_renderer_client.h"
#include "content/shell/shell_switches.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

#if defined(OS_ANDROID)
#include "base/global_descriptors_posix.h"
#include "content/shell/android/shell_descriptors.h"
#endif

#if defined(OS_MACOSX)
#include "content/shell/paths_mac.h"
#endif  // OS_MACOSX

#if defined(OS_WIN)
#include "base/logging_win.h"
#include <initguid.h>
#endif

namespace {

#if defined(OS_WIN)
// If "Content Shell" doesn't show up in your list of trace providers in
// Sawbuck, add these registry entries to your machine (NOTE the optional
// Wow6432Node key for x64 machines):
// 1. Find:  HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers
// 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}"
// 3. Add these values:
//    "default_flags"=dword:00000001
//    "default_level"=dword:00000004
//    @="Content Shell"

// {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}
const GUID kContentShellProviderName = {
    0x6a3e50a4, 0x7e15, 0x4099,
        { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } };
#endif

void InitLogging() {
  FilePath log_filename;
  PathService::Get(base::DIR_EXE, &log_filename);
  log_filename = log_filename.AppendASCII("content_shell.log");
  logging::InitLogging(
      log_filename.value().c_str(),
      logging::LOG_ONLY_TO_FILE,
      logging::LOCK_LOG_FILE,
      logging::DELETE_OLD_LOG_FILE,
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  logging::SetLogItems(true, true, true, true);
}

}  // namespace

namespace content {

ShellMainDelegate::ShellMainDelegate() {
}

ShellMainDelegate::~ShellMainDelegate() {
#if defined(OS_ANDROID)
  NOTREACHED();
#endif
}

bool ShellMainDelegate::BasicStartupComplete(int* exit_code) {
#if defined(OS_WIN)
  // Enable trace control and transport through event tracing for Windows.
  logging::LogEventProvider::Initialize(kContentShellProviderName);
#endif

  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) {
    InitLogging();
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kAllowFileAccessFromFiles);
  }
  SetContentClient(&content_client_);
  return false;
}

void ShellMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideFrameworkBundlePath();
  OverrideChildProcessPath();
#endif  // OS_MACOSX
  InitializeResourceBundle();

  // Just prevent sandbox
  CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoSandbox);
}

int ShellMainDelegate::RunProcess(
    const std::string& process_type,
    const MainFunctionParams& main_function_params) {
  if (!process_type.empty())
    return -1;

#if !defined(OS_ANDROID)
  return ShellBrowserMain(main_function_params);
#else
  // If no process type is specified, we are creating the main browser process.
  browser_runner_.reset(BrowserMainRunner::Create());
  int exit_code = browser_runner_->Initialize(main_function_params);
  DCHECK(exit_code < 0)
      << "BrowserRunner::Initialize failed in ShellMainDelegate";

  return exit_code;
#endif
}

void ShellMainDelegate::InitializeResourceBundle() {
#if defined(OS_ANDROID)
  // In the Android case, the renderer runs with a different UID and can never
  // access the file system.  So we are passed a file descriptor to the
  // ResourceBundle pak at launch time.
  int pak_fd =
      base::GlobalDescriptors::GetInstance()->MaybeGet(kShellPakDescriptor);
  if (pak_fd != base::kInvalidPlatformFileValue) {
    ui::ResourceBundle::InitSharedInstanceWithPakFile(pak_fd, false);
    ResourceBundle::GetSharedInstance().AddDataPackFromFile(
        pak_fd, ui::SCALE_FACTOR_100P);
    return;
  }
#endif

  FilePath pak_file;
#if defined(OS_MACOSX)
  pak_file = GetResourcesPakFilePath();
#else
  FilePath pak_dir;

#if defined(OS_ANDROID)
  bool got_path = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_dir);
  DCHECK(got_path);
  pak_dir = pak_dir.Append(FILE_PATH_LITERAL("paks"));
#else
  PathService::Get(base::DIR_MODULE, &pak_dir);
#endif

  pak_file = pak_dir.Append(FILE_PATH_LITERAL("nw.pak"));
#endif
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}

ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new ShellContentBrowserClient);
  return browser_client_.get();
}

ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new ShellContentRendererClient);
  return renderer_client_.get();
}

}  // namespace content
<commit_msg>Add --version<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
//  to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
//  OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "shell_main_delegate.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "shell_browser_main.h"
#include "shell_content_browser_client.h"
#include "shell_content_renderer_client.h"
#include "shell_switches.h"
#include "third_party/node/src/node_version.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "nw_version.h"

#include <stdio.h>

#if defined(OS_ANDROID)
#include "base/global_descriptors_posix.h"
#include "content/shell/android/shell_descriptors.h"
#endif

#if defined(OS_MACOSX)
#include "content/shell/paths_mac.h"
#endif  // OS_MACOSX

#if defined(OS_WIN)
#include "base/logging_win.h"
#include <initguid.h>
#endif

namespace {

#if defined(OS_WIN)
// If "Content Shell" doesn't show up in your list of trace providers in
// Sawbuck, add these registry entries to your machine (NOTE the optional
// Wow6432Node key for x64 machines):
// 1. Find:  HKLM\SOFTWARE\[Wow6432Node\]Google\Sawbuck\Providers
// 2. Add a subkey with the name "{6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}"
// 3. Add these values:
//    "default_flags"=dword:00000001
//    "default_level"=dword:00000004
//    @="Content Shell"

// {6A3E50A4-7E15-4099-8413-EC94D8C2A4B6}
const GUID kContentShellProviderName = {
    0x6a3e50a4, 0x7e15, 0x4099,
        { 0x84, 0x13, 0xec, 0x94, 0xd8, 0xc2, 0xa4, 0xb6 } };
#endif

void InitLogging() {
  FilePath log_filename;
  PathService::Get(base::DIR_EXE, &log_filename);
  log_filename = log_filename.AppendASCII("content_shell.log");
  logging::InitLogging(
      log_filename.value().c_str(),
      logging::LOG_ONLY_TO_FILE,
      logging::LOCK_LOG_FILE,
      logging::DELETE_OLD_LOG_FILE,
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS);
  logging::SetLogItems(true, true, true, true);
}

}  // namespace

namespace content {

ShellMainDelegate::ShellMainDelegate() {
}

ShellMainDelegate::~ShellMainDelegate() {
#if defined(OS_ANDROID)
  NOTREACHED();
#endif
}

bool ShellMainDelegate::BasicStartupComplete(int* exit_code) {
#if defined(OS_WIN)
  // Enable trace control and transport through event tracing for Windows.
  logging::LogEventProvider::Initialize(kContentShellProviderName);
#endif

  // Print version and quit
  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kVersion)) {
    printf("nw %s\nnode %s\n", NW_VERSION, NODE_VERSION);
    *exit_code = 0;
    return true;
  }

  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) {
    InitLogging();
    CommandLine::ForCurrentProcess()->AppendSwitch(
        switches::kAllowFileAccessFromFiles);
  }
  SetContentClient(&content_client_);
  return false;
}

void ShellMainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
  OverrideFrameworkBundlePath();
  OverrideChildProcessPath();
#endif  // OS_MACOSX
  InitializeResourceBundle();

  // Just prevent sandbox
  CommandLine::ForCurrentProcess()->AppendSwitch(switches::kNoSandbox);
}

int ShellMainDelegate::RunProcess(
    const std::string& process_type,
    const MainFunctionParams& main_function_params) {
  if (!process_type.empty())
    return -1;

#if !defined(OS_ANDROID)
  return ShellBrowserMain(main_function_params);
#else
  // If no process type is specified, we are creating the main browser process.
  browser_runner_.reset(BrowserMainRunner::Create());
  int exit_code = browser_runner_->Initialize(main_function_params);
  DCHECK(exit_code < 0)
      << "BrowserRunner::Initialize failed in ShellMainDelegate";

  return exit_code;
#endif
}

void ShellMainDelegate::InitializeResourceBundle() {
#if defined(OS_ANDROID)
  // In the Android case, the renderer runs with a different UID and can never
  // access the file system.  So we are passed a file descriptor to the
  // ResourceBundle pak at launch time.
  int pak_fd =
      base::GlobalDescriptors::GetInstance()->MaybeGet(kShellPakDescriptor);
  if (pak_fd != base::kInvalidPlatformFileValue) {
    ui::ResourceBundle::InitSharedInstanceWithPakFile(pak_fd, false);
    ResourceBundle::GetSharedInstance().AddDataPackFromFile(
        pak_fd, ui::SCALE_FACTOR_100P);
    return;
  }
#endif

  FilePath pak_file;
#if defined(OS_MACOSX)
  pak_file = GetResourcesPakFilePath();
#else
  FilePath pak_dir;

#if defined(OS_ANDROID)
  bool got_path = PathService::Get(base::DIR_ANDROID_APP_DATA, &pak_dir);
  DCHECK(got_path);
  pak_dir = pak_dir.Append(FILE_PATH_LITERAL("paks"));
#else
  PathService::Get(base::DIR_MODULE, &pak_dir);
#endif

  pak_file = pak_dir.Append(FILE_PATH_LITERAL("nw.pak"));
#endif
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}

ContentBrowserClient* ShellMainDelegate::CreateContentBrowserClient() {
  browser_client_.reset(new ShellContentBrowserClient);
  return browser_client_.get();
}

ContentRendererClient* ShellMainDelegate::CreateContentRendererClient() {
  renderer_client_.reset(new ShellContentRendererClient);
  return renderer_client_.get();
}

}  // namespace content
<|endoftext|>


<commit_before>/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 * This file is part of sot-core.
 * sot-core is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * sot-core is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.  You should
 * have received a copy of the GNU Lesser General Public License along
 * with sot-core.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sot-core/pool.h>
#include <sot-core/signal-cast.h>
#include <iomanip>
#include <sot-core/feature-abstract.h>

using namespace std;
using namespace sot;

SignalCast_sotFeatureAbstractPtr SignalCast<SignalCast_sotFeatureAbstractPtr>::
cast( std::istringstream& iss )
{
  SignalCast_sotFeatureAbstractPtr ref;
  std::string name; iss >> name;
  if( name.length())
    {
      ref = &sotPool.getFeature(name);
    }
  else { ref = NULL; }
  return ref;
}

void SignalCast<SignalCast_sotFeatureAbstractPtr>::
disp(  const SignalCast_sotFeatureAbstractPtr & t,std::ostream& os )
{
  if( t ) { t->display(os); os<<std::endl; }
  else { os << "NULL" << std::endl; }
}

struct timeval SignalCast<struct timeval>::
cast( std::istringstream& iss )
{
  int u,s; iss >> s >> u;
  struct timeval t; t.tv_sec = s; t.tv_usec = u;
  return t;
}
void SignalCast<struct timeval>::
disp( const struct timeval& t,std::ostream& os )
{
  os << t.tv_sec << "s "<< t.tv_usec << "ms";
}

void SignalCast<VectorMultiBound>::
trace( const VectorMultiBound& t,std::ostream& os )
{
  for( VectorMultiBound::const_iterator iter=t.begin();t.end()!=iter;++iter )
    {
      switch( iter->mode )
        {
        case MultiBound::MODE_SINGLE:
          os << iter->getSingleBound() << "\t";
          break;
        case MultiBound::MODE_DOUBLE:
          if( iter->getDoubleBoundSetup(MultiBound::BOUND_INF) )
            os << iter->getDoubleBound(MultiBound::BOUND_INF)<<"\t";
          else os <<"-inf\t";
          if( iter->getDoubleBoundSetup(MultiBound::BOUND_SUP) )
            os << iter->getDoubleBound(MultiBound::BOUND_SUP)<<"\t";
          else os <<"+inf\t";
          break;
        }
    }
}

namespace {
	SOT_SIGNAL_CAST_DECLARATION(SignalCast_sotFeatureAbstractPtr);
	SOT_SIGNAL_CAST_DECLARATION(Flags);
	SOT_SIGNAL_CAST_DECLARATION(VectorMultiBound);
	SOT_SIGNAL_CAST_DECLARATION(timeval );
}
<commit_msg>Declare MatrixHomogeneous as signal compatible type<commit_after>/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 * This file is part of sot-core.
 * sot-core is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * sot-core is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.  You should
 * have received a copy of the GNU Lesser General Public License along
 * with sot-core.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <dynamic-graph/signal-caster.h>
#include <sot-core/pool.h>
#include <sot-core/signal-cast.h>
#include <iomanip>
#include <sot-core/feature-abstract.h>

#include "sot-core/matrix-homogeneous.h"

using namespace std;
using namespace sot;

SignalCast_sotFeatureAbstractPtr SignalCast<SignalCast_sotFeatureAbstractPtr>::
cast( std::istringstream& iss )
{
  SignalCast_sotFeatureAbstractPtr ref;
  std::string name; iss >> name;
  if( name.length())
    {
      ref = &sotPool.getFeature(name);
    }
  else { ref = NULL; }
  return ref;
}

void SignalCast<SignalCast_sotFeatureAbstractPtr>::
disp(  const SignalCast_sotFeatureAbstractPtr & t,std::ostream& os )
{
  if( t ) { t->display(os); os<<std::endl; }
  else { os << "NULL" << std::endl; }
}

struct timeval SignalCast<struct timeval>::
cast( std::istringstream& iss )
{
  int u,s; iss >> s >> u;
  struct timeval t; t.tv_sec = s; t.tv_usec = u;
  return t;
}
void SignalCast<struct timeval>::
disp( const struct timeval& t,std::ostream& os )
{
  os << t.tv_sec << "s "<< t.tv_usec << "ms";
}

void SignalCast<VectorMultiBound>::
trace( const VectorMultiBound& t,std::ostream& os )
{
  for( VectorMultiBound::const_iterator iter=t.begin();t.end()!=iter;++iter )
    {
      switch( iter->mode )
        {
        case MultiBound::MODE_SINGLE:
          os << iter->getSingleBound() << "\t";
          break;
        case MultiBound::MODE_DOUBLE:
          if( iter->getDoubleBoundSetup(MultiBound::BOUND_INF) )
            os << iter->getDoubleBound(MultiBound::BOUND_INF)<<"\t";
          else os <<"-inf\t";
          if( iter->getDoubleBoundSetup(MultiBound::BOUND_SUP) )
            os << iter->getDoubleBound(MultiBound::BOUND_SUP)<<"\t";
          else os <<"+inf\t";
          break;
        }
    }
}

namespace {
	SOT_SIGNAL_CAST_DECLARATION(SignalCast_sotFeatureAbstractPtr);
	SOT_SIGNAL_CAST_DECLARATION(Flags);
	SOT_SIGNAL_CAST_DECLARATION(VectorMultiBound);
	SOT_SIGNAL_CAST_DECLARATION(timeval );
  dynamicgraph::DefaultCastRegisterer <sot::MatrixHomogeneous>
  matrixHomegeneousCastRegisterer;
}
<|endoftext|>


<commit_before>/*
Resembla
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

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

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

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

#ifndef RESEMBLA_SIMSTRING_DATABASE_HPP
#define RESEMBLA_SIMSTRING_DATABASE_HPP

#include <string>
#include <vector>
#include <unordered_map>
#include <memory>
#include <algorithm>
#include <mutex>

#include <simstring/simstring.h>

#include "csv_reader.hpp"
#include "eliminator.hpp"

namespace resembla {

template<typename Indexer>
class SimStringDatabase
{
public:
    using string_type = typename Indexer::output_type;

    SimStringDatabase(const std::string& simstring_db_path, int measure, double threshold,
            std::shared_ptr<Indexer> index_func, const std::string& index_path):
        measure(measure), threshold(threshold), index_func(index_func)
    {
        db.open(simstring_db_path);

        for(const auto& columns: CsvReader<string_type>(index_path, 2)){
            const auto& indexed = columns[0];
            const auto& original = columns[1];

            const auto& p = variants.insert(std::pair<string_type, std::vector<string_type>>(indexed, {original}));
            if(!p.second){
                p.first->second.push_back(original);
            }
        }
    }

    std::vector<string_type> search(const string_type& query, size_t max_output = 0) const
    {
        auto search_query = (*index_func)(query);

        std::vector<string_type> simstring_result;
        {
            std::lock_guard<std::mutex> lock(mutex_simstring);
            db.retrieve(search_query, measure, threshold,
                    std::back_inserter(simstring_result));
        }
        if(max_output != 0 && simstring_result.size() > max_output){
            Eliminator<string_type> eliminate(search_query);
            eliminate(simstring_result, max_output);
        }

        std::vector<string_type> result;
        for(const auto& i: simstring_result){
            if(i.empty()){
                continue;
            }
            const auto& j = variants.at(i);
            std::copy(std::begin(j), std::end(j), std::back_inserter(result));
        }

        return result;
    }

protected:
    mutable simstring::reader db;
    mutable std::mutex mutex_simstring;

    const int measure;
    const double threshold;

    const std::shared_ptr<Indexer> index_func;

    std::unordered_map<string_type, std::vector<string_type>> variants;
};

}
#endif
<commit_msg>modify variable name<commit_after>/*
Resembla
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

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

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

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

#ifndef RESEMBLA_SIMSTRING_DATABASE_HPP
#define RESEMBLA_SIMSTRING_DATABASE_HPP

#include <string>
#include <vector>
#include <unordered_map>
#include <memory>
#include <algorithm>
#include <mutex>

#include <simstring/simstring.h>

#include "csv_reader.hpp"
#include "eliminator.hpp"

namespace resembla {

template<typename Indexer>
class SimStringDatabase
{
public:
    using string_type = typename Indexer::output_type;

    SimStringDatabase(const std::string& simstring_db_path, int measure, double threshold,
            std::shared_ptr<Indexer> index_func, const std::string& index_path):
        measure(measure), threshold(threshold), index_func(index_func)
    {
        db.open(simstring_db_path);

        for(const auto& columns: CsvReader<string_type>(index_path, 2)){
            const auto& indexed = columns[0];
            const auto& original = columns[1];

            const auto& p = originals.insert(std::pair<string_type,
                    std::vector<string_type>>(indexed, {original}));
            if(!p.second){
                p.first->second.push_back(original);
            }
        }
    }

    std::vector<string_type> search(const string_type& query, size_t max_output = 0) const
    {
        auto search_query = (*index_func)(query);

        std::vector<string_type> simstring_result;
        {
            std::lock_guard<std::mutex> lock(mutex_simstring);
            db.retrieve(search_query, measure, threshold,
                    std::back_inserter(simstring_result));
        }
        if(max_output != 0 && simstring_result.size() > max_output){
            Eliminator<string_type> eliminate(search_query);
            eliminate(simstring_result, max_output);
        }

        std::vector<string_type> result;
        for(const auto& i: simstring_result){
            if(i.empty()){
                continue;
            }
            const auto& j = originals.at(i);
            std::copy(std::begin(j), std::end(j), std::back_inserter(result));
        }

        return result;
    }

protected:
    mutable simstring::reader db;
    mutable std::mutex mutex_simstring;

    const int measure;
    const double threshold;

    const std::shared_ptr<Indexer> index_func;

    std::unordered_map<string_type, std::vector<string_type>> originals;
};

}
#endif
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#if     qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../../../Foundation/Characters/String_Constant.h"
#include    "../../../Foundation/Debug/Assertions.h"
#include    "../../../Foundation/Execution/Sleep.h"

#include    "SystemCPU.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::DataExchange;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;
using   namespace   Stroika::Frameworks::SystemPerformance::Instruments::SystemCPU;

using   Characters::String_Constant;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
/*
 ********************************************************************************
 ********************* Instruments::SystemCPU::Info::LoadAverage ****************
 ********************************************************************************
 */
Instruments::SystemCPU::Info::LoadAverage::LoadAverage (double oneMinuteAve, double fiveMinuteAve, double fifteenMinuteAve)
    : f1MinuteAve (oneMinuteAve)
    , f5MinuteAve (fiveMinuteAve)
    , f15MinuteAve (fifteenMinuteAve)
{
}
#endif

/*
 ********************************************************************************
 ***************** Instruments::SystemCPU::GetObjectVariantMapper ***************
 ********************************************************************************
 */
ObjectVariantMapper Instruments::SystemCPU::GetObjectVariantMapper ()
{
    using   StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
    ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
        ObjectVariantMapper mapper;
        DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\"");   // Really probably an issue, but not to debug here -- LGP 2014-01-04
        DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\"");       // Really probably an issue, but not to debug here -- LGP 2014-01-04
#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
        mapper.AddClass<Info::LoadAverage> (initializer_list<StructureFieldInfo> {
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f1MinuteAve), String_Constant (L"1-minute") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f5MinuteAve), String_Constant (L"5-minute") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f15MinuteAve), String_Constant (L"15-minute") },
        });
        mapper.AddCommonType<Optional_Indirect_Storage<Info::LoadAverage>> ();
#endif
        mapper.AddClass<Info> (initializer_list<StructureFieldInfo> {
#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLoadAverage), String_Constant (L"Load-Average"), StructureFieldInfo::NullFieldHandling::eOmit },
#endif
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalCPUUsage), String_Constant (L"Total-CPU-Usage") },
        });
        DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
        DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
        return mapper;
    } ();
    return sMapper_;
}

#if     qPlatform_Windows
namespace {
    inline  double  GetAsSeconds_ (FILETIME ft)
    {
        ULARGE_INTEGER  ui;
        ui.LowPart = ft.dwLowDateTime;
        ui.HighPart = ft.dwHighDateTime;
        // convert from 100-nanosecond units
        return static_cast<double> (ui.QuadPart) / 10000000;
    }

    inline  void    GetSysTimes_ (double* idleTime, double* kernelTime, double* userTime)
    {
        RequireNotNull (idleTime);
        RequireNotNull (kernelTime);
        RequireNotNull (userTime);
        FILETIME    curIdleTime_;
        FILETIME    curKernelTime_;
        FILETIME    curUserTime_;
        memset (&curIdleTime_, 0, sizeof (curIdleTime_));
        memset (&curKernelTime_, 0, sizeof (curKernelTime_));
        memset (&curUserTime_, 0, sizeof (curUserTime_));
        Verify (::GetSystemTimes (&curIdleTime_, &curKernelTime_, &curUserTime_));
        *idleTime = GetAsSeconds_ (curIdleTime_);
        *kernelTime = GetAsSeconds_ (curKernelTime_);
        *userTime = GetAsSeconds_ (curUserTime_);
    }

    struct WinSysTimeCaptureContext_ {
        double  IdleTime {};
        double  KernelTime  {};
        double UserTime  {};
    };
    double  cputime_ (Optional<WinSysTimeCaptureContext_> prevContextObject = Optional<WinSysTimeCaptureContext_> (), WinSysTimeCaptureContext_* newContext = nullptr)
    {
        WinSysTimeCaptureContext_   baseline;
        if (prevContextObject) {
            baseline = *prevContextObject;
        }
        else {
            GetSysTimes_ (&baseline.IdleTime, &baseline.KernelTime, &baseline.UserTime);
            const Time::DurationSecondsType kUseIntervalIfNoBaseline_ { 1.0 };
            Execution::Sleep (kUseIntervalIfNoBaseline_);
        }
        WinSysTimeCaptureContext_   newVal;
        GetSysTimes_ (&newVal.IdleTime, &newVal.KernelTime, &newVal.UserTime);

        if (newContext != nullptr) {
            *newContext = newVal;
        }

        double  idleTimeOverInterval = newVal.IdleTime - baseline.IdleTime;
        double  kernelTimeOverInterval = newVal.KernelTime - baseline.KernelTime;
        double  userTimeOverInterval = newVal.UserTime - baseline.UserTime;

        double sys = kernelTimeOverInterval + userTimeOverInterval;
        Assert (sys > 0);
        double cpu =  (sys - idleTimeOverInterval) * 100 / sys;
        return cpu;
    }
}
#endif

namespace {
    Info capture_ ()
    {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
        Debug::TraceContextBumper ctx ("Instruments::SystemCPU capture_");
#endif
        Info    result;
#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
        {
            double loadAve[3];
            int lr = ::getloadavg (loadAve, 3);
            if (lr == 3) {
                result.fLoadAverage = Info::LoadAverage (loadAve[0], loadAve[1], loadAve[2]);
            }
            else {
                DbgTrace ("getloadave failed - with result = %d", lr);
            }
        }
#endif
#if     qPlatform_POSIX
        //result.fTotalCPUUsage = cputime_ ();
#elif     qPlatform_Windows
        result.fTotalCPUUsage = cputime_ ();
#endif

        return result;
    }
}

/*
 ********************************************************************************
 ******************* Instruments::SystemCPU::GetInstrument **********************
 ********************************************************************************
 */
Instrument  SystemPerformance::Instruments::SystemCPU::GetInstrument ()
{
    static  const   MeasurementType kSystemCPUMeasurment_         =   MeasurementType (String_Constant (L"System-CPU-Usage"));
    static  Instrument  kInstrument_    = Instrument (
            InstrumentNameType (String_Constant (L"System-CPU")),
    [] () -> MeasurementSet {
        MeasurementSet    results;
        DateTime    before = DateTime::Now ();
        Info rawMeasurement = capture_ ();
        results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
        Measurement m;
        m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
        m.fType = kSystemCPUMeasurment_;
        results.fMeasurements.Add (m);
        return results;
    },
    {kSystemCPUMeasurment_},
    GetObjectVariantMapper ()
                                          );
    return kInstrument_;
}
<commit_msg>use capture context in mutable lambda to repserve past values so we average over interval since last use for SystemPerformance/Instruments/SystemCPU (windows only so far)<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#if     qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../../../Foundation/Characters/String_Constant.h"
#include    "../../../Foundation/Debug/Assertions.h"
#include    "../../../Foundation/Execution/Sleep.h"

#include    "SystemCPU.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::DataExchange;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;
using   namespace   Stroika::Frameworks::SystemPerformance::Instruments::SystemCPU;

using   Characters::String_Constant;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
/*
 ********************************************************************************
 ********************* Instruments::SystemCPU::Info::LoadAverage ****************
 ********************************************************************************
 */
Instruments::SystemCPU::Info::LoadAverage::LoadAverage (double oneMinuteAve, double fiveMinuteAve, double fifteenMinuteAve)
    : f1MinuteAve (oneMinuteAve)
    , f5MinuteAve (fiveMinuteAve)
    , f15MinuteAve (fifteenMinuteAve)
{
}
#endif

/*
 ********************************************************************************
 ***************** Instruments::SystemCPU::GetObjectVariantMapper ***************
 ********************************************************************************
 */
ObjectVariantMapper Instruments::SystemCPU::GetObjectVariantMapper ()
{
    using   StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
    ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
        ObjectVariantMapper mapper;
        DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\"");   // Really probably an issue, but not to debug here -- LGP 2014-01-04
        DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\"");       // Really probably an issue, but not to debug here -- LGP 2014-01-04
#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
        mapper.AddClass<Info::LoadAverage> (initializer_list<StructureFieldInfo> {
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f1MinuteAve), String_Constant (L"1-minute") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f5MinuteAve), String_Constant (L"5-minute") },
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info::LoadAverage, f15MinuteAve), String_Constant (L"15-minute") },
        });
        mapper.AddCommonType<Optional_Indirect_Storage<Info::LoadAverage>> ();
#endif
        mapper.AddClass<Info> (initializer_list<StructureFieldInfo> {
#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLoadAverage), String_Constant (L"Load-Average"), StructureFieldInfo::NullFieldHandling::eOmit },
#endif
            { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalCPUUsage), String_Constant (L"Total-CPU-Usage") },
        });
        DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
        DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
        return mapper;
    } ();
    return sMapper_;
}

#if     qPlatform_Windows
namespace {
    inline  double  GetAsSeconds_ (FILETIME ft)
    {
        ULARGE_INTEGER  ui;
        ui.LowPart = ft.dwLowDateTime;
        ui.HighPart = ft.dwHighDateTime;
        // convert from 100-nanosecond units
        return static_cast<double> (ui.QuadPart) / 10000000;
    }

    inline  void    GetSysTimes_ (double* idleTime, double* kernelTime, double* userTime)
    {
        RequireNotNull (idleTime);
        RequireNotNull (kernelTime);
        RequireNotNull (userTime);
        FILETIME    curIdleTime_;
        FILETIME    curKernelTime_;
        FILETIME    curUserTime_;
        memset (&curIdleTime_, 0, sizeof (curIdleTime_));
        memset (&curKernelTime_, 0, sizeof (curKernelTime_));
        memset (&curUserTime_, 0, sizeof (curUserTime_));
        Verify (::GetSystemTimes (&curIdleTime_, &curKernelTime_, &curUserTime_));
        *idleTime = GetAsSeconds_ (curIdleTime_);
        *kernelTime = GetAsSeconds_ (curKernelTime_);
        *userTime = GetAsSeconds_ (curUserTime_);
    }

    struct WinSysTimeCaptureContext_ {
        double  IdleTime {};
        double  KernelTime  {};
        double UserTime  {};
    };
    double  cputime_ (Optional<WinSysTimeCaptureContext_> prevContextObject = Optional<WinSysTimeCaptureContext_> (), WinSysTimeCaptureContext_* newContext = nullptr)
    {
        WinSysTimeCaptureContext_   baseline;
        if (prevContextObject) {
            baseline = *prevContextObject;
        }
        else {
            GetSysTimes_ (&baseline.IdleTime, &baseline.KernelTime, &baseline.UserTime);
            const Time::DurationSecondsType kUseIntervalIfNoBaseline_ { 1.0 };
            Execution::Sleep (kUseIntervalIfNoBaseline_);
        }
        WinSysTimeCaptureContext_   newVal;
        GetSysTimes_ (&newVal.IdleTime, &newVal.KernelTime, &newVal.UserTime);

        if (newContext != nullptr) {
            *newContext = newVal;
        }

        double  idleTimeOverInterval = newVal.IdleTime - baseline.IdleTime;
        double  kernelTimeOverInterval = newVal.KernelTime - baseline.KernelTime;
        double  userTimeOverInterval = newVal.UserTime - baseline.UserTime;

        double sys = kernelTimeOverInterval + userTimeOverInterval;
        Assert (sys > 0);
        double cpu =  (sys - idleTimeOverInterval) * 100 / sys;
        return cpu;
    }
}
#endif

namespace {
    struct  CaptureContext_ {
#if     qPlatform_Windows
        Optional<WinSysTimeCaptureContext_> fContext_;
#endif
        Info capture_ ()
        {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            Debug::TraceContextBumper ctx ("Instruments::SystemCPU capture_");
#endif
            Info    result;
#if     qSupport_SystemPerformance_Instruments_SystemCPU_LoadAverage
            {
                double loadAve[3];
                int lr = ::getloadavg (loadAve, 3);
                if (lr == 3) {
                    result.fLoadAverage = Info::LoadAverage (loadAve[0], loadAve[1], loadAve[2]);
                }
                else {
                    DbgTrace ("getloadave failed - with result = %d", lr);
                }
            }
#endif
#if     qPlatform_POSIX
            //result.fTotalCPUUsage = cputime_ ();
#elif     qPlatform_Windows
            WinSysTimeCaptureContext_   tmp;
            result.fTotalCPUUsage = cputime_ (fContext_, &tmp);
            fContext_ = tmp;
#endif
            return result;
        }
    };
}

/*
 ********************************************************************************
 ******************* Instruments::SystemCPU::GetInstrument **********************
 ********************************************************************************
 */
Instrument  SystemPerformance::Instruments::SystemCPU::GetInstrument ()
{
    CaptureContext_ useCaptureContext;
    static  const   MeasurementType kSystemCPUMeasurment_         =   MeasurementType (String_Constant (L"System-CPU-Usage"));
    static  Instrument  kInstrument_    = Instrument (
            InstrumentNameType (String_Constant (L"System-CPU")),
    [useCaptureContext] () mutable -> MeasurementSet {
        MeasurementSet    results;
        DateTime    before = DateTime::Now ();
        Info rawMeasurement = useCaptureContext.capture_ ();
        results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
        Measurement m;
        m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement);
        m.fType = kSystemCPUMeasurment_;
        results.fMeasurements.Add (m);
        return results;
    },
    {kSystemCPUMeasurment_},
    GetObjectVariantMapper ()
                                          );
    return kInstrument_;
}
<|endoftext|>