<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MultipleItemConverter.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:03:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "MultipleItemConverter.hxx"
#include "ItemPropertyMap.hxx"

#include <algorithm>

using namespace ::com::sun::star;

namespace comphelper
{

MultipleItemConverter::MultipleItemConverter( SfxItemPool& rItemPool )
        : ItemConverter( NULL, rItemPool )
{
}
MultipleItemConverter::~MultipleItemConverter()
{
    ::std::for_each( m_aConverters.begin(), m_aConverters.end(),
                     DeleteItemConverterPtr() );
}

void MultipleItemConverter::FillItemSet( SfxItemSet & rOutItemSet ) const
{
    ::std::vector< ItemConverter* >::const_iterator       aIter = m_aConverters.begin();
    const ::std::vector< ItemConverter* >::const_iterator aEnd  = m_aConverters.end();
    if( aIter != aEnd )
    {
        (*aIter)->FillItemSet( rOutItemSet );
        aIter++;
    }
    for( ; aIter != aEnd; aIter++ )
    {
        SfxItemSet aSet = this->CreateEmptyItemSet();
        (*aIter)->FillItemSet( aSet );
        InvalidateUnequalItems( rOutItemSet, aSet );
    }
    // no own items
}

bool MultipleItemConverter::ApplyItemSet( const SfxItemSet & rItemSet )
{
    bool bResult = false;

    ::std::for_each( m_aConverters.begin(), m_aConverters.end(),
                     ApplyItemSetFunc( rItemSet, bResult ));

    // no own items
    return bResult;
}

bool MultipleItemConverter::GetItemPropertyName( USHORT nWhichId, ::rtl::OUString & rOutName ) const
{
    return false;
}

} //  namespace comphelper
<commit_msg>INTEGRATION: CWS chart2mst3 (1.3.4); FILE MERGED 2006/10/18 17:06:44 bm 1.3.4.3: RESYNC: (1.4-1.5); FILE MERGED 2005/10/07 11:32:19 bm 1.3.4.2: RESYNC: (1.3-1.4); FILE MERGED 2004/05/07 09:14:21 bm 1.3.4.1: enabling member-ids for all items<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MultipleItemConverter.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:01:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "MultipleItemConverter.hxx"
#include "ItemPropertyMap.hxx"

#include <algorithm>

using namespace ::com::sun::star;

namespace comphelper
{

MultipleItemConverter::MultipleItemConverter( SfxItemPool& rItemPool )
        : ItemConverter( NULL, rItemPool )
{
}
MultipleItemConverter::~MultipleItemConverter()
{
    ::std::for_each( m_aConverters.begin(), m_aConverters.end(),
                     DeleteItemConverterPtr() );
}

void MultipleItemConverter::FillItemSet( SfxItemSet & rOutItemSet ) const
{
    ::std::vector< ItemConverter* >::const_iterator       aIter = m_aConverters.begin();
    const ::std::vector< ItemConverter* >::const_iterator aEnd  = m_aConverters.end();
    if( aIter != aEnd )
    {
        (*aIter)->FillItemSet( rOutItemSet );
        aIter++;
    }
    for( ; aIter != aEnd; aIter++ )
    {
        SfxItemSet aSet = this->CreateEmptyItemSet();
        (*aIter)->FillItemSet( aSet );
        InvalidateUnequalItems( rOutItemSet, aSet );
    }
    // no own items
}

bool MultipleItemConverter::ApplyItemSet( const SfxItemSet & rItemSet )
{
    bool bResult = false;

    ::std::for_each( m_aConverters.begin(), m_aConverters.end(),
                     ApplyItemSetFunc( rItemSet, bResult ));

    // no own items
    return bResult;
}

bool MultipleItemConverter::GetItemProperty( tWhichIdType nWhichId, tPropertyNameWithMemberId & rOutProperty ) const
{
    return false;
}

} //  namespace comphelper
<|endoftext|>


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

#include "chrome/browser/automation/testing_automation_provider.h"

#include "base/values.h"
#include "chrome/browser/automation/automation_provider_json.h"
#include "chrome/browser/automation/automation_provider_observers.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/cros/screen_lock_library.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"

using chromeos::CrosLibrary;
using chromeos::NetworkLibrary;

namespace {

DictionaryValue* GetNetworkInfoDict(const chromeos::Network* network) {
  DictionaryValue* item = new DictionaryValue;
  item->SetString("service_path", network->service_path());
  item->SetString("name", network->name());
  item->SetString("device_path", network->device_path());
  item->SetString("ip_address", network->ip_address());
  item->SetString("status", network->GetStateString());
  return item;
}

}  // namespace

void TestingAutomationProvider::LoginAsGuest(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->LoginAsGuest();
}

void TestingAutomationProvider::Login(DictionaryValue* args,
                                      IPC::Message* reply_message) {
  std::string username, password;
  if (!args->GetString("username", &username) ||
      !args->GetString("password", &password)) {
    AutomationJSONReply(this, reply_message).SendError(
        "Invalid or missing args");
    return;
  }

  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->Login(username, password);
}

// Logging out could have other undesirable side effects: session_manager is
// killed, so its children, including chrome and the window manager will also
// be killed. SSH connections might be closed, the test binary might be killed.
void TestingAutomationProvider::Logout(DictionaryValue* args,
                                       IPC::Message* reply_message) {
  // Send success before stopping session because if we're a child of
  // session manager then we'll die when the session is stopped.
  AutomationJSONReply(this, reply_message).SendSuccess(NULL);
  if (chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->StopSession("");
}

void TestingAutomationProvider::ScreenLock(DictionaryValue* args,
                                           IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, true);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenLockRequested();
}

void TestingAutomationProvider::ScreenUnlock(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, false);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenUnlockRequested();
}

void TestingAutomationProvider::GetNetworkInfo(DictionaryValue* args,
                                               IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  scoped_ptr<DictionaryValue> return_value(new DictionaryValue);

  // IP address.
  return_value->SetString("ip_address", network_library->IPAddress());

  // Ethernet network.
  bool ethernet_available = network_library->ethernet_available();
  bool ethernet_enabled = network_library->ethernet_enabled();
  if (ethernet_available && ethernet_enabled) {
    const chromeos::EthernetNetwork* ethernet_network =
        network_library->ethernet_network();
    if (ethernet_network)
      return_value->Set("ethernet_network",
                        GetNetworkInfoDict(ethernet_network));
  }

  // Wi-fi networks.
  bool wifi_available = network_library->wifi_available();
  bool wifi_enabled = network_library->wifi_enabled();
  if (wifi_available && wifi_enabled) {
    const chromeos::WifiNetworkVector& wifi_networks =
        network_library->wifi_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < wifi_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(wifi_networks[i]);
      item->SetInteger("strength", wifi_networks[i]->strength());
      item->SetBoolean("encrypted", wifi_networks[i]->encrypted());
      item->SetString("encryption", wifi_networks[i]->GetEncryptionString());
      items->Append(item);
    }
    return_value->Set("wifi_networks", items);
  }

  // Cellular networks.
  bool cellular_available = network_library->cellular_available();
  bool cellular_enabled = network_library->cellular_enabled();
  if (cellular_available && cellular_enabled) {
    const chromeos::CellularNetworkVector& cellular_networks =
        network_library->cellular_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < cellular_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(cellular_networks[i]);
      item->SetInteger("strength", cellular_networks[i]->strength());
      item->SetString("operator_name", cellular_networks[i]->operator_name());
      item->SetString("operator_code", cellular_networks[i]->operator_code());
      item->SetString("payment_url", cellular_networks[i]->payment_url());
      item->SetString("usage_url", cellular_networks[i]->usage_url());
      item->SetString("network_technology",
                      cellular_networks[i]->GetNetworkTechnologyString());
      item->SetString("connectivity_state",
                      cellular_networks[i]->GetConnectivityStateString());
      item->SetString("activation_state",
                      cellular_networks[i]->GetActivationStateString());
      item->SetString("roaming_state",
                      cellular_networks[i]->GetRoamingStateString());
      items->Append(item);
    }
    return_value->Set("cellular_networks", items);
  }

  reply.SendSuccess(return_value.get());
}

void TestingAutomationProvider::ConnectToWifiNetwork(
    DictionaryValue* args, IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);
  std::string service_path, password, identity, certpath;
  if (!args->GetString("service_path", &service_path) ||
      !args->GetString("password", &password) ||
      !args->GetString("identity", &identity) ||
      !args->GetString("certpath", &certpath)) {
    reply.SendError("Invalid or missing args");
    return;
  }

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  if (!network_library->ConnectToWifiNetwork(
      service_path, password, identity, certpath)) {
    reply.SendError("Failed to connect");
    return;
  }

  reply.SendSuccess(NULL);
}

<commit_msg>Patch for http://codereview.chromium.org/6628023/<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/automation/testing_automation_provider.h"

#include "base/values.h"
#include "chrome/browser/automation/automation_provider_json.h"
#include "chrome/browser/automation/automation_provider_observers.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/cros/screen_lock_library.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"

using chromeos::CrosLibrary;
using chromeos::NetworkLibrary;

namespace {

DictionaryValue* GetNetworkInfoDict(const chromeos::Network* network) {
  DictionaryValue* item = new DictionaryValue;
  item->SetString("service_path", network->service_path());
  item->SetString("name", network->name());
  item->SetString("device_path", network->device_path());
  item->SetString("ip_address", network->ip_address());
  item->SetString("status", network->GetStateString());
  return item;
}

}  // namespace

void TestingAutomationProvider::LoginAsGuest(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->LoginAsGuest();
}

void TestingAutomationProvider::Login(DictionaryValue* args,
                                      IPC::Message* reply_message) {
  std::string username, password;
  if (!args->GetString("username", &username) ||
      !args->GetString("password", &password)) {
    AutomationJSONReply(this, reply_message).SendError(
        "Invalid or missing args");
    return;
  }

  chromeos::ExistingUserController* controller =
      chromeos::ExistingUserController::current_controller();
  // Set up an observer (it will delete itself).
  new LoginManagerObserver(this, reply_message);
  controller->Login(username, password);
}

// Logging out could have other undesirable side effects: session_manager is
// killed, so its children, including chrome and the window manager will also
// be killed. SSH connections might be closed, the test binary might be killed.
void TestingAutomationProvider::Logout(DictionaryValue* args,
                                       IPC::Message* reply_message) {
  // Send success before stopping session because if we're a child of
  // session manager then we'll die when the session is stopped.
  AutomationJSONReply(this, reply_message).SendSuccess(NULL);
  if (chromeos::CrosLibrary::Get()->EnsureLoaded())
    chromeos::CrosLibrary::Get()->GetLoginLibrary()->StopSession("");
}

void TestingAutomationProvider::ScreenLock(DictionaryValue* args,
                                           IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, true);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenLockRequested();
}

void TestingAutomationProvider::ScreenUnlock(DictionaryValue* args,
                                             IPC::Message* reply_message) {
  new ScreenLockUnlockObserver(this, reply_message, false);
  chromeos::CrosLibrary::Get()->GetScreenLockLibrary()->
      NotifyScreenUnlockRequested();
}

void TestingAutomationProvider::GetNetworkInfo(DictionaryValue* args,
                                               IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  scoped_ptr<DictionaryValue> return_value(new DictionaryValue);

  // IP address.
  return_value->SetString("ip_address", network_library->IPAddress());

  // Ethernet network.
  bool ethernet_available = network_library->ethernet_available();
  bool ethernet_enabled = network_library->ethernet_enabled();
  if (ethernet_available && ethernet_enabled) {
    const chromeos::EthernetNetwork* ethernet_network =
        network_library->ethernet_network();
    if (ethernet_network)
      return_value->Set("ethernet_network",
                        GetNetworkInfoDict(ethernet_network));
  }

  // Wi-fi networks.
  bool wifi_available = network_library->wifi_available();
  bool wifi_enabled = network_library->wifi_enabled();
  if (wifi_available && wifi_enabled) {
    const chromeos::WifiNetworkVector& wifi_networks =
        network_library->wifi_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < wifi_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(wifi_networks[i]);
      item->SetInteger("strength", wifi_networks[i]->strength());
      item->SetBoolean("encrypted", wifi_networks[i]->encrypted());
      item->SetString("encryption", wifi_networks[i]->GetEncryptionString());
      items->Append(item);
    }
    return_value->Set("wifi_networks", items);
  }

  // Cellular networks.
  bool cellular_available = network_library->cellular_available();
  bool cellular_enabled = network_library->cellular_enabled();
  if (cellular_available && cellular_enabled) {
    const chromeos::CellularNetworkVector& cellular_networks =
        network_library->cellular_networks();
    ListValue* items = new ListValue;
    for (size_t i = 0; i < cellular_networks.size(); ++i) {
      DictionaryValue* item = GetNetworkInfoDict(cellular_networks[i]);
      item->SetInteger("strength", cellular_networks[i]->strength());
      item->SetString("operator_name", cellular_networks[i]->operator_name());
      item->SetString("operator_code", cellular_networks[i]->operator_code());
      item->SetString("payment_url", cellular_networks[i]->payment_url());
      item->SetString("usage_url", cellular_networks[i]->usage_url());
      item->SetString("network_technology",
                      cellular_networks[i]->GetNetworkTechnologyString());
      item->SetString("connectivity_state",
                      cellular_networks[i]->GetConnectivityStateString());
      item->SetString("activation_state",
                      cellular_networks[i]->GetActivationStateString());
      item->SetString("roaming_state",
                      cellular_networks[i]->GetRoamingStateString());
      items->Append(item);
    }
    return_value->Set("cellular_networks", items);
  }

  reply.SendSuccess(return_value.get());
}

void TestingAutomationProvider::ConnectToWifiNetwork(
    DictionaryValue* args, IPC::Message* reply_message) {
  AutomationJSONReply reply(this, reply_message);
  std::string service_path, password, identity, certpath;
  if (!args->GetString("service_path", &service_path) ||
      !args->GetString("password", &password) ||
      !args->GetString("identity", &identity) ||
      !args->GetString("certpath", &certpath)) {
    reply.SendError("Invalid or missing args");
    return;
  }

  if (!CrosLibrary::Get()->EnsureLoaded()) {
    reply.SendError("Could not load cros library.");
    return;
  }

  NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
  WifiNetwork* wifi = network_library->FindWifiNetworkByPath(service_path);
  if (!wifi) {
    reply.SendError("Failed to connect");
    return;
  }
  if (!password.empty())
    wifi->SetPassphrase(password);
  if (!identity.empty())
    wifi->SetIdentity(identity);
  if (!certpath.empty())
    wifi->SetCertPath(certpath);
  network_library->ConnectToWifiNetwork(service_path);

  // TODO(stevenjb): Observe the network library and check for a successful
  // connection.

  reply.SendSuccess(NULL);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012-2015 Dano Pernis
// See LICENSE for details

#include <gtk/gtk.h>
#include <glib.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include "CPU.h"

namespace hcc {

struct ROM : public IROM {
    unsigned short *data;
    static const unsigned int size = 0x8000;
    ROM() {
        data = new unsigned short[size];
    }
    virtual ~ROM() {
        delete[] data;
    }

    bool load(const char *filename) {
        std::ifstream input(filename);
        std::string line;
        unsigned int counter = 0;
        while (input.good() && counter < size) {
            getline(input, line);
            if (line.size() == 0)
                continue;
            if (line.size() != 16)
                return false;

            unsigned int instruction = 0;
            for (unsigned int i = 0; i<16; ++i) {
                instruction <<= 1;
                switch (line[i]) {
                case '0':
                    break;
                case '1':
                    instruction |= 1;
                    break;
                default:
                    return false;
                }
            }
            data[counter++] = instruction;
        }
        // clear the rest
        while (counter < size) {
            data[counter++] = 0;
        }

        return true;
    }
    virtual unsigned short get(unsigned int address) const {
        if (address < size) {
            return data[address];
        } else {
            std::cerr << "requested memory at " << address << '\n';
            throw std::runtime_error("Memory::get");
        }
    }
};

} // end namespace

struct GUIEmulatorRAM : public hcc::IRAM {
    static const unsigned int CHANNELS = 3;
    static const unsigned int SCREEN_WIDTH = 512;
    static const unsigned int SCREEN_HEIGHT = 256;
    static const unsigned int size = 0x6001;

    unsigned short *data;
    unsigned char *vram;
    GdkPixbuf *pixbuf;
    GtkWidget *screen;

    void putpixel(unsigned short x, unsigned short y, bool black) {
        unsigned int offset = CHANNELS*(SCREEN_WIDTH*y + x);
        for (unsigned int channel = 0; channel<CHANNELS; ++channel) {
            vram[offset++] = black ? 0x00 : 0xff;
        }
    }
public:
    GUIEmulatorRAM() {
        data = new unsigned short[size];
        vram = new unsigned char[CHANNELS*SCREEN_WIDTH*SCREEN_HEIGHT];
        pixbuf = gdk_pixbuf_new_from_data(vram, GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT, CHANNELS*SCREEN_WIDTH, NULL, NULL);
        screen = gtk_image_new_from_pixbuf(pixbuf);
    }
    virtual ~GUIEmulatorRAM() {
        delete[] data;
        delete[] vram;
    }
    void keyboard(unsigned short value) {
        data[0x6000] = value;
    }
    GtkWidget* getScreenWidget() {
        return screen;
    }
    virtual void set(unsigned int address, unsigned short value) {
        if (address >= size) {
            throw std::runtime_error("RAM::set");
        }

        data[address] = value;

        // check if we are writing to video RAM
        if (0x4000 <= address && address <0x6000) {
            address -= 0x4000;

            unsigned short y = address / 32;
            unsigned short x = 16*(address % 32);
            for (int bit = 0; bit<16; ++bit) {
                putpixel(x + bit, y, value & 1);
                value = value >> 1;
            }
            gdk_threads_enter();
            gtk_widget_queue_draw(screen);
            gdk_threads_leave();
        }
    }
    virtual unsigned short get(unsigned int address) const {
        if (address >= size) {
            throw std::runtime_error("RAM::get");
        }

        return data[address];
    }
};
hcc::ROM rom;
GUIEmulatorRAM *ram;
hcc::CPU cpu;

bool running = false;

GtkWidget *window;
GtkToolItem *button_load, *button_run, *button_pause;

void load_clicked(GtkButton *button, gpointer user_data)
{
    bool loaded = false;

    GtkWidget *dialog = gtk_file_chooser_dialog_new("Load ROM",
        GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL,
        GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
    if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
        loaded = rom.load(filename);
        g_free(filename);
    }
    gtk_widget_destroy(dialog);

    if (!loaded) {
        GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
            "Error loading program");
        gtk_dialog_run(GTK_DIALOG(dialog));
        gtk_widget_destroy(dialog);
    } else {
        cpu.reset();
        gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
    }
}

gpointer run_thread(gpointer user_data)
{
    int steps = 0;
    while (running) {
        cpu.step(&rom, ram);
        if (steps>100) {
            g_usleep(10);
            steps = 0;
        }
        ++steps;
    }
    return NULL;
}
void run_clicked()
{
    assert(!running);

    running = true;
    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
    gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE);
    gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE);

    g_thread_create(run_thread, NULL, FALSE, NULL);
}
void pause_clicked()
{
    assert(running);

    running = false;
    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
    gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE);
}

gboolean keyboard_callback(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
    if (event->type == GDK_KEY_RELEASE) {
        ram->keyboard(0);
    } else {
        // Translate special keys. See Figure 5.6 in TECS book.
        switch (event->keyval) {
        case GDK_KEY_Return:
            ram->keyboard(128);
            break;
        case GDK_KEY_BackSpace:
            ram->keyboard(129);
            break;
        case GDK_KEY_Left:
            ram->keyboard(130);
            break;
        case GDK_KEY_Up:
            ram->keyboard(131);
            break;
        case GDK_KEY_Right:
            ram->keyboard(132);
            break;
        case GDK_KEY_Down:
            ram->keyboard(133);
            break;
        case GDK_KEY_Home:
            ram->keyboard(134);
            break;
        case GDK_KEY_End:
            ram->keyboard(135);
            break;
        case GDK_KEY_Page_Up:
            ram->keyboard(136);
            break;
        case GDK_KEY_Page_Down:
            ram->keyboard(137);
            break;
        case GDK_KEY_Insert:
            ram->keyboard(138);
            break;
        case GDK_KEY_Delete:
            ram->keyboard(139);
            break;
        case GDK_KEY_Escape:
            ram->keyboard(140);
            break;
        case GDK_KEY_F1:
            ram->keyboard(141);
            break;
        case GDK_KEY_F2:
            ram->keyboard(142);
            break;
        case GDK_KEY_F3:
            ram->keyboard(143);
            break;
        case GDK_KEY_F4:
            ram->keyboard(144);
            break;
        case GDK_KEY_F5:
            ram->keyboard(145);
            break;
        case GDK_KEY_F6:
            ram->keyboard(146);
            break;
        case GDK_KEY_F7:
            ram->keyboard(147);
            break;
        case GDK_KEY_F8:
            ram->keyboard(148);
            break;
        case GDK_KEY_F9:
            ram->keyboard(149);
            break;
        case GDK_KEY_F10:
            ram->keyboard(150);
            break;
        case GDK_KEY_F11:
            ram->keyboard(151);
            break;
        case GDK_KEY_F12:
            ram->keyboard(152);
            break;
        default:
            ram->keyboard(event->keyval);
        }
    }
    return TRUE;
}

GtkToolItem *create_button(const gchar *stock_id, const gchar *text, GCallback callback)
{
    GtkToolItem *button = gtk_tool_button_new_from_stock(stock_id);
    gtk_tool_button_set_label(GTK_TOOL_BUTTON(button), text);
    gtk_tool_item_set_tooltip_text(button, text);
    g_signal_connect(button, "clicked", callback, NULL);
    return button;
}

int main(int argc, char *argv[])
{
    gtk_init(&argc, &argv);
    ram = new GUIEmulatorRAM();

    /* toolbar buttons */
    button_load    = create_button(GTK_STOCK_OPEN,        "Load...", G_CALLBACK(load_clicked));
    button_run     = create_button(GTK_STOCK_MEDIA_PLAY,  "Run",     G_CALLBACK(run_clicked));
    button_pause   = create_button(GTK_STOCK_MEDIA_PAUSE, "Pause",   G_CALLBACK(pause_clicked));

    GtkToolItem *separator1 = gtk_separator_tool_item_new();

    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);

    /* toolbar itself */
    GtkWidget *toolbar = gtk_toolbar_new();
    gtk_widget_set_hexpand(toolbar, TRUE);
    gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load,  -1);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1,   -1);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run,   -1);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1);

    /* keyboard */
    GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus");
    gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);
    g_signal_connect(keyboard, "key-press-event",   G_CALLBACK(keyboard_callback), NULL);
    g_signal_connect(keyboard, "key-release-event", G_CALLBACK(keyboard_callback), NULL);

    /* main layout */
    GtkWidget *grid = gtk_grid_new();
    gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), ram->getScreenWidget(), 0, 1, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);

    /* main window */
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(window), "HACK emulator");
    gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
    gtk_window_set_focus(GTK_WINDOW(window), NULL);
    g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
    gtk_container_add(GTK_CONTAINER(window), grid);
    gtk_widget_show_all(window);
    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);

    gtk_main();
    return 0;
}
<commit_msg>Refactored key translation<commit_after>// Copyright (c) 2012-2015 Dano Pernis
// See LICENSE for details

#include <gtk/gtk.h>
#include <glib.h>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <cassert>
#include "CPU.h"

namespace hcc {

struct ROM : public IROM {
    unsigned short *data;
    static const unsigned int size = 0x8000;
    ROM() {
        data = new unsigned short[size];
    }
    virtual ~ROM() {
        delete[] data;
    }

    bool load(const char *filename) {
        std::ifstream input(filename);
        std::string line;
        unsigned int counter = 0;
        while (input.good() && counter < size) {
            getline(input, line);
            if (line.size() == 0)
                continue;
            if (line.size() != 16)
                return false;

            unsigned int instruction = 0;
            for (unsigned int i = 0; i<16; ++i) {
                instruction <<= 1;
                switch (line[i]) {
                case '0':
                    break;
                case '1':
                    instruction |= 1;
                    break;
                default:
                    return false;
                }
            }
            data[counter++] = instruction;
        }
        // clear the rest
        while (counter < size) {
            data[counter++] = 0;
        }

        return true;
    }
    virtual unsigned short get(unsigned int address) const {
        if (address < size) {
            return data[address];
        } else {
            std::cerr << "requested memory at " << address << '\n';
            throw std::runtime_error("Memory::get");
        }
    }
};

} // end namespace

struct GUIEmulatorRAM : public hcc::IRAM {
    static const unsigned int CHANNELS = 3;
    static const unsigned int SCREEN_WIDTH = 512;
    static const unsigned int SCREEN_HEIGHT = 256;
    static const unsigned int size = 0x6001;

    unsigned short *data;
    unsigned char *vram;
    GdkPixbuf *pixbuf;
    GtkWidget *screen;

    void putpixel(unsigned short x, unsigned short y, bool black) {
        unsigned int offset = CHANNELS*(SCREEN_WIDTH*y + x);
        for (unsigned int channel = 0; channel<CHANNELS; ++channel) {
            vram[offset++] = black ? 0x00 : 0xff;
        }
    }
public:
    GUIEmulatorRAM() {
        data = new unsigned short[size];
        vram = new unsigned char[CHANNELS*SCREEN_WIDTH*SCREEN_HEIGHT];
        pixbuf = gdk_pixbuf_new_from_data(vram, GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT, CHANNELS*SCREEN_WIDTH, NULL, NULL);
        screen = gtk_image_new_from_pixbuf(pixbuf);
    }
    virtual ~GUIEmulatorRAM() {
        delete[] data;
        delete[] vram;
    }
    void keyboard(unsigned short value) {
        data[0x6000] = value;
    }
    GtkWidget* getScreenWidget() {
        return screen;
    }
    virtual void set(unsigned int address, unsigned short value) {
        if (address >= size) {
            throw std::runtime_error("RAM::set");
        }

        data[address] = value;

        // check if we are writing to video RAM
        if (0x4000 <= address && address <0x6000) {
            address -= 0x4000;

            unsigned short y = address / 32;
            unsigned short x = 16*(address % 32);
            for (int bit = 0; bit<16; ++bit) {
                putpixel(x + bit, y, value & 1);
                value = value >> 1;
            }
            gdk_threads_enter();
            gtk_widget_queue_draw(screen);
            gdk_threads_leave();
        }
    }
    virtual unsigned short get(unsigned int address) const {
        if (address >= size) {
            throw std::runtime_error("RAM::get");
        }

        return data[address];
    }
};
hcc::ROM rom;
GUIEmulatorRAM *ram;
hcc::CPU cpu;

bool running = false;

GtkWidget *window;
GtkToolItem *button_load, *button_run, *button_pause;

void load_clicked(GtkButton *button, gpointer user_data)
{
    bool loaded = false;

    GtkWidget *dialog = gtk_file_chooser_dialog_new("Load ROM",
        GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL,
        GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
    if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
        char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
        loaded = rom.load(filename);
        g_free(filename);
    }
    gtk_widget_destroy(dialog);

    if (!loaded) {
        GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(window),
            GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE,
            "Error loading program");
        gtk_dialog_run(GTK_DIALOG(dialog));
        gtk_widget_destroy(dialog);
    } else {
        cpu.reset();
        gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
    }
}

gpointer run_thread(gpointer user_data)
{
    int steps = 0;
    while (running) {
        cpu.step(&rom, ram);
        if (steps>100) {
            g_usleep(10);
            steps = 0;
        }
        ++steps;
    }
    return NULL;
}
void run_clicked()
{
    assert(!running);

    running = true;
    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
    gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE);
    gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE);

    g_thread_create(run_thread, NULL, FALSE, NULL);
}
void pause_clicked()
{
    assert(running);

    running = false;
    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);
    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE);
    gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE);
}

// Translate special keys. See Figure 5.6 in TECS book.
unsigned short translate(guint keyval)
{
    switch (keyval) {
    case GDK_KEY_Return:    return 128;
    case GDK_KEY_BackSpace: return 129;
    case GDK_KEY_Left:      return 130;
    case GDK_KEY_Up:        return 131;
    case GDK_KEY_Right:     return 132;
    case GDK_KEY_Down:      return 133;
    case GDK_KEY_Home:      return 134;
    case GDK_KEY_End:       return 135;
    case GDK_KEY_Page_Up:   return 136;
    case GDK_KEY_Page_Down: return 137;
    case GDK_KEY_Insert:    return 138;
    case GDK_KEY_Delete:    return 139;
    case GDK_KEY_Escape:    return 140;
    case GDK_KEY_F1:        return 141;
    case GDK_KEY_F2:        return 142;
    case GDK_KEY_F3:        return 143;
    case GDK_KEY_F4:        return 144;
    case GDK_KEY_F5:        return 145;
    case GDK_KEY_F6:        return 146;
    case GDK_KEY_F7:        return 147;
    case GDK_KEY_F8:        return 148;
    case GDK_KEY_F9:        return 149;
    case GDK_KEY_F10:       return 150;
    case GDK_KEY_F11:       return 151;
    case GDK_KEY_F12:       return 152;
    }
    return keyval;
}

gboolean keyboard_callback(GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
    if (event->type == GDK_KEY_RELEASE) {
        ram->keyboard(0);
    } else {
        ram->keyboard(translate(event->keyval));
    }
    return TRUE;
}

GtkToolItem *create_button(const gchar *stock_id, const gchar *text, GCallback callback)
{
    GtkToolItem *button = gtk_tool_button_new_from_stock(stock_id);
    gtk_tool_button_set_label(GTK_TOOL_BUTTON(button), text);
    gtk_tool_item_set_tooltip_text(button, text);
    g_signal_connect(button, "clicked", callback, NULL);
    return button;
}

int main(int argc, char *argv[])
{
    gtk_init(&argc, &argv);
    ram = new GUIEmulatorRAM();

    /* toolbar buttons */
    button_load    = create_button(GTK_STOCK_OPEN,        "Load...", G_CALLBACK(load_clicked));
    button_run     = create_button(GTK_STOCK_MEDIA_PLAY,  "Run",     G_CALLBACK(run_clicked));
    button_pause   = create_button(GTK_STOCK_MEDIA_PAUSE, "Pause",   G_CALLBACK(pause_clicked));

    GtkToolItem *separator1 = gtk_separator_tool_item_new();

    gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE);
    gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE);

    /* toolbar itself */
    GtkWidget *toolbar = gtk_toolbar_new();
    gtk_widget_set_hexpand(toolbar, TRUE);
    gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load,  -1);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1,   -1);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run,   -1);
    gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1);

    /* keyboard */
    GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus");
    gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK);
    g_signal_connect(keyboard, "key-press-event",   G_CALLBACK(keyboard_callback), NULL);
    g_signal_connect(keyboard, "key-release-event", G_CALLBACK(keyboard_callback), NULL);

    /* main layout */
    GtkWidget *grid = gtk_grid_new();
    gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), ram->getScreenWidget(), 0, 1, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1);

    /* main window */
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(window), "HACK emulator");
    gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
    gtk_window_set_focus(GTK_WINDOW(window), NULL);
    g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
    gtk_container_add(GTK_CONTAINER(window), grid);
    gtk_widget_show_all(window);
    gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE);

    gtk_main();
    return 0;
}
<|endoftext|>


<commit_before>#include "hof.h"

#include "cache.h"
#include "combinators.h"
#include "colors.h"
#include "verbose.h"

bool evaluationListIsWellFormed(const EvaluationList& list)
{
    EvaluationList::const_iterator it = list.begin();
    for (; it != list.end(); ++it) {
        if ((*it)->type() == Combinator::a_)
            return static_cast<const A*>((*it).data())->isWellFormed();
    }
    return true;
}

void cppInterpreter(const QString& string)
{
    Verbose::instance()->generateProgramString("program: " + string);
    Verbose::instance()->generateProgramString("begin", true /*replace*/);
    int postfixIndex = Verbose::instance()->addPostfix(string);

    if (string.isEmpty()) {
        Verbose::instance()->generateProgramString("end", true /*replace*/);
        return;
    }

    EvaluationList evaluationList;
    for (int x = 0; x < string.length(); x++) {
        CombinatorPtr term;
        QChar ch = string.at(x);
        switch (ch.unicode()) {
        case 'I': term = i(); break;
        case 'K': term = k(); break;
        case 'S': term = s(); break;
        case 'P': term = p(); break;
        case 'R': term = r(); break;
        case 'A': term = CombinatorPtr(new A); break;
        default:
            QString error = QString("Error: invalid char in hof program! ch=`%1`").arg(ch);
            Q_ASSERT_X(false, "hof", qPrintable(error));
            return;
        }

        if (evaluationList.isEmpty()) {
            evaluationList.append(term);
            continue;
        }

        if (term->type() == Combinator::a_) {
            if (evaluationList.back()->type() == Combinator::a_) {
                A* a = static_cast<A*>(evaluationList.back().data());
                Q_ASSERT(!a->isWellFormed());
                a->addCombinator(term);
            } else {
                evaluationList.append(term);
            }

            continue; // can't possibly be well formed at this point
        }

        if (evaluationList.back()->type() == Combinator::a_) {
            A* a = static_cast<A*>(evaluationList.back().data());
            Q_ASSERT(!a->isWellFormed());
            a->addCombinator(term);
            term = CombinatorPtr(); // remove the term since it was added
        }

        if (!evaluationListIsWellFormed(evaluationList))
            continue;

        CombinatorPtr evaluate = evaluationList.takeFirst();
        if (Verbose::instance()->isVerbose()) {
            Verbose::instance()->removePostfix(postfixIndex);
            postfixIndex = Verbose::instance()->addPostfix(string.right(string.length() - x - 1));

            SubEval subEval;
            subEval.addPostfix(!term.isNull() ? term->toString() : QString());

            EvaluationList::const_iterator it = evaluationList.begin();
            for (; it != evaluationList.end(); ++it)
                evaluate = eval(evaluate, *it);

            subEval.clear();
        } else {
            EvaluationList::const_iterator it = evaluationList.begin();
            for (; it != evaluationList.end(); ++it)
                evaluate = eval(evaluate, *it);
        }

        if (!term.isNull())
            evaluate = eval(evaluate, term);

        while (evaluate->type() == Combinator::a_) {
            A* a = static_cast<A*>(evaluate.data());
            if (!a->isWellFormed()) { break; }
            evaluate = a->apply();
        }

        evaluationList = EvaluationList() << evaluate;
    }

    Q_ASSERT(evaluationList.length() >= 1);

    CombinatorPtr evaluate = evaluationList.takeFirst();
    Verbose::instance()->generateReturnString(evaluate);
    Verbose::instance()->generateInputString(evaluationList);
    Verbose::instance()->generateProgramEnd();
}

Hof::Hof(QTextStream* outputStream, QTextStream* verboseStream)
{
    static_cast<P*>(p().data())->setStream(outputStream);
    Verbose::instance()->setStream(verboseStream);
}

Hof::~Hof()
{ }

void Hof::run(const QString& string)
{
    cppInterpreter(string);
}

<commit_msg>Fix verbose postfix of top-level evaluations.<commit_after>#include "hof.h"

#include "cache.h"
#include "combinators.h"
#include "colors.h"
#include "verbose.h"

bool evaluationListIsWellFormed(const EvaluationList& list)
{
    EvaluationList::const_iterator it = list.begin();
    for (; it != list.end(); ++it) {
        if ((*it)->type() == Combinator::a_)
            return static_cast<const A*>((*it).data())->isWellFormed();
    }
    return true;
}

void cppInterpreter(const QString& string)
{
    Verbose::instance()->generateProgramString("program: " + string);
    Verbose::instance()->generateProgramString("begin", true /*replace*/);
    int postfixIndex = Verbose::instance()->addPostfix(string);

    if (string.isEmpty()) {
        Verbose::instance()->generateProgramString("end", true /*replace*/);
        return;
    }

    EvaluationList evaluationList;
    for (int x = 0; x < string.length(); x++) {
        CombinatorPtr term;
        QChar ch = string.at(x);
        switch (ch.unicode()) {
        case 'I': term = i(); break;
        case 'K': term = k(); break;
        case 'S': term = s(); break;
        case 'P': term = p(); break;
        case 'R': term = r(); break;
        case 'A': term = CombinatorPtr(new A); break;
        default:
            QString error = QString("Error: invalid char in hof program! ch=`%1`").arg(ch);
            Q_ASSERT_X(false, "hof", qPrintable(error));
            return;
        }

        if (evaluationList.isEmpty()) {
            evaluationList.append(term);
            continue;
        }

        if (term->type() == Combinator::a_) {
            if (evaluationList.back()->type() == Combinator::a_) {
                A* a = static_cast<A*>(evaluationList.back().data());
                Q_ASSERT(!a->isWellFormed());
                a->addCombinator(term);
            } else {
                evaluationList.append(term);
            }

            continue; // can't possibly be well formed at this point
        }

        if (evaluationList.back()->type() == Combinator::a_) {
            A* a = static_cast<A*>(evaluationList.back().data());
            Q_ASSERT(!a->isWellFormed());
            a->addCombinator(term);
            term = CombinatorPtr(); // remove the term since it was added
        }

        if (!evaluationListIsWellFormed(evaluationList))
            continue;

        CombinatorPtr evaluate = evaluationList.takeFirst();
        if (Verbose::instance()->isVerbose()) {
            Verbose::instance()->removePostfix(postfixIndex);
            postfixIndex = Verbose::instance()->addPostfix(string.right(string.length() - x - 1));

            SubEval subEval;
            subEval.addPostfix(!term.isNull() ? term->toString() : QString());

            EvaluationList::const_iterator it = evaluationList.begin();
            for (; it != evaluationList.end(); ++it)
                evaluate = eval(evaluate, *it);
        } else {
            EvaluationList::const_iterator it = evaluationList.begin();
            for (; it != evaluationList.end(); ++it)
                evaluate = eval(evaluate, *it);
        }

        if (!term.isNull())
            evaluate = eval(evaluate, term);

        while (evaluate->type() == Combinator::a_) {
            A* a = static_cast<A*>(evaluate.data());
            if (!a->isWellFormed()) { break; }
            evaluate = a->apply();
        }

        evaluationList = EvaluationList() << evaluate;
    }

    Q_ASSERT(evaluationList.length() >= 1);

    CombinatorPtr evaluate = evaluationList.takeFirst();
    Verbose::instance()->generateReturnString(evaluate);
    Verbose::instance()->generateInputString(evaluationList);
    Verbose::instance()->generateProgramEnd();
}

Hof::Hof(QTextStream* outputStream, QTextStream* verboseStream)
{
    static_cast<P*>(p().data())->setStream(outputStream);
    Verbose::instance()->setStream(verboseStream);
}

Hof::~Hof()
{ }

void Hof::run(const QString& string)
{
    cppInterpreter(string);
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "tilemap.h"

void* al_img_loader2(const char* path)
{
    ALLEGRO_BITMAP *res = NULL;
    ALLEGRO_PATH   *alpath = NULL;

    if (!(alpath = al_create_path(path))) return NULL;

    al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_WITH_ALPHA);
    res = al_load_bitmap(al_path_cstr(alpath, ALLEGRO_NATIVE_PATH_SEP));

    al_destroy_path(alpath);

    return (void*) res;
}

TileMap::TileMap(std::string path)
{
    tmx_img_load_func = al_img_loader2;
    tmx_img_free_func = (void(*)(void*))al_destroy_bitmap;

    map = tmx_load(path.c_str());
    if (map == nullptr)
    {
        std::cerr << tmx_strerr() << std::endl;
        return;
    }

    int bmpWidth = map->tile_width * map->width;
    int bmpHeight = map->tile_height * map->height;
    fullMap = al_create_bitmap(bmpWidth, bmpHeight);
    if (fullMap == nullptr)
    {
        std::cerr << "Could not create a new bitmap resource! " << this << std::endl;
        tmx_map_free(map);
        return;
    }
    renderSurface = al_clone_bitmap(fullMap);

    renderFullMap();

    int arrLength = map->height * map->width;
    walkTable = new int[arrLength];
    for (int i = 0; i < arrLength; i++)
    {
        walkTable[i] = 1;
    }
    readWalkProperty(arrLength);
}

TileMap::~TileMap()
{
    tmx_map_free(map);
    al_destroy_bitmap(renderSurface);
    al_destroy_bitmap(fullMap);
    delete [] walkTable;
}

ALLEGRO_BITMAP* TileMap::GetFullMap()
{
    return fullMap;
}

/* TO DO:
   - Refactor code copied from DrawFUllMap on both functions
   - Find a way to avoid so much repeated functions on both cases (layer == null and layer = something)
*/
ALLEGRO_BITMAP* TileMap::GetLayerMap(std::string LayerName)
{
    tmx_layer *layer = getLayerByName(LayerName);

    if (layer == nullptr)
    {
        al_set_target_bitmap(renderSurface);
        al_clear_to_color(al_map_rgba(0, 0, 0, 0));
        al_set_target_backbuffer(al_get_current_display());
        return renderSurface; // Error message is printed by getLayerByName, so not needed here.
    }

    al_set_target_bitmap(renderSurface);
    al_clear_to_color(al_map_rgba(0, 0, 0, 0));

    if (layer->visible)
    {
        switch (layer->type)
        {
            case L_OBJGR:
                draw_objects(layer->content.head, int_to_al_color(layer->color));
                break;
            case L_IMAGE:
                if (layer->opacity < 1.)
                {
                    float op = layer->opacity;
                    al_draw_tinted_bitmap((ALLEGRO_BITMAP*) layer->content.image->resource_image, al_map_rgba_f(op, op, op, op), 0, 0, 0); /* TODO: does not render at correct position */
                } else
                {
                    al_draw_bitmap((ALLEGRO_BITMAP*) layer->content.image->resource_image, 0, 0, 0);
                }
                break;
            case L_LAYER:
                draw_layer(map, layer);
                break;
            default:
                std::cerr << "Warning: I just dropped an unknown layer: " << layer->name << std::endl;
                break;
        }
    }

    al_set_target_backbuffer(al_get_current_display());
    return renderSurface;
}

bool TileMap::CanWalktoTileAt(int x, int y)
{
    unsigned int range = x * y;
    if (range > ((map->height * map->width) - 1))
    {
        std::cerr << "Warning: Tile outside range: (" << x << "," << y << ")" <<std::endl;
        return false;
    }

    int value = walkTable[(y * map->height) + x];
    return value > 0 ? true : false;
}

ALLEGRO_COLOR TileMap::int_to_al_color(int color)
{
    unsigned char r, g, b;

    r = (color >> 16) & 0xFF;
    g = (color >> 8) & 0xFF;
    b = (color) & 0xFF;

    return al_map_rgb(r, g, b);
}

void TileMap::draw_polyline(double **points, double x, double y, int pointsC, ALLEGRO_COLOR color)
{
    int i;
    for (i = 1; i<pointsC; i++)
    {
        al_draw_line(x + points[i - 1][0], y + points[i - 1][1], x + points[i][0], y + points[i][1], color, LINE_THICKNESS);
    }
}

void TileMap::draw_polygone(double **points, double x, double y, int pointsC, ALLEGRO_COLOR color)
{
    draw_polyline(points, x, y, pointsC, color);
    if (pointsC > 2)
    {
        al_draw_line(x + points[0][0], y + points[0][1], x + points[pointsC - 1][0], y + points[pointsC - 1][1], color, LINE_THICKNESS);
    }
}

void TileMap::draw_objects(tmx_object *head, ALLEGRO_COLOR color)
{
    while (head)
    {
        if (head->visible)
        {
            switch (head->shape)
            {
                case S_SQUARE:
                    al_draw_rectangle(head->x, head->y, head->x + head->width, head->y + head->height, color, LINE_THICKNESS);
                    break;
                case S_POLYGON:
                    draw_polygone(head->points, head->x, head->y, head->points_len, color);
                    break;
                case S_POLYLINE:
                    draw_polyline(head->points, head->x, head->y, head->points_len, color);
                    break;
                case S_ELLIPSE:
                    al_draw_ellipse(head->x + head->width / 2.0, head->y + head->height / 2.0, head->width / 2.0, head->height / 2.0, color, LINE_THICKNESS);
                    break;
                default:
                    std::cerr << "Warning: An unknown object type was found: " << head->shape << std::endl;
                    break;
            }
        }

        head = head->next;
    }
}

int TileMap::gid_extract_flags(unsigned int gid)
{
    int res = 0;

    if (gid & TMX_FLIPPED_HORIZONTALLY) res |= ALLEGRO_FLIP_HORIZONTAL;
    if (gid & TMX_FLIPPED_VERTICALLY)   res |= ALLEGRO_FLIP_VERTICAL;
    /* FIXME allegro has no diagonal flip */
    return res;
}

int TileMap::gid_clear_flags(unsigned int gid)
{
    return gid & TMX_FLIP_BITS_REMOVAL;
}

void TileMap::draw_layer(tmx_map *map, tmx_layer *layer)
{
    unsigned long x, y; // The map coordinates
    unsigned int sx, sy, sw, sh, flags; // Individual tile coordinates
    float op; // Tile opacity value

    tmx_tileset *ts;
    ALLEGRO_BITMAP *tileset; /* Owned by the tmx library */

    op = layer->opacity;

    al_hold_bitmap_drawing(true);
    for (y = 0; y < map->height; y++)
    {
        for (x = 0; x < map->width; x++)
        {
            ts = tmx_get_tileset(map, layer->content.gids[(y*map->width) + x], &sx, &sy);
            if (ts)
            {
                sw = ts->tile_width;
                sh = ts->tile_height;

                tileset = (ALLEGRO_BITMAP*) ts->image->resource_image;
                flags = gid_extract_flags(layer->content.gids[(y*map->width) + x]);

                al_draw_tinted_bitmap_region(tileset, al_map_rgba_f(op, op, op, op),
                    sx, sy, sw, sh, x*ts->tile_width, y*ts->tile_height, flags);
            }
        }
    }
    al_hold_bitmap_drawing(false);
}

void TileMap::renderFullMap()
{
    tmx_layer *layers = map->ly_head;

    if (map->orient != O_ORT)
    {
        std::cerr << "only orthogonal orient currently supported in this example!" << std::endl;
        return;
    }

    al_set_target_bitmap(fullMap);
    al_clear_to_color(int_to_al_color(map->backgroundcolor));

    while (layers)
    {
        if (layers->visible)
        {
            switch (layers->type)
            {
                case L_OBJGR:
                    draw_objects(layers->content.head, int_to_al_color(layers->color));
                    break;
                case L_IMAGE:
                    if (layers->opacity < 1.)
                    {
                        float op = layers->opacity;
                        al_draw_tinted_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, al_map_rgba_f(op, op, op, op), 0, 0, 0); /* TODO: does not render at correct position */
                    } else
                    {
                        al_draw_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, 0, 0, 0);
                    }
                    break;
                case L_LAYER:
                    draw_layer(map, layers);
                    break;
                default:
                    std::cerr << "Warning: I just dropped an unknown layer: " << layers->name << std::endl;
                    break;
            }
        }
        layers = layers->next;
    }

    al_set_target_backbuffer(al_get_current_display());
}

tmx_layer *TileMap::getLayerByName(std::string name)
{
    tmx_layer *currLayer = map->ly_head;
    std::string layerName = currLayer->name;

    while (currLayer)
    {
        if (layerName == name)
        {
            return currLayer;
        } else
        {
            currLayer = currLayer->next;
            layerName = currLayer->name;
        }
    }

    std::cerr << "Error: Layer " << name << " not found." << std::endl;
    return nullptr;
}

void TileMap::readWalkProperty(int arrLength)
{
    tmx_layer *layer = map->ly_head;

    while (layer)
    {
        if (layer->type == L_LAYER)
        {
            for (int i = 0; i < arrLength; i++)
            {
                tmx_tile *tile = tmx_get_tile(map, layer->content.gids[i]);

                if (tile != nullptr)
                {
                    tmx_property *props = tile->properties;
                    while (props)
                    {
                        std::string name = props->name;
                        if (name == "canWalk")
                        {
                            walkTable[i] = atoi(props->value);
                        }
                        props = props->next;
                    }
                }
            }
        }

        layer = layer->next;
    }
}
<commit_msg>Add task list<commit_after>#include "stdafx.h"
#include "tilemap.h"

/*
TODO:

- Make the drawing calls here avoid using a buffer, consider drawing to the screen directly.
*/

void* al_img_loader2(const char* path)
{
    ALLEGRO_BITMAP *res = NULL;
    ALLEGRO_PATH   *alpath = NULL;

    if (!(alpath = al_create_path(path))) return NULL;

    al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_WITH_ALPHA);
    res = al_load_bitmap(al_path_cstr(alpath, ALLEGRO_NATIVE_PATH_SEP));

    al_destroy_path(alpath);

    return (void*) res;
}

TileMap::TileMap(std::string path)
{
    tmx_img_load_func = al_img_loader2;
    tmx_img_free_func = (void(*)(void*))al_destroy_bitmap;

    map = tmx_load(path.c_str());
    if (map == nullptr)
    {
        std::cerr << tmx_strerr() << std::endl;
        return;
    }

    int bmpWidth = map->tile_width * map->width;
    int bmpHeight = map->tile_height * map->height;
    fullMap = al_create_bitmap(bmpWidth, bmpHeight);
    if (fullMap == nullptr)
    {
        std::cerr << "Could not create a new bitmap resource! " << this << std::endl;
        tmx_map_free(map);
        return;
    }
    renderSurface = al_clone_bitmap(fullMap);

    renderFullMap();

    int arrLength = map->height * map->width;
    walkTable = new int[arrLength];
    for (int i = 0; i < arrLength; i++)
    {
        walkTable[i] = 1; // Default to all spaces walkable in the tilemap
    }
    readWalkProperty(arrLength);
}

TileMap::~TileMap()
{
    tmx_map_free(map);
    al_destroy_bitmap(renderSurface);
    al_destroy_bitmap(fullMap);
    delete [] walkTable;
}

ALLEGRO_BITMAP* TileMap::GetFullMap()
{
    return fullMap;
}

/* TO DO for GetLayerMap:
   - Refactor code copied from DrawFUllMap on both functions
   - Find a way to avoid so much repeated functions on both cases (layer == null and layer = something)
*/
ALLEGRO_BITMAP* TileMap::GetLayerMap(std::string LayerName)
{
    tmx_layer *layer = getLayerByName(LayerName);

    if (layer == nullptr)
    {
        al_set_target_bitmap(renderSurface);
        al_clear_to_color(al_map_rgba(0, 0, 0, 0));
        al_set_target_backbuffer(al_get_current_display());
        return renderSurface; // Error message is printed by getLayerByName, so not needed here.
    }

    al_set_target_bitmap(renderSurface);
    al_clear_to_color(al_map_rgba(0, 0, 0, 0));

    if (layer->visible)
    {
        switch (layer->type)
        {
            case L_OBJGR:
                draw_objects(layer->content.head, int_to_al_color(layer->color));
                break;
            case L_IMAGE:
                if (layer->opacity < 1.)
                {
                    float op = layer->opacity;
                    al_draw_tinted_bitmap((ALLEGRO_BITMAP*) layer->content.image->resource_image, al_map_rgba_f(op, op, op, op), 0, 0, 0); /* TODO: does not render at correct position */
                } else
                {
                    al_draw_bitmap((ALLEGRO_BITMAP*) layer->content.image->resource_image, 0, 0, 0);
                }
                break;
            case L_LAYER:
                draw_layer(map, layer);
                break;
            default:
                std::cerr << "Warning: I just dropped an unknown layer: " << layer->name << std::endl;
                break;
        }
    }

    al_set_target_backbuffer(al_get_current_display());
    return renderSurface;
}

bool TileMap::CanWalktoTileAt(int x, int y)
{
    unsigned int range = x * y;
    if (range > ((map->height * map->width) - 1))
    {
        std::cerr << "Warning: Tile outside range: (" << x << "," << y << ")" <<std::endl;
        return false;
    }

    int value = walkTable[(y * map->height) + x];
    return value > 0 ? true : false;
}

ALLEGRO_COLOR TileMap::int_to_al_color(int color)
{
    unsigned char r, g, b;

    r = (color >> 16) & 0xFF;
    g = (color >> 8) & 0xFF;
    b = (color) & 0xFF;

    return al_map_rgb(r, g, b);
}

void TileMap::draw_polyline(double **points, double x, double y, int pointsC, ALLEGRO_COLOR color)
{
    int i;
    for (i = 1; i<pointsC; i++)
    {
        al_draw_line(x + points[i - 1][0], y + points[i - 1][1], x + points[i][0], y + points[i][1], color, LINE_THICKNESS);
    }
}

void TileMap::draw_polygone(double **points, double x, double y, int pointsC, ALLEGRO_COLOR color)
{
    draw_polyline(points, x, y, pointsC, color);
    if (pointsC > 2)
    {
        al_draw_line(x + points[0][0], y + points[0][1], x + points[pointsC - 1][0], y + points[pointsC - 1][1], color, LINE_THICKNESS);
    }
}

void TileMap::draw_objects(tmx_object *head, ALLEGRO_COLOR color)
{
    while (head)
    {
        if (head->visible)
        {
            switch (head->shape)
            {
                case S_SQUARE:
                    al_draw_rectangle(head->x, head->y, head->x + head->width, head->y + head->height, color, LINE_THICKNESS);
                    break;
                case S_POLYGON:
                    draw_polygone(head->points, head->x, head->y, head->points_len, color);
                    break;
                case S_POLYLINE:
                    draw_polyline(head->points, head->x, head->y, head->points_len, color);
                    break;
                case S_ELLIPSE:
                    al_draw_ellipse(head->x + head->width / 2.0, head->y + head->height / 2.0, head->width / 2.0, head->height / 2.0, color, LINE_THICKNESS);
                    break;
                default:
                    std::cerr << "Warning: An unknown object type was found: " << head->shape << std::endl;
                    break;
            }
        }

        head = head->next;
    }
}

int TileMap::gid_extract_flags(unsigned int gid)
{
    int res = 0;

    if (gid & TMX_FLIPPED_HORIZONTALLY) res |= ALLEGRO_FLIP_HORIZONTAL;
    if (gid & TMX_FLIPPED_VERTICALLY)   res |= ALLEGRO_FLIP_VERTICAL;
    /* FIXME allegro has no diagonal flip */
    return res;
}

int TileMap::gid_clear_flags(unsigned int gid)
{
    return gid & TMX_FLIP_BITS_REMOVAL;
}

void TileMap::draw_layer(tmx_map *map, tmx_layer *layer)
{
    unsigned long x, y; // The map coordinates
    unsigned int sx, sy, sw, sh, flags; // Individual tile coordinates
    float op; // Tile opacity value

    tmx_tileset *ts;
    ALLEGRO_BITMAP *tileset; /* Owned by the tmx library */

    op = layer->opacity;

    al_hold_bitmap_drawing(true);
    for (y = 0; y < map->height; y++)
    {
        for (x = 0; x < map->width; x++)
        {
            ts = tmx_get_tileset(map, layer->content.gids[(y*map->width) + x], &sx, &sy);
            if (ts)
            {
                sw = ts->tile_width;
                sh = ts->tile_height;

                tileset = (ALLEGRO_BITMAP*) ts->image->resource_image;
                flags = gid_extract_flags(layer->content.gids[(y*map->width) + x]);

                al_draw_tinted_bitmap_region(tileset, al_map_rgba_f(op, op, op, op),
                    sx, sy, sw, sh, x*ts->tile_width, y*ts->tile_height, flags);
            }
        }
    }
    al_hold_bitmap_drawing(false);
}

void TileMap::renderFullMap()
{
    tmx_layer *layers = map->ly_head;

    if (map->orient != O_ORT)
    {
        std::cerr << "only orthogonal orient currently supported in this example!" << std::endl;
        return;
    }

    al_set_target_bitmap(fullMap);
    al_clear_to_color(int_to_al_color(map->backgroundcolor));

    while (layers)
    {
        if (layers->visible)
        {
            switch (layers->type)
            {
                case L_OBJGR:
                    draw_objects(layers->content.head, int_to_al_color(layers->color));
                    break;
                case L_IMAGE:
                    if (layers->opacity < 1.)
                    {
                        float op = layers->opacity;
                        al_draw_tinted_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, al_map_rgba_f(op, op, op, op), 0, 0, 0); /* TODO: does not render at correct position */
                    } else
                    {
                        al_draw_bitmap((ALLEGRO_BITMAP*) layers->content.image->resource_image, 0, 0, 0);
                    }
                    break;
                case L_LAYER:
                    draw_layer(map, layers);
                    break;
                default:
                    std::cerr << "Warning: I just dropped an unknown layer: " << layers->name << std::endl;
                    break;
            }
        }
        layers = layers->next;
    }

    al_set_target_backbuffer(al_get_current_display());
}

tmx_layer *TileMap::getLayerByName(std::string name)
{
    tmx_layer *currLayer = map->ly_head;
    std::string layerName = currLayer->name;

    while (currLayer)
    {
        if (layerName == name)
        {
            return currLayer;
        } else
        {
            currLayer = currLayer->next;
            layerName = currLayer->name;
        }
    }

    std::cerr << "Error: Layer " << name << " not found." << std::endl;
    return nullptr;
}

void TileMap::readWalkProperty(int arrLength)
{
    tmx_layer *layer = map->ly_head;

    while (layer)
    {
        if (layer->type == L_LAYER)
        {
            for (int i = 0; i < arrLength; i++)
            {
                tmx_tile *tile = tmx_get_tile(map, layer->content.gids[i]);

                if (tile != nullptr)
                {
                    tmx_property *props = tile->properties;
                    while (props)
                    {
                        std::string name = props->name;
                        if (name == "canWalk")
                        {
                            walkTable[i] = atoi(props->value);
                        }
                        props = props->next;
                    }
                }
            }
        }

        layer = layer->next;
    }
}
<|endoftext|>


<commit_before>//
//  DialogueBoxSystem.cpp
//  Chilli Source
//  Created by Ian Copland on 04/03/2014.
//
//  The MIT License (MIT)
//
//  Copyright (c) 2014 Tag Games Limited
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#ifdef CS_TARGETPLATFORM_ANDROID

#include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxSystem.h>

#include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxJavaInterface.h>
#include <CSBackend/Platform/Android/Main/JNI/Core/Java/JavaInterfaceManager.h>
#include <ChilliSource/Core/Threading.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/PlatformSystem.h>

namespace CSBackend
{
	namespace Android
	{
        CS_DEFINE_NAMEDTYPE(DialogueBoxSystem);
        //----------------------------------------------------
        //----------------------------------------------------
        DialogueBoxSystem::DialogueBoxSystem()
        {
        	m_dialogueBoxJI = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<DialogueBoxJavaInterface>();
        	if (m_dialogueBoxJI == nullptr)
        	{
        		m_dialogueBoxJI = std::make_shared<DialogueBoxJavaInterface>();
        		JavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_dialogueBoxJI);
        	}
        }
        //----------------------------------------------------
        //----------------------------------------------------
        bool DialogueBoxSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const
        {
            return (DialogueBoxSystem::InterfaceID == in_interfaceId || ChilliSource::DialogueBoxSystem::InterfaceID == in_interfaceId);
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        void DialogueBoxSystem::ShowSystemDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                m_dialogueBoxJI->ShowSystemDialogue(in_id, in_title, in_message, in_confirm);
                m_activeSysConfirmDelegate = in_delegate;
            });
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        void DialogueBoxSystem::ShowSystemConfirmDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm, const std::string& in_cancel)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                m_dialogueBoxJI->ShowSystemConfirmDialogue(in_id, in_title, in_message, in_confirm, in_cancel);
                m_activeSysConfirmDelegate = in_delegate;
            });
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        void DialogueBoxSystem::MakeToast(const std::string& in_text)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                m_dialogueBoxJI->MakeToast(in_text);
            });
        }
        //------------------------------------------------------
        //------------------------------------------------------
        void DialogueBoxSystem::OnSystemConfirmDialogueResult(u32 in_id, ChilliSource::DialogueBoxSystem::DialogueResult in_result)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                if (m_activeSysConfirmDelegate)
                {
                    m_activeSysConfirmDelegate(in_id, in_result);
                    m_activeSysConfirmDelegate = nullptr;
                }
            });
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        DialogueBoxSystem::~DialogueBoxSystem()
        {
        }
	}
}

#endif
<commit_msg>Added some mutexes to the Android DialogueBoxSystem implementation.<commit_after>//
//  DialogueBoxSystem.cpp
//  Chilli Source
//  Created by Ian Copland on 04/03/2014.
//
//  The MIT License (MIT)
//
//  Copyright (c) 2014 Tag Games Limited
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#ifdef CS_TARGETPLATFORM_ANDROID

#include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxSystem.h>

#include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxJavaInterface.h>
#include <CSBackend/Platform/Android/Main/JNI/Core/Java/JavaInterfaceManager.h>
#include <ChilliSource/Core/Threading.h>
#include <ChilliSource/Core/Base/Application.h>
#include <ChilliSource/Core/Base/PlatformSystem.h>

namespace CSBackend
{
	namespace Android
	{
        CS_DEFINE_NAMEDTYPE(DialogueBoxSystem);
        //----------------------------------------------------
        //----------------------------------------------------
        DialogueBoxSystem::DialogueBoxSystem()
        {
        	m_dialogueBoxJI = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<DialogueBoxJavaInterface>();
        	if (m_dialogueBoxJI == nullptr)
        	{
        		m_dialogueBoxJI = std::make_shared<DialogueBoxJavaInterface>();
        		JavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_dialogueBoxJI);
        	}
        }
        //----------------------------------------------------
        //----------------------------------------------------
        bool DialogueBoxSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const
        {
            return (DialogueBoxSystem::InterfaceID == in_interfaceId || ChilliSource::DialogueBoxSystem::InterfaceID == in_interfaceId);
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        void DialogueBoxSystem::ShowSystemDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                m_dialogueBoxJI->ShowSystemDialogue(in_id, in_title, in_message, in_confirm);
                std::mutex delegateMutex;
                std::unique_lock<std::mutex> lock(delegateMutex);
                m_activeSysConfirmDelegate = in_delegate;
            });
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        void DialogueBoxSystem::ShowSystemConfirmDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm, const std::string& in_cancel)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                m_dialogueBoxJI->ShowSystemConfirmDialogue(in_id, in_title, in_message, in_confirm, in_cancel);
                std::mutex delegateMutex;
                std::unique_lock<std::mutex> lock(delegateMutex);
                m_activeSysConfirmDelegate = in_delegate;
            });
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        void DialogueBoxSystem::MakeToast(const std::string& in_text)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                m_dialogueBoxJI->MakeToast(in_text);
            });
        }
        //------------------------------------------------------
        //------------------------------------------------------
        void DialogueBoxSystem::OnSystemConfirmDialogueResult(u32 in_id, ChilliSource::DialogueBoxSystem::DialogueResult in_result)
        {
            CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext)
            {
                std::mutex delegateMutex;
                std::unique_lock<std::mutex> lock(delegateMutex);
                if (m_activeSysConfirmDelegate)
                {
                    m_activeSysConfirmDelegate(in_id, in_result);
                    m_activeSysConfirmDelegate = nullptr;
                }
            });
        }
        //-----------------------------------------------------
        //-----------------------------------------------------
        DialogueBoxSystem::~DialogueBoxSystem()
        {
        }
	}
}

#endif
<|endoftext|>


<commit_before>/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include "TcpClient.h"

namespace ZL {
namespace Network {

TcpClient::TcpClient() : SocketHelper(nullptr) {
}

TcpClient::~TcpClient() {
}

void TcpClient::shutdown() {
    weak_ptr<TcpClient> weakSelf = shared_from_this();
    ASYNC_TRACE([weakSelf,this](){
        auto strongSelf = weakSelf.lock();
        if(!strongSelf){
            return;
        }
        SocketHelper::setSock(nullptr);
        _managerTimer.reset();
    });
}

bool TcpClient::alive() {
    bool ret = _sock.operator bool();
    return ret;
}

void TcpClient::startConnect(const string &strUrl, uint16_t iPort,float fTimeOutSec) {
    weak_ptr<TcpClient> weakSelf = shared_from_this();
    ASYNC_TRACE([strUrl,iPort,fTimeOutSec,weakSelf,this](){
        auto strongSelf = weakSelf.lock();
        if(!strongSelf){
            return;
        }
        shutdown();
        SocketHelper::setSock(std::make_shared<Socket>());

        weak_ptr<TcpClient> weakSelf = shared_from_this();
        _sock->connect(strUrl, iPort, [weakSelf](const SockException &err){
            auto strongSelf = weakSelf.lock();
            if(strongSelf){
                if(err){
                    strongSelf->SocketHelper::setSock(nullptr);
                }
                strongSelf->onSockConnect(err);
            }
        }, fTimeOutSec);
    });
}
void TcpClient::onSockConnect(const SockException &ex) {
	if(!ex && _sock) {
        weak_ptr<TcpClient> weakSelf = shared_from_this();
        _sock->setOnErr([weakSelf](const SockException &ex) {
			auto strongSelf = weakSelf.lock();
			if (!strongSelf) {
				return;
			}
            strongSelf->onSockErr(ex);
		});
        _sock->setOnFlush([weakSelf]() {
			auto strongSelf = weakSelf.lock();
			if (!strongSelf) {
				return false;
			}
            strongSelf->onSockSend();
			return true;
		});
        _sock->setOnRead([weakSelf](const Buffer::Ptr &pBuf, struct sockaddr *addr) {
			auto strongSelf = weakSelf.lock();
			if (!strongSelf) {
				return;
			}
            strongSelf->onSockRecv(pBuf);
		});
        _managerTimer.reset(new Timer(2,[weakSelf](){
            auto strongSelf = weakSelf.lock();
            if (!strongSelf) {
                return false;
            }
            strongSelf->onManager();
            return true;
        }));
	}
    onConnect(ex);
}

void TcpClient::onSockRecv(const Buffer::Ptr& pBuf) {
	onRecv(pBuf);
}

void TcpClient::onSockSend() {
	onSend();
}

void TcpClient::onSockErr(const SockException& ex) {
	shutdown();
	onErr(ex);
}

} /* namespace Network */
} /* namespace ZL */
<commit_msg>buf fixed when reconnect<commit_after>/*
 * MIT License
 *
 * Copyright (c) 2016 xiongziliang <771730766@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include "TcpClient.h"

namespace ZL {
namespace Network {

TcpClient::TcpClient() : SocketHelper(nullptr) {
}

TcpClient::~TcpClient() {
}

void TcpClient::shutdown() {
    weak_ptr<TcpClient> weakSelf = shared_from_this();
    ASYNC_TRACE([weakSelf,this](){
        auto strongSelf = weakSelf.lock();
        if(!strongSelf){
            return;
        }
        if(_sock){
            _sock->setOnErr(nullptr);
            _sock->setOnRead(nullptr);
            _sock->setOnFlush(nullptr);
            setSock(nullptr);
        }
        _managerTimer.reset();
    });
}

bool TcpClient::alive() {
    bool ret = _sock.operator bool();
    return ret;
}

void TcpClient::startConnect(const string &strUrl, uint16_t iPort,float fTimeOutSec) {
    weak_ptr<TcpClient> weakSelf = shared_from_this();
    ASYNC_TRACE([strUrl,iPort,fTimeOutSec,weakSelf,this](){
        auto strongSelf = weakSelf.lock();
        if(!strongSelf){
            return;
        }
        shutdown();
        SocketHelper::setSock(std::make_shared<Socket>());

        weak_ptr<TcpClient> weakSelf = shared_from_this();
        _sock->connect(strUrl, iPort, [weakSelf](const SockException &err){
            auto strongSelf = weakSelf.lock();
            if(strongSelf){
                if(err){
                    strongSelf->SocketHelper::setSock(nullptr);
                }
                strongSelf->onSockConnect(err);
            }
        }, fTimeOutSec);
    });
}
void TcpClient::onSockConnect(const SockException &ex) {
	if(!ex && _sock) {
        weak_ptr<TcpClient> weakSelf = shared_from_this();
        _sock->setOnErr([weakSelf](const SockException &ex) {
			auto strongSelf = weakSelf.lock();
			if (!strongSelf) {
				return;
			}
            strongSelf->onSockErr(ex);
		});
        _sock->setOnFlush([weakSelf]() {
			auto strongSelf = weakSelf.lock();
			if (!strongSelf) {
				return false;
			}
            strongSelf->onSockSend();
			return true;
		});
        _sock->setOnRead([weakSelf](const Buffer::Ptr &pBuf, struct sockaddr *addr) {
			auto strongSelf = weakSelf.lock();
			if (!strongSelf) {
				return;
			}
            strongSelf->onSockRecv(pBuf);
		});
        _managerTimer.reset(new Timer(2,[weakSelf](){
            auto strongSelf = weakSelf.lock();
            if (!strongSelf) {
                return false;
            }
            strongSelf->onManager();
            return true;
        }));
	}
    onConnect(ex);
}

void TcpClient::onSockRecv(const Buffer::Ptr& pBuf) {
	onRecv(pBuf);
}

void TcpClient::onSockSend() {
	onSend();
}

void TcpClient::onSockErr(const SockException& ex) {
	shutdown();
	onErr(ex);
}

} /* namespace Network */
} /* namespace ZL */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cexports.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:41:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "cppuhelper/implementationentry.hxx"
#include "jvmfwk.hxx"
#include "basicmigration.hxx"
#include "autocorrmigration.hxx"

extern "C"
{

::cppu::ImplementationEntry entries [] =
{
    {
        migration::jvmfwk_create, migration::jvmfwk_getImplementationName,
        migration::jvmfwk_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
        0, 0
    },
    {
        migration::BasicMigration_create, migration::BasicMigration_getImplementationName,
        migration::BasicMigration_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
        0, 0
    },
    {
        migration::AutocorrectionMigration_create, migration::AutocorrectionMigration_getImplementationName,
        migration::AutocorrectionMigration_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
        0, 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_writeInfoHelper(
        pServiceManager, pRegistryKey, entries );
}

void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_getFactoryHelper(
        pImplName, pServiceManager, pRegistryKey, entries );
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.222); FILE MERGED 2006/09/01 17:25:16 kaib 1.5.222.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cexports.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 09:46:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_desktop.hxx"

#include "cppuhelper/implementationentry.hxx"
#include "jvmfwk.hxx"
#include "basicmigration.hxx"
#include "autocorrmigration.hxx"

extern "C"
{

::cppu::ImplementationEntry entries [] =
{
    {
        migration::jvmfwk_create, migration::jvmfwk_getImplementationName,
        migration::jvmfwk_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
        0, 0
    },
    {
        migration::BasicMigration_create, migration::BasicMigration_getImplementationName,
        migration::BasicMigration_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
        0, 0
    },
    {
        migration::AutocorrectionMigration_create, migration::AutocorrectionMigration_getImplementationName,
        migration::AutocorrectionMigration_getSupportedServiceNames, ::cppu::createSingleComponentFactory,
        0, 0
    },
    { 0, 0, 0, 0, 0, 0 }
};

void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

sal_Bool SAL_CALL component_writeInfo(
    void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_writeInfoHelper(
        pServiceManager, pRegistryKey, entries );
}

void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    return ::cppu::component_getFactoryHelper(
        pImplName, pServiceManager, pRegistryKey, entries );
}

}
<|endoftext|>