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

#include "webkit/tools/test_shell/test_shell_devtools_agent.h"

#include "base/message_loop.h"
#include "grit/webkit_chromium_resources.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_devtools_callargs.h"
#include "webkit/tools/test_shell/test_shell_devtools_client.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebCString;
using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsMessageData;
using WebKit::WebString;
using WebKit::WebView;

namespace {

class WebKitClientMessageLoopImpl
    : public WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop {
 public:
  WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { }
  virtual ~WebKitClientMessageLoopImpl() {
    message_loop_ = NULL;
  }
  virtual void run() {
    bool old_state = message_loop_->NestableTasksAllowed();
    message_loop_->SetNestableTasksAllowed(true);
    message_loop_->Run();
    message_loop_->SetNestableTasksAllowed(old_state);
  }
  virtual void quitNow() {
    message_loop_->QuitNow();
  }
 private:
  MessageLoop* message_loop_;
};

} //  namespace

// static
void TestShellDevToolsAgent::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// Warning at call_method_factory_(this) treated as error is switched off.

#if defined(OS_WIN)
#pragma warning(disable : 4355)
#endif // defined(OS_WIN)

TestShellDevToolsAgent::TestShellDevToolsAgent(WebView* web_view)
    : call_method_factory_(this),
      dev_tools_client_(NULL),
      web_view_(web_view) {
  static int dev_tools_agent_counter;
  routing_id_ = ++dev_tools_agent_counter;
  if (routing_id_ == 1)
    WebDevToolsAgent::setMessageLoopDispatchHandler(
        &TestShellDevToolsAgent::DispatchMessageLoop);
  web_dev_tools_agent_ = WebDevToolsAgent::create(web_view_, this);
  web_view_->setDevToolsAgent(web_dev_tools_agent_);
}

void TestShellDevToolsAgent::sendMessageToFrontend(
       const WebDevToolsMessageData& data) {
  if (dev_tools_client_)
    dev_tools_client_->AsyncCall(TestShellDevToolsCallArgs(data));
}

void TestShellDevToolsAgent::forceRepaint() {
}

void TestShellDevToolsAgent::runtimeFeatureStateChanged(
    const WebKit::WebString& feature, bool enabled) {
  // TODO(loislo): implement this.
}

WebCString TestShellDevToolsAgent::injectedScriptSource() {
  base::StringPiece injectjsWebkit =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
  return WebCString(injectjsWebkit.data(), injectjsWebkit.length());
}

WebCString TestShellDevToolsAgent::injectedScriptDispatcherSource() {
  base::StringPiece injectDispatchjs =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_DISPATCH_JS);
  return WebCString(injectDispatchjs.data(), injectDispatchjs.length());
}

WebCString TestShellDevToolsAgent::debuggerScriptSource() {
  base::StringPiece debuggerScriptjs =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS);
  return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length());
}

WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop*
    TestShellDevToolsAgent::createClientMessageLoop() {
  return new WebKitClientMessageLoopImpl();
}

void TestShellDevToolsAgent::AsyncCall(const TestShellDevToolsCallArgs &args) {
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      call_method_factory_.NewRunnableMethod(&TestShellDevToolsAgent::Call,
                                             args),
      0);
}

void TestShellDevToolsAgent::Call(const TestShellDevToolsCallArgs &args) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->dispatchMessageFromFrontend(args.data_);
  if (TestShellDevToolsCallArgs::calls_count() == 1 && dev_tools_client_)
    dev_tools_client_->all_messages_processed();
}

WebDevToolsAgent* TestShellDevToolsAgent::GetWebAgent() {
  if (!web_view_)
    return NULL;
  return web_view_->devToolsAgent();
}

void TestShellDevToolsAgent::attach(TestShellDevToolsClient* client) {
  DCHECK(!dev_tools_client_);
  dev_tools_client_ = client;
  WebDevToolsAgent *web_agent = GetWebAgent();
  if (web_agent)
    web_agent->attach();
}

void TestShellDevToolsAgent::detach(TestShellDevToolsClient* client) {
  DCHECK(dev_tools_client_);
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->detach();
  dev_tools_client_ = NULL;
}

bool TestShellDevToolsAgent::setTimelineProfilingEnabled(bool enabled) {
  WebDevToolsAgent* agent = GetWebAgent();
  if (!agent)
    return false;
  agent->setTimelineProfilingEnabled(enabled);
  return true;
}

bool TestShellDevToolsAgent::evaluateInWebInspector(
      long call_id,
      const std::string& script) {
  WebDevToolsAgent* agent = GetWebAgent();
  if (!agent)
    return false;
  agent->evaluateInWebInspector(call_id, WebString::fromUTF8(script));
  return true;
}

// static
void WebKit::WebDevToolsAgentClient::sendMessageToFrontendOnIOThread(
    WebKit::WebDevToolsMessageData const &) {
  NOTIMPLEMENTED();
}
<commit_msg>Remove sendMessageToFrontendOnIOThread implementation from test_shell_devtools_agent.cc<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/tools/test_shell/test_shell_devtools_agent.h"

#include "base/message_loop.h"
#include "grit/webkit_chromium_resources.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h"
#include "third_party/WebKit/WebKit/chromium/public/WebView.h"
#include "webkit/tools/test_shell/test_shell_devtools_callargs.h"
#include "webkit/tools/test_shell/test_shell_devtools_client.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebCString;
using WebKit::WebDevToolsAgent;
using WebKit::WebDevToolsMessageData;
using WebKit::WebString;
using WebKit::WebView;

namespace {

class WebKitClientMessageLoopImpl
    : public WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop {
 public:
  WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { }
  virtual ~WebKitClientMessageLoopImpl() {
    message_loop_ = NULL;
  }
  virtual void run() {
    bool old_state = message_loop_->NestableTasksAllowed();
    message_loop_->SetNestableTasksAllowed(true);
    message_loop_->Run();
    message_loop_->SetNestableTasksAllowed(old_state);
  }
  virtual void quitNow() {
    message_loop_->QuitNow();
  }
 private:
  MessageLoop* message_loop_;
};

} //  namespace

// static
void TestShellDevToolsAgent::DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

// Warning at call_method_factory_(this) treated as error is switched off.

#if defined(OS_WIN)
#pragma warning(disable : 4355)
#endif // defined(OS_WIN)

TestShellDevToolsAgent::TestShellDevToolsAgent(WebView* web_view)
    : call_method_factory_(this),
      dev_tools_client_(NULL),
      web_view_(web_view) {
  static int dev_tools_agent_counter;
  routing_id_ = ++dev_tools_agent_counter;
  if (routing_id_ == 1)
    WebDevToolsAgent::setMessageLoopDispatchHandler(
        &TestShellDevToolsAgent::DispatchMessageLoop);
  web_dev_tools_agent_ = WebDevToolsAgent::create(web_view_, this);
  web_view_->setDevToolsAgent(web_dev_tools_agent_);
}

void TestShellDevToolsAgent::sendMessageToFrontend(
       const WebDevToolsMessageData& data) {
  if (dev_tools_client_)
    dev_tools_client_->AsyncCall(TestShellDevToolsCallArgs(data));
}

void TestShellDevToolsAgent::forceRepaint() {
}

void TestShellDevToolsAgent::runtimeFeatureStateChanged(
    const WebKit::WebString& feature, bool enabled) {
  // TODO(loislo): implement this.
}

WebCString TestShellDevToolsAgent::injectedScriptSource() {
  base::StringPiece injectjsWebkit =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
  return WebCString(injectjsWebkit.data(), injectjsWebkit.length());
}

WebCString TestShellDevToolsAgent::injectedScriptDispatcherSource() {
  base::StringPiece injectDispatchjs =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_DISPATCH_JS);
  return WebCString(injectDispatchjs.data(), injectDispatchjs.length());
}

WebCString TestShellDevToolsAgent::debuggerScriptSource() {
  base::StringPiece debuggerScriptjs =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS);
  return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length());
}

WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop*
    TestShellDevToolsAgent::createClientMessageLoop() {
  return new WebKitClientMessageLoopImpl();
}

void TestShellDevToolsAgent::AsyncCall(const TestShellDevToolsCallArgs &args) {
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      call_method_factory_.NewRunnableMethod(&TestShellDevToolsAgent::Call,
                                             args),
      0);
}

void TestShellDevToolsAgent::Call(const TestShellDevToolsCallArgs &args) {
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->dispatchMessageFromFrontend(args.data_);
  if (TestShellDevToolsCallArgs::calls_count() == 1 && dev_tools_client_)
    dev_tools_client_->all_messages_processed();
}

WebDevToolsAgent* TestShellDevToolsAgent::GetWebAgent() {
  if (!web_view_)
    return NULL;
  return web_view_->devToolsAgent();
}

void TestShellDevToolsAgent::attach(TestShellDevToolsClient* client) {
  DCHECK(!dev_tools_client_);
  dev_tools_client_ = client;
  WebDevToolsAgent *web_agent = GetWebAgent();
  if (web_agent)
    web_agent->attach();
}

void TestShellDevToolsAgent::detach(TestShellDevToolsClient* client) {
  DCHECK(dev_tools_client_);
  WebDevToolsAgent* web_agent = GetWebAgent();
  if (web_agent)
    web_agent->detach();
  dev_tools_client_ = NULL;
}

bool TestShellDevToolsAgent::setTimelineProfilingEnabled(bool enabled) {
  WebDevToolsAgent* agent = GetWebAgent();
  if (!agent)
    return false;
  agent->setTimelineProfilingEnabled(enabled);
  return true;
}

bool TestShellDevToolsAgent::evaluateInWebInspector(
      long call_id,
      const std::string& script) {
  WebDevToolsAgent* agent = GetWebAgent();
  if (!agent)
    return false;
  agent->evaluateInWebInspector(call_id, WebString::fromUTF8(script));
  return true;
}
<|endoftext|>


<commit_before><commit_msg>winaccessibility: avoid warning C4005 macro redefinition<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ChartPlotAreaOOoTContext.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:45:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef XMLOFF_XMLCHARTPLOTAREAOOOTCONTEXT_HXX
#define XMLOFF_XMLCHARTPLOTAREAOOOTCONTEXT_HXX

#ifndef _XMLOFF_PROCATTRTCONTEXT_HXX
#include "ProcAttrTContext.hxx"
#endif
#ifndef _XMLOFF_TCONTEXTVECTOR_HXX
#include "TContextVector.hxx"
#endif

class XMLChartPlotAreaOOoTContext  : public XMLProcAttrTransformerContext
{
public:
    TYPEINFO();

    explicit XMLChartPlotAreaOOoTContext(
        XMLTransformerBase & rTransformer, const ::rtl::OUString & rQName );
    virtual ~XMLChartPlotAreaOOoTContext();

    virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::rtl::OUString& rQName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();
    virtual void ExportContent();

protected:
    void AddContent( XMLTransformerContext *pContent );

private:
    XMLTransformerContextVector m_aChildContexts;
};

// XMLOFF_XMLCHARTPLOTAREAOOOTCONTEXT_HXX
#endif
<commit_msg>INTEGRATION: CWS schoasis02 (1.2.92); FILE MERGED 2004/11/04 17:19:30 bm 1.2.92.1: #i36581# axis: class->dimension<commit_after>/*************************************************************************
 *
 *  $RCSfile: ChartPlotAreaOOoTContext.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-15 12:36:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef XMLOFF_XMLCHARTPLOTAREAOOOTCONTEXT_HXX
#define XMLOFF_XMLCHARTPLOTAREAOOOTCONTEXT_HXX

#ifndef _XMLOFF_PROCATTRTCONTEXT_HXX
#include "ProcAttrTContext.hxx"
#endif
#ifndef _XMLOFF_TCONTEXTVECTOR_HXX
#include "TContextVector.hxx"
#endif

class XMLAxisOOoContext;

class XMLAxisContextVector :
    public ::std::vector< ::rtl::Reference< XMLAxisOOoContext > >
{
};

class XMLChartPlotAreaOOoTContext  : public XMLProcAttrTransformerContext
{
public:
    TYPEINFO();

    explicit XMLChartPlotAreaOOoTContext(
        XMLTransformerBase & rTransformer, const ::rtl::OUString & rQName );
    virtual ~XMLChartPlotAreaOOoTContext();

    virtual XMLTransformerContext *CreateChildContext( sal_uInt16 nPrefix,
                                   const ::rtl::OUString& rLocalName,
                                   const ::rtl::OUString& rQName,
                                   const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );
    virtual void EndElement();
    virtual void ExportContent();

protected:
    void AddContent( XMLAxisOOoContext *pContent );

private:
    XMLAxisContextVector m_aChildContexts;
};

// XMLOFF_XMLCHARTPLOTAREAOOOTCONTEXT_HXX
#endif
<|endoftext|>


<commit_before>/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "soundemittercomponent.h"

#include <QtCore/QDebug>

#include <audio/engine.h>
#include <audio/sound.h>
#include <engine/assets/audio/sound/soundasset.h>
#include <engine/gameobject.h>
#include <gluon/audio/sound.h>

REGISTER_OBJECTTYPE(GluonEngine,SoundEmitterComponent)

using namespace GluonEngine;

SoundEmitterComponent::SoundEmitterComponent(QObject *parent)
    : Component(parent),
      m_sound(0)
{
}

SoundEmitterComponent::SoundEmitterComponent(const GluonEngine::SoundEmitterComponent &other)
    : Component(other)
{
}

GluonCore::GluonObject *SoundEmitterComponent::instantiate()
{
    return new SoundEmitterComponent(this);
}

void SoundEmitterComponent::play()
{
    m_sound->play();
}

void SoundEmitterComponent::setSound(SoundAsset *asset)
{
    m_soundAsset = asset;
    m_sound->load(asset->buffer());
}

void SoundEmitterComponent::start()
{
    m_sound = new GluonAudio::Sound();
}

void SoundEmitterComponent::draw(int timeLapse)
{
    Q_UNUSED(timeLapse);
    m_sound->setPosition(gameObject()->position());

    if(m_sound->isLooping() && !m_sound->isPlaying())
        m_sound->play();
}

void SoundEmitterComponent::update(int elapsedMilliseconds)
{
    Q_UNUSED(elapsedMilliseconds)
}

bool SoundEmitterComponent::isLooping()
{

}

void SoundEmitterComponent::setLoop(bool loop)
{

}

/*void SoundEmitterComponent::stop()
{
    m_sound->stop();
}*/

Q_EXPORT_PLUGIN2(gluon_component_soundemitter, GluonEngine::SoundEmitterComponent)

#include "soundemittercomponent.moc"
<commit_msg>Fix build error<commit_after>/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "soundemittercomponent.h"

#include <QtCore/QDebug>

#include <audio/engine.h>
#include <audio/sound.h>
#include <engine/assets/audio/sound/soundasset.h>
#include <engine/gameobject.h>

REGISTER_OBJECTTYPE(GluonEngine,SoundEmitterComponent)

using namespace GluonEngine;

SoundEmitterComponent::SoundEmitterComponent(QObject *parent)
    : Component(parent),
      m_sound(0)
{
}

SoundEmitterComponent::SoundEmitterComponent(const GluonEngine::SoundEmitterComponent &other)
    : Component(other)
{
}

GluonCore::GluonObject *SoundEmitterComponent::instantiate()
{
    return new SoundEmitterComponent(this);
}

void SoundEmitterComponent::play()
{
    m_sound->play();
}

void SoundEmitterComponent::setSound(SoundAsset *asset)
{
    m_soundAsset = asset;
    m_sound->load(asset->buffer());
}

void SoundEmitterComponent::start()
{
    m_sound = new GluonAudio::Sound();
}

void SoundEmitterComponent::draw(int timeLapse)
{
    Q_UNUSED(timeLapse);
    m_sound->setPosition(gameObject()->position());

    if(m_sound->isLooping() && !m_sound->isPlaying())
        m_sound->play();
}

void SoundEmitterComponent::update(int elapsedMilliseconds)
{
    Q_UNUSED(elapsedMilliseconds)
}

bool SoundEmitterComponent::isLooping()
{

}

void SoundEmitterComponent::setLoop(bool loop)
{

}

/*void SoundEmitterComponent::stop()
{
    m_sound->stop();
}*/

Q_EXPORT_PLUGIN2(gluon_component_soundemitter, GluonEngine::SoundEmitterComponent)

#include "soundemittercomponent.moc"
<|endoftext|>


<commit_before>#include "sqltenging.h"

sqltenging::sqltenging()
{
    _db = QSqlDatabase::database();
    if (!_db.isOpen())
    {
        _db = QSqlDatabase::addDatabase("QSQLITE");
        QString dbName = "vln1.sqlite";
        _db.setDatabaseName(dbName);
        _db.open();
    }
}
// VELAR
vector<velar> sqltenging::lesaVelar(int id) const
{
    string sql = "SELECT * FROM TolvuVelar";

    if (id != -1){
        sql += " WHERE id = " + to_string(id);
    }

    return selectVelar(sql);
}

vector<velar> sqltenging::lesaVelarSorted(string flokkur, string rod) const
{
    string sql = "SELECT * FROM TolvuVelar "
            "ORDER BY " + flokkur + " " + rod;

    return selectVelar(sql);
}

vector<velar> sqltenging::leitaVelar(string flokkur, string leitarord, char pos)
{
    string sql = "SELECT * FROM TolvuVelar "
            "WHERE " + flokkur + " LIKE ";

    if (pos == 'b'){
        sql += "'" + leitarord + "%'";
    }else if (pos == 'e'){
        sql += "'%" + leitarord + "'";
    }else{
        sql += "'%" + leitarord + "%'";
    }

    return selectVelar(sql);
}

vector<velar> sqltenging::leitaVelar(string flokkur, char type, int leitarord)
{
    string sql = "SELECT * FROM TolvuVelar "
            "WHERE " + flokkur + " " + type + " " + to_string(leitarord);

    return selectVelar(sql);
}

vector<velar> sqltenging::leitaVelar(string flokkur, int laegraBil, int haerraBil)
{
    string sql = "SELECT * FROM TolvuVelar "
            "WHERE " + flokkur + " BETWEEN " + to_string(laegraBil) + " AND " + to_string(haerraBil);

    return selectVelar(sql);
}

void sqltenging::baetaVidVel(string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "INSERT INTO TolvuVelar(Nafn, Byggingarar, Byggd, Tegund)"
                  "VALUES('" + nafn + "'," + to_string(bAr) + "," + to_string(byggd) + ",'" + tegund + "')";
    udiSkipun(sql);
}

void sqltenging::eydaVel(int id)
{

    string sql = "DELETE FROM TolvuVelar WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraVel(int id, string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "UPDATE TolvuVelar "
                 "SET nafn = '" +  nafn + "'"
                 ", byggingarar = " + to_string(bAr) +
                 ", byggd = " + to_string(byggd) +
                 ", tegund = '" + tegund + "'"
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaVelum()
{
    string terminator = "DELETE FROM TolvuVelar";
    udiSkipun(terminator);
}

// FOLK
vector<tolvufolk> sqltenging::lesaFolk(int id) const
{
    string sql = "SELECT * FROM TolvuFolk";

    if (id != -1){
        sql += " WHERE ID = " + to_string(id);
    }

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::lesaFolkSorted(string flokkur, string rod)
{
    string sql = "SELECT * FROM TolvuFolk "
            "ORDER BY " + flokkur + " " + rod;

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::leitaFolk(string flokkur, string leitarord, char pos)
{
    string sql = "SELECT * FROM Tolvufolk "
            "WHERE " + flokkur + " LIKE ";

    if (pos == 'b'){
        sql += "'" + leitarord + "%'";
    }else if (pos == 'e'){
        sql += "'%" + leitarord + "'";
    }else{
        sql += "'%" + leitarord + "%'";
    }

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::leitaFolk(string flokkur, char type, int leitarord)
{
    string sql = "SELECT * FROM TolvuFolk "
            "WHERE " + flokkur + " " + type + " " + to_string(leitarord);

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::leitaFolk(string flokkur, int laegraBil, int haerraBil)
{
    string sql = "SELECT * FROM TolvuFolk "
            "WHERE " + flokkur + " BETWEEN " + to_string(laegraBil) + " AND " + to_string(haerraBil);

    return selectFolk(sql);
}

void sqltenging::baetaVidFolk(string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "INSERT INTO TolvuFolk(ForNafn, EftirNafn, Kyn, FaedingarAr, DanarAr)"
                  "VALUES('" + fNafn + "','" + eNafn + "','" + kyn + "'," + to_string(fAr) + "," + to_string(dAr) + ")";
    udiSkipun(sql);
}
void sqltenging::eydaFolk(int id)
{

    string sql = "DELETE FROM TolvuFolk WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraFolk(int id, string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "UPDATE TolvuFolk "
                 "SET fornafn = '" +  fNafn + "'"
                 ", eftirnafn = '" + eNafn + "'"
                 ", kyn = '" + kyn + "'"
                 ", faedingarAr = " + to_string(fAr) +
                 ", danarAr = " + to_string(dAr) + " "
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaFolki()
{
    string terminator = "DELETE FROM tolvufolk";
    udiSkipun(terminator);
}

int sqltenging::saekjaSize(string flokkur) const
{
    int size = 0;
    string sql = "SELECT COUNT(*) as Size from ";
    if (flokkur == "velar"){
        sql += "TolvuVelar";
    }else if (flokkur == "folk"){
        sql += "TolvuFolk";
    }else{
        size = -1;
    }

    if (size != -1)
    {
        QSqlQuery query(_db);
        char* cstr = new char[sql.length()+1];
        strcpy(cstr, sql.c_str());
        query.exec(cstr);
        if (query.next()){
            size = query.value("Size").toUInt();
        }
    }
    return size;
}

//Vensl

<<<<<<< HEAD
void sqltenging::buaTilVensl(int folkID, int velID)
{
    string sql = "INSERT INTO venslfolkvelar(folk_id,vel_id)"
                 "VALUES(" + to_string(folkID) + "," + to_string(velID) + ")";
    udiSkipun(sql);

}

void sqltenging::eydaVenslFolk(int id)
{
    string sql = "DELETE FROM venslfolkvelar WHERE folk_id = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::eydaVenslVel(int id)
{
    string sql = "DELETE FROM venslfolkvelar WHERE folk_id = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::eydaStakiVensl(int folkID, int velID)
{
    string sql = "DELETE FROM venslfolkvelar"
                 "WHERE folk_id = " + to_string(folkID) + " "
                 "AND vel_id = " + to_string(velID);
    udiSkipun(sql);

vector<tolvufolk> sqltenging::lesaFolkVenslad(int velarID) const
{
    string sql = "SELECT f.id, f.fornafn, f.eftirnafn, f.kyn, f.faedingarar, f.danarar "
            "FROM tolvufolk f "
            "INNER JOIN venslfolkvelar v ON v.folk_id = f.id "
            "INNER JOIN tolvuvelar t ON v.vel_id = t.id "
            "WHERE t.id = " + to_string(velarID);

    return selectFolk(sql);
}

vector<velar> sqltenging::lesaVelarVenslad(int folkID) const
{
    string sql = "SELECT t.id, t.nafn, t.byggingarar, t.byggd, t.tegund "
            "FROM tolvulvelar t "
            "INNER JOIN venslfolkvelar v ON v.vel_id = t.id "
            "INNER JOIN tolvufolk f ON v.folk_id = f.id "
            "WHERE f.id = " + to_string(folkID);

    return selectVelar(sql);
}

// Private Functions
vector<tolvufolk> sqltenging::selectFolk(string sql) const
{
    vector<tolvufolk> t;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string fornafn = query.value("fornafn").toString().toStdString();
        string eftirnafn = query.value("eftirnafn").toString().toStdString();
        char kyn = query.value("kyn").toString().toStdString()[0];
        int faedingarar = query.value("faedingarar").toUInt();
        int danarar = query.value("danarar").toUInt();

        t.push_back(tolvufolk(id, fornafn, eftirnafn, kyn, faedingarar, danarar));
    }

    return t;
}

vector<velar> sqltenging::selectVelar(string sql) const
{
    vector<velar> v;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string nafn = query.value("Nafn").toString().toStdString();
        int ar = query.value("byggingarar").toUInt();
        bool byggd = query.value("byggd").toBool();
        string tegund = query.value("tegund").toString().toStdString();

        v.push_back(velar(id, nafn, ar, tegund, byggd));
    }

    return v;
}

void sqltenging::udiSkipun(string sql)
{
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    QSqlQuery query(_db);
    query.exec(cstr);
    delete[] cstr;
}
// End of private functions
<commit_msg>Lagaði það sem unnsteinn skemmdi<commit_after>#include "sqltenging.h"

sqltenging::sqltenging()
{
    _db = QSqlDatabase::database();
    if (!_db.isOpen())
    {
        _db = QSqlDatabase::addDatabase("QSQLITE");
        QString dbName = "vln1.sqlite";
        _db.setDatabaseName(dbName);
        _db.open();
    }
}
// VELAR
vector<velar> sqltenging::lesaVelar(int id) const
{
    string sql = "SELECT * FROM TolvuVelar";

    if (id != -1){
        sql += " WHERE id = " + to_string(id);
    }

    return selectVelar(sql);
}

vector<velar> sqltenging::lesaVelarSorted(string flokkur, string rod) const
{
    string sql = "SELECT * FROM TolvuVelar "
            "ORDER BY " + flokkur + " " + rod;

    return selectVelar(sql);
}

vector<velar> sqltenging::leitaVelar(string flokkur, string leitarord, char pos)
{
    string sql = "SELECT * FROM TolvuVelar "
            "WHERE " + flokkur + " LIKE ";

    if (pos == 'b'){
        sql += "'" + leitarord + "%'";
    }else if (pos == 'e'){
        sql += "'%" + leitarord + "'";
    }else{
        sql += "'%" + leitarord + "%'";
    }

    return selectVelar(sql);
}

vector<velar> sqltenging::leitaVelar(string flokkur, char type, int leitarord)
{
    string sql = "SELECT * FROM TolvuVelar "
            "WHERE " + flokkur + " " + type + " " + to_string(leitarord);

    return selectVelar(sql);
}

vector<velar> sqltenging::leitaVelar(string flokkur, int laegraBil, int haerraBil)
{
    string sql = "SELECT * FROM TolvuVelar "
            "WHERE " + flokkur + " BETWEEN " + to_string(laegraBil) + " AND " + to_string(haerraBil);

    return selectVelar(sql);
}

void sqltenging::baetaVidVel(string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "INSERT INTO TolvuVelar(Nafn, Byggingarar, Byggd, Tegund)"
                  "VALUES('" + nafn + "'," + to_string(bAr) + "," + to_string(byggd) + ",'" + tegund + "')";
    udiSkipun(sql);
}

void sqltenging::eydaVel(int id)
{

    string sql = "DELETE FROM TolvuVelar WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraVel(int id, string nafn, int bAr, bool byggd, string tegund)
{
    string sql = "UPDATE TolvuVelar "
                 "SET nafn = '" +  nafn + "'"
                 ", byggingarar = " + to_string(bAr) +
                 ", byggd = " + to_string(byggd) +
                 ", tegund = '" + tegund + "'"
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaVelum()
{
    string terminator = "DELETE FROM TolvuVelar";
    udiSkipun(terminator);
}

// FOLK
vector<tolvufolk> sqltenging::lesaFolk(int id) const
{
    string sql = "SELECT * FROM TolvuFolk";

    if (id != -1){
        sql += " WHERE ID = " + to_string(id);
    }

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::lesaFolkSorted(string flokkur, string rod)
{
    string sql = "SELECT * FROM TolvuFolk "
            "ORDER BY " + flokkur + " " + rod;

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::leitaFolk(string flokkur, string leitarord, char pos)
{
    string sql = "SELECT * FROM Tolvufolk "
            "WHERE " + flokkur + " LIKE ";

    if (pos == 'b'){
        sql += "'" + leitarord + "%'";
    }else if (pos == 'e'){
        sql += "'%" + leitarord + "'";
    }else{
        sql += "'%" + leitarord + "%'";
    }

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::leitaFolk(string flokkur, char type, int leitarord)
{
    string sql = "SELECT * FROM TolvuFolk "
            "WHERE " + flokkur + " " + type + " " + to_string(leitarord);

    return selectFolk(sql);
}

vector<tolvufolk> sqltenging::leitaFolk(string flokkur, int laegraBil, int haerraBil)
{
    string sql = "SELECT * FROM TolvuFolk "
            "WHERE " + flokkur + " BETWEEN " + to_string(laegraBil) + " AND " + to_string(haerraBil);

    return selectFolk(sql);
}

void sqltenging::baetaVidFolk(string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "INSERT INTO TolvuFolk(ForNafn, EftirNafn, Kyn, FaedingarAr, DanarAr)"
                  "VALUES('" + fNafn + "','" + eNafn + "','" + kyn + "'," + to_string(fAr) + "," + to_string(dAr) + ")";
    udiSkipun(sql);
}
void sqltenging::eydaFolk(int id)
{

    string sql = "DELETE FROM TolvuFolk WHERE ID = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::uppfaeraFolk(int id, string fNafn, string eNafn, char kyn, int fAr, int dAr)
{
    string sql = "UPDATE TolvuFolk "
                 "SET fornafn = '" +  fNafn + "'"
                 ", eftirnafn = '" + eNafn + "'"
                 ", kyn = '" + kyn + "'"
                 ", faedingarAr = " + to_string(fAr) +
                 ", danarAr = " + to_string(dAr) + " "
                 "WHERE ID = " + to_string(id);

    udiSkipun(sql);
}

void sqltenging::tortimaFolki()
{
    string terminator = "DELETE FROM tolvufolk";
    udiSkipun(terminator);
}

int sqltenging::saekjaSize(string flokkur) const
{
    int size = 0;
    string sql = "SELECT COUNT(*) as Size from ";
    if (flokkur == "velar"){
        sql += "TolvuVelar";
    }else if (flokkur == "folk"){
        sql += "TolvuFolk";
    }else{
        size = -1;
    }

    if (size != -1)
    {
        QSqlQuery query(_db);
        char* cstr = new char[sql.length()+1];
        strcpy(cstr, sql.c_str());
        query.exec(cstr);
        if (query.next()){
            size = query.value("Size").toUInt();
        }
    }
    return size;
}

//Vensl

void sqltenging::buaTilVensl(int folkID, int velID)
{
    string sql = "INSERT INTO venslfolkvelar(folk_id,vel_id)"
                 "VALUES(" + to_string(folkID) + "," + to_string(velID) + ")";
    udiSkipun(sql);

}

void sqltenging::eydaVenslFolk(int id)
{
    string sql = "DELETE FROM venslfolkvelar WHERE folk_id = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::eydaVenslVel(int id)
{
    string sql = "DELETE FROM venslfolkvelar WHERE folk_id = " + to_string(id);
    udiSkipun(sql);
}

void sqltenging::eydaStakiVensl(int folkID, int velID)
{
    string sql = "DELETE FROM venslfolkvelar"
                 "WHERE folk_id = " + to_string(folkID) + " "
                 "AND vel_id = " + to_string(velID);
    udiSkipun(sql);
}

vector<tolvufolk> sqltenging::lesaFolkVenslad(int velarID) const
{
    string sql = "SELECT f.id, f.fornafn, f.eftirnafn, f.kyn, f.faedingarar, f.danarar "
            "FROM tolvufolk f "
            "INNER JOIN venslfolkvelar v ON v.folk_id = f.id "
            "INNER JOIN tolvuvelar t ON v.vel_id = t.id "
            "WHERE t.id = " + to_string(velarID);

    return selectFolk(sql);
}

vector<velar> sqltenging::lesaVelarVenslad(int folkID) const
{
    string sql = "SELECT t.id, t.nafn, t.byggingarar, t.byggd, t.tegund "
            "FROM tolvulvelar t "
            "INNER JOIN venslfolkvelar v ON v.vel_id = t.id "
            "INNER JOIN tolvufolk f ON v.folk_id = f.id "
            "WHERE f.id = " + to_string(folkID);

    return selectVelar(sql);
}

// Private Functions
vector<tolvufolk> sqltenging::selectFolk(string sql) const
{
    vector<tolvufolk> t;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string fornafn = query.value("fornafn").toString().toStdString();
        string eftirnafn = query.value("eftirnafn").toString().toStdString();
        char kyn = query.value("kyn").toString().toStdString()[0];
        int faedingarar = query.value("faedingarar").toUInt();
        int danarar = query.value("danarar").toUInt();

        t.push_back(tolvufolk(id, fornafn, eftirnafn, kyn, faedingarar, danarar));
    }

    return t;
}

vector<velar> sqltenging::selectVelar(string sql) const
{
    vector<velar> v;
    QSqlQuery query(_db);
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    query.exec(cstr);

    while(query.next())
    {
        int id = query.value("id").toUInt();
        string nafn = query.value("Nafn").toString().toStdString();
        int ar = query.value("byggingarar").toUInt();
        bool byggd = query.value("byggd").toBool();
        string tegund = query.value("tegund").toString().toStdString();

        v.push_back(velar(id, nafn, ar, tegund, byggd));
    }

    return v;
}

void sqltenging::udiSkipun(string sql)
{
    char* cstr = new char[sql.length()+1];
    strcpy(cstr, sql.c_str());
    QSqlQuery query(_db);
    query.exec(cstr);
    delete[] cstr;
}
// End of private functions
<|endoftext|>


<commit_before>// WCSRequestHandler.cc

#include "config.h"

#include "WCSRequestHandler.h"
#include "BESResponseHandler.h"
#include "BESResponseNames.h"
#include "BESVersionInfo.h"
#include "BESTextInfo.h"

WCSRequestHandler::WCSRequestHandler( const string &name )
    : BESRequestHandler( name )
{
    add_handler( VERS_RESPONSE, WCSRequestHandler::sample_build_vers ) ;
    add_handler( HELP_RESPONSE, WCSRequestHandler::sample_build_help ) ;
}

WCSRequestHandler::~WCSRequestHandler()
{
}

bool
WCSRequestHandler::sample_build_vers( BESDataHandlerInterface &dhi )
{
    bool ret = true ;
    BESVersionInfo *info = dynamic_cast<BESVersionInfo *>(dhi.response_handler->get_response_object() ) ;
    info->addHandlerVersion( PACKAGE_NAME, PACKAGE_VERSION ) ;
    return ret ;
}

bool
WCSRequestHandler::sample_build_help( BESDataHandlerInterface &dhi )
{
    bool ret = true ;
    BESInfo *info = dynamic_cast<BESInfo *>(dhi.response_handler->get_response_object());

    info->begin_tag("Handler");
    info->add_tag("name", PACKAGE_NAME);
    info->add_tag("version", PACKAGE_STRING);
    info->end_tag("Handler");

    return ret ;
}

void
WCSRequestHandler::dump( ostream &strm ) const
{
    strm << BESIndent::LMarg << "WCSRequestHandler::dump - ("
			     << (void *)this << ")" << endl ;
    BESIndent::Indent() ;
    BESRequestHandler::dump( strm ) ;
    BESIndent::UnIndent() ;
}

<commit_msg>Checking results of dynamic casts and throwing a cast error if fails. M    WCSRequestHandler.cc<commit_after>// WCSRequestHandler.cc

#include "config.h"

#include "WCSRequestHandler.h"
#include "BESResponseHandler.h"
#include "BESResponseNames.h"
#include "BESVersionInfo.h"
#include "BESTextInfo.h"

WCSRequestHandler::WCSRequestHandler( const string &name )
    : BESRequestHandler( name )
{
    add_handler( VERS_RESPONSE, WCSRequestHandler::sample_build_vers ) ;
    add_handler( HELP_RESPONSE, WCSRequestHandler::sample_build_help ) ;
}

WCSRequestHandler::~WCSRequestHandler()
{
}

bool
WCSRequestHandler::sample_build_vers( BESDataHandlerInterface &dhi )
{
    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESVersionInfo *info = dynamic_cast < BESVersionInfo * >(response);
    if( !info )
	throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    info->addHandlerVersion( PACKAGE_NAME, PACKAGE_VERSION ) ;

    return true ;
}

bool
WCSRequestHandler::sample_build_help( BESDataHandlerInterface &dhi )
{
    BESResponseObject *response = dhi.response_handler->get_response_object();
    BESInfo *info = dynamic_cast<BESInfo *>(response);
    if( !info )
	throw BESInternalError( "cast error", __FILE__, __LINE__ ) ;

    info->begin_tag("Handler");
    info->add_tag("name", PACKAGE_NAME);
    info->add_tag("version", PACKAGE_STRING);
    info->end_tag("Handler");

    return true ;
}

void
WCSRequestHandler::dump( ostream &strm ) const
{
    strm << BESIndent::LMarg << "WCSRequestHandler::dump - ("
			     << (void *)this << ")" << endl ;
    BESIndent::Indent() ;
    BESRequestHandler::dump( strm ) ;
    BESIndent::UnIndent() ;
}

<|endoftext|>


<commit_before>//====================================================================================================
// Filename:    GBCartridge.h
// Created by:  Jeff Padgham
// Description: Emulates a Game Boy cartridge.
//====================================================================================================

//====================================================================================================
// Includes
//====================================================================================================

#include "GBCartridge.h"

#include "emutypes.h"
#include "GBMem.h"
#include "GBMemBankController0.h"
#include "GBMemBankController1.h"
#include "GBMemBankController2.h"
#include "GBMemBankController3.h"

#include <memory.h>
#include <assert.h>
#include <string.h>

//====================================================================================================
// Static initializers
//====================================================================================================

const uint16 GBCartridge::CARTRIDGE_ENTRY_POINT = 0x100;

//====================================================================================================
// Class
//====================================================================================================

GBCartridge::GBCartridge( GBMem* pMemoryModule ) :
	m_pMem( pMemoryModule ),
	m_pRom( NULL ),
	m_pRam( NULL ),
	m_pMemBankController( NULL ),
	m_szBatteryDirectory( NULL ),
	m_bLoaded( false )
{
}

//----------------------------------------------------------------------------------------------------
GBCartridge::~GBCartridge()
{
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::Reset()
{
	if( m_bLoaded )
	{
		memset( m_pRam, 0, sizeof( m_pRam ) );
		m_pMem->LoadMemory( m_pRom, 0, sizeof( ubyte ) * 0x4000 );
		m_pMem->SetMemBankController( CreateMemBankController( m_oHeader.u8CartridgeType ) );

		LoadBattery();
	}
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::LoadFromFile( const char *szFilepath, const char* szBatteryDirectory )
{
	FILE*	pFile			= NULL;
	bool	bLoaded			= false;

	fopen_s( &pFile, szFilepath, "rb" );
	if( NULL != pFile )
	{
		ubyte u8CartridgeHeader[ 0x150 ];

		fread_s( u8CartridgeHeader, sizeof( u8CartridgeHeader ), sizeof( u8CartridgeHeader ), 1, pFile );

		if( ValidateCartridgeHeader( u8CartridgeHeader ) )
		{
			LoadCartridgeHeader( u8CartridgeHeader );
			bLoaded = LoadCartridge( pFile );
		}

		// Attempt to load the .sav file for this rom
		if(		bLoaded
			&&	szBatteryDirectory )
		{
			m_szBatteryDirectory = szBatteryDirectory;
			LoadBattery();
		}

		fclose( pFile );
	}

	return bLoaded;
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::HasBattery() const
{
	switch( m_oHeader.u8CartridgeType )
	{
		case 0x03:
		case 0x06:
		case 0x09:
		case 0x0D:
		case 0x0F:
		case 0x10:
		case 0x13:
		case 0x1B:
		case 0x1E:
			return true;
	}

	return false;
}
//----------------------------------------------------------------------------------------------------

bool GBCartridge::IsRamDirty() const
{
	return m_pMemBankController->IsRamDirty();
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::FlushRamToSaveFile( const char *szBatteryDirectory )
{
	FILE*	pBatteryFile	= NULL;
	char szBatteryFilepath[ 1024 ] = { 0 };

	sprintf_s( szBatteryFilepath, "%s%s%s", szBatteryDirectory, m_oHeader.szTitle, ".sav" );

	fopen_s( &pBatteryFile, szBatteryFilepath, "wb" );
	if( NULL != pBatteryFile )
	{
		fwrite( m_pRam, GetRamSize(), 1, pBatteryFile );

		fclose( pBatteryFile );
	}
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::Unload()
{
	if( NULL != m_pRom )
	{
		delete m_pRom;
		m_pRom = NULL;
	}

	if( NULL != m_pRam )
	{
		delete m_pRam;
		m_pRam = NULL;
	}

	if( NULL != m_pMemBankController )
	{
		m_pMem->SetMemBankController( NULL );
		delete m_pMemBankController;
		m_pMemBankController = NULL;
	}

	m_bLoaded = false;
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::LoadCartridgeHeader( ubyte *pHeaderData )
{
	memcpy( &m_oHeader, pHeaderData + CARTRIDGE_ENTRY_POINT, sizeof( m_oHeader ) );
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::ValidateCartridgeHeader( ubyte* pHeaderData )
{
	ubyte x = 0;

	for( int i = 0x134; i <= 0x14C; ++i )
	{
		x = x - pHeaderData[ i ] - 1;
	}

	return pHeaderData[ 0x14D ] == x;
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::LoadCartridge( FILE* pFile )
{
	uint32 u32RomSize = GetRomSize();
	uint32 u32RamSize = GetRamSize();

	m_pRom = new ubyte[ u32RomSize ];
	memset( m_pRom, 0, u32RomSize );

	rewind( pFile );
	fread_s( m_pRom, u32RomSize, 1, u32RomSize, pFile );

	if( u32RamSize < 2048 )
	{
		u32RamSize = 2048;
	}
	m_pRam = new ubyte[ u32RamSize ];

	m_bLoaded = true;

	Reset();

	return true;
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::LoadBattery()
{
	FILE*	pBatteryFile				= NULL;
	char	szBatteryFilepath[ 1024 ]	= { 0 };

	if( m_szBatteryDirectory )
	{
		sprintf_s( szBatteryFilepath, "%s%s%s", m_szBatteryDirectory, m_oHeader.szTitle, ".sav" );

		fopen_s( &pBatteryFile, szBatteryFilepath, "rb" );
		if( NULL != pBatteryFile )
		{
			uint32 u32RamSize = GetRamSize();

			fread_s( m_pRam, u32RamSize, 1, u32RamSize, pBatteryFile );

			fclose( pBatteryFile );
		}
	}
}

//----------------------------------------------------------------------------------------------------
IGBMemBankController* GBCartridge::CreateMemBankController( ubyte u8CartridgeType )
{
	IGBMemBankController* pMBC	= NULL;

	// 0-ROM ONLY				12-ROM+MBC3+RAM
	// 1-ROM+MBC1				13-ROM+MBC3+RAM+BATT
	// 2-ROM+MBC1+RAM			19-ROM+MBC5
	// 3-ROM+MBC1+RAM+BATT		1A-ROM+MBC5+RAM
	// 5-ROM+MBC2				1B-ROM+MBC5+RAM+BATT
	// 6-ROM+MBC2+BATTERY		1C-ROM+MBC5+RUMBLE
	// 8-ROM+RAM				1D-ROM+MBC5+RUMBLE+SRAM
	// 9-ROM+RAM+BATTERY		1E-ROM+MBC5+RUMBLE+SRAM+BATT
	// B-ROM+MMM01				1F-Pocket Camera
	// C-ROM+MMM01+SRAM			FD-Bandai TAMA5
	// D-ROM+MMM01+SRAM+BATT	FE - Hudson HuC-3
	// F-ROM+MBC3+TIMER+BATT	FF - Hudson HuC-1
	// 10-ROM+MBC3+TIMER+RAM+BATT
	// 11-ROM+MBC3

	if( NULL != m_pMemBankController )
	{
		delete m_pMemBankController;
		m_pMemBankController = NULL;
	}

	switch( u8CartridgeType )
	{
		case 0x00:
		case 0x08:
		case 0x09:
			pMBC = new GBMemBankController0( m_pRom );
			break;
		case 0x01:
		case 0x02:
		case 0x03:
			pMBC = new GBMemBankController1( m_pRom, m_pRam );
			break;
		case 0x05:
		case 0x06:
			pMBC = new GBMemBankController2( m_pRom, m_pRam );
			break;
		case 0x0F:
		case 0x10:
			pMBC = new GBMemBankController3( m_pRom, m_pRam, true );
		case 0x11:
		case 0x12:
		case 0x13:
			pMBC = new GBMemBankController3( m_pRom, m_pRam );
			break;
		default:
			assert( "Unimplemented cartridge type!" );
			__asm int 3;
	}

	m_pMemBankController = pMBC;

	return pMBC;
}

//----------------------------------------------------------------------------------------------------
uint32 GBCartridge::GetRomSize() const
{
	return ( 1 << 15 ) << m_oHeader.u8RomSize;
}

//----------------------------------------------------------------------------------------------------
uint32 GBCartridge::GetRamSize() const
{
	return ( 1 << 9 ) << m_oHeader.u8RamSize * 2;
}<commit_msg>Fixing a double battery load on initial cart load<commit_after>//====================================================================================================
// Filename:    GBCartridge.h
// Created by:  Jeff Padgham
// Description: Emulates a Game Boy cartridge.
//====================================================================================================

//====================================================================================================
// Includes
//====================================================================================================

#include "GBCartridge.h"

#include "emutypes.h"
#include "GBMem.h"
#include "GBMemBankController0.h"
#include "GBMemBankController1.h"
#include "GBMemBankController2.h"
#include "GBMemBankController3.h"

#include <memory.h>
#include <assert.h>
#include <string.h>

//====================================================================================================
// Static initializers
//====================================================================================================

const uint16 GBCartridge::CARTRIDGE_ENTRY_POINT = 0x100;

//====================================================================================================
// Class
//====================================================================================================

GBCartridge::GBCartridge( GBMem* pMemoryModule ) :
	m_pMem( pMemoryModule ),
	m_pRom( NULL ),
	m_pRam( NULL ),
	m_pMemBankController( NULL ),
	m_szBatteryDirectory( NULL ),
	m_bLoaded( false )
{
}

//----------------------------------------------------------------------------------------------------
GBCartridge::~GBCartridge()
{
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::Reset()
{
	if( m_bLoaded )
	{
		memset( m_pRam, 0, sizeof( m_pRam ) );
		m_pMem->LoadMemory( m_pRom, 0, sizeof( ubyte ) * 0x4000 );
		m_pMem->SetMemBankController( CreateMemBankController( m_oHeader.u8CartridgeType ) );

		// Attempt to load the .sav file for this rom
		LoadBattery();
	}
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::LoadFromFile( const char *szFilepath, const char* szBatteryDirectory )
{
	FILE*	pFile			= NULL;
	bool	bLoaded			= false;

	fopen_s( &pFile, szFilepath, "rb" );
	if( NULL != pFile )
	{
		ubyte u8CartridgeHeader[ 0x150 ];

		fread_s( u8CartridgeHeader, sizeof( u8CartridgeHeader ), sizeof( u8CartridgeHeader ), 1, pFile );

		if( ValidateCartridgeHeader( u8CartridgeHeader ) )
		{
			m_szBatteryDirectory = szBatteryDirectory;

			LoadCartridgeHeader( u8CartridgeHeader );
			bLoaded = LoadCartridge( pFile );
		}

		fclose( pFile );
	}

	return bLoaded;
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::HasBattery() const
{
	switch( m_oHeader.u8CartridgeType )
	{
		case 0x03:
		case 0x06:
		case 0x09:
		case 0x0D:
		case 0x0F:
		case 0x10:
		case 0x13:
		case 0x1B:
		case 0x1E:
			return true;
	}

	return false;
}
//----------------------------------------------------------------------------------------------------

bool GBCartridge::IsRamDirty() const
{
	return m_pMemBankController->IsRamDirty();
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::FlushRamToSaveFile( const char *szBatteryDirectory )
{
	FILE*	pBatteryFile	= NULL;
	char szBatteryFilepath[ 1024 ] = { 0 };

	sprintf_s( szBatteryFilepath, "%s%s%s", szBatteryDirectory, m_oHeader.szTitle, ".sav" );

	fopen_s( &pBatteryFile, szBatteryFilepath, "wb" );
	if( NULL != pBatteryFile )
	{
		fwrite( m_pRam, GetRamSize(), 1, pBatteryFile );

		fclose( pBatteryFile );
	}
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::Unload()
{
	if( NULL != m_pRom )
	{
		delete m_pRom;
		m_pRom = NULL;
	}

	if( NULL != m_pRam )
	{
		delete m_pRam;
		m_pRam = NULL;
	}

	if( NULL != m_pMemBankController )
	{
		m_pMem->SetMemBankController( NULL );
		delete m_pMemBankController;
		m_pMemBankController = NULL;
	}

	m_szBatteryDirectory = NULL;

	m_bLoaded = false;
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::LoadCartridgeHeader( ubyte *pHeaderData )
{
	memcpy( &m_oHeader, pHeaderData + CARTRIDGE_ENTRY_POINT, sizeof( m_oHeader ) );
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::ValidateCartridgeHeader( ubyte* pHeaderData )
{
	ubyte x = 0;

	for( int i = 0x134; i <= 0x14C; ++i )
	{
		x = x - pHeaderData[ i ] - 1;
	}

	return pHeaderData[ 0x14D ] == x;
}

//----------------------------------------------------------------------------------------------------
bool GBCartridge::LoadCartridge( FILE* pFile )
{
	uint32 u32RomSize = GetRomSize();
	uint32 u32RamSize = GetRamSize();

	m_pRom = new ubyte[ u32RomSize ];
	memset( m_pRom, 0, u32RomSize );

	rewind( pFile );
	fread_s( m_pRom, u32RomSize, 1, u32RomSize, pFile );

	if( u32RamSize < 2048 )
	{
		u32RamSize = 2048;
	}
	m_pRam = new ubyte[ u32RamSize ];

	m_bLoaded = true;

	Reset();

	return true;
}

//----------------------------------------------------------------------------------------------------
void GBCartridge::LoadBattery()
{
	FILE*	pBatteryFile				= NULL;
	char	szBatteryFilepath[ 1024 ]	= { 0 };

	if( m_szBatteryDirectory )
	{
		sprintf_s( szBatteryFilepath, "%s%s%s", m_szBatteryDirectory, m_oHeader.szTitle, ".sav" );

		fopen_s( &pBatteryFile, szBatteryFilepath, "rb" );
		if( NULL != pBatteryFile )
		{
			uint32 u32RamSize = GetRamSize();

			fread_s( m_pRam, u32RamSize, 1, u32RamSize, pBatteryFile );

			fclose( pBatteryFile );
		}
	}
}

//----------------------------------------------------------------------------------------------------
IGBMemBankController* GBCartridge::CreateMemBankController( ubyte u8CartridgeType )
{
	IGBMemBankController* pMBC	= NULL;

	// 0-ROM ONLY				12-ROM+MBC3+RAM
	// 1-ROM+MBC1				13-ROM+MBC3+RAM+BATT
	// 2-ROM+MBC1+RAM			19-ROM+MBC5
	// 3-ROM+MBC1+RAM+BATT		1A-ROM+MBC5+RAM
	// 5-ROM+MBC2				1B-ROM+MBC5+RAM+BATT
	// 6-ROM+MBC2+BATTERY		1C-ROM+MBC5+RUMBLE
	// 8-ROM+RAM				1D-ROM+MBC5+RUMBLE+SRAM
	// 9-ROM+RAM+BATTERY		1E-ROM+MBC5+RUMBLE+SRAM+BATT
	// B-ROM+MMM01				1F-Pocket Camera
	// C-ROM+MMM01+SRAM			FD-Bandai TAMA5
	// D-ROM+MMM01+SRAM+BATT	FE - Hudson HuC-3
	// F-ROM+MBC3+TIMER+BATT	FF - Hudson HuC-1
	// 10-ROM+MBC3+TIMER+RAM+BATT
	// 11-ROM+MBC3

	if( NULL != m_pMemBankController )
	{
		delete m_pMemBankController;
		m_pMemBankController = NULL;
	}

	switch( u8CartridgeType )
	{
		case 0x00:
		case 0x08:
		case 0x09:
			pMBC = new GBMemBankController0( m_pRom );
			break;
		case 0x01:
		case 0x02:
		case 0x03:
			pMBC = new GBMemBankController1( m_pRom, m_pRam );
			break;
		case 0x05:
		case 0x06:
			pMBC = new GBMemBankController2( m_pRom, m_pRam );
			break;
		case 0x0F:
		case 0x10:
			pMBC = new GBMemBankController3( m_pRom, m_pRam, true );
		case 0x11:
		case 0x12:
		case 0x13:
			pMBC = new GBMemBankController3( m_pRom, m_pRam );
			break;
		default:
			assert( "Unimplemented cartridge type!" );
			__asm int 3;
	}

	m_pMemBankController = pMBC;

	return pMBC;
}

//----------------------------------------------------------------------------------------------------
uint32 GBCartridge::GetRomSize() const
{
	return ( 1 << 15 ) << m_oHeader.u8RomSize;
}

//----------------------------------------------------------------------------------------------------
uint32 GBCartridge::GetRamSize() const
{
	return ( 1 << 9 ) << m_oHeader.u8RamSize * 2;
}<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ChromePostman implementation.
#include "ceee/ie/broker/chrome_postman.h"

#include "base/string_util.h"
#include "ceee/ie/broker/api_dispatcher.h"
#include "ceee/ie/common/api_registration.h"
#include "ceee/ie/common/ceee_module_util.h"
#include "chrome/browser/automation/extension_automation_constants.h"
#include "chrome/common/url_constants.h"
#include "ceee/common/com_utils.h"

namespace ext = extension_automation_constants;

namespace {
  // The maximum number of times we should try to start Frame.
  const unsigned int kMaxFrameResetCount = 5;
}

class ChromeFrameMessageTask : public Task {
 public:
  explicit ChromeFrameMessageTask(
      ChromePostman::ChromePostmanThread* thread_object,
      BSTR message, BSTR target)
      : thread_object_(thread_object),
        message_(message),
        target_(target) {
  }

  virtual void Run() {
    thread_object_->PostMessage(message_, target_);
  }
 private:
  ChromePostman::ChromePostmanThread* thread_object_;
  CComBSTR message_;
  CComBSTR target_;
};

class ChromeFrameResetTask : public Task {
 public:
  explicit ChromeFrameResetTask(
      ChromePostman::ChromePostmanThread* thread_object)
      : thread_object_(thread_object) {
  }

  virtual void Run() {
    thread_object_->ResetChromeFrame();
  }
 private:
  ChromePostman::ChromePostmanThread* thread_object_;
};

class ApiExecutionTask : public Task {
 public:
  explicit ApiExecutionTask(BSTR message) : message_(message) {}

  virtual void Run() {
    ProductionApiDispatcher::get()->HandleApiRequest(message_, NULL);
  }
 private:
  CComBSTR message_;
};

class FireEventTask : public Task {
 public:
  FireEventTask(const char* event_name, const char* event_args)
      : event_name_(event_name), event_args_(event_args) {}

  virtual void Run() {
    ProductionApiDispatcher::get()->FireEvent(event_name_.c_str(),
                                              event_args_.c_str());
  }
 private:
  std::string event_name_;
  std::string event_args_;
};

ChromePostman* ChromePostman::single_instance_ = NULL;
ChromePostman::ChromePostman() {
  DCHECK(single_instance_ == NULL);
  single_instance_ = this;
  frame_reset_count_ = 0;
}

ChromePostman::~ChromePostman() {
  DCHECK(single_instance_ == this);
  single_instance_ = NULL;
}

void ChromePostman::Init() {
  // The postman thread must be a UI thread so that it can pump windows
  // messages and allow COM to handle cross apartment calls.

  chrome_postman_thread_.StartWithOptions(
      base::Thread::Options(MessageLoop::TYPE_UI, 0));
  api_worker_thread_.Start();
}

void ChromePostman::Term() {
  api_worker_thread_.Stop();
  chrome_postman_thread_.Stop();
}

void ChromePostman::PostMessage(BSTR message, BSTR target) {
  MessageLoop* message_loop = chrome_postman_thread_.message_loop();
  if (message_loop) {
    // TODO(siggi@chromium.org): Remove the task subclass and change this to
    // use NewRunnableMethod.
    message_loop->PostTask(
        FROM_HERE, new ChromeFrameMessageTask(&chrome_postman_thread_,
                                              message, target));
  } else {
    LOG(ERROR) << "Trying to post a message before the postman thread is"
                  "completely initialized and ready.";
  }
}

void ChromePostman::FireEvent(const char* event_name, const char* event_args) {
  MessageLoop* message_loop = api_worker_thread_.message_loop();
  if (message_loop) {
    // TODO(siggi@chromium.org): Remove the task subclass and change this to
    // use NewRunnableMethod.
    message_loop->PostTask(FROM_HERE,
                           new FireEventTask(event_name, event_args));
  } else {
    LOG(ERROR) << "Trying to post a message before the API worker thread is"
                  "completely initialized and ready.";
  }
}

HRESULT ChromePostman::OnCfReadyStateChanged(LONG state) {
  if (state == READYSTATE_COMPLETE) {
    // If the page is fully loaded, we reset the count to 0 to ensure we restart
    // it if it's the user's fault (no max count).
    DLOG(INFO) << "frame_reset_count_ reset";
    frame_reset_count_ = 0;
  }
  return S_OK;
}

HRESULT ChromePostman::OnCfPrivateMessage(BSTR msg, BSTR origin, BSTR target) {
  if (CComBSTR(target) == ext::kAutomationRequestTarget) {
    MessageLoop* message_loop = api_worker_thread_.message_loop();
    if (message_loop) {
      message_loop->PostTask(FROM_HERE, new ApiExecutionTask(msg));
    } else {
      LOG(ERROR) << "Trying to post a message before the API worker thread is"
                    "completely initialized and ready.";
    }
  }
  return S_OK;
}

HRESULT ChromePostman::OnCfExtensionReady(BSTR path, int response) {
  return S_OK;
}

HRESULT ChromePostman::OnCfGetEnabledExtensionsComplete(
    SAFEARRAY* tab_delimited_paths) {
  return S_OK;
}

HRESULT ChromePostman::OnCfGetExtensionApisToAutomate(BSTR* functions_enabled) {
  DCHECK(functions_enabled != NULL);
  std::vector<std::string> function_names;
#define REGISTER_API_FUNCTION(func) \
  function_names.push_back(func##Function::function_name())
  REGISTER_ALL_API_FUNCTIONS();
#undef REGISTER_API_FUNCTION
  // There is a special case with CreateWindow that is explained in the
  // class comments.
  function_names.push_back(CreateWindowFunction::function_name());
  std::string function_names_delim = JoinString(function_names, ',');
  *functions_enabled = CComBSTR(function_names_delim.c_str()).Detach();

  // CF is asking for the list of extension APIs to automate so the
  // automation channel is ready.  Set a dummy URL so we get the OnLoad
  // callback.
  //
  // The current function call should come to us on the COM thread so we can
  // just call the ChromeFrameHost directly from here.
  CComPtr<IChromeFrameHost> host;
  chrome_postman_thread_.GetHost(&host);
  return host->SetUrl(CComBSTR(chrome::kAboutBlankURL));

  return S_OK;
}

HRESULT ChromePostman::OnCfChannelError() {
  MessageLoop* message_loop = chrome_postman_thread_.message_loop();
  if (message_loop) {
    frame_reset_count_++;
    LOG(INFO) << "frame_reset_count_ = " << frame_reset_count_;

    // No use staying alive if Chrome Frame can't start.
    CHECK(frame_reset_count_ < kMaxFrameResetCount)
      << "Trying to reset Chrome Frame too many times already. Something's "
         "wrong.";

    message_loop->PostTask(FROM_HERE,
                           new ChromeFrameResetTask(&chrome_postman_thread_));
  } else {
    LOG(ERROR) << "Trying to reset Chrome Frame before the postman thread is"
                  "completely initialized and ready.";
  }
  return S_OK;
}

ChromePostman::ChromePostmanThread::ChromePostmanThread()
    : base::Thread("ChromePostman") {
}

void ChromePostman::ChromePostmanThread::Init() {
  HRESULT hr = ::CoInitializeEx(0, COINIT_APARTMENTTHREADED);
  DCHECK(SUCCEEDED(hr)) << "Can't Init COM??? " << com::LogHr(hr);

  hr = InitializeChromeFrameHost();
  DCHECK(SUCCEEDED(hr)) << "InitializeChromeFrameHost failed " <<
      com::LogHr(hr);
}

HRESULT ChromePostman::ChromePostmanThread::InitializeChromeFrameHost() {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  HRESULT hr = CreateChromeFrameHost();
  DCHECK(SUCCEEDED(hr) && chrome_frame_host_ != NULL);
  if (FAILED(hr) || chrome_frame_host_ == NULL) {
    LOG(ERROR) << "Failed to get chrome frame host " << com::LogHr(hr);
    return com::AlwaysError(hr);
  }

  DCHECK(ChromePostman::GetInstance() != NULL);
  chrome_frame_host_->SetEventSink(ChromePostman::GetInstance());
  chrome_frame_host_->SetChromeProfileName(
      ceee_module_util::GetBrokerProfileNameForIe());
  hr = chrome_frame_host_->StartChromeFrame();
  DCHECK(SUCCEEDED(hr));
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to start chrome frame " << com::LogHr(hr);
    return hr;
  }
  return hr;
}

HRESULT ChromePostman::ChromePostmanThread::CreateChromeFrameHost() {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  return ChromeFrameHost::CreateInitializedIID(IID_IChromeFrameHost,
                                               &chrome_frame_host_);
}

void ChromePostman::ChromePostmanThread::CleanUp() {
  TeardownChromeFrameHost();
  ::CoUninitialize();
}

void ChromePostman::ChromePostmanThread::TeardownChromeFrameHost() {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  if (chrome_frame_host_) {
    chrome_frame_host_->SetEventSink(NULL);
    HRESULT hr = chrome_frame_host_->TearDown();
    DCHECK(SUCCEEDED(hr)) << "ChromeFrameHost TearDown failed " <<
        com::LogHr(hr);
    chrome_frame_host_.Release();
  }
}

void ChromePostman::ChromePostmanThread::ResetChromeFrame() {
  TeardownChromeFrameHost();
  HRESULT hr = InitializeChromeFrameHost();
  DCHECK(SUCCEEDED(hr)) << "InitializeChromeFrameHost failed " <<
      com::LogHr(hr);
}

void ChromePostman::ChromePostmanThread::PostMessage(BSTR message,
                                                     BSTR target) {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  HRESULT hr = chrome_frame_host_->PostMessage(message, target);
  DCHECK(SUCCEEDED(hr)) << "ChromeFrameHost PostMessage failed " <<
      com::LogHr(hr);
}

void ChromePostman::ChromePostmanThread::GetHost(IChromeFrameHost** host) {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  chrome_frame_host_.CopyTo(host);
}

ChromePostman::ApiInvocationWorkerThread::ApiInvocationWorkerThread()
    : base::Thread("ApiInvocationWorker") {
}

void ChromePostman::ApiInvocationWorkerThread::Init() {
  ::CoInitializeEx(0, COINIT_MULTITHREADED);
  ProductionApiDispatcher::get()->SetApiInvocationThreadId(
      ::GetCurrentThreadId());
}

void ChromePostman::ApiInvocationWorkerThread::CleanUp() {
  ::CoUninitialize();
  ProductionApiDispatcher::get()->SetApiInvocationThreadId(0);
}
<commit_msg>We need to pin Chrome Frame so that it doesn't get stuck on releasing Breakpad.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// ChromePostman implementation.
#include "ceee/ie/broker/chrome_postman.h"

#include "base/string_util.h"
#include "ceee/ie/broker/api_dispatcher.h"
#include "ceee/ie/common/api_registration.h"
#include "ceee/ie/common/ceee_module_util.h"
#include "chrome/browser/automation/extension_automation_constants.h"
#include "chrome/common/url_constants.h"
#include "ceee/common/com_utils.h"

namespace ext = extension_automation_constants;

namespace {
  // The maximum number of times we should try to start Frame.
  const unsigned int kMaxFrameResetCount = 5;
}

class ChromeFrameMessageTask : public Task {
 public:
  explicit ChromeFrameMessageTask(
      ChromePostman::ChromePostmanThread* thread_object,
      BSTR message, BSTR target)
      : thread_object_(thread_object),
        message_(message),
        target_(target) {
  }

  virtual void Run() {
    thread_object_->PostMessage(message_, target_);
  }
 private:
  ChromePostman::ChromePostmanThread* thread_object_;
  CComBSTR message_;
  CComBSTR target_;
};

class ChromeFrameResetTask : public Task {
 public:
  explicit ChromeFrameResetTask(
      ChromePostman::ChromePostmanThread* thread_object)
      : thread_object_(thread_object) {
  }

  virtual void Run() {
    thread_object_->ResetChromeFrame();
  }
 private:
  ChromePostman::ChromePostmanThread* thread_object_;
};

class ApiExecutionTask : public Task {
 public:
  explicit ApiExecutionTask(BSTR message) : message_(message) {}

  virtual void Run() {
    ProductionApiDispatcher::get()->HandleApiRequest(message_, NULL);
  }
 private:
  CComBSTR message_;
};

class FireEventTask : public Task {
 public:
  FireEventTask(const char* event_name, const char* event_args)
      : event_name_(event_name), event_args_(event_args) {}

  virtual void Run() {
    ProductionApiDispatcher::get()->FireEvent(event_name_.c_str(),
                                              event_args_.c_str());
  }
 private:
  std::string event_name_;
  std::string event_args_;
};

ChromePostman* ChromePostman::single_instance_ = NULL;
ChromePostman::ChromePostman() {
  DCHECK(single_instance_ == NULL);
  single_instance_ = this;
  frame_reset_count_ = 0;
}

ChromePostman::~ChromePostman() {
  DCHECK(single_instance_ == this);
  single_instance_ = NULL;
}

void ChromePostman::Init() {
  // The postman thread must be a UI thread so that it can pump windows
  // messages and allow COM to handle cross apartment calls.

  chrome_postman_thread_.StartWithOptions(
      base::Thread::Options(MessageLoop::TYPE_UI, 0));
  api_worker_thread_.Start();
}

void ChromePostman::Term() {
  api_worker_thread_.Stop();
  chrome_postman_thread_.Stop();
}

void ChromePostman::PostMessage(BSTR message, BSTR target) {
  MessageLoop* message_loop = chrome_postman_thread_.message_loop();
  if (message_loop) {
    // TODO(siggi@chromium.org): Remove the task subclass and change this to
    // use NewRunnableMethod.
    message_loop->PostTask(
        FROM_HERE, new ChromeFrameMessageTask(&chrome_postman_thread_,
                                              message, target));
  } else {
    LOG(ERROR) << "Trying to post a message before the postman thread is"
                  "completely initialized and ready.";
  }
}

void ChromePostman::FireEvent(const char* event_name, const char* event_args) {
  MessageLoop* message_loop = api_worker_thread_.message_loop();
  if (message_loop) {
    // TODO(siggi@chromium.org): Remove the task subclass and change this to
    // use NewRunnableMethod.
    message_loop->PostTask(FROM_HERE,
                           new FireEventTask(event_name, event_args));
  } else {
    LOG(ERROR) << "Trying to post a message before the API worker thread is"
                  "completely initialized and ready.";
  }
}

HRESULT ChromePostman::OnCfReadyStateChanged(LONG state) {
  if (state == READYSTATE_COMPLETE) {
    // If the page is fully loaded, we reset the count to 0 to ensure we restart
    // it if it's the user's fault (no max count).
    DLOG(INFO) << "frame_reset_count_ reset";
    frame_reset_count_ = 0;
  }
  return S_OK;
}

HRESULT ChromePostman::OnCfPrivateMessage(BSTR msg, BSTR origin, BSTR target) {
  if (CComBSTR(target) == ext::kAutomationRequestTarget) {
    MessageLoop* message_loop = api_worker_thread_.message_loop();
    if (message_loop) {
      message_loop->PostTask(FROM_HERE, new ApiExecutionTask(msg));
    } else {
      LOG(ERROR) << "Trying to post a message before the API worker thread is"
                    "completely initialized and ready.";
    }
  }
  return S_OK;
}

HRESULT ChromePostman::OnCfExtensionReady(BSTR path, int response) {
  return S_OK;
}

HRESULT ChromePostman::OnCfGetEnabledExtensionsComplete(
    SAFEARRAY* tab_delimited_paths) {
  return S_OK;
}

HRESULT ChromePostman::OnCfGetExtensionApisToAutomate(BSTR* functions_enabled) {
  DCHECK(functions_enabled != NULL);
  std::vector<std::string> function_names;
#define REGISTER_API_FUNCTION(func) \
  function_names.push_back(func##Function::function_name())
  REGISTER_ALL_API_FUNCTIONS();
#undef REGISTER_API_FUNCTION
  // There is a special case with CreateWindow that is explained in the
  // class comments.
  function_names.push_back(CreateWindowFunction::function_name());
  std::string function_names_delim = JoinString(function_names, ',');
  *functions_enabled = CComBSTR(function_names_delim.c_str()).Detach();

  // CF is asking for the list of extension APIs to automate so the
  // automation channel is ready.  Set a dummy URL so we get the OnLoad
  // callback.
  //
  // The current function call should come to us on the COM thread so we can
  // just call the ChromeFrameHost directly from here.
  CComPtr<IChromeFrameHost> host;
  chrome_postman_thread_.GetHost(&host);
  return host->SetUrl(CComBSTR(chrome::kAboutBlankURL));

  return S_OK;
}

HRESULT ChromePostman::OnCfChannelError() {
  MessageLoop* message_loop = chrome_postman_thread_.message_loop();
  if (message_loop) {
    frame_reset_count_++;
    LOG(INFO) << "frame_reset_count_ = " << frame_reset_count_;

    // No use staying alive if Chrome Frame can't start.
    CHECK(frame_reset_count_ < kMaxFrameResetCount)
      << "Trying to reset Chrome Frame too many times already. Something's "
         "wrong.";

    message_loop->PostTask(FROM_HERE,
                           new ChromeFrameResetTask(&chrome_postman_thread_));
  } else {
    LOG(ERROR) << "Trying to reset Chrome Frame before the postman thread is"
                  "completely initialized and ready.";
  }
  return S_OK;
}

ChromePostman::ChromePostmanThread::ChromePostmanThread()
    : base::Thread("ChromePostman") {
}

void ChromePostman::ChromePostmanThread::Init() {
  HRESULT hr = ::CoInitializeEx(0, COINIT_APARTMENTTHREADED);
  DCHECK(SUCCEEDED(hr)) << "Can't Init COM??? " << com::LogHr(hr);

  hr = InitializeChromeFrameHost();
  DCHECK(SUCCEEDED(hr)) << "InitializeChromeFrameHost failed " <<
      com::LogHr(hr);
}

HRESULT ChromePostman::ChromePostmanThread::InitializeChromeFrameHost() {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  HRESULT hr = CreateChromeFrameHost();
  DCHECK(SUCCEEDED(hr) && chrome_frame_host_ != NULL);
  if (FAILED(hr) || chrome_frame_host_ == NULL) {
    LOG(ERROR) << "Failed to get chrome frame host " << com::LogHr(hr);
    return com::AlwaysError(hr);
  }

  DCHECK(ChromePostman::GetInstance() != NULL);
  chrome_frame_host_->SetEventSink(ChromePostman::GetInstance());
  chrome_frame_host_->SetChromeProfileName(
      ceee_module_util::GetBrokerProfileNameForIe());
  hr = chrome_frame_host_->StartChromeFrame();
  DCHECK(SUCCEEDED(hr));
  if (FAILED(hr)) {
    LOG(ERROR) << "Failed to start chrome frame " << com::LogHr(hr);
    return hr;
  }
  // We need to pin the Chrome Frame DLL so that it doesn't get unloaded
  // while we call CoUninitialize in our thread cleanup, otherwise we would
  // get stuck on breakpad termination as filed in http://crbug.com/64388.
  static bool s_pinned = false;
  if (!s_pinned) {
    HMODULE unused;
    if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_PIN, L"npchrome_frame.dll",
                           &unused)) {
      NOTREACHED() << "Failed to pin Chrome Frame. " << com::LogWe();
    } else {
      s_pinned = true;
    }
  }
  return hr;
}

HRESULT ChromePostman::ChromePostmanThread::CreateChromeFrameHost() {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  return ChromeFrameHost::CreateInitializedIID(IID_IChromeFrameHost,
                                               &chrome_frame_host_);
}

void ChromePostman::ChromePostmanThread::CleanUp() {
  TeardownChromeFrameHost();
  ::CoUninitialize();
}

void ChromePostman::ChromePostmanThread::TeardownChromeFrameHost() {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  if (chrome_frame_host_) {
    chrome_frame_host_->SetEventSink(NULL);
    HRESULT hr = chrome_frame_host_->TearDown();
    DCHECK(SUCCEEDED(hr)) << "ChromeFrameHost TearDown failed " <<
        com::LogHr(hr);
    chrome_frame_host_.Release();
  }
}

void ChromePostman::ChromePostmanThread::ResetChromeFrame() {
  TeardownChromeFrameHost();
  HRESULT hr = InitializeChromeFrameHost();
  DCHECK(SUCCEEDED(hr)) << "InitializeChromeFrameHost failed " <<
      com::LogHr(hr);
}

void ChromePostman::ChromePostmanThread::PostMessage(BSTR message,
                                                     BSTR target) {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  HRESULT hr = chrome_frame_host_->PostMessage(message, target);
  DCHECK(SUCCEEDED(hr)) << "ChromeFrameHost PostMessage failed " <<
      com::LogHr(hr);
}

void ChromePostman::ChromePostmanThread::GetHost(IChromeFrameHost** host) {
  DCHECK(thread_id() == ::GetCurrentThreadId());
  chrome_frame_host_.CopyTo(host);
}

ChromePostman::ApiInvocationWorkerThread::ApiInvocationWorkerThread()
    : base::Thread("ApiInvocationWorker") {
}

void ChromePostman::ApiInvocationWorkerThread::Init() {
  ::CoInitializeEx(0, COINIT_MULTITHREADED);
  ProductionApiDispatcher::get()->SetApiInvocationThreadId(
      ::GetCurrentThreadId());
}

void ChromePostman::ApiInvocationWorkerThread::CleanUp() {
  ::CoUninitialize();
  ProductionApiDispatcher::get()->SetApiInvocationThreadId(0);
}
<|endoftext|>


<commit_before>#include "Validator.h"

namespace Validator
{

double diceCoeff2DSlice( MaskType2D::Pointer mask, MaskType2D::Pointer groundtruth )
{
    // check if mask and groudntruth sizes match
    int width = mask->GetLargestPossibleRegion().GetSize()[0];
    int height = mask->GetLargestPossibleRegion().GetSize()[1];
    if( width != groundtruth->GetLargestPossibleRegion().GetSize()[0] ||
        height != groundtruth->GetLargestPossibleRegion().GetSize()[1] )
    {
        std::cerr << "diceCoeff2DSlice: mask and groundtruth must be same sice!" << std::endl;
        return -1;
    }

    // count mask and groundtruth pixels and how many they have in common
    size_t maskCnt = 0;
    size_t groundtruthCnt = 0;
    size_t maskAndGroundtruthCnt = 0;
    MaskType2D::IndexType index;
    for( int y = 0; y < height; ++y )
    {
        for( int x = 0; x < width; ++x )
        {
            index[0] = x;
            index[1] = y;
            bool maskIsSet = static_cast<bool>( mask->GetPixel( index ) );
            bool groundtruthIsSet = static_cast<bool>( groundtruth->GetPixel( index ) );
            if( maskIsSet ) maskCnt++;
            if( groundtruthIsSet ) groundtruthCnt++;
            if( groundtruthIsSet && maskIsSet ) maskAndGroundtruthCnt++;
        }
    }

    // compute dice coefficent
    return static_cast<double>( 2 * maskAndGroundtruthCnt ) / ( maskCnt + groundtruthCnt );
}

double diceCoeff3DVolume( MaskType::Pointer mask, MaskType::Pointer groundtruth )
{
    // check if mask and groudntruth sizes match
    int width = mask->GetLargestPossibleRegion().GetSize()[0];
    int height = mask->GetLargestPossibleRegion().GetSize()[1];
    int depth = mask->GetLargestPossibleRegion().GetSize()[2];
    if( width != groundtruth->GetLargestPossibleRegion().GetSize()[0] ||
        height != groundtruth->GetLargestPossibleRegion().GetSize()[1] ||
        depth != groundtruth->GetLargestPossibleRegion().GetSize()[2] )
    {
        std::cerr << "diceCoeff3DVolume: mask and groundtruth must be same sice!" << std::endl;
        return -1;
    }

    // count mask and groundtruth pixels and how many they have in common
    size_t maskCnt = 0;
    size_t groundtruthCnt = 0;
    size_t maskAndGroundtruthCnt = 0;
    MaskType::IndexType index;
    for( int z = 0; z < depth; ++z )
    {
        index[2] = z;
        for( int y = 0; y < height; ++y )
        {
            index[1] = y;
            for( int x = 0; x < width; ++x )
            {
                index[0] = x;
                bool maskIsSet = static_cast<bool>( mask->GetPixel( index ) );
                bool groundtruthIsSet = static_cast<bool>( groundtruth->GetPixel( index ) );
                if( maskIsSet ) maskCnt++;
                if( groundtruthIsSet ) groundtruthCnt++;
                if( groundtruthIsSet && maskIsSet ) maskAndGroundtruthCnt++;
            }
        }
    }

    // compute dice coefficent
    return static_cast<double>( 2 * maskAndGroundtruthCnt ) / ( maskCnt + groundtruthCnt );
}

double averageEuclideanContourDistance( Contour const & contour, Contour const & groundtruth )
{
    double avgMinDist = 0;
    // TODO: make this less dumb, this currently has O(n^2) run complexity
    // use Kd-Tree or something like this .. vtkKdTree??
    for( size_t i = 0; i < contour.size(); ++i )
    {
        double minDistSqr = std::numeric_limits<double>::max();
        for( size_t j = 0; j < groundtruth.size(); ++j )
        {
            minDistSqr = std::min( cv::norm( cv::Vec2d( contour[i] - groundtruth[j] ), cv::NORM_L2SQR ), minDistSqr );
        }
        avgMinDist += sqrt( minDistSqr );
    }

    return avgMinDist / contour.size();
}

} // namespace Validator
<commit_msg>changes if pixelvalue is smaller than zero<commit_after>#include "Validator.h"

namespace Validator
{

double diceCoeff2DSlice( MaskType2D::Pointer mask, MaskType2D::Pointer groundtruth )
{
    // check if mask and groudntruth sizes match
    int width = mask->GetLargestPossibleRegion().GetSize()[0];
    int height = mask->GetLargestPossibleRegion().GetSize()[1];
    if( width != groundtruth->GetLargestPossibleRegion().GetSize()[0] ||
        height != groundtruth->GetLargestPossibleRegion().GetSize()[1] )
    {
        std::cerr << "diceCoeff2DSlice: mask and groundtruth must be same sice!" << std::endl;
        return -1;
    }

    // count mask and groundtruth pixels and how many they have in common
    size_t maskCnt = 0;
    size_t groundtruthCnt = 0;
    size_t maskAndGroundtruthCnt = 0;
    MaskType2D::IndexType index;
    for( int y = 0; y < height; ++y )
    {
        for( int x = 0; x < width; ++x )
        {
            index[0] = x;
            index[1] = y;
            bool maskIsSet = static_cast<bool>( mask->GetPixel( index )>0 );

            bool groundtruthIsSet = static_cast<bool>( groundtruth->GetPixel( index )>0 );
            if( maskIsSet ) maskCnt++;
            if( groundtruthIsSet ) groundtruthCnt++;
            if( groundtruthIsSet && maskIsSet ) maskAndGroundtruthCnt++;
        }
    }

    // compute dice coefficent
    return static_cast<double>( 2 * maskAndGroundtruthCnt ) / ( maskCnt + groundtruthCnt );
}

double diceCoeff3DVolume( MaskType::Pointer mask, MaskType::Pointer groundtruth )
{
    // check if mask and groudntruth sizes match
    int width = mask->GetLargestPossibleRegion().GetSize()[0];
    int height = mask->GetLargestPossibleRegion().GetSize()[1];
    int depth = mask->GetLargestPossibleRegion().GetSize()[2];
    if( width != groundtruth->GetLargestPossibleRegion().GetSize()[0] ||
        height != groundtruth->GetLargestPossibleRegion().GetSize()[1] ||
        depth != groundtruth->GetLargestPossibleRegion().GetSize()[2] )
    {
        std::cerr << "diceCoeff3DVolume: mask and groundtruth must be same sice!" << std::endl;
        return -1;
    }

    // count mask and groundtruth pixels and how many they have in common
    size_t maskCnt = 0;
    size_t groundtruthCnt = 0;
    size_t maskAndGroundtruthCnt = 0;
    MaskType::IndexType index;
    for( int z = 0; z < depth; ++z )
    {
        index[2] = z;
        for( int y = 0; y < height; ++y )
        {
            index[1] = y;
            for( int x = 0; x < width; ++x )
            {
                index[0] = x;
                bool maskIsSet = static_cast<bool>( mask->GetPixel( index ) );
                bool groundtruthIsSet = static_cast<bool>( groundtruth->GetPixel( index ) );
                if( maskIsSet ) maskCnt++;
                if( groundtruthIsSet ) groundtruthCnt++;
                if( groundtruthIsSet && maskIsSet ) maskAndGroundtruthCnt++;
            }
        }
    }

    // compute dice coefficent
    return static_cast<double>( 2 * maskAndGroundtruthCnt ) / ( maskCnt + groundtruthCnt );
}

double averageEuclideanContourDistance( Contour const & contour, Contour const & groundtruth )
{
    double avgMinDist = 0;
    // TODO: make this less dumb, this currently has O(n^2) run complexity
    // use Kd-Tree or something like this .. vtkKdTree??
    for( size_t i = 0; i < contour.size(); ++i )
    {
        double minDistSqr = std::numeric_limits<double>::max();
        for( size_t j = 0; j < groundtruth.size(); ++j )
        {
            minDistSqr = std::min( cv::norm( cv::Vec2d( contour[i] - groundtruth[j] ), cv::NORM_L2SQR ), minDistSqr );
        }
        avgMinDist += sqrt( minDistSqr );
    }

    return avgMinDist / contour.size();
}

} // namespace Validator
<|endoftext|>


<commit_before>/*******************************************************************************
 * c7a/engine/stage_builder.hpp
 *
 * Functions to build stages
 ******************************************************************************/

#pragma once

#include "../api/dia_base.hpp"
#include "../common/logger.hpp"
#include <stack>
#include <string>
#include <utility>
#include <algorithm>

namespace c7a {
namespace engine {

class Stage {
public:
    Stage(DIABase* node) : node_(node) {
        SpacingLogger(true) << "CREATING stage" << node_->ToString() << "node" << node_;
    }
    void Run() {
        SpacingLogger(true) << "RUNNING stage " << node_->ToString() << "node" << node_;
        //GOAL: Make sure the stage is executed efficiently.
        node_->execute();
    };
private:
    DIABase* node_;
};

// Returns a list of stages of graph scope
void  FindStages(DIABase* action, std::vector<Stage> & stages_result) {
    SpacingLogger(true) << "FINDING stages:";

    // GOAL: Returns a vector with stages
    // TEMP SOLUTION: Every node is a stage
    std::stack<DIABase*> dia_stack;
    dia_stack.push(action);
    while (!dia_stack.empty()) {
        DIABase* curr = dia_stack.top();
        // SpacingLogger(true) << curr;
        dia_stack.pop();
        stages_result.emplace_back(Stage(curr));
        std::vector<DIABase*> parents = curr->get_parents();
        for (DIABase* p : parents) {
            // SpacingLogger(true) << "PTR IS" << p;
            if (p) dia_stack.push(p);
            else SpacingLogger(true) << "OMG NULLPTR";
        }
    }

    std::reverse(stages_result.begin(),stages_result.end());
};

}}// !C7A_ENGINE_STAGE_BUILD
<commit_msg>make find stages better<commit_after>/*******************************************************************************
 * c7a/engine/stage_builder.hpp
 *
 * Functions to build stages
 ******************************************************************************/

#pragma once

#include "../api/dia_base.hpp"
#include "../common/logger.hpp"
#include <stack>
#include <string>
#include <utility>
#include <algorithm>
#include <set>

namespace c7a {
namespace engine {

class Stage {
public:
    Stage(DIABase* node) : node_(node) {
        SpacingLogger(true) << "CREATING stage" << node_->ToString() << "node" << node_;
    }
    void Run() {
        SpacingLogger(true) << "RUNNING stage " << node_->ToString() << "node" << node_;
        //GOAL: Make sure the stage is executed efficiently.
        node_->execute();
    };
private:
    DIABase* node_;
};

// Returns a list of stages of graph scope
void  FindStages(DIABase* action, std::vector<Stage> & stages_result) {
    SpacingLogger(true) << "FINDING stages:";
    std::set<DIABase*> stages_found;
    // GOAL: Returns a vector with stages
    // TEMP SOLUTION: Every node is a stage
    std::stack<DIABase*> dia_stack;
    dia_stack.push(action);
    stages_found.insert(action);
    while (!dia_stack.empty()) {
        DIABase* curr = dia_stack.top();
        dia_stack.pop();
        stages_result.emplace_back(Stage(curr));
        std::vector<DIABase*> parents = curr->get_parents();
        for (DIABase* p : parents) {

            if (p && (stages_found.find(p) == stages_found.end())) {
                dia_stack.push(p);
                stages_found.insert(p);
            }
            else SpacingLogger(true) << "OMG NULLPTR";
        }
    }

    std::reverse(stages_result.begin(),stages_result.end());
};

}}// !C7A_ENGINE_STAGE_BUILD
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// 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 "cc/dual_net/lite_dual_net.h"

#include <sys/sysinfo.h>
#include <iostream>

#include "absl/strings/string_view.h"
#include "cc/check.h"
#include "cc/constants.h"
#include "tensorflow/contrib/lite/kernels/register.h"

using tflite::FlatBufferModel;
using tflite::InterpreterBuilder;
using tflite::ops::builtin::BuiltinOpResolver;

namespace minigo {

LiteDualNet::LiteDualNet(const std::string& graph_path)
    : graph_path_(graph_path) {
  model_ = FlatBufferModel::BuildFromFile(graph_path.c_str());
  MG_CHECK(model_ != nullptr);

  BuiltinOpResolver resolver;
  InterpreterBuilder(*model_.get(), resolver)(&interpreter_);
  MG_CHECK(interpreter_ != nullptr);

  // Let's just use all the processors we can.
  interpreter_->SetNumThreads(get_nprocs());

  // Initialize input.
  const auto& inputs = interpreter_->inputs();
  MG_CHECK(inputs.size() == 1);
  absl::string_view input_name = interpreter_->GetInputName(0);
  MG_CHECK(input_name == "pos_tensor");

  auto* input_tensor = interpreter_->tensor(inputs[0]);
  MG_CHECK(input_tensor != nullptr);
  MG_CHECK(input_tensor->dims->size == 4);
  MG_CHECK(input_tensor->dims->data[1] == kN);
  MG_CHECK(input_tensor->dims->data[2] == kN);
  MG_CHECK(input_tensor->dims->data[3] == DualNet::kNumStoneFeatures);

  // Initialize outputs.
  const auto& outputs = interpreter_->outputs();
  MG_CHECK(outputs.size() == 2);
  absl::string_view output_0_name = interpreter_->GetOutputName(0);
  absl::string_view output_1_name = interpreter_->GetOutputName(1);
  if (output_0_name == "policy_output") {
    MG_CHECK(output_1_name == "value_output") << output_1_name;
    policy_ = 0;
    value_ = 1;
  } else {
    MG_CHECK(output_1_name == "policy_output") << output_1_name;
    MG_CHECK(output_0_name == "value_output") << output_0_name;
    policy_ = 1;
    value_ = 0;
  }

  auto* policy_tensor = interpreter_->tensor(outputs[policy_]);
  MG_CHECK(policy_tensor != nullptr);
  MG_CHECK(policy_tensor->dims->size == 2) << policy_tensor->dims->size;

  auto* value_tensor = interpreter_->tensor(outputs[value_]);
  MG_CHECK(value_tensor != nullptr);
  MG_CHECK(value_tensor->dims->size == 1);

  MG_CHECK(interpreter_->AllocateTensors() == kTfLiteOk);
}

LiteDualNet::~LiteDualNet() {}

void LiteDualNet::RunMany(absl::Span<const BoardFeatures> features,
                          absl::Span<Output> outputs, std::string* model) {
  int batch_size = static_cast<int>(features.size());
  auto* input_tensor = interpreter_->tensor(interpreter_->inputs()[0]);
  MG_CHECK(input_tensor->dims->data[0] == batch_size);

  auto* data = interpreter_->typed_input_tensor<float>(0);
  memcpy(data, features.data(), features.size() * sizeof(BoardFeatures));

  MG_CHECK(interpreter_->Invoke() == kTfLiteOk);

  auto* policy_data = interpreter_->typed_output_tensor<float>(policy_);
  auto* value_data = interpreter_->typed_output_tensor<float>(value_);
  for (int i = 0; i < batch_size; ++i) {
    memcpy(outputs[i].policy.data(), policy_data + i * kNumMoves,
           sizeof(outputs[i].policy));
    outputs[i].value = value_data[i];
  }

  if (model != nullptr) {
    *model = graph_path_;
  }
}

}  // namespace minigo
<commit_msg>Remove redundant get() call on smart pointer<commit_after>// Copyright 2018 Google LLC
//
// 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 "cc/dual_net/lite_dual_net.h"

#include <sys/sysinfo.h>
#include <iostream>

#include "absl/strings/string_view.h"
#include "cc/check.h"
#include "cc/constants.h"
#include "tensorflow/contrib/lite/kernels/register.h"

using tflite::FlatBufferModel;
using tflite::InterpreterBuilder;
using tflite::ops::builtin::BuiltinOpResolver;

namespace minigo {

LiteDualNet::LiteDualNet(const std::string& graph_path)
    : graph_path_(graph_path) {
  model_ = FlatBufferModel::BuildFromFile(graph_path.c_str());
  MG_CHECK(model_ != nullptr);

  BuiltinOpResolver resolver;
  InterpreterBuilder(*model_, resolver)(&interpreter_);
  MG_CHECK(interpreter_ != nullptr);

  // Let's just use all the processors we can.
  interpreter_->SetNumThreads(get_nprocs());

  // Initialize input.
  const auto& inputs = interpreter_->inputs();
  MG_CHECK(inputs.size() == 1);
  absl::string_view input_name = interpreter_->GetInputName(0);
  MG_CHECK(input_name == "pos_tensor");

  auto* input_tensor = interpreter_->tensor(inputs[0]);
  MG_CHECK(input_tensor != nullptr);
  MG_CHECK(input_tensor->dims->size == 4);
  MG_CHECK(input_tensor->dims->data[1] == kN);
  MG_CHECK(input_tensor->dims->data[2] == kN);
  MG_CHECK(input_tensor->dims->data[3] == DualNet::kNumStoneFeatures);

  // Initialize outputs.
  const auto& outputs = interpreter_->outputs();
  MG_CHECK(outputs.size() == 2);
  absl::string_view output_0_name = interpreter_->GetOutputName(0);
  absl::string_view output_1_name = interpreter_->GetOutputName(1);
  if (output_0_name == "policy_output") {
    MG_CHECK(output_1_name == "value_output") << output_1_name;
    policy_ = 0;
    value_ = 1;
  } else {
    MG_CHECK(output_1_name == "policy_output") << output_1_name;
    MG_CHECK(output_0_name == "value_output") << output_0_name;
    policy_ = 1;
    value_ = 0;
  }

  auto* policy_tensor = interpreter_->tensor(outputs[policy_]);
  MG_CHECK(policy_tensor != nullptr);
  MG_CHECK(policy_tensor->dims->size == 2) << policy_tensor->dims->size;

  auto* value_tensor = interpreter_->tensor(outputs[value_]);
  MG_CHECK(value_tensor != nullptr);
  MG_CHECK(value_tensor->dims->size == 1);

  MG_CHECK(interpreter_->AllocateTensors() == kTfLiteOk);
}

LiteDualNet::~LiteDualNet() {}

void LiteDualNet::RunMany(absl::Span<const BoardFeatures> features,
                          absl::Span<Output> outputs, std::string* model) {
  int batch_size = static_cast<int>(features.size());
  auto* input_tensor = interpreter_->tensor(interpreter_->inputs()[0]);
  MG_CHECK(input_tensor->dims->data[0] == batch_size);

  auto* data = interpreter_->typed_input_tensor<float>(0);
  memcpy(data, features.data(), features.size() * sizeof(BoardFeatures));

  MG_CHECK(interpreter_->Invoke() == kTfLiteOk);

  auto* policy_data = interpreter_->typed_output_tensor<float>(policy_);
  auto* value_data = interpreter_->typed_output_tensor<float>(value_);
  for (int i = 0; i < batch_size; ++i) {
    memcpy(outputs[i].policy.data(), policy_data + i * kNumMoves,
           sizeof(outputs[i].policy));
    outputs[i].value = value_data[i];
  }

  if (model != nullptr) {
    *model = graph_path_;
  }
}

}  // namespace minigo
<|endoftext|>