<commit_before>/*Copyright 2014 George Karagoulis

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

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

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

#include "entryview.h"
#include "ui_entryview.h"
#include <grypto_entrymodel.h>
#include <grypto_databasemodel.h>
#include <QKeyEvent>
#include <QFileDialog>
#include <QSortFilterProxyModel>

namespace Grypt{

EntryView::EntryView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EntryView),
    m_dbModel(NULL)
{
    ui->setupUi(this);

    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableView->installEventFilter(this);

    ui->tableView->setModel(new QSortFilterProxyModel(this));
    _get_proxy_model()->setSourceModel(new EntryModel(this));
}

EntryView::~EntryView()
{
    delete ui;
}

void EntryView::SetDatabaseModel(DatabaseModel *dbm)
{
    m_dbModel = dbm;
}

void EntryView::SetEntry(const Entry &e)
{
    ui->lbl_name->setText(e.GetName());
    ui->lbl_description->setText(e.GetDescription());

    ui->btn_exportFile->setVisible(!e.GetFileId().IsNull());
    ui->lbl_file->setVisible(!e.GetFileId().IsNull());
    ui->lbl_fileStatus->setVisible(!e.GetFileId().IsNull());
    ui->lbl_fileName->setVisible(!e.GetFileId().IsNull());

    if(e.GetFileId().IsNull() || NULL == m_dbModel){
        ui->lbl_fileStatus->clear();
        ui->lbl_fileName->clear();
    }
    else
    {
        ui->lbl_fileName->setText(e.GetFileName());
        if(m_dbModel->FileExists(e.GetFileId())){
            ui->lbl_fileStatus->setText(tr("(Uploaded)"));
            ui->btn_exportFile->setEnabled(true);
        }
        else{
            ui->lbl_fileStatus->setText(tr("(Missing)"));
            ui->btn_exportFile->setEnabled(false);
        }
    }

    _get_entry_model()->SetEntry(e);
    m_entry = e;
}

EntryModel *EntryView::_get_entry_model() const
{
    return static_cast<EntryModel *>(_get_proxy_model()->sourceModel());
}

QSortFilterProxyModel *EntryView::_get_proxy_model() const
{
    return static_cast<QSortFilterProxyModel *>(ui->tableView->model());
}

bool EntryView::eventFilter(QObject *, QEvent *ev)
{
    bool ret = false;
    if(ev->type() == QEvent::KeyPress)
    {
        QKeyEvent *kev = static_cast<QKeyEvent *>(ev);

        if(kev->key() == ::Qt::Key_Enter || kev->key() == ::Qt::Key_Return){
            _index_doubleClicked(ui->tableView->currentIndex());
            ret = true;
        }
        else if(kev->key() == ::Qt::Key_Escape){
            _get_proxy_model()->sort(-1);
        }
    }
    return ret;
}

void EntryView::_index_doubleClicked(const QModelIndex &ind)
{
    if(ind.isValid()){
        int row = _get_proxy_model()->mapToSource(ind).row();
        GASSERT(0 <= row);
        emit RowActivated(row);
    }
}

void EntryView::_export_file()
{
    GASSERT(NULL != m_dbModel);

    QString file_path = QFileDialog::getSaveFileName(this, tr("Export File"), m_entry.GetFileName());
    if(!file_path.isEmpty())
        m_dbModel->ExportFile(m_entry.GetFileId(), file_path.toUtf8());
}

}
<commit_msg>Fixed a bug with the event of pressing escape<commit_after>/*Copyright 2014 George Karagoulis

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

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

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

#include "entryview.h"
#include "ui_entryview.h"
#include <grypto_entrymodel.h>
#include <grypto_databasemodel.h>
#include <QKeyEvent>
#include <QFileDialog>
#include <QSortFilterProxyModel>

namespace Grypt{

EntryView::EntryView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::EntryView),
    m_dbModel(NULL)
{
    ui->setupUi(this);

    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->tableView->installEventFilter(this);

    ui->tableView->setModel(new QSortFilterProxyModel(this));
    _get_proxy_model()->setSourceModel(new EntryModel(this));
}

EntryView::~EntryView()
{
    delete ui;
}

void EntryView::SetDatabaseModel(DatabaseModel *dbm)
{
    m_dbModel = dbm;
}

void EntryView::SetEntry(const Entry &e)
{
    ui->lbl_name->setText(e.GetName());
    ui->lbl_description->setText(e.GetDescription());

    ui->btn_exportFile->setVisible(!e.GetFileId().IsNull());
    ui->lbl_file->setVisible(!e.GetFileId().IsNull());
    ui->lbl_fileStatus->setVisible(!e.GetFileId().IsNull());
    ui->lbl_fileName->setVisible(!e.GetFileId().IsNull());

    if(e.GetFileId().IsNull() || NULL == m_dbModel){
        ui->lbl_fileStatus->clear();
        ui->lbl_fileName->clear();
    }
    else
    {
        ui->lbl_fileName->setText(e.GetFileName());
        if(m_dbModel->FileExists(e.GetFileId())){
            ui->lbl_fileStatus->setText(tr("(Uploaded)"));
            ui->btn_exportFile->setEnabled(true);
        }
        else{
            ui->lbl_fileStatus->setText(tr("(Missing)"));
            ui->btn_exportFile->setEnabled(false);
        }
    }

    _get_entry_model()->SetEntry(e);
    m_entry = e;
}

EntryModel *EntryView::_get_entry_model() const
{
    return static_cast<EntryModel *>(_get_proxy_model()->sourceModel());
}

QSortFilterProxyModel *EntryView::_get_proxy_model() const
{
    return static_cast<QSortFilterProxyModel *>(ui->tableView->model());
}

bool EntryView::eventFilter(QObject *, QEvent *ev)
{
    bool ret = false;
    if(ev->type() == QEvent::KeyPress)
    {
        QKeyEvent *kev = static_cast<QKeyEvent *>(ev);

        if(kev->key() == ::Qt::Key_Enter || kev->key() == ::Qt::Key_Return){
            _index_doubleClicked(ui->tableView->currentIndex());
            ret = true;
        }
        else if(kev->key() == ::Qt::Key_Escape){
            // If the model is sorted, restore the original order, or let someone else handle this event
            if(-1 != _get_proxy_model()->sortColumn()){
                _get_proxy_model()->sort(-1);
                ret = true;
            }
        }
    }
    return ret;
}

void EntryView::_index_doubleClicked(const QModelIndex &ind)
{
    if(ind.isValid()){
        int row = _get_proxy_model()->mapToSource(ind).row();
        GASSERT(0 <= row);
        emit RowActivated(row);
    }
}

void EntryView::_export_file()
{
    GASSERT(NULL != m_dbModel);

    QString file_path = QFileDialog::getSaveFileName(this, tr("Export File"), m_entry.GetFileName());
    if(!file_path.isEmpty())
        m_dbModel->ExportFile(m_entry.GetFileId(), file_path.toUtf8());
}

}
<|endoftext|>


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

// mapnik
#include <mapnik/debug.hpp>

// stl
#include <ctime>
#include <stdexcept>
#include <fstream>

#ifndef MAPNIK_LOG_FORMAT
  #define MAPNIK_LOG_FORMAT  Mapnik LOG> %Y-%m-%d %H:%M:%S:
#endif

#ifndef MAPNIK_DEFAULT_LOG_SEVERITY
  #ifdef MAPNIK_DEBUG
    #define MAPNIK_DEFAULT_LOG_SEVERITY 0
  #else
    #define MAPNIK_DEFAULT_LOG_SEVERITY 2
  #endif
#endif

namespace mapnik {

// mutexes

#ifdef MAPNIK_THREADSAFE
std::mutex logger::severity_mutex_;
std::mutex logger::format_mutex_;
#endif

// first time checks

bool logger::severity_env_check_ = true;
bool logger::format_env_check_ = true;

// severity

logger::severity_type logger::severity_level_ =
    #if MAPNIK_DEFAULT_LOG_SEVERITY == 0
        logger::debug
    #elif MAPNIK_DEFAULT_LOG_SEVERITY == 1
        logger::warn
    #elif MAPNIK_DEFAULT_LOG_SEVERITY == 2
        logger::error
    #elif MAPNIK_DEFAULT_LOG_SEVERITY == 3
        logger::none
    #else
        #error "Wrong default log severity level specified!"
    #endif
;

logger::severity_map logger::object_severity_level_ = logger::severity_map();

// format

#define __xstr__(s) __str__(s)
#define __str__(s) #s
std::string logger::format_ = __xstr__(MAPNIK_LOG_FORMAT);
#undef __xstr__
#undef __str__

std::string logger::str()
{
#if 0
    // update the format from getenv if this is the first time
    if (logger::format_env_check_)
    {
        logger::format_env_check_ = false;

        const char* log_format = getenv("MAPNIK_LOG_FORMAT");
        if (log_format != nullptr)
        {
            logger::format_ = log_format;
        }
    }
#endif

    char buf[256];
    const time_t tm = time(0);
    strftime(buf, sizeof(buf), logger::format_.c_str(), localtime(&tm));
    return buf;
}

// output

std::ofstream logger::file_output_;
std::string logger::file_name_;
std::streambuf* logger::saved_buf_ = 0;

void logger::use_file(std::string const& filepath)
{
    // save clog rdbuf
    if (saved_buf_ == 0)
    {
        saved_buf_ = std::clog.rdbuf();
    }

    // use a file to output as clog rdbuf
    if (file_name_ != filepath)
    {
        file_name_ = filepath;

        if (file_output_.is_open())
        {
            file_output_.close();
        }

        file_output_.open(file_name_.c_str(), std::ios::out | std::ios::app);
        if (file_output_)
        {
            std::clog.rdbuf(file_output_.rdbuf());
        }
        else
        {
            std::stringstream s;
            s << "cannot redirect log to file " << file_name_;
            throw std::runtime_error(s.str());
        }
    }
}

void logger::use_console()
{
    // save clog rdbuf
    if (saved_buf_ == 0)
    {
        saved_buf_ = std::clog.rdbuf();
    }

    // close the file to force a flush
    if (file_output_.is_open())
    {
        file_output_.close();
    }

    std::clog.rdbuf(saved_buf_);
}

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

// mapnik
#include <mapnik/debug.hpp>

// stl
#include <ctime>
#include <stdexcept>
#include <fstream>
#include <cstdlib>

#ifndef MAPNIK_LOG_FORMAT
  #define MAPNIK_LOG_FORMAT  Mapnik LOG> %Y-%m-%d %H:%M:%S:
#endif

#ifndef MAPNIK_DEFAULT_LOG_SEVERITY
  #ifdef MAPNIK_DEBUG
    #define MAPNIK_DEFAULT_LOG_SEVERITY 0
  #else
    #define MAPNIK_DEFAULT_LOG_SEVERITY 2
  #endif
#endif

namespace mapnik {

// mutexes

#ifdef MAPNIK_THREADSAFE
std::mutex logger::severity_mutex_;
std::mutex logger::format_mutex_;
#endif

// first time checks

bool logger::severity_env_check_ = true;
bool logger::format_env_check_ = true;

// severity

logger::severity_type logger::severity_level_ =
    #if MAPNIK_DEFAULT_LOG_SEVERITY == 0
        logger::debug
    #elif MAPNIK_DEFAULT_LOG_SEVERITY == 1
        logger::warn
    #elif MAPNIK_DEFAULT_LOG_SEVERITY == 2
        logger::error
    #elif MAPNIK_DEFAULT_LOG_SEVERITY == 3
        logger::none
    #else
        #error "Wrong default log severity level specified!"
    #endif
;

logger::severity_map logger::object_severity_level_ = logger::severity_map();

// format

#define __xstr__(s) __str__(s)
#define __str__(s) #s
std::string logger::format_ = __xstr__(MAPNIK_LOG_FORMAT);
#undef __xstr__
#undef __str__

std::string logger::str()
{
#if MAPNIK_CHECK_ENV
    // update the format from getenv if this is the first time
    if (logger::format_env_check_)
    {
        logger::format_env_check_ = false;

        const char* log_format = std::getenv("MAPNIK_LOG_FORMAT");
        if (log_format != nullptr)
        {
            logger::format_ = log_format;
        }
    }
#endif

    char buf[256];
    const time_t tm = time(0);
    std::strftime(buf, sizeof(buf), logger::format_.c_str(), localtime(&tm));
    return buf;
}

// output

std::ofstream logger::file_output_;
std::string logger::file_name_;
std::streambuf* logger::saved_buf_ = 0;

void logger::use_file(std::string const& filepath)
{
    // save clog rdbuf
    if (saved_buf_ == 0)
    {
        saved_buf_ = std::clog.rdbuf();
    }

    // use a file to output as clog rdbuf
    if (file_name_ != filepath)
    {
        file_name_ = filepath;

        if (file_output_.is_open())
        {
            file_output_.close();
        }

        file_output_.open(file_name_.c_str(), std::ios::out | std::ios::app);
        if (file_output_)
        {
            std::clog.rdbuf(file_output_.rdbuf());
        }
        else
        {
            std::stringstream s;
            s << "cannot redirect log to file " << file_name_;
            throw std::runtime_error(s.str());
        }
    }
}

void logger::use_console()
{
    // save clog rdbuf
    if (saved_buf_ == 0)
    {
        saved_buf_ = std::clog.rdbuf();
    }

    // close the file to force a flush
    if (file_output_.is_open())
    {
        file_output_.close();
    }

    std::clog.rdbuf(saved_buf_);
}

} // namespace mapnik
<|endoftext|>


<commit_before>// Check if trailing return types are supported
#include <algorithm>
#include <vector>

void fun() {
  int val = 0;
  std::vector<int> v{0, 1, 2, 4, 8};
  std::sort(v.begin(), v.end(),
            [&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}
<commit_msg>Make independent of initializer list support.<commit_after>// Check if trailing return types are supported
#include <algorithm>
#include <vector>

void fun() {
  int val = 0;
  std::vector<int> v(5);
  std::sort(v.begin(), v.end(),
            [&](int i, int j)->bool{ val++; return i < j && val++ < i; });
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QObject>
#include <QtWidgets>

/****************SETTING UP STATUS BAR*********************/
QWidget *topFiller = new QWidget;
topFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

#ifdef Q_OS_SYMBIAN
_infoLabel = new QLabel(tr("Choose a menu option"));
#else
_infoLabel = new QLabel(tr("Choose a menu option, or right-click to "
                          "invoke a context menu"));
#endif
_infoLabel->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
_infoLabel->setAlignment(Qt::AlignCenter);

QWidget *bottomFiller = new QWidget;
bottomFiller->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(5);
layout->addWidget(topFiller);
layout->addWidget(_infoLabel);
layout->addWidget(bottomFiller);

/****************SETTING UP MENUS*********************/
createActions();
createMenus();

/************SETTING UP STATUS BAR********************/
#ifndef Q_OS_SYMBIAN
QString message = tr("A context menu is available by right-clicking");
statusBar()->showMessage(message);
#endif

_player->setVolume(50);

setupButtons();
setupProgressBar();
setupVolumeLabelAndSlider();
setupShuffleCheckbox();
setupMetadataLabel();
<commit_msg>Got rid of statusbar.cpp which wasn't even being used.<commit_after><|endoftext|>


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

#include <sys/resource.h>
#include <sys/time.h>

#include "modules/common/monitor_log/monitor_log_buffer.h"

#include "gtest/gtest.h"

#include "cybertron/common/log.h"

namespace apollo {
namespace common {
namespace monitor {

class MonitorBufferTest : public ::testing::Test {
 protected:
  void SetUp() override { cybertron::Init(); }
  void TearDown() override {}
  MonitorLogBuffer buffer_{MonitorMessageItem::CONTROL};
};

TEST_F(MonitorBufferTest, RegisterMacro) {
  {
    buffer_.INFO("Info");
    EXPECT_EQ(MonitorMessageItem::INFO, buffer_.level_);
    ASSERT_EQ(1, buffer_.monitor_msg_items_.size());
    const auto &item = buffer_.monitor_msg_items_.back();
    EXPECT_EQ(MonitorMessageItem::INFO, item.first);
    EXPECT_EQ("Info", item.second);
  }

  {
    buffer_.ERROR("Error");
    EXPECT_EQ(MonitorMessageItem::ERROR, buffer_.level_);
    ASSERT_EQ(2, buffer_.monitor_msg_items_.size());
    const auto &item = buffer_.monitor_msg_items_.back();
    EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
    EXPECT_EQ("Error", item.second);
  }
}

TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
  buffer_.AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_.level_);
  ASSERT_EQ(1, buffer_.monitor_msg_items_.size());
  const auto &item = buffer_.monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("TestError", item.second);
}

}  // namespace monitor
}  // namespace common
}  // namespace apollo
<commit_msg>monitor log: fix test fail<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include <sys/resource.h>
#include <sys/time.h>

#include "modules/common/monitor_log/monitor_log_buffer.h"

#include "gtest/gtest.h"

#include "cybertron/common/log.h"

namespace apollo {
namespace common {
namespace monitor {

class MonitorBufferTest : public ::testing::Test {
 protected:
  void SetUp() override { cybertron::Init(); }
  void TearDown() override {}
  MonitorLogBuffer buffer_{MonitorMessageItem::CONTROL};
};

TEST_F(MonitorBufferTest, RegisterMacro) {
  {
    buffer_.INFO("Info");
    EXPECT_EQ(MonitorMessageItem::INFO, buffer_.level_);
    ASSERT_EQ(0, buffer_.monitor_msg_items_.size());
  }

  {
    buffer_.ERROR("Error");
    EXPECT_EQ(MonitorMessageItem::INFO, buffer_.level_);
    ASSERT_EQ(0, buffer_.monitor_msg_items_.size());
  }
}

TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
  buffer_.AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
  EXPECT_EQ(MonitorMessageItem::ERROR, buffer_.level_);
  ASSERT_EQ(1, buffer_.monitor_msg_items_.size());
  const auto &item = buffer_.monitor_msg_items_.back();
  EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
  EXPECT_EQ("TestError", item.second);
}

}  // namespace monitor
}  // namespace common
}  // namespace apollo
<|endoftext|>


<commit_before>// Copyright 2012 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 "cc/tile_manager.h"

#include <algorithm>

#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/resource_pool.h"
#include "cc/tile.h"
#include "third_party/skia/include/core/SkDevice.h"

namespace {

void RasterizeTile(cc::PicturePile* picture_pile,
                   uint8_t* mapped_buffer,
                   const gfx::Rect& rect) {
  TRACE_EVENT0("cc", "RasterizeTile");
  DCHECK(mapped_buffer);
  SkBitmap bitmap;
  bitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height());
  bitmap.setPixels(mapped_buffer);
  SkDevice device(bitmap);
  SkCanvas canvas(&device);
  picture_pile->Raster(&canvas, rect);
}

const int kMaxRasterThreads = 1;

const char* kRasterThreadNamePrefix = "CompositorRaster";

// Allow two pending raster tasks per thread. This keeps resource usage
// low while making sure raster threads aren't unnecessarily idle.
const int kNumPendingRasterTasksPerThread = 2;

}  // namespace

namespace cc {

ManagedTileState::ManagedTileState()
    : can_use_gpu_memory(false),
      can_be_freed(true),
      resource_id(0),
      resource_id_is_being_initialized(false) {
}

ManagedTileState::~ManagedTileState() {
  DCHECK(!resource_id);
  DCHECK(!resource_id_is_being_initialized);
}

TileManager::TileManager(
    TileManagerClient* client, ResourceProvider* resource_provider)
    : client_(client),
      resource_pool_(ResourcePool::Create(resource_provider,
                                          Renderer::ImplPool)),
      manage_tiles_pending_(false),
      pending_raster_tasks_(0),
      worker_pool_(new base::SequencedWorkerPool(kMaxRasterThreads,
                                                 kRasterThreadNamePrefix)) {
}

TileManager::~TileManager() {
  // Reset global state and manage. This should cause
  // our memory usage to drop to zero.
  global_state_ = GlobalStateThatImpactsTilePriority();
  ManageTiles();
  DCHECK(tiles_.size() == 0);
  // This should finish all pending raster tasks and release any
  // uninitialized resources.
  worker_pool_->Shutdown();
  DCHECK(pending_raster_tasks_ == 0);
}

void TileManager::SetGlobalState(const GlobalStateThatImpactsTilePriority& global_state) {
  global_state_ = global_state;
  ScheduleManageTiles();
}

void TileManager::RegisterTile(Tile* tile) {
  tiles_.push_back(tile);
  ScheduleManageTiles();
}

void TileManager::UnregisterTile(Tile* tile) {
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); it++) {
    if (*it == tile) {
      FreeResourcesForTile(tile);
      tiles_.erase(it);
      return;
    }
  }
  DCHECK(false) << "Could not find tile version.";
}

void TileManager::WillModifyTilePriority(Tile*, WhichTree tree, const TilePriority& new_priority) {
  // TODO(nduca): Do something smarter if reprioritization turns out to be
  // costly.
  ScheduleManageTiles();
}

void TileManager::ScheduleManageTiles() {
  if (manage_tiles_pending_)
    return;
  client_->ScheduleManageTiles();
  manage_tiles_pending_ = true;
}

class BinComparator {
public:
  bool operator() (const Tile* a, const Tile* b) const {
    const ManagedTileState& ams = a->managed_state();
    const ManagedTileState& bms = b->managed_state();
    if (ams.bin != bms.bin)
      return ams.bin < bms.bin;

    if (ams.resolution != bms.resolution)
      return ams.resolution < ams.resolution;

    return
      ams.time_to_needed_in_seconds <
      bms.time_to_needed_in_seconds;
  }
};

void TileManager::ManageTiles() {
  TRACE_EVENT0("cc", "TileManager::ManageTiles");
  manage_tiles_pending_ = false;

  // The amount of time for which we want to have prepainting coverage.
  const double prepainting_window_time_seconds = 1.0;
  const double backfling_guard_distance_pixels = 314.0;

  const bool smoothness_takes_priority = global_state_.smoothness_takes_priority;

  // Bin into three categories of tiles: things we need now, things we need soon, and eventually
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    ManagedTileState& mts = tile->managed_state();
    TilePriority prio;
    if (smoothness_takes_priority)
      prio = tile->priority(ACTIVE_TREE);
    else
      prio = tile->combined_priority();

    mts.resolution = prio.resolution;
    mts.time_to_needed_in_seconds = prio.time_to_needed_in_seconds();

    if (mts.time_to_needed_in_seconds ==
        std::numeric_limits<float>::max()) {
      mts.bin = NEVER_BIN;
      continue;
    }

    if (mts.resolution == NON_IDEAL_RESOLUTION) {
      mts.bin = EVENTUALLY_BIN;
      continue;
    }

    if (mts.time_to_needed_in_seconds == 0 ||
        prio.distance_to_visible_in_pixels < backfling_guard_distance_pixels) {
      mts.bin = NOW_BIN;
      continue;
    }

    if (prio.time_to_needed_in_seconds() < prepainting_window_time_seconds) {
      mts.bin = SOON_BIN;
      continue;
    }

    mts.bin = EVENTUALLY_BIN;
  }

  // Memory limit policy works by mapping some bin states to the NEVER bin.
  TileManagerBin bin_map[NUM_BINS];
  if (global_state_.memory_limit_policy == ALLOW_NOTHING) {
    bin_map[NOW_BIN] = NEVER_BIN;
    bin_map[SOON_BIN] = NEVER_BIN;
    bin_map[EVENTUALLY_BIN] = NEVER_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  } else if (global_state_.memory_limit_policy == ALLOW_ABSOLUTE_MINIMUM) {
    bin_map[NOW_BIN] = NOW_BIN;
    bin_map[SOON_BIN] = NEVER_BIN;
    bin_map[EVENTUALLY_BIN] = NEVER_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  } else if (global_state_.memory_limit_policy == ALLOW_PREPAINT_ONLY) {
    bin_map[NOW_BIN] = NOW_BIN;
    bin_map[SOON_BIN] = SOON_BIN;
    bin_map[EVENTUALLY_BIN] = NEVER_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  } else {
    bin_map[NOW_BIN] = NOW_BIN;
    bin_map[SOON_BIN] = SOON_BIN;
    bin_map[EVENTUALLY_BIN] = NEVER_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  }
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    TileManagerBin bin = bin_map[tile->managed_state().bin];
    tile->managed_state().bin = bin;
  }

  // Sort by bin.
  std::sort(tiles_.begin(), tiles_.end(), BinComparator());

  // Assign gpu memory and determine what tiles need to be rasterized.
  AssignGpuMemoryToTiles();

  // Finally, kick the rasterizer.
  DispatchMoreRasterTasks();
}

void TileManager::AssignGpuMemoryToTiles() {
  TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
  // Some memory cannot be released. Figure out which.
  size_t unreleasable_bytes = 0;
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    if (!tile->managed_state().can_be_freed)
      unreleasable_bytes += tile->bytes_consumed_if_allocated();
  }

  // Now give memory out to the tiles until we're out, and build
  // the needs-to-be-rasterized queue.
  tiles_that_need_to_be_rasterized_.erase(
      tiles_that_need_to_be_rasterized_.begin(),
      tiles_that_need_to_be_rasterized_.end());

  size_t bytes_left = global_state_.memory_limit_in_bytes - unreleasable_bytes;
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    size_t tile_bytes = tile->bytes_consumed_if_allocated();
    ManagedTileState& managed_tile_state = tile->managed_state();
    if (!managed_tile_state.can_be_freed)
      continue;
    if (managed_tile_state.bin == NEVER_BIN) {
      managed_tile_state.can_use_gpu_memory = false;
      FreeResourcesForTile(tile);
      continue;
    }
    if (tile_bytes > bytes_left) {
      managed_tile_state.can_use_gpu_memory = false;
      FreeResourcesForTile(tile);
      continue;
    }
    bytes_left -= tile_bytes;
    managed_tile_state.can_use_gpu_memory = true;
    if (!managed_tile_state.resource_id &&
        !managed_tile_state.resource_id_is_being_initialized)
      tiles_that_need_to_be_rasterized_.push_back(tile);
  }

  // Reverse two tiles_that_need_* vectors such that pop_back gets
  // the highest priority tile.
  std::reverse(
      tiles_that_need_to_be_rasterized_.begin(),
      tiles_that_need_to_be_rasterized_.end());
}

void TileManager::FreeResourcesForTile(Tile* tile) {
  ManagedTileState& managed_tile_state = tile->managed_state();
  DCHECK(managed_tile_state.can_be_freed);
  if (managed_tile_state.resource_id) {
    resource_pool_->ReleaseResource(managed_tile_state.resource_id);
    managed_tile_state.resource_id = 0;
  }
}

void TileManager::DispatchMoreRasterTasks() {
  while (!tiles_that_need_to_be_rasterized_.empty()) {
    int max_pending_tasks = kNumPendingRasterTasksPerThread *
        kMaxRasterThreads;

    // Stop dispatching raster tasks when too many are pending.
    if (pending_raster_tasks_ >= max_pending_tasks)
      break;

    DispatchOneRasterTask(tiles_that_need_to_be_rasterized_.back());
    tiles_that_need_to_be_rasterized_.pop_back();
  }
}

void TileManager::DispatchOneRasterTask(scoped_refptr<Tile> tile) {
  TRACE_EVENT0("cc", "TileManager::DispatchOneRasterTask");
  scoped_ptr<PicturePile> cloned_picture_pile =
      tile->picture_pile()->CloneForDrawing();

  ManagedTileState& managed_tile_state = tile->managed_state();
  DCHECK(managed_tile_state.can_use_gpu_memory);
  ResourceProvider::ResourceId resource_id =
      resource_pool_->AcquireResource(tile->tile_size_.size(), tile->format_);
  resource_pool_->resource_provider()->acquirePixelBuffer(resource_id);

  managed_tile_state.resource_id_is_being_initialized = true;
  managed_tile_state.can_be_freed = false;

  ++pending_raster_tasks_;
  worker_pool_->GetTaskRunnerWithShutdownBehavior(
      base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)->PostTaskAndReply(
          FROM_HERE,
          base::Bind(&RasterizeTile,
                     cloned_picture_pile.get(),
                     resource_pool_->resource_provider()->mapPixelBuffer(
                         resource_id),
                     tile->rect_inside_picture_),
          base::Bind(&TileManager::OnRasterTaskCompleted,
                     base::Unretained(this),
                     tile,
                     resource_id,
                     base::Passed(&cloned_picture_pile)));
}

void TileManager::OnRasterTaskCompleted(
    scoped_refptr<Tile> tile,
    ResourceProvider::ResourceId resource_id,
    scoped_ptr<PicturePile> cloned_picture_pile) {
  TRACE_EVENT0("cc", "TileManager::OnRasterTaskCompleted");
  --pending_raster_tasks_;

  // Release raster resources.
  resource_pool_->resource_provider()->unmapPixelBuffer(resource_id);
  cloned_picture_pile.reset();

  ManagedTileState& managed_tile_state = tile->managed_state();
  managed_tile_state.can_be_freed = true;

  // Tile can be freed after the completion of the raster task. Call
  // AssignGpuMemoryToTiles() to re-assign gpu memory to highest priority
  // tiles. The result of this could be that this tile is no longer
  // allowed to use gpu memory and in that case we need to abort
  // initialization and free all associated resources before calling
  // DispatchMoreRasterTasks().
  AssignGpuMemoryToTiles();

  // Finish resource initialization if |can_use_gpu_memory| is true.
  if (managed_tile_state.can_use_gpu_memory) {
    resource_pool_->resource_provider()->setPixelsFromBuffer(resource_id);
    resource_pool_->resource_provider()->releasePixelBuffer(resource_id);

    DidFinishTileInitialization(tile, resource_id);
  } else {
    resource_pool_->resource_provider()->releasePixelBuffer(resource_id);
    resource_pool_->ReleaseResource(resource_id);
    managed_tile_state.resource_id_is_being_initialized = false;
  }

  DispatchMoreRasterTasks();
}

void TileManager::DidFinishTileInitialization(
    Tile* tile, ResourceProvider::ResourceId resource_id) {
  ManagedTileState& managed_tile_state = tile->managed_state();
  DCHECK(!managed_tile_state.resource_id);
  managed_tile_state.resource_id = resource_id;
  managed_tile_state.resource_id_is_being_initialized = false;
}

}
<commit_msg>[cc] ALLOW_ANYTHING should map EVENTUALLY_BIN to EVENTUALLY<commit_after>// Copyright 2012 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 "cc/tile_manager.h"

#include <algorithm>

#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/resource_pool.h"
#include "cc/tile.h"
#include "third_party/skia/include/core/SkDevice.h"

namespace {

void RasterizeTile(cc::PicturePile* picture_pile,
                   uint8_t* mapped_buffer,
                   const gfx::Rect& rect) {
  TRACE_EVENT0("cc", "RasterizeTile");
  DCHECK(mapped_buffer);
  SkBitmap bitmap;
  bitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height());
  bitmap.setPixels(mapped_buffer);
  SkDevice device(bitmap);
  SkCanvas canvas(&device);
  picture_pile->Raster(&canvas, rect);
}

const int kMaxRasterThreads = 1;

const char* kRasterThreadNamePrefix = "CompositorRaster";

// Allow two pending raster tasks per thread. This keeps resource usage
// low while making sure raster threads aren't unnecessarily idle.
const int kNumPendingRasterTasksPerThread = 2;

}  // namespace

namespace cc {

ManagedTileState::ManagedTileState()
    : can_use_gpu_memory(false),
      can_be_freed(true),
      resource_id(0),
      resource_id_is_being_initialized(false) {
}

ManagedTileState::~ManagedTileState() {
  DCHECK(!resource_id);
  DCHECK(!resource_id_is_being_initialized);
}

TileManager::TileManager(
    TileManagerClient* client, ResourceProvider* resource_provider)
    : client_(client),
      resource_pool_(ResourcePool::Create(resource_provider,
                                          Renderer::ImplPool)),
      manage_tiles_pending_(false),
      pending_raster_tasks_(0),
      worker_pool_(new base::SequencedWorkerPool(kMaxRasterThreads,
                                                 kRasterThreadNamePrefix)) {
}

TileManager::~TileManager() {
  // Reset global state and manage. This should cause
  // our memory usage to drop to zero.
  global_state_ = GlobalStateThatImpactsTilePriority();
  ManageTiles();
  DCHECK(tiles_.size() == 0);
  // This should finish all pending raster tasks and release any
  // uninitialized resources.
  worker_pool_->Shutdown();
  DCHECK(pending_raster_tasks_ == 0);
}

void TileManager::SetGlobalState(const GlobalStateThatImpactsTilePriority& global_state) {
  global_state_ = global_state;
  ScheduleManageTiles();
}

void TileManager::RegisterTile(Tile* tile) {
  tiles_.push_back(tile);
  ScheduleManageTiles();
}

void TileManager::UnregisterTile(Tile* tile) {
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); it++) {
    if (*it == tile) {
      FreeResourcesForTile(tile);
      tiles_.erase(it);
      return;
    }
  }
  DCHECK(false) << "Could not find tile version.";
}

void TileManager::WillModifyTilePriority(Tile*, WhichTree tree, const TilePriority& new_priority) {
  // TODO(nduca): Do something smarter if reprioritization turns out to be
  // costly.
  ScheduleManageTiles();
}

void TileManager::ScheduleManageTiles() {
  if (manage_tiles_pending_)
    return;
  client_->ScheduleManageTiles();
  manage_tiles_pending_ = true;
}

class BinComparator {
public:
  bool operator() (const Tile* a, const Tile* b) const {
    const ManagedTileState& ams = a->managed_state();
    const ManagedTileState& bms = b->managed_state();
    if (ams.bin != bms.bin)
      return ams.bin < bms.bin;

    if (ams.resolution != bms.resolution)
      return ams.resolution < ams.resolution;

    return
      ams.time_to_needed_in_seconds <
      bms.time_to_needed_in_seconds;
  }
};

void TileManager::ManageTiles() {
  TRACE_EVENT0("cc", "TileManager::ManageTiles");
  manage_tiles_pending_ = false;

  // The amount of time for which we want to have prepainting coverage.
  const double prepainting_window_time_seconds = 1.0;
  const double backfling_guard_distance_pixels = 314.0;

  const bool smoothness_takes_priority = global_state_.smoothness_takes_priority;

  // Bin into three categories of tiles: things we need now, things we need soon, and eventually
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    ManagedTileState& mts = tile->managed_state();
    TilePriority prio;
    if (smoothness_takes_priority)
      prio = tile->priority(ACTIVE_TREE);
    else
      prio = tile->combined_priority();

    mts.resolution = prio.resolution;
    mts.time_to_needed_in_seconds = prio.time_to_needed_in_seconds();

    if (mts.time_to_needed_in_seconds ==
        std::numeric_limits<float>::max()) {
      mts.bin = NEVER_BIN;
      continue;
    }

    if (mts.resolution == NON_IDEAL_RESOLUTION) {
      mts.bin = EVENTUALLY_BIN;
      continue;
    }

    if (mts.time_to_needed_in_seconds == 0 ||
        prio.distance_to_visible_in_pixels < backfling_guard_distance_pixels) {
      mts.bin = NOW_BIN;
      continue;
    }

    if (prio.time_to_needed_in_seconds() < prepainting_window_time_seconds) {
      mts.bin = SOON_BIN;
      continue;
    }

    mts.bin = EVENTUALLY_BIN;
  }

  // Memory limit policy works by mapping some bin states to the NEVER bin.
  TileManagerBin bin_map[NUM_BINS];
  if (global_state_.memory_limit_policy == ALLOW_NOTHING) {
    bin_map[NOW_BIN] = NEVER_BIN;
    bin_map[SOON_BIN] = NEVER_BIN;
    bin_map[EVENTUALLY_BIN] = NEVER_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  } else if (global_state_.memory_limit_policy == ALLOW_ABSOLUTE_MINIMUM) {
    bin_map[NOW_BIN] = NOW_BIN;
    bin_map[SOON_BIN] = NEVER_BIN;
    bin_map[EVENTUALLY_BIN] = NEVER_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  } else if (global_state_.memory_limit_policy == ALLOW_PREPAINT_ONLY) {
    bin_map[NOW_BIN] = NOW_BIN;
    bin_map[SOON_BIN] = SOON_BIN;
    bin_map[EVENTUALLY_BIN] = NEVER_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  } else {
    bin_map[NOW_BIN] = NOW_BIN;
    bin_map[SOON_BIN] = SOON_BIN;
    bin_map[EVENTUALLY_BIN] = EVENTUALLY_BIN;
    bin_map[NEVER_BIN] = NEVER_BIN;
  }
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    TileManagerBin bin = bin_map[tile->managed_state().bin];
    tile->managed_state().bin = bin;
  }

  // Sort by bin.
  std::sort(tiles_.begin(), tiles_.end(), BinComparator());

  // Assign gpu memory and determine what tiles need to be rasterized.
  AssignGpuMemoryToTiles();

  // Finally, kick the rasterizer.
  DispatchMoreRasterTasks();
}

void TileManager::AssignGpuMemoryToTiles() {
  TRACE_EVENT0("cc", "TileManager::AssignGpuMemoryToTiles");
  // Some memory cannot be released. Figure out which.
  size_t unreleasable_bytes = 0;
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    if (!tile->managed_state().can_be_freed)
      unreleasable_bytes += tile->bytes_consumed_if_allocated();
  }

  // Now give memory out to the tiles until we're out, and build
  // the needs-to-be-rasterized queue.
  tiles_that_need_to_be_rasterized_.erase(
      tiles_that_need_to_be_rasterized_.begin(),
      tiles_that_need_to_be_rasterized_.end());

  size_t bytes_left = global_state_.memory_limit_in_bytes - unreleasable_bytes;
  for (TileVector::iterator it = tiles_.begin(); it != tiles_.end(); ++it) {
    Tile* tile = *it;
    size_t tile_bytes = tile->bytes_consumed_if_allocated();
    ManagedTileState& managed_tile_state = tile->managed_state();
    if (!managed_tile_state.can_be_freed)
      continue;
    if (managed_tile_state.bin == NEVER_BIN) {
      managed_tile_state.can_use_gpu_memory = false;
      FreeResourcesForTile(tile);
      continue;
    }
    if (tile_bytes > bytes_left) {
      managed_tile_state.can_use_gpu_memory = false;
      FreeResourcesForTile(tile);
      continue;
    }
    bytes_left -= tile_bytes;
    managed_tile_state.can_use_gpu_memory = true;
    if (!managed_tile_state.resource_id &&
        !managed_tile_state.resource_id_is_being_initialized)
      tiles_that_need_to_be_rasterized_.push_back(tile);
  }

  // Reverse two tiles_that_need_* vectors such that pop_back gets
  // the highest priority tile.
  std::reverse(
      tiles_that_need_to_be_rasterized_.begin(),
      tiles_that_need_to_be_rasterized_.end());
}

void TileManager::FreeResourcesForTile(Tile* tile) {
  ManagedTileState& managed_tile_state = tile->managed_state();
  DCHECK(managed_tile_state.can_be_freed);
  if (managed_tile_state.resource_id) {
    resource_pool_->ReleaseResource(managed_tile_state.resource_id);
    managed_tile_state.resource_id = 0;
  }
}

void TileManager::DispatchMoreRasterTasks() {
  while (!tiles_that_need_to_be_rasterized_.empty()) {
    int max_pending_tasks = kNumPendingRasterTasksPerThread *
        kMaxRasterThreads;

    // Stop dispatching raster tasks when too many are pending.
    if (pending_raster_tasks_ >= max_pending_tasks)
      break;

    DispatchOneRasterTask(tiles_that_need_to_be_rasterized_.back());
    tiles_that_need_to_be_rasterized_.pop_back();
  }
}

void TileManager::DispatchOneRasterTask(scoped_refptr<Tile> tile) {
  TRACE_EVENT0("cc", "TileManager::DispatchOneRasterTask");
  scoped_ptr<PicturePile> cloned_picture_pile =
      tile->picture_pile()->CloneForDrawing();

  ManagedTileState& managed_tile_state = tile->managed_state();
  DCHECK(managed_tile_state.can_use_gpu_memory);
  ResourceProvider::ResourceId resource_id =
      resource_pool_->AcquireResource(tile->tile_size_.size(), tile->format_);
  resource_pool_->resource_provider()->acquirePixelBuffer(resource_id);

  managed_tile_state.resource_id_is_being_initialized = true;
  managed_tile_state.can_be_freed = false;

  ++pending_raster_tasks_;
  worker_pool_->GetTaskRunnerWithShutdownBehavior(
      base::SequencedWorkerPool::SKIP_ON_SHUTDOWN)->PostTaskAndReply(
          FROM_HERE,
          base::Bind(&RasterizeTile,
                     cloned_picture_pile.get(),
                     resource_pool_->resource_provider()->mapPixelBuffer(
                         resource_id),
                     tile->rect_inside_picture_),
          base::Bind(&TileManager::OnRasterTaskCompleted,
                     base::Unretained(this),
                     tile,
                     resource_id,
                     base::Passed(&cloned_picture_pile)));
}

void TileManager::OnRasterTaskCompleted(
    scoped_refptr<Tile> tile,
    ResourceProvider::ResourceId resource_id,
    scoped_ptr<PicturePile> cloned_picture_pile) {
  TRACE_EVENT0("cc", "TileManager::OnRasterTaskCompleted");
  --pending_raster_tasks_;

  // Release raster resources.
  resource_pool_->resource_provider()->unmapPixelBuffer(resource_id);
  cloned_picture_pile.reset();

  ManagedTileState& managed_tile_state = tile->managed_state();
  managed_tile_state.can_be_freed = true;

  // Tile can be freed after the completion of the raster task. Call
  // AssignGpuMemoryToTiles() to re-assign gpu memory to highest priority
  // tiles. The result of this could be that this tile is no longer
  // allowed to use gpu memory and in that case we need to abort
  // initialization and free all associated resources before calling
  // DispatchMoreRasterTasks().
  AssignGpuMemoryToTiles();

  // Finish resource initialization if |can_use_gpu_memory| is true.
  if (managed_tile_state.can_use_gpu_memory) {
    resource_pool_->resource_provider()->setPixelsFromBuffer(resource_id);
    resource_pool_->resource_provider()->releasePixelBuffer(resource_id);

    DidFinishTileInitialization(tile, resource_id);
  } else {
    resource_pool_->resource_provider()->releasePixelBuffer(resource_id);
    resource_pool_->ReleaseResource(resource_id);
    managed_tile_state.resource_id_is_being_initialized = false;
  }

  DispatchMoreRasterTasks();
}

void TileManager::DidFinishTileInitialization(
    Tile* tile, ResourceProvider::ResourceId resource_id) {
  ManagedTileState& managed_tile_state = tile->managed_state();
  DCHECK(!managed_tile_state.resource_id);
  managed_tile_state.resource_id = resource_id;
  managed_tile_state.resource_id_is_being_initialized = false;
}

}
<|endoftext|>


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

#include "ginac_util.h"
#include "seed.h"

namespace {
typedef cluster::LabelledSeed LSeed;

cluster::Seed::Cluster
default_cluster(size_t size) {
	cluster::Seed::Cluster result(size);
	std::string var = "x";
	for(size_t i = 0; i < size; ++i) {
		result[i] = cluster::ginac::symbol(var + std::to_string(i));
	}
	return std::move(result);
}
}
namespace cluster {
TEST(ExchangeGraph, Pentagon) {
	EquivQuiverMatrix m("{ { 0 1 } { -1 0 } }");
	auto c = default_cluster(2);
	Seed s(std::move(m), std::move(c));

	ExchangeGraph g(s);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(5), num_seeds);
}
TEST(LabelledExchangeGraph, Decagon) {
	QuiverMatrix m("{ { 0 1 } { -1 0 } }");
	auto c = default_cluster(2);
	LSeed s(std::move(m), std::move(c));

	LabelledExchangeGraph g(s);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(10), num_seeds);
}
TEST(LabelledQuiverGraph, Pentagon) {
	QuiverMatrix m("{ { 0 1  0 } { -1 0 1 } { 0 -1 0 } }");

	LabelledQuiverGraph g(m);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(14), num_seeds);
}
TEST(QuiverGraph, Pentagon) {
	EquivQuiverMatrix m("{ { 0 1  0 } { -1 0 1 } { 0 -1 0 } }");

	QuiverGraph g(m);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(4), num_seeds);
}
namespace {
	typedef _EGContinueChecks::InfiniteTypeSink GCheck;
}
TEST(GreenContinue, Simple) {
	const QuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
	GCheck chk;
	EXPECT_TRUE(chk(&m, 0));
	EXPECT_TRUE(chk(&m, 1));
	EXPECT_TRUE(chk(&m, 2));
	EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, Cycle) {
	const QuiverMatrix m("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_TRUE(chk(&m, 0));
	EXPECT_TRUE(chk(&m, 1));
	EXPECT_TRUE(chk(&m, 2));
	EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, InfiniteCycle) {
	const QuiverMatrix m("{ { 0 2 -1 0 } { -2 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_TRUE(chk(&m, 0));
	/* Disabled as this functionality is not implemented.
	 * The vertex is not taken into account at this point, instead only the matrix
	 * is considered, and the computation of the exchange graph stops after these
	 * infinite type matrices have been computed, not before
	EXPECT_FALSE(chk(&m, 1));
	*/
	EXPECT_TRUE(chk(&m, 2));
	EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, AllInfiniteCycle) {
	const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_FALSE(chk(&m, 0));
	EXPECT_FALSE(chk(&m, 1));
	EXPECT_FALSE(chk(&m, 2));
	EXPECT_FALSE(chk(&m, 3));
}
TEST(GreenContinue, Reuse) {
	const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_FALSE(chk(&m, 0));
	EXPECT_FALSE(chk(&m, 1));
	EXPECT_FALSE(chk(&m, 2));
	EXPECT_FALSE(chk(&m, 3));

	const QuiverMatrix n("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
	EXPECT_TRUE(chk(&n, 0));
	EXPECT_TRUE(chk(&n, 1));
	EXPECT_TRUE(chk(&n, 2));
	EXPECT_TRUE(chk(&n, 3));

	const QuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 5 } { 0 4 -5 0 } }");
	EXPECT_FALSE(chk(&k, 0));
	EXPECT_FALSE(chk(&k, 1));
	EXPECT_FALSE(chk(&k, 2));
	EXPECT_FALSE(chk(&k, 3));
}
TEST(GreenContinue, Seed) {
	EquivQuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 2 } { 0 4 -2 0 } }");
	Seed::Cluster cl = default_cluster(4);
	Seed s(std::move(k), std::move(cl));

	GCheck chk;
	EXPECT_FALSE(chk(&s, 0));
	EXPECT_FALSE(chk(&s, 1));
	EXPECT_FALSE(chk(&s, 2));
	EXPECT_FALSE(chk(&s, 3));
}
}

<commit_msg>Removes trailing whitespace<commit_after>/*
 * exchange_graph_test.cc
 * Copyright 2014-2015 John Lawson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "gtest/gtest.h"
#include "exchange_graph.h"

#include "ginac_util.h"
#include "seed.h"

namespace {
typedef cluster::LabelledSeed LSeed;

cluster::Seed::Cluster
default_cluster(size_t size) {
	cluster::Seed::Cluster result(size);
	std::string var = "x";
	for(size_t i = 0; i < size; ++i) {
		result[i] = cluster::ginac::symbol(var + std::to_string(i));
	}
	return std::move(result);
}
}
namespace cluster {
TEST(ExchangeGraph, Pentagon) {
	EquivQuiverMatrix m("{ { 0 1 } { -1 0 } }");
	auto c = default_cluster(2);
	Seed s(std::move(m), std::move(c));

	ExchangeGraph g(s);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(5), num_seeds);
}
TEST(LabelledExchangeGraph, Decagon) {
	QuiverMatrix m("{ { 0 1 } { -1 0 } }");
	auto c = default_cluster(2);
	LSeed s(std::move(m), std::move(c));

	LabelledExchangeGraph g(s);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(10), num_seeds);
}
TEST(LabelledQuiverGraph, Pentagon) {
	QuiverMatrix m("{ { 0 1  0 } { -1 0 1 } { 0 -1 0 } }");

	LabelledQuiverGraph g(m);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(14), num_seeds);
}
TEST(QuiverGraph, Pentagon) {
	EquivQuiverMatrix m("{ { 0 1  0 } { -1 0 1 } { 0 -1 0 } }");

	QuiverGraph g(m);
	uint num_seeds = 0;
	for(auto it = g.begin(); it != g.end(); ++it) {
		++num_seeds;
		for(auto l_it = it->second.begin(); l_it != it->second.end(); ++l_it) {
			EXPECT_NE(*l_it, nullptr);
		}
	}
	EXPECT_EQ(static_cast<std::size_t>(4), num_seeds);
}
namespace {
	typedef _EGContinueChecks::InfiniteTypeSink GCheck;
}
TEST(GreenContinue, Simple) {
	const QuiverMatrix m("{ { 0 1 0 } { -1 0 1 } { 0 -1 0 } }");
	GCheck chk;
	EXPECT_TRUE(chk(&m, 0));
	EXPECT_TRUE(chk(&m, 1));
	EXPECT_TRUE(chk(&m, 2));
	EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, Cycle) {
	const QuiverMatrix m("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_TRUE(chk(&m, 0));
	EXPECT_TRUE(chk(&m, 1));
	EXPECT_TRUE(chk(&m, 2));
	EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, InfiniteCycle) {
	const QuiverMatrix m("{ { 0 2 -1 0 } { -2 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_TRUE(chk(&m, 0));
	/* Disabled as this functionality is not implemented.
	 * The vertex is not taken into account at this point, instead only the matrix
	 * is considered, and the computation of the exchange graph stops after these
	 * infinite type matrices have been computed, not before
	EXPECT_FALSE(chk(&m, 1));
	*/
	EXPECT_TRUE(chk(&m, 2));
	EXPECT_TRUE(chk(&m, 3));
}
TEST(GreenContinue, AllInfiniteCycle) {
	const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_FALSE(chk(&m, 0));
	EXPECT_FALSE(chk(&m, 1));
	EXPECT_FALSE(chk(&m, 2));
	EXPECT_FALSE(chk(&m, 3));
}
TEST(GreenContinue, Reuse) {
	const QuiverMatrix m("{ { 0 2 -2 0 } { -2 0 2 1 } { 2 -2 0 1 } { 0 -1 -1 0 } }");
	GCheck chk;
	EXPECT_FALSE(chk(&m, 0));
	EXPECT_FALSE(chk(&m, 1));
	EXPECT_FALSE(chk(&m, 2));
	EXPECT_FALSE(chk(&m, 3));

	const QuiverMatrix n("{ { 0 1 -1 0 } { -1 0 1 1 } { 1 -1 0 1 } { 0 -1 -1 0 } }");
	EXPECT_TRUE(chk(&n, 0));
	EXPECT_TRUE(chk(&n, 1));
	EXPECT_TRUE(chk(&n, 2));
	EXPECT_TRUE(chk(&n, 3));

	const QuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 5 } { 0 4 -5 0 } }");
	EXPECT_FALSE(chk(&k, 0));
	EXPECT_FALSE(chk(&k, 1));
	EXPECT_FALSE(chk(&k, 2));
	EXPECT_FALSE(chk(&k, 3));
}
TEST(GreenContinue, Seed) {
	EquivQuiverMatrix k("{ { 0 1 0 0 } { -1 0 3 -4 } { 0 -3 0 2 } { 0 4 -2 0 } }");
	Seed::Cluster cl = default_cluster(4);
	Seed s(std::move(k), std::move(cl));

	GCheck chk;
	EXPECT_FALSE(chk(&s, 0));
	EXPECT_FALSE(chk(&s, 1));
	EXPECT_FALSE(chk(&s, 2));
	EXPECT_FALSE(chk(&s, 3));
}
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsSlideFunction.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:20:04 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SD_SLIDESORTER_SLIDE_FUNCTION_HXX
#define SD_SLIDESORTER_SLIDE_FUNCTION_HXX

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

class SdDrawDocument;

namespace sd { namespace slidesorter { namespace controller {

class SlideSorterController;

/** Base class for functions of the slide sorter.
*/
class SlideFunction
    : public FuPoor
{
public:
    TYPEINFO();

    SlideFunction (
        SlideSorterController& rController,
        SfxRequest& rRequest);

    virtual ~SlideFunction (void);

    virtual BOOL KeyInput (const KeyEvent& rKEvt);
    virtual BOOL MouseMove (const MouseEvent& rMEvt) { return FALSE; }
    virtual BOOL MouseButtonUp (const MouseEvent& rMEvt) { return FALSE; }
    virtual BOOL MouseButtonDown (const MouseEvent& rMEvt) { return FALSE; }

    virtual void Activate (void);
    virtual void Deactivate (void);

    /** Called from ForceScroll() before the actual scrolling.
    */
    virtual void ScrollStart (void);

    /** Called from ForceScroll() after the actual scrolling.
    */
    virtual void ScrollEnd (void);
};

} } } // end of namespace ::sd::slidesorter::controller

#endif
<commit_msg>INTEGRATION: CWS impressfunctions (1.3.40); FILE MERGED 2005/10/28 11:00:54 cl 1.3.40.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsSlideFunction.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-12-14 17:22:22 $
 *
 *  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
 *
 ************************************************************************/

#ifndef SD_SLIDESORTER_SLIDE_FUNCTION_HXX
#define SD_SLIDESORTER_SLIDE_FUNCTION_HXX

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

class SdDrawDocument;

namespace sd { namespace slidesorter { namespace controller {

class SlideSorterController;

/** Base class for functions of the slide sorter.
*/
class SlideFunction
    : public FuPoor
{
public:
    TYPEINFO();

    static FunctionReference Create( SlideSorterController& rController, SfxRequest& rRequest );

    virtual BOOL MouseMove (const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp (const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown (const MouseEvent& rMEvt);

    /** Called from ForceScroll() before the actual scrolling.
    */
    virtual void ScrollStart (void);

    /** Called from ForceScroll() after the actual scrolling.
    */
    virtual void ScrollEnd (void);

protected:
    SlideFunction (
        SlideSorterController& rController,
        SfxRequest& rRequest);
};

} } } // end of namespace ::sd::slidesorter::controller

#endif
<|endoftext|>


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

/**
 * @file mc_pos_control_m_start_nuttx.cpp
 *
 * @author Thomas Gubler <thomasgubler@gmail.com>
 */
#include <string.h>
#include <cstdlib>
#include <systemlib/err.h>
#include <systemlib/systemlib.h>

extern bool thread_running;
int daemon_task;             /**< Handle of deamon task / thread */
namespace px4
{
bool task_should_exit = false;
}
using namespace px4;

extern int main(int argc, char **argv);

extern "C" __EXPORT int mc_pos_control_m_main(int argc, char *argv[]);
int mc_pos_control_m_main(int argc, char *argv[])
{
	if (argc < 1) {
		errx(1, "usage: mc_pos_control_m {start|stop|status}");
	}

	if (!strcmp(argv[1], "start")) {

		if (thread_running) {
			warnx("already running");
			/* this is not an error */
			exit(0);
		}

		task_should_exit = false;

		daemon_task = task_spawn_cmd("mc_pos_control_m",
				       SCHED_DEFAULT,
				       SCHED_PRIORITY_MAX - 5,
				       3000,
				       main,
					(argv) ? (char* const*)&argv[2] : (char* const*)NULL);

		exit(0);
	}

	if (!strcmp(argv[1], "stop")) {
		task_should_exit = true;
		exit(0);
	}

	if (!strcmp(argv[1], "status")) {
		if (thread_running) {
			warnx("is running");

		} else {
			warnx("not started");
		}

		exit(0);
	}

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

/**
 * @file mc_pos_control_m_start_nuttx.cpp
 *
 * @author Thomas Gubler <thomasgubler@gmail.com>
 */
#include <string.h>
#include <cstdlib>
#include <systemlib/err.h>
#include <systemlib/systemlib.h>

extern bool thread_running;
int daemon_task;             /**< Handle of deamon task / thread */
namespace px4
{
bool task_should_exit = false;
}
using namespace px4;

extern int main(int argc, char **argv);

extern "C" __EXPORT int mc_pos_control_m_main(int argc, char *argv[]);
int mc_pos_control_m_main(int argc, char *argv[])
{
	if (argc < 1) {
		errx(1, "usage: mc_pos_control_m {start|stop|status}");
	}

	if (!strcmp(argv[1], "start")) {

		if (thread_running) {
			warnx("already running");
			/* this is not an error */
			exit(0);
		}

		task_should_exit = false;

		daemon_task = task_spawn_cmd("mc_pos_control_m",
				       SCHED_DEFAULT,
				       SCHED_PRIORITY_MAX - 5,
				       2500,
				       main,
					(argv) ? (char* const*)&argv[2] : (char* const*)NULL);

		exit(0);
	}

	if (!strcmp(argv[1], "stop")) {
		task_should_exit = true;
		exit(0);
	}

	if (!strcmp(argv[1], "status")) {
		if (thread_running) {
			warnx("is running");

		} else {
			warnx("not started");
		}

		exit(0);
	}

	warnx("unrecognized command");
	return 1;
}
<|endoftext|>


<commit_before>/**
 * 2.2.2 变量声明和定义的关系
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/6/28
 */

#include <iostream>

int main() {

  /**
   * 为了支持分离式编译，C++语言将生命和定义区分开来。
   * 声明：使得名字为程度所知，一个文件如果想使用别处定义的名字，则必须包含对那个名字的声明，使用关键字extern。【ˈekstɜ:n】
   * 定义：负责创建与名字关联的实体，申请内存空间，还可能会为变量赋一个初始值。
   * 注意：变量只能被定义一次，但是可以被多次声明。
   */
  extern int i; // 声明 i 而非定义 i，以为还未初始化，所以还不能被引用，引用的话编译能通过，但是运行会报错
  int j;        // 声明并定义 j
  // extern double pi = 3.1416; // 有 extern 关键字的话就不能进行初始化操作，编译报错

  std::cout << j << std::endl;

  return 0;
}<commit_msg>2.2.2 变量声明和定义的关系<commit_after>/**
 * 2.2.2 变量声明和定义的关系
 * @Author Bob
 * @Eamil 0haizhu0@gmail.com
 * @Date 2017/6/28
 */

#include <iostream>

/**
 * 为了支持分离式编译，C++语言将生命和定义区分开来。
 * 声明：使得名字为程度所知，一个文件如果想使用别处定义的名字，则必须包含对那个名字的声明，使用关键字extern。【ˈekstɜ:n】
 * 定义：负责创建与名字关联的实体，申请内存空间，还可能会为变量赋一个初始值。
 * 注意：变量只能被定义一次，但是可以被多次声明。
 */
extern int i; // 声明 i 而非定义 i，以为还未初始化，所以还不能被引用，引用的话编译能通过，但是运行会报错
int j;        // 声明并定义 j
extern double pi = 3.1416; // extern 修饰的变量初始化的时候会有警告

int main() {

  /**
   * 注意：需要强调的一点是，因为
   */
  std::cout << j << std::endl;

  return 0;
}<|endoftext|>


<commit_before>// bsls_assert.cpp                                                    -*-C++-*-
#include <bsls_assert.h>

#include <bsls_ident.h>
BSLS_IDENT("$Id$ $CSID$")

#include <bsls_asserttestexception.h>
#include <bsls_pointercastutil.h>
#include <bsls_types.h>
#include <bsls_log.h>
#include <bsls_logseverity.h>

#include <exception>

#include <cstdio>
#include <cstdlib>
#include <cstring>

#ifdef BSLS_PLATFORM_OS_AIX
#include <signal.h>
#endif

#ifdef BSLS_PLATFORM_OS_UNIX
#include <unistd.h>    // 'sleep'
#endif

#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h>   // IsDebbugerPresent
#include <crtdbg.h>    // '_CrtSetReportMode', to suppress pop-ups

typedef unsigned long DWORD;

extern "C" {
    __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);
};
#endif

#ifdef BSLS_ASSERT_NORETURN
#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file
#endif

// Note that a portable syntax for 'noreturn' will be available once we have
// access to conforming C++0x compilers.
//# define BSLS_ASSERT_NORETURN [[noreturn]]

#ifdef BSLS_PLATFORM_CMP_MSVC
#   define BSLS_ASSERT_NORETURN __declspec(noreturn)
#else
#   define BSLS_ASSERT_NORETURN
#endif

namespace BloombergLP {

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// We want to print the error message to 'stderr', not 'stdout'.   The old
// documentation for 'printError' is:
//..
//  Print a formatted error message to standard output.  (Most Bloomberg
//  processes will send standard output to a log file.)
//..
// TBD: find out whether 'stderr' goes to 'act.log'.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

static
void printError(const char *text, const char *file, int line)
    // Print a formatted error message to 'stderr' using the specified
    // expression 'text', 'file' name, and 'line' number.  If either
    // 'text' or 'file' is empty ("") or null (0), replace it with some
    // informative, "human-readable" text, before formatting.
{
    if (!text) {
        text = "(* Unspecified Expression Text *)";
    }
    else if (!*text) {
        text = "(* Empty Expression Text *)";
    }

    if (!file) {
        file = "(* Unspecified File Name *)";
    }
    else if (!*file) {
        file = "(* Empty File Name *)";
    }

    bsls::Log::logFormattedMessage(
        bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text);
}

namespace bsls {

                                // ------------
                                // class Assert
                                // ------------

// CLASS DATA
bsls::AtomicOperations::AtomicTypes::Pointer
    Assert::s_handler = {(void *) &Assert::failAbort};
bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};

// CLASS METHODS
void Assert::setFailureHandlerRaw(Assert::Handler function)
{
    bsls::AtomicOperations::setPtrRelease(
        &s_handler, PointerCastUtil::cast<void *>(function));
}

void Assert::setFailureHandler(Assert::Handler function)
{
    if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {
        setFailureHandlerRaw(function);
    }
}

void Assert::lockAssertAdministration()
{
    bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);
}

Assert::Handler Assert::failureHandler()
{
    return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);
}

                       // Macro Dispatcher Method

#define IS_POWER_OF_TWO(X) (0 == ((X) & ((X) - 1)))

BSLS_ASSERT_NORETURN_INVOKE_HANDLER
void Assert::invokeHandler(const char *text, const char *file, int line)
{
    static AtomicOperations::AtomicTypes::Int failureReturnCount = {0};

    Assert::Handler currentHandlerAddress = failureHandler();

    currentHandlerAddress(text, file, line);

    // The failure handler should not return.  If a returning failure handler
    // has been installed, alert the user that the program is continuing to
    // run.

    unsigned count = static_cast<unsigned>(
                AtomicOperations::incrementIntNvAcqRel(&failureReturnCount));

    if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(IS_POWER_OF_TWO(count))) {
        BSLS_PERFORMANCEHINT_UNLIKELY_HINT;

        // Log when 'count' is a power of 2.

        if (count == (1 << 30)) {
            // Avoid undefined behavior by resetting the counter.

            AtomicOperations::setInt(&failureReturnCount, 1 << 29);
        }

        Log::logFormattedMessage(LogSeverity::e_FATAL,
                                 file,
                                 line,
                                 "BSLS_ASSERT failure: '%s'",
                                 text);

        BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: "
                       "violation handler at %p must not return.",
                       currentHandlerAddress);
    }

#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER
    std::abort();
#endif
}

                     // Standard Assertion-Failure Handlers

BSLS_ASSERT_NORETURN
void Assert::failAbort(const char *text, const char *file, int line)
{
    printError(text, file, line);

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 8923441: The following is a work-around for a Fortran compiler bug.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_AIX
    sigset_t newset;
    sigemptyset(&newset);
    sigaddset(&newset, SIGABRT);
#if defined(BDE_BUILD_TARGET_MT)
    pthread_sigmask(SIG_UNBLOCK, &newset, 0);
#else
    sigprocmask(SIG_UNBLOCK, &newset, 0);
#endif
#endif

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 13882128: Note that (according to Oleg) the first line alone may be
    // sufficient.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_WINDOWS
    // The following configures the runtime library on how to report asserts,
    // errors, and warnings in order to avoid pop-up windows when 'abort' is
    // called.
    if (!IsDebuggerPresent()) {
        _CrtSetReportMode(_CRT_ASSERT, 0);
        _CrtSetReportMode(_CRT_ERROR, 0);
        _CrtSetReportMode(_CRT_WARN, 0);
    }
#endif

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failSleep(const char *text, const char *file, int line)
{
    printError(text, file, line);

    volatile int sleepDuration = 1;

    while (1 == sleepDuration) {

#if defined(BSLS_PLATFORM_OS_UNIX)
        sleep(sleepDuration);
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
        Sleep(sleepDuration * 1000);  // milliseconds
#else
        #error "Do not know how to sleep on this platform."
#endif

    }

    // We will never reach this line, but it is needed to let the compiler know
    // that this function does not return.

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failThrow(const char *text, const char *file, int line)
{

#ifdef BDE_BUILD_TARGET_EXC
    if (!std::uncaught_exception()) {
        throw AssertTestException(text, file, line);
    }
    else {
        bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,
                "BSLS_ASSERT: An uncaught exception is pending;"
                " cannot throw 'AssertTestException'.");
    }
#endif

    failAbort(text, file, line);
}

}  // close package namespace

#undef BSLS_ASSERT_NORETURN

namespace bsls {

                    // -------------------------------
                    // class AssertFailureHandlerGuard
                    // -------------------------------

AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)
: d_original(Assert::failureHandler())
{
    Assert::setFailureHandlerRaw(temporary);
}

AssertFailureHandlerGuard::~AssertFailureHandlerGuard()
{
    Assert::setFailureHandlerRaw(d_original);
}

}  // close package namespace

}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Rename local copy of failure handler.<commit_after>// bsls_assert.cpp                                                    -*-C++-*-
#include <bsls_assert.h>

#include <bsls_ident.h>
BSLS_IDENT("$Id$ $CSID$")

#include <bsls_asserttestexception.h>
#include <bsls_pointercastutil.h>
#include <bsls_types.h>
#include <bsls_log.h>
#include <bsls_logseverity.h>

#include <exception>

#include <cstdio>
#include <cstdlib>
#include <cstring>

#ifdef BSLS_PLATFORM_OS_AIX
#include <signal.h>
#endif

#ifdef BSLS_PLATFORM_OS_UNIX
#include <unistd.h>    // 'sleep'
#endif

#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h>   // IsDebbugerPresent
#include <crtdbg.h>    // '_CrtSetReportMode', to suppress pop-ups

typedef unsigned long DWORD;

extern "C" {
    __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);
};
#endif

#ifdef BSLS_ASSERT_NORETURN
#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file
#endif

// Note that a portable syntax for 'noreturn' will be available once we have
// access to conforming C++0x compilers.
//# define BSLS_ASSERT_NORETURN [[noreturn]]

#ifdef BSLS_PLATFORM_CMP_MSVC
#   define BSLS_ASSERT_NORETURN __declspec(noreturn)
#else
#   define BSLS_ASSERT_NORETURN
#endif

namespace BloombergLP {

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// We want to print the error message to 'stderr', not 'stdout'.   The old
// documentation for 'printError' is:
//..
//  Print a formatted error message to standard output.  (Most Bloomberg
//  processes will send standard output to a log file.)
//..
// TBD: find out whether 'stderr' goes to 'act.log'.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

static
void printError(const char *text, const char *file, int line)
    // Print a formatted error message to 'stderr' using the specified
    // expression 'text', 'file' name, and 'line' number.  If either
    // 'text' or 'file' is empty ("") or null (0), replace it with some
    // informative, "human-readable" text, before formatting.
{
    if (!text) {
        text = "(* Unspecified Expression Text *)";
    }
    else if (!*text) {
        text = "(* Empty Expression Text *)";
    }

    if (!file) {
        file = "(* Unspecified File Name *)";
    }
    else if (!*file) {
        file = "(* Empty File Name *)";
    }

    bsls::Log::logFormattedMessage(
        bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text);
}

namespace bsls {

                                // ------------
                                // class Assert
                                // ------------

// CLASS DATA
bsls::AtomicOperations::AtomicTypes::Pointer
    Assert::s_handler = {(void *) &Assert::failAbort};
bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};

// CLASS METHODS
void Assert::setFailureHandlerRaw(Assert::Handler function)
{
    bsls::AtomicOperations::setPtrRelease(
        &s_handler, PointerCastUtil::cast<void *>(function));
}

void Assert::setFailureHandler(Assert::Handler function)
{
    if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {
        setFailureHandlerRaw(function);
    }
}

void Assert::lockAssertAdministration()
{
    bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);
}

Assert::Handler Assert::failureHandler()
{
    return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);
}

                       // Macro Dispatcher Method

#define IS_POWER_OF_TWO(X) (0 == ((X) & ((X) - 1)))

BSLS_ASSERT_NORETURN_INVOKE_HANDLER
void Assert::invokeHandler(const char *text, const char *file, int line)
{
    static AtomicOperations::AtomicTypes::Int failureReturnCount = {0};

    Assert::Handler failureHandlerPtr = failureHandler();

    failureHandlerPtr(text, file, line);

    // The failure handler should not return.  If a returning failure handler
    // has been installed, alert the user that the program is continuing to
    // run.

    unsigned count = static_cast<unsigned>(
                AtomicOperations::incrementIntNvAcqRel(&failureReturnCount));

    if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(IS_POWER_OF_TWO(count))) {
        BSLS_PERFORMANCEHINT_UNLIKELY_HINT;

        // Log when 'count' is a power of 2.

        if (count == (1 << 30)) {
            // Avoid undefined behavior by resetting the counter.

            AtomicOperations::setInt(&failureReturnCount, 1 << 29);
        }

        Log::logFormattedMessage(LogSeverity::e_FATAL,
                                 file,
                                 line,
                                 "BSLS_ASSERT failure: '%s'",
                                 text);

        BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: "
                       "violation handler at %p must not return.",
                       failureHandlerPtr);
    }

#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER
    std::abort();
#endif
}

                     // Standard Assertion-Failure Handlers

BSLS_ASSERT_NORETURN
void Assert::failAbort(const char *text, const char *file, int line)
{
    printError(text, file, line);

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 8923441: The following is a work-around for a Fortran compiler bug.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_AIX
    sigset_t newset;
    sigemptyset(&newset);
    sigaddset(&newset, SIGABRT);
#if defined(BDE_BUILD_TARGET_MT)
    pthread_sigmask(SIG_UNBLOCK, &newset, 0);
#else
    sigprocmask(SIG_UNBLOCK, &newset, 0);
#endif
#endif

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 13882128: Note that (according to Oleg) the first line alone may be
    // sufficient.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_WINDOWS
    // The following configures the runtime library on how to report asserts,
    // errors, and warnings in order to avoid pop-up windows when 'abort' is
    // called.
    if (!IsDebuggerPresent()) {
        _CrtSetReportMode(_CRT_ASSERT, 0);
        _CrtSetReportMode(_CRT_ERROR, 0);
        _CrtSetReportMode(_CRT_WARN, 0);
    }
#endif

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failSleep(const char *text, const char *file, int line)
{
    printError(text, file, line);

    volatile int sleepDuration = 1;

    while (1 == sleepDuration) {

#if defined(BSLS_PLATFORM_OS_UNIX)
        sleep(sleepDuration);
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
        Sleep(sleepDuration * 1000);  // milliseconds
#else
        #error "Do not know how to sleep on this platform."
#endif

    }

    // We will never reach this line, but it is needed to let the compiler know
    // that this function does not return.

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failThrow(const char *text, const char *file, int line)
{

#ifdef BDE_BUILD_TARGET_EXC
    if (!std::uncaught_exception()) {
        throw AssertTestException(text, file, line);
    }
    else {
        bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,
                "BSLS_ASSERT: An uncaught exception is pending;"
                " cannot throw 'AssertTestException'.");
    }
#endif

    failAbort(text, file, line);
}

}  // close package namespace

#undef BSLS_ASSERT_NORETURN

namespace bsls {

                    // -------------------------------
                    // class AssertFailureHandlerGuard
                    // -------------------------------

AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)
: d_original(Assert::failureHandler())
{
    Assert::setFailureHandlerRaw(temporary);
}

AssertFailureHandlerGuard::~AssertFailureHandlerGuard()
{
    Assert::setFailureHandlerRaw(d_original);
}

}  // close package namespace

}  // close enterprise namespace

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


<commit_before>#include "NumberTest.h"
#include "SimpleAudioEngine.h"
#include "LanguageManager.h"
#include "Planet.h"

USING_NS_CC;
using namespace CocosDenshion;

NumberTest * NumberTest::create(int _number, Sprite * _bg)
{
	NumberTest * tip = new NumberTest();

	if (tip && tip->init())
	{
		tip->autorelease();
		tip->initNumberTest(_number, _bg);
		return tip;
	}
	CC_SAFE_DELETE(tip);
	return NULL;
}

NumberTest::~NumberTest()
{

}

void NumberTest::initNumberTest(int _number, Sprite * _bg)
{
	number = _number;
	setupDirector();
	setupBoundary();
	setupSprite();
	setupAudio();
	setupLabel();
	consumed = false;
	this->setScale(0.9);
	bg = _bg;
	BaseObject::initObject();
}

void NumberTest::setupDirector()
{
	visibleSize = Director::getInstance()->getVisibleSize();
	winSize = Director::getInstance()->getWinSize(); //design size?
	frameSize = Director::getInstance()->getOpenGLView()->getFrameSize();
	origin = Director::getInstance()->getVisibleOrigin(); // common to all maps i hope
}

void NumberTest::setupBoundary()
{
	boundary.shape = SHAPE::circle;
	boundary.active = true;
	boundary.r = 20;
}

void NumberTest::setupSprite()
{
	auto sprite = Sprite::createWithSpriteFrameName("tip.png");
	auto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);
	auto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);
	auto seq1 = Sequence::create(moveUp, moveBack, nullptr);
	sprite->runAction(RepeatForever::create(seq1));
	this->addChild(sprite);
}

void NumberTest::setupAudio()
{
	auto audio = SimpleAudioEngine::getInstance();
	audio->preloadEffect("sfx/bot.wav");
	audio->preloadEffect("sfx/correct.wav");
	langCode = "en";
	if (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)
		langCode = "sw";
	for (int i = 0; i <= 10; i++)
	{
		audio->preloadEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
	}
}

void NumberTest::setupLabel()
{
	numberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString("font"), 50);
	numberLabel->setPosition(Vec2(0, 100));
	auto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);
	auto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);
	ActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);
	auto action = RepeatForever::create(bouncingAction);
	numberLabel->runAction(action);
	numberLabel->setVisible(false);
	this->addChild(numberLabel);
}

void NumberTest::update(bool hit)
{
	if (hit && !isMessagevisible && !consumed)
	{
		auto audio = SimpleAudioEngine::getInstance();
		isMessagevisible = true;
		audio->playEffect("sfx/bot.wav");

		Vector<FiniteTimeAction *>  allActions;
		auto action = MoveTo::create(1.5, Vec2(0, 0));
		TargetedAction * t1 = TargetedAction::create(bg, action);
		allActions.pushBack(t1);

		Vector<MenuItem *> menuItems;
		auto wrongChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/hurt.wav");
		};
		auto rightChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/correct.wav");
			auto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));
			bg->runAction(moveUp);
			consumed = true;
			numberLabel->setVisible(true);
		};

		int n = -1;
		int correctPicked = RandomHelper::random_int(1, 3);
		Label * labelA = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelA->setScale(0.9);
		MenuItemLabel * mLabelA;
		if (correctPicked == 1)
		{
			labelA->setString(std::to_string(number));
			mLabelA = MenuItemLabel::create(labelA, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number)
			{
				n = RandomHelper::random_int(1, 10);
			}
			labelA->setString(std::to_string(n));
			mLabelA = MenuItemLabel::create(labelA, wrongChoice);
		}

		Label * labelB = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelB->setScale(0.9);
		MenuItemLabel * mLabelB;
		if (correctPicked == 2)
		{
			labelB->setString(std::to_string(number));
			mLabelB = MenuItemLabel::create(labelB, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number)
			{
				n = RandomHelper::random_int(1, 10);
			}
			labelB->setString(std::to_string(n));
			mLabelB = MenuItemLabel::create(labelB, wrongChoice);
		}

		Label * labelC = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelC->setScale(0.9);
		MenuItemLabel * mLabelC;
		if (correctPicked == 3)
		{
			labelC->setString(std::to_string(number));
			mLabelC = MenuItemLabel::create(labelC, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number)
			{
				n = RandomHelper::random_int(1, 10);
			}
			labelC->setString(std::to_string(n));
			mLabelC = MenuItemLabel::create(labelC, wrongChoice);
		}

		auto scaleUp = ScaleTo::create(1, 1.01);
		auto scaleDown = ScaleTo::create(1, 1);
		auto seqScale = Sequence::create(scaleUp, scaleDown, NULL);
		auto repScale = RepeatForever::create(seqScale);
		labelA->runAction(repScale);
		labelB->runAction(repScale->clone());
		labelC->runAction(repScale->clone());

		menuItems.pushBack(mLabelA);
		menuItems.pushBack(mLabelB);
		menuItems.pushBack(mLabelC);
		Menu * menu = Menu::createWithArray(menuItems);
		menu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height / 2));
		menu->alignItemsVerticallyWithPadding(-20);
		menu->setEnabled(false);

		menu->setOpacity(100);
		bg->addChild(menu);

		auto scaleTo1 = ScaleTo::create(1.3, 1);
		int vLevel = 2;
		int hLevel = 1;
		for (int i = 1; i <= number; i++)
		{
			auto planet = Planet::create(-1);
			planet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height / 3));
			bg->addChild(planet);
			hLevel++;
			if (i == 5)
			{
				vLevel = 1;
				hLevel = 1;
			}
			planet->setScale(0.01);
			TargetedAction * tA = TargetedAction::create(planet, scaleTo1);
			allActions.pushBack(tA);
			auto playAudio = CallFunc::create([this, i]() {
				auto audio = SimpleAudioEngine::getInstance();
				audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
			});
			allActions.pushBack(playAudio);
		}
		auto * delay = DelayTime::create(1);
		allActions.pushBack(delay);

		auto * fadeIn = FadeIn::create(0.5);
		TargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);
		allActions.pushBack(fadeInMenu);

		auto * enableMenuLambda = CallFunc::create([menu]() {
			menu->setEnabled(true);
		});
		allActions.pushBack(enableMenuLambda);

		auto seq = Sequence::create(allActions);
		bg->stopAllActions();
		bg->runAction(seq);
	}
	else if (!hit && isMessagevisible)
	{
		isMessagevisible = false;
		auto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));
		bg->stopAllActions();
		bg->runAction(action);
		bg->removeAllChildren();
	}

	if (hit && !isMessagevisible && consumed)
	{
		isMessagevisible = true;
		auto audio = SimpleAudioEngine::getInstance();
		audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(number) + ".wav").c_str());
	}
}

<commit_msg>Avoid repeated numbers<commit_after>#include "NumberTest.h"
#include "SimpleAudioEngine.h"
#include "LanguageManager.h"
#include "Planet.h"

USING_NS_CC;
using namespace CocosDenshion;

NumberTest * NumberTest::create(int _number, Sprite * _bg)
{
	NumberTest * tip = new NumberTest();

	if (tip && tip->init())
	{
		tip->autorelease();
		tip->initNumberTest(_number, _bg);
		return tip;
	}
	CC_SAFE_DELETE(tip);
	return NULL;
}

NumberTest::~NumberTest()
{

}

void NumberTest::initNumberTest(int _number, Sprite * _bg)
{
	number = _number;
	setupDirector();
	setupBoundary();
	setupSprite();
	setupAudio();
	setupLabel();
	consumed = false;
	this->setScale(0.9);
	bg = _bg;
	BaseObject::initObject();
}

void NumberTest::setupDirector()
{
	visibleSize = Director::getInstance()->getVisibleSize();
	winSize = Director::getInstance()->getWinSize(); //design size?
	frameSize = Director::getInstance()->getOpenGLView()->getFrameSize();
	origin = Director::getInstance()->getVisibleOrigin(); // common to all maps i hope
}

void NumberTest::setupBoundary()
{
	boundary.shape = SHAPE::circle;
	boundary.active = true;
	boundary.r = 20;
}

void NumberTest::setupSprite()
{
	auto sprite = Sprite::createWithSpriteFrameName("tip.png");
	auto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);
	auto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);
	auto seq1 = Sequence::create(moveUp, moveBack, nullptr);
	sprite->runAction(RepeatForever::create(seq1));
	this->addChild(sprite);
}

void NumberTest::setupAudio()
{
	auto audio = SimpleAudioEngine::getInstance();
	audio->preloadEffect("sfx/bot.wav");
	audio->preloadEffect("sfx/correct.wav");
	langCode = "en";
	if (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)
		langCode = "sw";
	for (int i = 0; i <= 10; i++)
	{
		audio->preloadEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
	}
}

void NumberTest::setupLabel()
{
	numberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString("font"), 50);
	numberLabel->setPosition(Vec2(0, 100));
	auto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);
	auto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);
	ActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);
	auto action = RepeatForever::create(bouncingAction);
	numberLabel->runAction(action);
	numberLabel->setVisible(false);
	this->addChild(numberLabel);
}

void NumberTest::update(bool hit)
{
	if (hit && !isMessagevisible && !consumed)
	{
		auto audio = SimpleAudioEngine::getInstance();
		isMessagevisible = true;
		audio->playEffect("sfx/bot.wav");

		Vector<FiniteTimeAction *>  allActions;
		auto action = MoveTo::create(1.5, Vec2(0, 0));
		TargetedAction * t1 = TargetedAction::create(bg, action);
		allActions.pushBack(t1);

		Vector<MenuItem *> menuItems;
		auto wrongChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/hurt.wav");
		};
		auto rightChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/correct.wav");
			auto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));
			bg->runAction(moveUp);
			consumed = true;
			numberLabel->setVisible(true);
		};

		int n = -1;
		int n2 = -1;
		int correctPicked = RandomHelper::random_int(1, 3);
		Label * labelA = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelA->setScale(0.9);
		MenuItemLabel * mLabelA;
		if (correctPicked == 1)
		{
			labelA->setString(std::to_string(number));
			mLabelA = MenuItemLabel::create(labelA, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number)
			{
				n = RandomHelper::random_int(1, 10);
			}
			n2 = n;
			labelA->setString(std::to_string(n));
			mLabelA = MenuItemLabel::create(labelA, wrongChoice);
		}

		Label * labelB = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelB->setScale(0.9);
		MenuItemLabel * mLabelB;
		if (correctPicked == 2)
		{
			labelB->setString(std::to_string(number));
			mLabelB = MenuItemLabel::create(labelB, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number || n == n2)
			{
				n = RandomHelper::random_int(1, 10);
			}
			labelB->setString(std::to_string(n));
			mLabelB = MenuItemLabel::create(labelB, wrongChoice);
		}

		Label * labelC = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelC->setScale(0.9);
		MenuItemLabel * mLabelC;
		if (correctPicked == 3)
		{
			labelC->setString(std::to_string(number));
			mLabelC = MenuItemLabel::create(labelC, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number)
			{
				n = RandomHelper::random_int(1, 10);
			}
			labelC->setString(std::to_string(n));
			mLabelC = MenuItemLabel::create(labelC, wrongChoice);
		}

		auto scaleUp = ScaleTo::create(1, 1.01);
		auto scaleDown = ScaleTo::create(1, 1);
		auto seqScale = Sequence::create(scaleUp, scaleDown, NULL);
		auto repScale = RepeatForever::create(seqScale);
		labelA->runAction(repScale);
		labelB->runAction(repScale->clone());
		labelC->runAction(repScale->clone());

		menuItems.pushBack(mLabelA);
		menuItems.pushBack(mLabelB);
		menuItems.pushBack(mLabelC);
		Menu * menu = Menu::createWithArray(menuItems);
		menu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height / 2));
		menu->alignItemsVerticallyWithPadding(-20);
		menu->setEnabled(false);

		menu->setOpacity(100);
		bg->addChild(menu);

		auto scaleTo1 = ScaleTo::create(1.3, 1);
		int vLevel = 2;
		int hLevel = 1;
		for (int i = 1; i <= number; i++)
		{
			auto planet = Planet::create(-1);
			planet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height / 3));
			bg->addChild(planet);
			hLevel++;
			if (i == 5)
			{
				vLevel = 1;
				hLevel = 1;
			}
			planet->setScale(0.01);
			TargetedAction * tA = TargetedAction::create(planet, scaleTo1);
			allActions.pushBack(tA);
			auto playAudio = CallFunc::create([this, i]() {
				auto audio = SimpleAudioEngine::getInstance();
				audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
			});
			allActions.pushBack(playAudio);
		}
		auto * delay = DelayTime::create(1);
		allActions.pushBack(delay);

		auto * fadeIn = FadeIn::create(0.5);
		TargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);
		allActions.pushBack(fadeInMenu);

		auto * enableMenuLambda = CallFunc::create([menu]() {
			menu->setEnabled(true);
		});
		allActions.pushBack(enableMenuLambda);

		auto seq = Sequence::create(allActions);
		bg->stopAllActions();
		bg->runAction(seq);
	}
	else if (!hit && isMessagevisible)
	{
		isMessagevisible = false;
		auto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));
		bg->stopAllActions();
		bg->runAction(action);
		bg->removeAllChildren();
	}

	if (hit && !isMessagevisible && consumed)
	{
		isMessagevisible = true;
		auto audio = SimpleAudioEngine::getInstance();
		audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(number) + ".wav").c_str());
	}
}

<|endoftext|>