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

#include "mbed_error.h"
#include "rtos_idle.h"

// rt_tid2ptcb is an internal function which we exposed to get TCB for thread id
#undef NULL  //Workaround for conflicting macros in rt_TypeDef.h and stdio.h
#include "rt_TypeDef.h"

extern "C" P_TCB rt_tid2ptcb(osThreadId thread_id);

namespace rtos {

Thread::Thread(osPriority priority,
        uint32_t stack_size, unsigned char *stack_pointer):
        _tid(NULL), _dynamic_stack(stack_pointer == NULL) {
#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
    _thread_def.tpriority = priority;
    _thread_def.stacksize = stack_size;
    _thread_def.stack_pointer = (uint32_t*)stack_pointer;
#endif
}

Thread::Thread(void (*task)(void const *argument), void *argument,
        osPriority priority, uint32_t stack_size, unsigned char *stack_pointer):
        _tid(NULL), _dynamic_stack(stack_pointer == NULL) {
#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
    _thread_def.tpriority = priority;
    _thread_def.stacksize = stack_size;
    _thread_def.stack_pointer = (uint32_t*)stack_pointer;
#endif
    switch (start(task, argument)) {
        case osErrorResource:
            error("OS ran out of threads!\n");
            break;
        case osErrorParameter:
            error("Thread already running!\n");
            break;
        case osErrorNoMemory:
            error("Error allocating the stack memory\n");
        default:
            break;
    }
}

osStatus Thread::start(void (*task)(void const *argument), void *argument) {
    if (_tid != NULL) {
        return osErrorParameter;
    }

#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
    _thread_def.pthread = task;
    if (_thread_def.stack_pointer == NULL) {
        _thread_def.stack_pointer = new uint32_t[_thread_def.stacksize/sizeof(uint32_t)];
        if (_thread_def.stack_pointer == NULL)
            return osErrorNoMemory;
    }

    //Fill the stack with a magic word for maximum usage checking
    for (uint32_t i = 0; i < (_thread_def.stacksize / sizeof(uint32_t)); i++) {
        _thread_def.stack_pointer[i] = 0xE25A2EA5;
    }
#endif
    _tid = osThreadCreate(&_thread_def, argument);
    if (_tid == NULL) {
        if (_dynamic_stack) delete[] (_thread_def.stack_pointer);
        return osErrorResource;
    }
    return osOK;
}

osStatus Thread::terminate() {
    return osThreadTerminate(_tid);
}

osStatus Thread::join() {
    while (true) {
        uint8_t state = get_state();
        if (state == Thread::Inactive || state == osErrorParameter) {
            return osOK;
        }

        osStatus status = yield();
        if (status != osOK) {
            return status;
        }
    }
}

osStatus Thread::set_priority(osPriority priority) {
    return osThreadSetPriority(_tid, priority);
}

osPriority Thread::get_priority() {
    return osThreadGetPriority(_tid);
}

int32_t Thread::signal_set(int32_t signals) {
    return osSignalSet(_tid, signals);
}

int32_t Thread::signal_clr(int32_t signals) {
    return osSignalClear(_tid, signals);
}

Thread::State Thread::get_state() {
#if !defined(__MBED_CMSIS_RTOS_CA9) && !defined(__MBED_CMSIS_RTOS_CM)
#ifdef CMSIS_OS_RTX
    return ((State)_thread_def.tcb.state);
#endif
#else
    uint8_t status;
    status = osThreadGetState(_tid);
    return ((State)status);
#endif
}

uint32_t Thread::stack_size() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    return _thread_def.tcb.priv_stack;
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    return tcb->priv_stack;
#endif
#else
    return 0;
#endif
}

uint32_t Thread::free_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    uint32_t bottom = (uint32_t)_thread_def.tcb.stack;
    return _thread_def.tcb.tsk_stack - bottom;
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    uint32_t bottom = (uint32_t)tcb->stack;
    return tcb->tsk_stack - bottom;
#endif
#else
    return 0;
#endif
}

uint32_t Thread::used_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    uint32_t top = (uint32_t)_thread_def.tcb.stack + _thread_def.tcb.priv_stack;
    return top - _thread_def.tcb.tsk_stack;
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    uint32_t top = (uint32_t)tcb->stack + tcb->priv_stack;
    return top - tcb->tsk_stack;
#endif
#else
    return 0;
#endif
}

uint32_t Thread::max_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    uint32_t high_mark = 0;
    while (_thread_def.tcb.stack[high_mark] == 0xE25A2EA5)
        high_mark++;
    return _thread_def.tcb.priv_stack - (high_mark * 4);
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    uint32_t high_mark = 0;
    while (tcb->stack[high_mark] == 0xE25A2EA5)
        high_mark++;
    return tcb->priv_stack - (high_mark * 4);
#endif
#else
    return 0;
#endif
}

osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) {
    return osSignalWait(signals, millisec);
}

osStatus Thread::wait(uint32_t millisec) {
    return osDelay(millisec);
}

osStatus Thread::yield() {
    return osThreadYield();
}

osThreadId Thread::gettid() {
    return osThreadGetId();
}

void Thread::attach_idle_hook(void (*fptr)(void)) {
    rtos_attach_idle_hook(fptr);
}

Thread::~Thread() {
    terminate();
#ifdef __MBED_CMSIS_RTOS_CM
    if (_dynamic_stack) {
        delete[] (_thread_def.stack_pointer);
    }
#endif
}

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

#include "mbed_error.h"
#include "rtos_idle.h"

// rt_tid2ptcb is an internal function which we exposed to get TCB for thread id
#undef NULL  //Workaround for conflicting macros in rt_TypeDef.h and stdio.h
#include "rt_TypeDef.h"

extern "C" P_TCB rt_tid2ptcb(osThreadId thread_id);

namespace rtos {

Thread::Thread(osPriority priority,
        uint32_t stack_size, unsigned char *stack_pointer):
        _tid(0), _dynamic_stack(stack_pointer == NULL) {
#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
    _thread_def.tpriority = priority;
    _thread_def.stacksize = stack_size;
    _thread_def.stack_pointer = (uint32_t*)stack_pointer;
#endif
}

Thread::Thread(void (*task)(void const *argument), void *argument,
        osPriority priority, uint32_t stack_size, unsigned char *stack_pointer):
        _tid(0), _dynamic_stack(stack_pointer == NULL) {
#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
    _thread_def.tpriority = priority;
    _thread_def.stacksize = stack_size;
    _thread_def.stack_pointer = (uint32_t*)stack_pointer;
#endif
    switch (start(task, argument)) {
        case osErrorResource:
            error("OS ran out of threads!\n");
            break;
        case osErrorParameter:
            error("Thread already running!\n");
            break;
        case osErrorNoMemory:
            error("Error allocating the stack memory\n");
        default:
            break;
    }
}

osStatus Thread::start(void (*task)(void const *argument), void *argument) {
    if (_tid != NULL) {
        return osErrorParameter;
    }

#if defined(__MBED_CMSIS_RTOS_CA9) || defined(__MBED_CMSIS_RTOS_CM)
    _thread_def.pthread = task;
    if (_thread_def.stack_pointer == NULL) {
        _thread_def.stack_pointer = new uint32_t[_thread_def.stacksize/sizeof(uint32_t)];
        if (_thread_def.stack_pointer == NULL)
            return osErrorNoMemory;
    }

    //Fill the stack with a magic word for maximum usage checking
    for (uint32_t i = 0; i < (_thread_def.stacksize / sizeof(uint32_t)); i++) {
        _thread_def.stack_pointer[i] = 0xE25A2EA5;
    }
#endif
    _tid = osThreadCreate(&_thread_def, argument);
    if (_tid == NULL) {
        if (_dynamic_stack) delete[] (_thread_def.stack_pointer);
        return osErrorResource;
    }
    return osOK;
}

osStatus Thread::terminate() {
    return osThreadTerminate(_tid);
}

osStatus Thread::join() {
    while (true) {
        uint8_t state = get_state();
        if (state == Thread::Inactive || state == osErrorParameter) {
            return osOK;
        }

        osStatus status = yield();
        if (status != osOK) {
            return status;
        }
    }
}

osStatus Thread::set_priority(osPriority priority) {
    return osThreadSetPriority(_tid, priority);
}

osPriority Thread::get_priority() {
    return osThreadGetPriority(_tid);
}

int32_t Thread::signal_set(int32_t signals) {
    return osSignalSet(_tid, signals);
}

int32_t Thread::signal_clr(int32_t signals) {
    return osSignalClear(_tid, signals);
}

Thread::State Thread::get_state() {
#if !defined(__MBED_CMSIS_RTOS_CA9) && !defined(__MBED_CMSIS_RTOS_CM)
#ifdef CMSIS_OS_RTX
    return ((State)_thread_def.tcb.state);
#endif
#else
    uint8_t status;
    status = osThreadGetState(_tid);
    return ((State)status);
#endif
}

uint32_t Thread::stack_size() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    return _thread_def.tcb.priv_stack;
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    return tcb->priv_stack;
#endif
#else
    return 0;
#endif
}

uint32_t Thread::free_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    uint32_t bottom = (uint32_t)_thread_def.tcb.stack;
    return _thread_def.tcb.tsk_stack - bottom;
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    uint32_t bottom = (uint32_t)tcb->stack;
    return tcb->tsk_stack - bottom;
#endif
#else
    return 0;
#endif
}

uint32_t Thread::used_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    uint32_t top = (uint32_t)_thread_def.tcb.stack + _thread_def.tcb.priv_stack;
    return top - _thread_def.tcb.tsk_stack;
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    uint32_t top = (uint32_t)tcb->stack + tcb->priv_stack;
    return top - tcb->tsk_stack;
#endif
#else
    return 0;
#endif
}

uint32_t Thread::max_stack() {
#ifndef __MBED_CMSIS_RTOS_CA9
#if defined(CMSIS_OS_RTX) && !defined(__MBED_CMSIS_RTOS_CM)
    uint32_t high_mark = 0;
    while (_thread_def.tcb.stack[high_mark] == 0xE25A2EA5)
        high_mark++;
    return _thread_def.tcb.priv_stack - (high_mark * 4);
#else
    P_TCB tcb = rt_tid2ptcb(_tid);
    uint32_t high_mark = 0;
    while (tcb->stack[high_mark] == 0xE25A2EA5)
        high_mark++;
    return tcb->priv_stack - (high_mark * 4);
#endif
#else
    return 0;
#endif
}

osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) {
    return osSignalWait(signals, millisec);
}

osStatus Thread::wait(uint32_t millisec) {
    return osDelay(millisec);
}

osStatus Thread::yield() {
    return osThreadYield();
}

osThreadId Thread::gettid() {
    return osThreadGetId();
}

void Thread::attach_idle_hook(void (*fptr)(void)) {
    rtos_attach_idle_hook(fptr);
}

Thread::~Thread() {
    terminate();
#ifdef __MBED_CMSIS_RTOS_CM
    if (_dynamic_stack) {
        delete[] (_thread_def.stack_pointer);
    }
#endif
}

}
<|endoftext|>


<commit_before><commit_msg>Final.<commit_after><|endoftext|>


<commit_before>/****************************************************************************
 *   Copyright (C) 2011  Andreas Kling <awesomekling@gmail.com>             *
 *   Copyright (C) 2011  Instituto Nokia de Tecnologia (INdT)               *
 *                                                                          *
 *   This file may be used under the terms of the GNU Lesser                *
 *   General Public License version 2.1 as published by the Free Software   *
 *   Foundation and appearing in the file LICENSE.LGPL included in the      *
 *   packaging of this file.  Please review the following information to    *
 *   ensure the GNU Lesser General Public License version 2.1 requirements  *
 *   will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.   *
 *                                                                          *
 *   This program is distributed in the hope that it will be useful,        *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *   GNU Lesser General Public License for more details.                    *
 ****************************************************************************/

#include "MainView.h"

#include "BrowserWindow.h"
#include "DeclarativeDesktopWebView.h"
#include "TripleClickMonitor.h"

#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeItem>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QLineEdit>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>

#include <QUrl>

// Keeping this feature commented out until we have support for it in the new API.
//QWKPage* newPageCallback(QWKPage* parentPage)
//{
//    BrowserWindow* window = BrowserWindow::create(parentPage->context());
//    PageWidget* page = window->openNewTab();
//    window->show();
//    return page->page();
//}

MainView::MainView(QWidget* parent)
    : QDeclarativeView(parent)
    , m_tabWidget(0)
{
    setResizeMode(QDeclarativeView::SizeRootObjectToView);
    setSource(QUrl("qrc:/qml/main.qml"));

    connect(engine(), SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));

    m_tabWidget = qobject_cast<QDeclarativeItem*>(rootObject());
    Q_ASSERT(m_tabWidget);

    connect(m_tabWidget, SIGNAL(tabAdded(QVariant)), this, SLOT(onTabAdded(QVariant)));
    connect(m_tabWidget, SIGNAL(currentTabChanged()), this, SLOT(onCurrentTabChanged()));

    onTabAdded(m_tabWidget->property("currentActiveTab"));

    QAction* focusLocationBarAction = new QAction(this);
    focusLocationBarAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L));
    connect(focusLocationBarAction, SIGNAL(triggered()), this, SLOT(focusUrlBarRequested()));
    addAction(focusLocationBarAction);

    QAction* newTabAction = new QAction(this);
    newTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_T));
    connect(newTabAction, SIGNAL(triggered()), this, SLOT(newTabRequested()));
    addAction(newTabAction);

    QAction* closeTabAction = new QAction(this);
    closeTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_W));
    connect(closeTabAction, SIGNAL(triggered()), this, SLOT(closeTabRequested()));
    addAction(closeTabAction);

//    page()->setCreateNewPageFunction(newPageCallback);
}

MainView::~MainView()
{
}

void MainView::openInNewTab(const QString& urlFromUserInput)
{
    QUrl url = QUrl::fromUserInput(urlFromUserInput);
    if (!url.isEmpty()) {
        QObject* currentActiveTab = m_tabWidget->property("currentActiveTab").value<QObject*>();
        QObject* mainView = currentActiveTab->property("mainView").value<QObject*>();
        QObject* urlEdit = mainView->findChild<QDeclarativeItem*>("urlEdit");
        urlEdit->setProperty("text", url.toString());
        getWebViewForUrlEdit(urlEdit)->setUrl(url);
    }
}

void MainView::jumpToNextTab()
{
    QMetaObject::invokeMethod(m_tabWidget, "jumpToNextTab");
}

void MainView::jumpToPreviousTab()
{
    QMetaObject::invokeMethod(m_tabWidget, "jumpToPreviousTab");
}

void MainView::onTabAdded(QVariant tab)
{
    QObject* mainView = tab.value<QObject*>()->property("mainView").value<QObject*>();
    QDeclarativeItem* urlEdit = mainView->findChild<QDeclarativeItem*>("urlEdit");
    connect(urlEdit, SIGNAL(urlEntered(QString)), this, SLOT(onUrlChanged(QString)));
    QObject* webView = getWebViewForUrlEdit(urlEdit);
    connect(webView, SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString)));
    QDeclarativeItem* urlInput = urlEdit->findChild<QDeclarativeItem*>("urlInput");
    TripleClickMonitor* urlEditMonitor = new TripleClickMonitor(mainView);
    urlInput->installEventFilter(urlEditMonitor);
    connect(urlEditMonitor, SIGNAL(tripleClicked()), urlInput, SLOT(selectAll()));
}

void MainView::onCurrentTabChanged()
{
    QObject* currentActiveTab = m_tabWidget->property("currentActiveTab").value<QObject*>();
    emit titleChanged(currentActiveTab->property("text").toString());
}

void MainView::onTitleChanged(const QString& title)
{
    emit titleChanged(title);
}

DeclarativeDesktopWebView* MainView::getWebViewForUrlEdit(QObject* urlEdit)
{
    QObject* view = urlEdit->property("view").value<QObject*>();
    return qobject_cast<DeclarativeDesktopWebView* >(view);
}

void MainView::onUrlChanged(const QString& url)
{
    getWebViewForUrlEdit(sender())->setUrl(QUrl::fromUserInput(url));
}

void MainView::newTabRequested()
{
    QMetaObject::invokeMethod(m_tabWidget, "addNewTab");
}

void MainView::closeTabRequested()
{
    QMetaObject::invokeMethod(m_tabWidget, "closeTab", Q_ARG(QVariant, m_tabWidget->property("currentActiveTab")));
}

void MainView::focusUrlBarRequested()
{
    QObject* currentActiveTab = m_tabWidget->property("currentActiveTab").value<QObject*>();
    QObject* mainView = currentActiveTab->property("mainView").value<QObject*>();
    QMetaObject::invokeMethod(mainView, "focusUrlBar");
}
<commit_msg>Remove commented code<commit_after>/****************************************************************************
 *   Copyright (C) 2011  Andreas Kling <awesomekling@gmail.com>             *
 *   Copyright (C) 2011  Instituto Nokia de Tecnologia (INdT)               *
 *                                                                          *
 *   This file may be used under the terms of the GNU Lesser                *
 *   General Public License version 2.1 as published by the Free Software   *
 *   Foundation and appearing in the file LICENSE.LGPL included in the      *
 *   packaging of this file.  Please review the following information to    *
 *   ensure the GNU Lesser General Public License version 2.1 requirements  *
 *   will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.   *
 *                                                                          *
 *   This program is distributed in the hope that it will be useful,        *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *   GNU Lesser General Public License for more details.                    *
 ****************************************************************************/

#include "MainView.h"

#include "BrowserWindow.h"
#include "DeclarativeDesktopWebView.h"
#include "TripleClickMonitor.h"

#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeItem>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QLineEdit>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>

#include <QUrl>

MainView::MainView(QWidget* parent)
    : QDeclarativeView(parent)
    , m_tabWidget(0)
{
    setResizeMode(QDeclarativeView::SizeRootObjectToView);
    setSource(QUrl("qrc:/qml/main.qml"));

    connect(engine(), SIGNAL(quit()), QCoreApplication::instance(), SLOT(quit()));

    m_tabWidget = qobject_cast<QDeclarativeItem*>(rootObject());
    Q_ASSERT(m_tabWidget);

    connect(m_tabWidget, SIGNAL(tabAdded(QVariant)), this, SLOT(onTabAdded(QVariant)));
    connect(m_tabWidget, SIGNAL(currentTabChanged()), this, SLOT(onCurrentTabChanged()));

    onTabAdded(m_tabWidget->property("currentActiveTab"));

    QAction* focusLocationBarAction = new QAction(this);
    focusLocationBarAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_L));
    connect(focusLocationBarAction, SIGNAL(triggered()), this, SLOT(focusUrlBarRequested()));
    addAction(focusLocationBarAction);

    QAction* newTabAction = new QAction(this);
    newTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_T));
    connect(newTabAction, SIGNAL(triggered()), this, SLOT(newTabRequested()));
    addAction(newTabAction);

    QAction* closeTabAction = new QAction(this);
    closeTabAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_W));
    connect(closeTabAction, SIGNAL(triggered()), this, SLOT(closeTabRequested()));
    addAction(closeTabAction);
}

MainView::~MainView()
{
}

void MainView::openInNewTab(const QString& urlFromUserInput)
{
    QUrl url = QUrl::fromUserInput(urlFromUserInput);
    if (!url.isEmpty()) {
        QObject* currentActiveTab = m_tabWidget->property("currentActiveTab").value<QObject*>();
        QObject* mainView = currentActiveTab->property("mainView").value<QObject*>();
        QObject* urlEdit = mainView->findChild<QDeclarativeItem*>("urlEdit");
        urlEdit->setProperty("text", url.toString());
        getWebViewForUrlEdit(urlEdit)->setUrl(url);
    }
}

void MainView::jumpToNextTab()
{
    QMetaObject::invokeMethod(m_tabWidget, "jumpToNextTab");
}

void MainView::jumpToPreviousTab()
{
    QMetaObject::invokeMethod(m_tabWidget, "jumpToPreviousTab");
}

void MainView::onTabAdded(QVariant tab)
{
    QObject* mainView = tab.value<QObject*>()->property("mainView").value<QObject*>();
    QDeclarativeItem* urlEdit = mainView->findChild<QDeclarativeItem*>("urlEdit");
    connect(urlEdit, SIGNAL(urlEntered(QString)), this, SLOT(onUrlChanged(QString)));
    QObject* webView = getWebViewForUrlEdit(urlEdit);
    connect(webView, SIGNAL(titleChanged(QString)), this, SIGNAL(titleChanged(QString)));
    QDeclarativeItem* urlInput = urlEdit->findChild<QDeclarativeItem*>("urlInput");
    TripleClickMonitor* urlEditMonitor = new TripleClickMonitor(mainView);
    urlInput->installEventFilter(urlEditMonitor);
    connect(urlEditMonitor, SIGNAL(tripleClicked()), urlInput, SLOT(selectAll()));
}

void MainView::onCurrentTabChanged()
{
    QObject* currentActiveTab = m_tabWidget->property("currentActiveTab").value<QObject*>();
    emit titleChanged(currentActiveTab->property("text").toString());
}

void MainView::onTitleChanged(const QString& title)
{
    emit titleChanged(title);
}

DeclarativeDesktopWebView* MainView::getWebViewForUrlEdit(QObject* urlEdit)
{
    QObject* view = urlEdit->property("view").value<QObject*>();
    return qobject_cast<DeclarativeDesktopWebView* >(view);
}

void MainView::onUrlChanged(const QString& url)
{
    getWebViewForUrlEdit(sender())->setUrl(QUrl::fromUserInput(url));
}

void MainView::newTabRequested()
{
    QMetaObject::invokeMethod(m_tabWidget, "addNewTab");
}

void MainView::closeTabRequested()
{
    QMetaObject::invokeMethod(m_tabWidget, "closeTab", Q_ARG(QVariant, m_tabWidget->property("currentActiveTab")));
}

void MainView::focusUrlBarRequested()
{
    QObject* currentActiveTab = m_tabWidget->property("currentActiveTab").value<QObject*>();
    QObject* mainView = currentActiveTab->property("mainView").value<QObject*>();
    QMetaObject::invokeMethod(mainView, "focusUrlBar");
}
<|endoftext|>


<commit_before>#include "Neohuman.h"
#include <iostream>

#include "BWEM/bwem.h"

using namespace BWAPI;
using namespace Filter;

using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;

#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))

#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200

#define SHOWTHINGS

namespace { auto & BWEMMap = Map::Instance(); }

bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
	_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
}

std::pair <int, int> Neohuman::getQueuedResources() {
	std::pair <int, int> resources;
	for (auto &o : _buildingQueue)
		resources.first  += o.second.mineralPrice(),
		resources.second += o.second.gasPrice();
	return resources;
}

std::pair <int, int> Neohuman::getSpendableResources() const {
	std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
	auto queued = this->getQueuedResources();
	result.first -= queued.first, result.second -= queued.second;
	return result;
}

void Neohuman::onStart() {
	Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;

	//Broodwar->enableFlag(Flag::UserInput);

	// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
	//Broodwar->enableFlag(Flag::CompleteMapInformation);

	// Set the command optimization level so that common commands can be grouped
	// and reduce the bot's APM (Actions Per Minute).
	Broodwar->setCommandOptimizationLevel(2);

	// Check if this is a replay
	if (!Broodwar->isReplay()) {
		if (Broodwar->enemy())
			Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
	}

	BWEMMap.Initialize();
	BWEMMap.EnableAutomaticPathAnalysis();

}

void Neohuman::onEnd(bool didWin) {
	// Called when the game ends
	if (didWin) {

	} else {

	}
}

int Neohuman::randint(int min, int max) {
	std::uniform_int_distribution<int> dist(min, max);
	return dist(_rand);
}

template <typename T>
T Neohuman::randele(std::vector <T> &v) {
	return v[randint(0, v.size())];
}

void Neohuman::onFrame() {
	// Called once every game frame
	int constructingLine = 0;
	int availableMinerals = Broodwar->self()->minerals();

#ifdef SHOWTHINGS

	// Display the game frame rate as text in the upper left area of the screen
	Broodwar->drawTextScreen(200, 0,  "FPS: %d", Broodwar->getFPS());
	Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
	Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
	Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);

#endif

	try {
		//BWEM::utils::gridMapExample(BWEMMap);
		//BWEM::utils::drawMap(BWEMMap);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}

	// Return if the game is a replay or is paused
	if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
		return;

	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->exists() && u->isBeingConstructed()) {
			Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
			constructingLine += 12;
		}
	}

#ifdef SHOWTHINGS

	// Show worker info
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->getType().isResourceDepot()) {
			Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
			auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
			auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
			auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
			auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
			Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
		}
	}

#endif

	// Prevent spamming by only running our onFrame once every number of latency frames.
	// Latency frames are the number of frames before commands are processed.
	if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
		return;

	_supplyBeingMade = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
			_supplyBeingMade += 8;
	}

	availableMinerals -= 100*_queuedSupply/8;

	if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
		_queuedSupply = 0;
		_timeLastQueuedSupply = Broodwar->elapsedTime();
	}

	_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
	_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;

	_nBarracks = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		// If a cc is under construction
		if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
			availableMinerals += 400;
		// If a barracks is under construction
		if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
			availableMinerals += 150;

		if (u->getType() == UnitTypes::Terran_Barracks) {
			++_nBarracks;
		}
	}

	if (_isExpanding) {
		availableMinerals -= 400;
	}

	if (_isBuildingBarracks) {
		availableMinerals -= 150;
	}

	int nWorkers = 0;
	for (auto &u : Broodwar->getAllUnits()) {
		if (u->getType() == u->getType().getRace().getWorker() && u->getPlayer() == Broodwar->self()) {
			++nWorkers;
		}
	}

	// Check if supply should be increased
	if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
		// Find unit to build our supply!
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
				// We have found our candidate!
				auto supplyType = unit->getType().getRace().getSupplyProvider();
				auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());

				if (unit->build(supplyType, buildPos)) {
					_queuedSupply += 8;
					_timeLastQueuedSupply = Broodwar->elapsedTime();
					break;
				}
			}
		}
	}

	if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
		// Build barracks!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				auto buildingType = UnitTypes::Terran_Barracks;
				auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildingPos)) {
					_isBuildingBarracks = true;
					availableMinerals -= 150;
					break;
				}
			}
		}
	}

	/*if (!_isExpanding && availableMinerals >= 400){
		// Expand!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				// Builder found!
				auto buildingType = u->getType().getRace().getCenter();
				auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildPos)) {
					_isExpanding = true;
					availableMinerals -= 400;
					break;
				}
			}
		}
	}*/

	// Iterate through all the units that we own
	for (auto &u : Broodwar->self()->getUnits()) {
		// Ignore the unit if it no longer exists
		// Make sure to include this block when handling any Unit pointer!
		if (!u->exists())
			continue;

		// Ignore the unit if it has one of the following status ailments
		if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
			continue;

		// Ignore the unit if it is in one of the following states
		if (u->isLoaded() || !u->isPowered() || u->isStuck())
			continue;

		// Ignore the unit if it is incomplete or busy constructing
		if (!u->isCompleted() || u->isConstructing())
			continue;

		// If the unit is a worker unit
		if (u->getType().isWorker()) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
			if (enemyUnit)
				u->attack(enemyUnit);

			// if our worker is idle
			if (u->isIdle()) {
				// Order workers carrying a resource to return them to the center,
				// otherwise find a mineral patch to harvest.
				if (u->isCarryingGas() || u->isCarryingMinerals())
					u->returnCargo();

				else if (!u->getPowerUp()) {
					// Probably need to set up some better logic for this
					auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
					u->gather(preferredMiningLocation);
				}
			}
		} else if (u->getType().isResourceDepot()) {
			auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
			if (u->isIdle()) {
				auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
				if (nWorkers >= 70)
					continue;
				auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
				if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
					if (u->train(u->getType().getRace().getWorker())) {
						Position pos = u->getPosition();
						Error lastErr = Broodwar->getLastError();
						Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); },   // action
							nullptr,    // condition
							Broodwar->getLatencyFrames());  // frames to run
					} else {
						availableMinerals -= 50;
					}
				}
			}
		} else if (u->getType() == UnitTypes::Terran_Barracks) {
			if (u->isIdle() && availableMinerals >= 50)
				if (!u->train(UnitTypes::Terran_Marine))
					availableMinerals -= 50;
		} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			enemyUnit = u->getClosestUnit(IsEnemy);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
			if (closestMarine) {
				auto walk = u->getPosition() - closestMarine->getPosition();
				u->move(u->getPosition() + walk);
			}
		}
	}
}

void Neohuman::onSendText(std::string text) {
	Broodwar->sendText("%s", text.c_str());
}

void Neohuman::onReceiveText(Player player, std::string text) {
	Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}

void Neohuman::onPlayerLeft(Player player) {
	Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}

void Neohuman::onNukeDetect(Position target) {
	if (target) {
		Broodwar << "Nuclear Launch Detected at " << target << std::endl;
	} else {
		Broodwar->sendText("Where's the nuke?");
	}
	// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}

void Neohuman::onUnitDiscover(Unit unit) {
}

void Neohuman::onUnitEvade(Unit unit) {
}

void Neohuman::onUnitShow(Unit unit) {
}

void Neohuman::onUnitHide(Unit unit) {
}

void Neohuman::onUnitCreate(Unit unit) {
}

void Neohuman::onUnitDestroy(Unit unit) {
	try {
		if (unit->getType().isMineralField())			BWEMMap.OnMineralDestroyed(unit);
		else if (unit->getType().isSpecialBuilding())	BWEMMap.OnStaticBuildingDestroyed(unit);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}
}

void Neohuman::onUnitMorph(Unit unit) {
	this->onUnitComplete(unit);
}

void Neohuman::onUnitRenegade(Unit unit){
}

void Neohuman::onSaveGame(std::string gameName){
}

void Neohuman::onUnitComplete(Unit unit){
	if (unit->getType() == unit->getType().getRace().getCenter())
		_isExpanding = false;
	if (unit->getType() == UnitTypes::Terran_Barracks)
		_isBuildingBarracks = false;
}
<commit_msg>And some more small edits<commit_after>#include "Neohuman.h"
#include <iostream>

#include "BWEM/bwem.h"

using namespace BWAPI;
using namespace Filter;

using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;

#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))

#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200

#define SHOWTHINGS

namespace { auto & BWEMMap = Map::Instance(); }

bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
	_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
	return Broodwar->canBuildHere(at, building);
}

std::pair <int, int> Neohuman::getQueuedResources() const {
	std::pair <int, int> resources;
	for (auto &o : _buildingQueue)
		resources.first  += o.second.mineralPrice(),
		resources.second += o.second.gasPrice();
	return resources;
}

std::pair <int, int> Neohuman::getSpendableResources() const {
	std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
	auto queued = this->getQueuedResources();
	result.first -= queued.first, result.second -= queued.second;
	return result;
}

void Neohuman::onStart() {
	Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;

	//Broodwar->enableFlag(Flag::UserInput);

	// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
	//Broodwar->enableFlag(Flag::CompleteMapInformation);

	// Set the command optimization level so that common commands can be grouped
	// and reduce the bot's APM (Actions Per Minute).
	Broodwar->setCommandOptimizationLevel(2);

	// Check if this is a replay
	if (!Broodwar->isReplay()) {
		if (Broodwar->enemy())
			Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
	}

	BWEMMap.Initialize();
	BWEMMap.EnableAutomaticPathAnalysis();

}

void Neohuman::onEnd(bool didWin) {
	// Called when the game ends
	if (didWin) {

	} else {

	}
}

int Neohuman::randint(int min, int max) {
	std::uniform_int_distribution<int> dist(min, max);
	return dist(_rand);
}

template <typename T>
T Neohuman::randele(std::vector <T> &v) {
	return v[randint(0, v.size())];
}

void Neohuman::onFrame() {
	// Called once every game frame
	int constructingLine = 0;
	int availableMinerals = Broodwar->self()->minerals();

#ifdef SHOWTHINGS

	// Display the game frame rate as text in the upper left area of the screen
	Broodwar->drawTextScreen(200, 0,  "FPS: %d", Broodwar->getFPS());
	Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
	Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
	Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);

#endif

	try {
		//BWEM::utils::gridMapExample(BWEMMap);
		//BWEM::utils::drawMap(BWEMMap);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}

	// Return if the game is a replay or is paused
	if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
		return;

	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->exists() && u->isBeingConstructed()) {
			Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
			constructingLine += 12;
		}
	}

#ifdef SHOWTHINGS

	// Show worker info
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->getType().isResourceDepot()) {
			Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
			auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
			auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
			auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
			auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
			Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
		}
	}

#endif

	// Prevent spamming by only running our onFrame once every number of latency frames.
	// Latency frames are the number of frames before commands are processed.
	if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
		return;

	_supplyBeingMade = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
			_supplyBeingMade += 8;
	}

	availableMinerals -= 100*_queuedSupply/8;

	if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
		_queuedSupply = 0;
		_timeLastQueuedSupply = Broodwar->elapsedTime();
	}

	_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
	_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;

	_nBarracks = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		// If a cc is under construction
		if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
			availableMinerals += 400;
		// If a barracks is under construction
		if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
			availableMinerals += 150;

		if (u->getType() == UnitTypes::Terran_Barracks) {
			++_nBarracks;
		}
	}

	if (_isExpanding) {
		availableMinerals -= 400;
	}

	if (_isBuildingBarracks) {
		availableMinerals -= 150;
	}

	int nWorkers = 0;
	for (auto &u : Broodwar->getAllUnits()) {
		if (u->getType() == u->getType().getRace().getWorker() && u->getPlayer() == Broodwar->self()) {
			++nWorkers;
		}
	}

	// Check if supply should be increased
	if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
		// Find unit to build our supply!
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
				// We have found our candidate!
				auto supplyType = unit->getType().getRace().getSupplyProvider();
				auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());

				if (unit->build(supplyType, buildPos)) {
					_queuedSupply += 8;
					_timeLastQueuedSupply = Broodwar->elapsedTime();
					break;
				}
			}
		}
	}

	if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
		// Build barracks!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				auto buildingType = UnitTypes::Terran_Barracks;
				auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildingPos)) {
					_isBuildingBarracks = true;
					availableMinerals -= 150;
					break;
				}
			}
		}
	}

	/*if (!_isExpanding && availableMinerals >= 400){
		// Expand!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				// Builder found!
				auto buildingType = u->getType().getRace().getCenter();
				auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildPos)) {
					_isExpanding = true;
					availableMinerals -= 400;
					break;
				}
			}
		}
	}*/

	// Iterate through all the units that we own
	for (auto &u : Broodwar->self()->getUnits()) {
		// Ignore the unit if it no longer exists
		// Make sure to include this block when handling any Unit pointer!
		if (!u->exists())
			continue;

		// Ignore the unit if it has one of the following status ailments
		if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
			continue;

		// Ignore the unit if it is in one of the following states
		if (u->isLoaded() || !u->isPowered() || u->isStuck())
			continue;

		// Ignore the unit if it is incomplete or busy constructing
		if (!u->isCompleted() || u->isConstructing())
			continue;

		// If the unit is a worker unit
		if (u->getType().isWorker()) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
			if (enemyUnit)
				u->attack(enemyUnit);

			// if our worker is idle
			if (u->isIdle()) {
				// Order workers carrying a resource to return them to the center,
				// otherwise find a mineral patch to harvest.
				if (u->isCarryingGas() || u->isCarryingMinerals())
					u->returnCargo();

				else if (!u->getPowerUp()) {
					// Probably need to set up some better logic for this
					auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
					u->gather(preferredMiningLocation);
				}
			}
		} else if (u->getType().isResourceDepot()) {
			auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
			if (u->isIdle()) {
				auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
				if (nWorkers >= 70)
					continue;
				auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
				if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
					if (u->train(u->getType().getRace().getWorker())) {
						Position pos = u->getPosition();
						Error lastErr = Broodwar->getLastError();
						Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); },   // action
							nullptr,    // condition
							Broodwar->getLatencyFrames());  // frames to run
					} else {
						availableMinerals -= 50;
					}
				}
			}
		} else if (u->getType() == UnitTypes::Terran_Barracks) {
			if (u->isIdle() && availableMinerals >= 50)
				if (!u->train(UnitTypes::Terran_Marine))
					availableMinerals -= 50;
		} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			enemyUnit = u->getClosestUnit(IsEnemy);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
			if (closestMarine) {
				auto walk = u->getPosition() - closestMarine->getPosition();
				u->move(u->getPosition() + walk);
			}
		}
	}
}

void Neohuman::onSendText(std::string text) {
	Broodwar->sendText("%s", text.c_str());
}

void Neohuman::onReceiveText(Player player, std::string text) {
	Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}

void Neohuman::onPlayerLeft(Player player) {
	Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}

void Neohuman::onNukeDetect(Position target) {
	if (target) {
		Broodwar << "Nuclear Launch Detected at " << target << std::endl;
	} else {
		Broodwar->sendText("Where's the nuke?");
	}
	// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}

void Neohuman::onUnitDiscover(Unit unit) {
}

void Neohuman::onUnitEvade(Unit unit) {
}

void Neohuman::onUnitShow(Unit unit) {
}

void Neohuman::onUnitHide(Unit unit) {
}

void Neohuman::onUnitCreate(Unit unit) {
}

void Neohuman::onUnitDestroy(Unit unit) {
	try {
		if (unit->getType().isMineralField())			BWEMMap.OnMineralDestroyed(unit);
		else if (unit->getType().isSpecialBuilding())	BWEMMap.OnStaticBuildingDestroyed(unit);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}
}

void Neohuman::onUnitMorph(Unit unit) {
	this->onUnitComplete(unit);
}

void Neohuman::onUnitRenegade(Unit unit){
}

void Neohuman::onSaveGame(std::string gameName){
}

void Neohuman::onUnitComplete(Unit unit){
	if (unit->getType() == unit->getType().getRace().getCenter())
		_isExpanding = false;
	if (unit->getType() == UnitTypes::Terran_Barracks)
		_isBuildingBarracks = false;
}
<|endoftext|>


<commit_before>// Copyright (c) 2020 The Orbit 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 "OrbitCaptureClient/CaptureClient.h"

#include "FunctionUtils.h"
#include "OrbitBase/Logging.h"

#include "absl/flags/flag.h"

ABSL_DECLARE_FLAG(uint16_t, sampling_rate);
ABSL_DECLARE_FLAG(bool, frame_pointer_unwinding);

using orbit_client_protos::FunctionInfo;

void CaptureClient::Capture(
    int32_t pid, const std::map<uint64_t, FunctionInfo*>& selected_functions) {
  CHECK(reader_writer_ == nullptr);

  event_processor_.emplace(capture_listener_);

  grpc::ClientContext context;
  reader_writer_ = capture_service_->Capture(&context);

  CaptureRequest request;
  CaptureOptions* capture_options = request.mutable_capture_options();
  capture_options->set_trace_context_switches(true);
  capture_options->set_pid(pid);
  uint16_t sampling_rate = absl::GetFlag(FLAGS_sampling_rate);
  if (sampling_rate == 0) {
    capture_options->set_unwinding_method(CaptureOptions::kUndefined);
  } else {
    capture_options->set_sampling_rate(sampling_rate);
    if (absl::GetFlag(FLAGS_frame_pointer_unwinding)) {
      capture_options->set_unwinding_method(CaptureOptions::kFramePointers);
    } else {
      capture_options->set_unwinding_method(CaptureOptions::kDwarf);
    }
  }
  capture_options->set_trace_gpu_driver(true);
  for (const auto& pair : selected_functions) {
    const FunctionInfo& function = *pair.second;
    CaptureOptions::InstrumentedFunction* instrumented_function =
        capture_options->add_instrumented_functions();
    instrumented_function->set_file_path(function.loaded_module_path());
    instrumented_function->set_file_offset(FunctionUtils::Offset(function));
    instrumented_function->set_absolute_address(
        FunctionUtils::GetAbsoluteAddress(function));
  }

  if (!reader_writer_->Write(request)) {
    ERROR("Sending CaptureRequest on Capture's gRPC stream");
    reader_writer_->WritesDone();
    FinishCapture();
    return;
  }
  LOG("Sent CaptureRequest on Capture's gRPC stream: asking to start "
      "capturing");

  CaptureResponse response;
  while (reader_writer_->Read(&response)) {
    event_processor_->ProcessEvents(response.capture_events());
  }
  LOG("Finished reading from Capture's gRPC stream: all capture data has been "
      "received");
  FinishCapture();
}

void CaptureClient::StopCapture() {
  CHECK(reader_writer_ != nullptr);

  if (!reader_writer_->WritesDone()) {
    ERROR("Finishing writing on Capture's gRPC stream");
    FinishCapture();
  }
  LOG("Finished writing on Capture's gRPC stream: asking to stop capturing");
}

void CaptureClient::FinishCapture() {
  if (reader_writer_ == nullptr) {
    return;
  }

  grpc::Status status = reader_writer_->Finish();
  if (!status.ok()) {
    ERROR("Finishing gRPC call to Capture: %s", status.error_message());
  }
  reader_writer_.reset();
  event_processor_.reset();
}<commit_msg>check selected functions for nullptr when start a capture<commit_after>// Copyright (c) 2020 The Orbit 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 "OrbitCaptureClient/CaptureClient.h"

#include "FunctionUtils.h"
#include "OrbitBase/Logging.h"

#include "absl/flags/flag.h"

ABSL_DECLARE_FLAG(uint16_t, sampling_rate);
ABSL_DECLARE_FLAG(bool, frame_pointer_unwinding);

using orbit_client_protos::FunctionInfo;

void CaptureClient::Capture(
    int32_t pid, const std::map<uint64_t, FunctionInfo*>& selected_functions) {
  CHECK(reader_writer_ == nullptr);

  event_processor_.emplace(capture_listener_);

  grpc::ClientContext context;
  reader_writer_ = capture_service_->Capture(&context);

  CaptureRequest request;
  CaptureOptions* capture_options = request.mutable_capture_options();
  capture_options->set_trace_context_switches(true);
  capture_options->set_pid(pid);
  uint16_t sampling_rate = absl::GetFlag(FLAGS_sampling_rate);
  if (sampling_rate == 0) {
    capture_options->set_unwinding_method(CaptureOptions::kUndefined);
  } else {
    capture_options->set_sampling_rate(sampling_rate);
    if (absl::GetFlag(FLAGS_frame_pointer_unwinding)) {
      capture_options->set_unwinding_method(CaptureOptions::kFramePointers);
    } else {
      capture_options->set_unwinding_method(CaptureOptions::kDwarf);
    }
  }
  capture_options->set_trace_gpu_driver(true);
  for (const auto& pair : selected_functions) {
    const FunctionInfo* function = pair.second;
    if (function == nullptr) {
      continue;
    }
    CaptureOptions::InstrumentedFunction* instrumented_function =
        capture_options->add_instrumented_functions();
    instrumented_function->set_file_path(function->loaded_module_path());
    instrumented_function->set_file_offset(FunctionUtils::Offset(*function));
    instrumented_function->set_absolute_address(
        FunctionUtils::GetAbsoluteAddress(*function));
  }

  if (!reader_writer_->Write(request)) {
    ERROR("Sending CaptureRequest on Capture's gRPC stream");
    reader_writer_->WritesDone();
    FinishCapture();
    return;
  }
  LOG("Sent CaptureRequest on Capture's gRPC stream: asking to start "
      "capturing");

  CaptureResponse response;
  while (reader_writer_->Read(&response)) {
    event_processor_->ProcessEvents(response.capture_events());
  }
  LOG("Finished reading from Capture's gRPC stream: all capture data has been "
      "received");
  FinishCapture();
}

void CaptureClient::StopCapture() {
  CHECK(reader_writer_ != nullptr);

  if (!reader_writer_->WritesDone()) {
    ERROR("Finishing writing on Capture's gRPC stream");
    FinishCapture();
  }
  LOG("Finished writing on Capture's gRPC stream: asking to stop capturing");
}

void CaptureClient::FinishCapture() {
  if (reader_writer_ == nullptr) {
    return;
  }

  grpc::Status status = reader_writer_->Finish();
  if (!status.ok()) {
    ERROR("Finishing gRPC call to Capture: %s", status.error_message());
  }
  reader_writer_.reset();
  event_processor_.reset();
}<|endoftext|>


<commit_before>//===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting arm_neon.h, which includes
// a declaration and definition of each function specified by the ARM NEON
// compiler interface.  See ARM document DUI0348B.
//
//===----------------------------------------------------------------------===//

#include "NeonEmitter.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include <string>

using namespace llvm;

void NeonEmitter::run(raw_ostream &OS) {
  EmitSourceFileHeader("ARM NEON Header", OS);

  // FIXME: emit license into file?

  OS << "#ifndef __ARM_NEON_H\n";
  OS << "#define __ARM_NEON_H\n\n";

  OS << "#ifndef __ARM_NEON__\n";
  OS << "#error \"NEON support not enabled\"\n";
  OS << "#endif\n\n";

  OS << "#include <stdint.h>\n\n";

  // EmitTypedefs(OS);

  // Process Records

  std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");

  // Unique the pattern types, and assign them

  // emit #define directives for uniq'd prototypes

  // emit record directives

  for (unsigned i = 0, e = RV.size(); i != e; ++i) {
    Record *R = RV[i];

    OS << LowercaseString(R->getName()) << "\n";

    std::string Types = R->getValueAsString("Types");
    std::string Pattern = R->getValueAsString("Pattern");

    OS << Types << "\n" << Pattern << "\n\n";
  }

  OS << "#endif /* __ARM_NEON_H */\n";
}
<commit_msg>Comment out some code in prep for actual .td file checkpoint.<commit_after>//===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting arm_neon.h, which includes
// a declaration and definition of each function specified by the ARM NEON
// compiler interface.  See ARM document DUI0348B.
//
//===----------------------------------------------------------------------===//

#include "NeonEmitter.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include <string>

using namespace llvm;

void NeonEmitter::run(raw_ostream &OS) {
  EmitSourceFileHeader("ARM NEON Header", OS);

  // FIXME: emit license into file?

  OS << "#ifndef __ARM_NEON_H\n";
  OS << "#define __ARM_NEON_H\n\n";

  OS << "#ifndef __ARM_NEON__\n";
  OS << "#error \"NEON support not enabled\"\n";
  OS << "#endif\n\n";

  OS << "#include <stdint.h>\n\n";

  // EmitTypedefs(OS);

  // Process Records

  std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");

  // Unique the pattern types, and assign them

  // emit #define directives for uniq'd prototypes

  // emit record directives

  for (unsigned i = 0, e = RV.size(); i != e; ++i) {
    Record *R = RV[i];

    OS << LowercaseString(R->getName()) << "\n";

    std::string Types = R->getValueAsString("Types");
    //std::string Pattern = R->getValueAsString("Pattern");
    //OS << Types << "\n" << Pattern << "\n\n";
  }

  OS << "#endif /* __ARM_NEON_H */\n";
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX
#define INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX

#include <sal/types.h>

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>

#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/xml/dom/events/XEventTarget.hpp>
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#include <com/sun/star/xml/dom/events/XEvent.hpp>

#include <cppuhelper/implbase3.hxx>

using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::dom::events;

namespace DOM { namespace events
{

    typedef ::cppu::WeakImplHelper3
        < ::com::sun::star::xml::dom::events::XEventListener
        , ::com::sun::star::lang::XInitialization
        , ::com::sun::star::lang::XServiceInfo
        > CTestListener_Base;

    class  CTestListener
        : public CTestListener_Base
    {

    private:
        Reference< ::com::sun::star::lang::XMultiServiceFactory > m_factory;
        Reference <XEventTarget> m_target;
        OUString m_type;
        sal_Bool m_capture;
        OUString m_name;

    public:

        // static helpers for service info and component management
        static const char* aImplementationName;
        static const char* aSupportedServiceNames[];
        static OUString _getImplementationName();
        static Sequence< OUString > _getSupportedServiceNames();
        static Reference< XInterface > _getInstance(
            const Reference< ::com::sun::star::lang::XMultiServiceFactory >&
                rSMgr);

        CTestListener(
                const Reference< ::com::sun::star::lang::XMultiServiceFactory >&
                    rSMgr)
            : m_factory(rSMgr){};

        virtual ~CTestListener();

        // XServiceInfo
        virtual OUString SAL_CALL getImplementationName()
            throw (RuntimeException, std::exception) SAL_OVERRIDE;
        virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
            throw (RuntimeException, std::exception) SAL_OVERRIDE;
        virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()
            throw (RuntimeException, std::exception) SAL_OVERRIDE;

        // XEventListener
        virtual void SAL_CALL initialize(const Sequence< Any >& args) throw (RuntimeException, std::exception) SAL_OVERRIDE;

        virtual void SAL_CALL handleEvent(const Reference< XEvent >& evt) throw (RuntimeException, std::exception) SAL_OVERRIDE;

    };
}}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#708568 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX
#define INCLUDED_UNOXML_SOURCE_EVENTS_TESTLISTENER_HXX

#include <sal/types.h>

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>

#include <com/sun/star/uno/XInterface.hpp>
#include <com/sun/star/uno/Exception.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/xml/dom/events/XEventTarget.hpp>
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#include <com/sun/star/xml/dom/events/XEvent.hpp>

#include <cppuhelper/implbase3.hxx>

using namespace com::sun::star::uno;
using namespace com::sun::star::xml::dom;
using namespace com::sun::star::xml::dom::events;

namespace DOM { namespace events
{

    typedef ::cppu::WeakImplHelper3
        < ::com::sun::star::xml::dom::events::XEventListener
        , ::com::sun::star::lang::XInitialization
        , ::com::sun::star::lang::XServiceInfo
        > CTestListener_Base;

    class  CTestListener
        : public CTestListener_Base
    {

    private:
        Reference< ::com::sun::star::lang::XMultiServiceFactory > m_factory;
        Reference <XEventTarget> m_target;
        OUString m_type;
        sal_Bool m_capture;
        OUString m_name;

    public:

        // static helpers for service info and component management
        static const char* aImplementationName;
        static const char* aSupportedServiceNames[];
        static OUString _getImplementationName();
        static Sequence< OUString > _getSupportedServiceNames();
        static Reference< XInterface > _getInstance(
            const Reference< ::com::sun::star::lang::XMultiServiceFactory >&
                rSMgr);

        CTestListener(
                const Reference< ::com::sun::star::lang::XMultiServiceFactory >&
                    rSMgr)
            : m_factory(rSMgr)
            , m_capture(sal_False)
        {
        }

        virtual ~CTestListener();

        // XServiceInfo
        virtual OUString SAL_CALL getImplementationName()
            throw (RuntimeException, std::exception) SAL_OVERRIDE;
        virtual sal_Bool SAL_CALL supportsService(const OUString& ServiceName)
            throw (RuntimeException, std::exception) SAL_OVERRIDE;
        virtual Sequence< OUString > SAL_CALL getSupportedServiceNames ()
            throw (RuntimeException, std::exception) SAL_OVERRIDE;

        // XEventListener
        virtual void SAL_CALL initialize(const Sequence< Any >& args) throw (RuntimeException, std::exception) SAL_OVERRIDE;

        virtual void SAL_CALL handleEvent(const Reference< XEvent >& evt) throw (RuntimeException, std::exception) SAL_OVERRIDE;

    };
}}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).
//
// Usage:
//   AddTrainPerformanceTRD.C(MC, friends, tasks)
//   tasks : "ALL" or one/more of the following:
//     "EFF"  : TRD Tracking Efficiency
//     "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations
//     "MULT"  : TRD single track selection
//     "RES"  : TRD tracking Resolution
//     "CLRES": clusters Resolution
//     "CAL"  : TRD calibration
//     "ALGN" : TRD alignment
//     "PID"  : TRD PID - pion efficiency
//     "PIDR" : TRD PID - reference data
//     "DET"  : Basic TRD Detector checks
//     "NOFR" : Data set does not have AliESDfriends.root
//     "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely
//              on MC information are switched off
//
// In compiled mode :
// Don't forget to load first the libraries
// gSystem->Load("libMemStat.so")
// gSystem->Load("libMemStatGui.so")
// gSystem->Load("libANALYSIS.so")
// gSystem->Load("libANALYSISalice.so")
// gSystem->Load("libPWG1.so");
//
// Authors:
//   Alex Bercuci (A.Bercuci@gsi.de)
//   Markus Fasel (m.Fasel@gsi.de)

#if ! defined (__CINT__) || defined (__MAKECINT__)
//#ifndef __CINT__
#include <Riostream.h>

#include "TStopwatch.h"
#include "TMemStat.h"
#include "TMemStatViewerGUI.h"

#include "TROOT.h"
#include "TClass.h"
#include "TSystem.h"
#include "TError.h"
#include "TChain.h"
#include "TGrid.h"
#include "TAlienCollection.h"
#include "TGridCollection.h"
#include "TGridResult.h"
#include "TGeoGlobalMagField.h"

#include "AliMagF.h"
#include "AliTracker.h"
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliGRPManager.h"
#include "AliGeomManager.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"

#include "TRD/AliTRDtrackerV1.h"
#include "TRD/AliTRDcalibDB.h"

#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/macros/AddTRDcheckESD.C"
#include "PWG1/TRD/macros/AddTRDinfoGen.C"
#include "PWG1/TRD/macros/AddTRDcheckDET.C"
#include "PWG1/TRD/macros/AddTRDefficiency.C"
#include "PWG1/TRD/macros/AddTRDresolution.C"
#include "PWG1/TRD/macros/AddTRDcheckPID.C"
#endif

#include "../TRD/macros/AliTRDperformanceTrain.h"

Bool_t AddTrainPerformanceTRD(Bool_t mc, Bool_t fr, Char_t *trd="ALL")
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if(!mgr) {
    Error("AddTrainPerformanceTRD", "AliAnalysisManager not set!");
    return kFALSE;
  }

  // TRD data containers
  AliAnalysisDataContainer *ci[] = {0x0, 0x0, 0x0};

  // initialize TRD settings
  AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
  AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBins());

  for(Int_t it=0; it<NTRDQATASKS; it++){
    if(gROOT->LoadMacro(Form("$ALICE_ROOT/PWG1/TRD/macros/Add%s.C+", TString(fgkTRDtaskClassName[it])(3,20).Data()))) {
      Error("AddTrainPerformanceTRD()", Form("Error loading %s task.", fgkTRDtaskClassName[it]));
      return kFALSE;
    }

    switch(it){
    case kCheckESD:
      AddTRDcheckESD(mgr); break;
    case kInfoGen:
      AddTRDinfoGen(mgr, trd, 0x0, ci); break;
    case kCheckDET:
      AddTRDcheckDET(mgr, trd, ci); break;
    case kEfficiency:
      AddTRDefficiency(mgr, trd, ci); break;
    case kResolution:
      AddTRDresolution(mgr, trd, ci); break;
    case kCheckPID:
      AddTRDcheckPID(mgr, trd, ci); break;
    default:
      Warning("AddTrainPerformanceTRD()", Form("No performance task registered at slot %d.", it));
    }
  }
  return kTRUE;
}

<commit_msg>update for AliTRDcalibDB::GetNumberOfTimeBinsDCS()<commit_after>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID).
//
// Usage:
//   AddTrainPerformanceTRD.C(MC, friends, tasks)
//   tasks : "ALL" or one/more of the following:
//     "EFF"  : TRD Tracking Efficiency
//     "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations
//     "MULT"  : TRD single track selection
//     "RES"  : TRD tracking Resolution
//     "CLRES": clusters Resolution
//     "CAL"  : TRD calibration
//     "ALGN" : TRD alignment
//     "PID"  : TRD PID - pion efficiency
//     "PIDR" : TRD PID - reference data
//     "DET"  : Basic TRD Detector checks
//     "NOFR" : Data set does not have AliESDfriends.root
//     "NOMC" : Data set does not have Monte Carlo Informations (real data), so all tasks which rely
//              on MC information are switched off
//
// In compiled mode :
// Don't forget to load first the libraries
// gSystem->Load("libMemStat.so")
// gSystem->Load("libMemStatGui.so")
// gSystem->Load("libANALYSIS.so")
// gSystem->Load("libANALYSISalice.so")
// gSystem->Load("libPWG1.so");
//
// Authors:
//   Alex Bercuci (A.Bercuci@gsi.de)
//   Markus Fasel (m.Fasel@gsi.de)

#if ! defined (__CINT__) || defined (__MAKECINT__)
//#ifndef __CINT__
#include <Riostream.h>

#include "TStopwatch.h"
#include "TMemStat.h"
#include "TMemStatViewerGUI.h"

#include "TROOT.h"
#include "TClass.h"
#include "TSystem.h"
#include "TError.h"
#include "TChain.h"
#include "TGrid.h"
#include "TAlienCollection.h"
#include "TGridCollection.h"
#include "TGridResult.h"
#include "TGeoGlobalMagField.h"

#include "AliMagF.h"
#include "AliTracker.h"
#include "AliLog.h"
#include "AliCDBManager.h"
#include "AliGRPManager.h"
#include "AliGeomManager.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliMCEventHandler.h"
#include "AliESDInputHandler.h"

#include "TRD/AliTRDtrackerV1.h"
#include "TRD/AliTRDcalibDB.h"

#include "PWG1/TRD/macros/AliTRDperformanceTrain.h"
#include "PWG1/TRD/macros/AddTRDcheckESD.C"
#include "PWG1/TRD/macros/AddTRDinfoGen.C"
#include "PWG1/TRD/macros/AddTRDcheckDET.C"
#include "PWG1/TRD/macros/AddTRDefficiency.C"
#include "PWG1/TRD/macros/AddTRDresolution.C"
#include "PWG1/TRD/macros/AddTRDcheckPID.C"
#endif

#include "../TRD/macros/AliTRDperformanceTrain.h"

Bool_t AddTrainPerformanceTRD(Bool_t mc, Bool_t fr, Char_t *trd="ALL")
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if(!mgr) {
    Error("AddTrainPerformanceTRD", "AliAnalysisManager not set!");
    return kFALSE;
  }

  // TRD data containers
  AliAnalysisDataContainer *ci[] = {0x0, 0x0, 0x0};

  // initialize TRD settings
  AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
  AliTRDtrackerV1::SetNTimeBins(cal->GetNumberOfTimeBinsDCS());
  for(Int_t it=0; it<NTRDQATASKS; it++){
    if(gROOT->LoadMacro(Form("$ALICE_ROOT/PWG1/TRD/macros/Add%s.C+", TString(fgkTRDtaskClassName[it])(3,20).Data()))) {
      Error("AddTrainPerformanceTRD()", Form("Error loading %s task.", fgkTRDtaskClassName[it]));
      return kFALSE;
    }

    switch(it){
    case kCheckESD:
      AddTRDcheckESD(mgr); break;
    case kInfoGen:
      AddTRDinfoGen(mgr, trd, 0x0, ci); break;
    case kCheckDET:
      AddTRDcheckDET(mgr, trd, ci); break;
    case kEfficiency:
      AddTRDefficiency(mgr, trd, ci); break;
    case kResolution:
      AddTRDresolution(mgr, trd, ci); break;
    case kCheckPID:
      AddTRDcheckPID(mgr, trd, ci); break;
    default:
      Warning("AddTrainPerformanceTRD()", Form("No performance task registered at slot %d.", it));
    }
  }
  return kTRUE;
}

<|endoftext|>


<commit_before>/**************************************************************************
 * Author: Andrey Ivanov.                                           *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
// Analysis task for Long Range Correlation (LRC) analysis using TPC data
// This includes a TList of AliLRCBase objects that are processing LRC analysis
// for a given Eta window
// This task is worcking with ESD data only

// Author : Andrey Ivanov , St.Peterburg State University
// Email: Andrey.Ivanov@cern.ch

#include <AliAnalysisManager.h>
#include <AliESDInputHandler.h>
#include "AliAnalysisTaskLRC.h"
#include <AliLRCBase.h>
#include <AliVEvent.h>
#include <AliMCEvent.h>
#include <AliESDEvent.h>
#include <AliPID.h>

#include <AliRunLoader.h>
#include <AliRun.h>
#include <AliStack.h>
#include <AliESDtrackCuts.h>
#include <AliPhysicsSelection.h>
#include <TParticle.h>
#include <TH1.h>
#include <TH2.h>

ClassImp(AliAnalysisTaskLRC)

//________________________________________________________________________
AliAnalysisTaskLRC::AliAnalysisTaskLRC(const char *name,Bool_t runKine)
  : AliAnalysisTaskSE(name),fEsdTrackCuts(0),fMaxPtLimit(5.0),fMinPtLimit(0.0),fMinAceptedTracksCut(0),fMaxAceptedTracksCut(0),fCheckForkVtx(kTRUE),fCheckForVtxPosition(kFALSE),fVxMax(0),fVyMax(0),fVzMax(0),fLRCproc(0),fOutList(0),fRunKine(0),fShowEventStats(kFALSE),fShowPerTrackStats(kFALSE),fHistEventCutStats(0),fHistTrackCutStats(0),fHistVx(0),fHistVy(0),fHistVz(0),fHistEtaVsZvCoverage(0),fHistEtaVsZvCoverageAcepted(0),fHistAceptedMult(0)
{
  //Init
  fRunKine=runKine;

  // Output slot #1 writes into a TList container for common task data and QA
  DefineOutput(1, TList::Class());

  //Defining output slots for each LRC processor (required to avoid TList of TLists on merging)
  for(Int_t i=0; i < fLRCproc.GetEntries(); i++)
  {
  DefineOutput(Proc(i)->GetOutputSlotNumber(),TList::Class());
  }
}

// ---------------------------------------  Setters ------------------

  void AliAnalysisTaskLRC::SetMaxPtLimit(Double_t MaxPtLimit)
  {
   //Sets  Max Pt filter
     fMaxPtLimit=MaxPtLimit;
  }
  void AliAnalysisTaskLRC::SetMinPtLimit(Double_t MinPtLimit)
  {
     //Sets  Min Pt filter
  fMinPtLimit=MinPtLimit;
  }
  AliLRCBase*  AliAnalysisTaskLRC::Proc(Int_t index)
  {
  // Get Processor i
  return (dynamic_cast<AliLRCBase*> (fLRCproc.At(index)));
  }

//________________________________________________________________________
void AliAnalysisTaskLRC::UserCreateOutputObjects()
{
  //Disabling "replacing existing TH2D ...etc" warning

   Bool_t lTH1oldStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE);

   Bool_t lTH2oldStatus = TH2::AddDirectoryStatus();
   TH2::AddDirectory(kFALSE);

  //LRC processors init
  Int_t lLrcNum=fLRCproc.GetEntries();

  for(Int_t i=0; i < lLrcNum; i++)
  {
    AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->InitDataMembers();
    else continue;
  }

    // --------- Output list

  fOutList = new TList();

  fOutList->Add( fEsdTrackCuts );

  //Event level QA
  fHistEventCutStats = new TH1D("fHistEventCutStats","Event statistics;;N_{events}", 7,-0.5,6.5);
  TString gEventCutBinNames[7] = {"Total","No trigger","No vertex","Bad vertex position","HighMult cut","LowMult cut","Analyzed"};
  for(Int_t i = 1; i <= 7; i++)fHistEventCutStats->GetXaxis()->SetBinLabel(i,gEventCutBinNames[i-1].Data());
  fOutList->Add(fHistEventCutStats);

  //Track level QA
  fHistTrackCutStats = new TH1D("fHistTrackCutStats","Event statistics;;N_{events}", 5,-0.5,4.5);
  TString gTrackCutBinNames[5] = {"Total","AliESDtrackCuts","HighPt cut","LowPt cut","Good"};
  for(Int_t i = 1; i <= 5; i++)fHistTrackCutStats->GetXaxis()->SetBinLabel(i,gTrackCutBinNames[i-1].Data());
  fOutList->Add(fHistTrackCutStats);

  //Vertex distributions
  fHistVx = new TH1D("fHistVx","Primary vertex distribution - x coordinate;V_{x} (cm);Entries",100,-0.5,0.5);
  fOutList->Add(fHistVx);
  fHistVy = new TH1D("fHistVy","Primary vertex distribution - y coordinate;V_{y} (cm);Entries",100,-0.5,0.5);
  fOutList->Add(fHistVy);
  fHistVz = new TH1D("fHistVz","Primary vertex distribution - z coordinate;V_{z} (cm);Entries",100,-20.,20.);
  fOutList->Add(fHistVz);

  //Eta vs Zv
  fHistEtaVsZvCoverage = new TH2D("fHistEtaVsZvCoverage","TPC tracks ETA vs Zv;V_{z} (cm);ETA",100,-20,20,50,-2,2);
  fHistEtaVsZvCoverageAcepted = new TH2D("fHistEtaVsZvCoverage","Acepted TPC tracks ETA vs Zv;V_{z} (cm);ETA",100,-20,20,50,-2,2);
  fOutList->Add(fHistEtaVsZvCoverage);
  fOutList->Add(fHistEtaVsZvCoverageAcepted);

  fHistAceptedMult = new TH1D("fHistAceptedMult","N_{ch} - accepted tracks;N_{ch} acepted;Entries",401,-0.5,400.5);
  fOutList->Add(fHistAceptedMult);

  // Returning TH1,TH2 AddDirectory status
  TH1::AddDirectory(lTH1oldStatus);
  TH2::AddDirectory(lTH2oldStatus);

}

//________________________________________________________________________
void AliAnalysisTaskLRC::UserExec(Option_t *)
{
  // Main loop
  // Called for each event

   AliVEvent *event = InputEvent();
   AliESDEvent *fESD = 0x0;
   fESD=dynamic_cast<AliESDEvent*> (event) ;
   AliStack *stack = 0x0;
   AliMCEvent *eventMC = 0x0;
   if( fRunKine )
   {
	eventMC=MCEvent();
	stack=eventMC->Stack();
	Printf("Number of primaries: %d",stack->GetNprimary());
   }

  if (!event) {
     Printf("ERROR: Could not retrieve event");
     return;
  }
  if((fESD)&&(!fEsdTrackCuts)){ AliDebug(AliLog::kError, "No ESD track cuts avalible"); return;}

   // Numbrt of processors attached
   Int_t lLrcNum=fLRCproc.GetEntries();

// Processing event selection
fHistEventCutStats->Fill(0);

Bool_t lTrigger=kTRUE;
Bool_t lVertexPresent=kTRUE;
Bool_t lVertexAceptable=kTRUE;

//Trigger
   if(fESD){
	if(fShowEventStats)Printf("Trigger classes: %s:", fESD->GetFiredTriggerClasses().Data());

   	lTrigger=((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
   	if(!lTrigger){
   		if(fShowEventStats)Printf("Rejected!");
		fHistEventCutStats->Fill(1);
 		PostData(1, fOutList);
		return;
	}
   }

// Vertex present
const AliESDVertex *vertex = fESD->GetPrimaryVertex();
 if(vertex) {
   lVertexPresent=((vertex)&&(vertex->GetNContributors() > 0)&&(vertex->GetZRes() != 0));
   if((!lVertexPresent)&&fCheckForkVtx)
     {if(fShowEventStats)Printf("No vertex");
       fHistEventCutStats->Fill(2);
       PostData(1, fOutList);
       return;
     }

   // Vertex in range
   lVertexAceptable=(TMath::Abs(vertex->GetXv()) < fVxMax) && (TMath::Abs(vertex->GetYv()) < fVyMax);
   if(lVertexAceptable)
     if(fVzMax>0)   //   fVzMax < 0 -> select Zv outside selected range
       { lVertexAceptable = (TMath::Abs(vertex->GetZv()) < fVzMax);}
     else
       { lVertexAceptable = (TMath::Abs(vertex->GetZv()) > -fVzMax);}

   if((!lVertexAceptable) && fCheckForVtxPosition)
     {if(fShowEventStats)Printf("Vertex out of range");
       fHistEventCutStats->Fill(3);
       PostData(1, fOutList);
       return;
     }

   fHistVx->Fill(vertex->GetXv());
   fHistVy->Fill(vertex->GetYv());
   fHistVz->Fill(vertex->GetZv());

int lNchTrigger=0;
// Pre event loop
if(fESD &&  !fRunKine )
	for (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++)
		if(fEsdTrackCuts->AcceptTrack(fESD->GetTrack(iTracks)))lNchTrigger++;

//if(fRunKine)lNchTrigger=eventMC->GetNumberOfPrimaries();

// Nch bins cut

if( (lNchTrigger > fMaxAceptedTracksCut) && (fMaxAceptedTracksCut != 0))
	{
	fHistEventCutStats->Fill(4);
 	PostData(1, fOutList);
	return;
	}

if(lNchTrigger < fMinAceptedTracksCut)
	{
	fHistEventCutStats->Fill(5);
	 PostData(1, fOutList);
	return;
	}
fHistAceptedMult->Fill(lNchTrigger);
fHistEventCutStats->Fill(6);

  //Track variables
  double lPt;   // Temp Pt
  double lEta;	  // Temp ETA
  double lPhi;    // Temp Phi

  //Track selection counters
  int lNaccept=0;
  int lPtOver=0;
  int lPtUnder=0;
  int lNoCharge=0;
  int lCutfail=0;
  int lDecay=0;

 for(Int_t i=0; i < lLrcNum; i++)
  {
    AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->StartEvent();
    else continue;
  }

    // Track loop -----------------------------------------------------------------
  for (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++) {

    AliVParticle* track = event->GetTrack(iTracks);
    if (!track) {
      Printf("ERROR: Could not receive track %d", iTracks);
      continue;
    }

    fHistTrackCutStats->Fill(0);
    fHistEtaVsZvCoverage->Fill(vertex->GetZv(),track->Eta());

    lPt=track->Pt();
    lEta=track->Eta();
    lPhi=track->Phi();

    // ESD track cuts
    if(fESD &&  !fRunKine )
    {
    	AliESDtrack* lESDtarck= fESD->GetTrack(iTracks);
	if(fShowPerTrackStats)printf("ESD Track N%d , Eta=%f, Pt=%f , TPC Nclusters =%d Sigma=%f ",  iTracks , lEta , lPt, lESDtarck-> GetTPCNcls(),fEsdTrackCuts->GetSigmaToVertex( lESDtarck) );
	if(!fEsdTrackCuts->AcceptTrack(lESDtarck))
		{
		lCutfail++;
		if(fShowPerTrackStats)Printf("Rejected by cuts");
		fHistTrackCutStats->Fill(1);
		continue;
		}
	else
		{
		if(fShowPerTrackStats)Printf("OK");
		}

    }
    // end of ESD tack cuts

      if(lPt>fMaxPtLimit)
	{lPtOver++;
	fHistTrackCutStats->Fill(2);
	continue;}     // Dropping traks with hi Pt

	if(lPt<fMinPtLimit)
	{lPtUnder++;
	fHistTrackCutStats->Fill(3);
	continue;}   // Dropping traks with lo Pt

	fHistTrackCutStats->Fill(4);

      for(Int_t i=0; i < lLrcNum; i++)
  {
    AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->AddTrackPtEta(lPt,lEta,lPhi);
    else continue;
  }

    lNaccept++;
    fHistEtaVsZvCoverageAcepted->Fill(vertex->GetZv(),track->Eta());

  } //end of track loop

   for(Int_t i=0; i < lLrcNum; i++)
  {
      AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->FinishEvent();
    else continue;
  }

  //Debuging output of track filter
  if(fShowPerTrackStats)Printf("NofTracks= %d , accepted %d , LowPt %d, HighPt %d, LowCharge %d,  ESD cut fail %d , Decay Filer %d", event->GetNumberOfTracks(), lNaccept, lPtUnder, lPtOver ,lNoCharge , lCutfail  , lDecay);

   // Post output data.

  PostData(1, fOutList);

  for(Int_t i=0; i < fLRCproc.GetEntries(); i++)
  {
  PostData(Proc(i)->GetOutputSlotNumber(),Proc(i)->CreateOutput());
  }

 }//vertex

}

//________________________________________________________________________
void AliAnalysisTaskLRC::Terminate(Option_t *)
{
  // Draw result to the screen
  // Called once at the end of the query
//fOutList = dynamic_cast<TList*> (GetOutputData(0));

//fEsdTrackCuts->DrawHistograms();

}

void AliAnalysisTaskLRC::AddLRCProcess(AliLRCBase *newProc)
{
// Add new AliLRCBase (Main LRC processor per ETA window) to the processing list
// Used to add new ETA window to AnalysisTask
if(!newProc)
{Printf("ERROR:No AliLRCBase object -  NULL pointer!");
return;
}

fLRCproc.Add(newProc);
newProc->SetOutputSlotNumber(fLRCproc.GetEntries()+1);
DefineOutput(newProc->GetOutputSlotNumber(),TList::Class());
return ;
}

<commit_msg>Coverity (LRC task)<commit_after>/**************************************************************************
 * Author: Andrey Ivanov.                                           *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
// Analysis task for Long Range Correlation (LRC) analysis using TPC data
// This includes a TList of AliLRCBase objects that are processing LRC analysis
// for a given Eta window
// This task is worcking with ESD data only

// Author : Andrey Ivanov , St.Peterburg State University
// Email: Andrey.Ivanov@cern.ch

#include <AliAnalysisManager.h>
#include <AliESDInputHandler.h>
#include "AliAnalysisTaskLRC.h"
#include <AliLRCBase.h>
#include <AliVEvent.h>
#include <AliMCEvent.h>
#include <AliESDEvent.h>
#include <AliPID.h>

#include <AliRunLoader.h>
#include <AliRun.h>
#include <AliStack.h>
#include <AliESDtrackCuts.h>
#include <AliPhysicsSelection.h>
#include <TParticle.h>
#include <TH1.h>
#include <TH2.h>

ClassImp(AliAnalysisTaskLRC)

//________________________________________________________________________
AliAnalysisTaskLRC::AliAnalysisTaskLRC(const char *name,Bool_t runKine)
  : AliAnalysisTaskSE(name),fEsdTrackCuts(0),fMaxPtLimit(5.0),fMinPtLimit(0.0),fMinAceptedTracksCut(0),fMaxAceptedTracksCut(0),fCheckForkVtx(kTRUE),fCheckForVtxPosition(kFALSE),fVxMax(0),fVyMax(0),fVzMax(0),fLRCproc(0),fOutList(0),fRunKine(0),fShowEventStats(kFALSE),fShowPerTrackStats(kFALSE),fHistEventCutStats(0),fHistTrackCutStats(0),fHistVx(0),fHistVy(0),fHistVz(0),fHistEtaVsZvCoverage(0),fHistEtaVsZvCoverageAcepted(0),fHistAceptedMult(0)
{
  //Init
  fRunKine=runKine;

  // Output slot #1 writes into a TList container for common task data and QA
  DefineOutput(1, TList::Class());

  //Defining output slots for each LRC processor (required to avoid TList of TLists on merging)
  for(Int_t i=0; i < fLRCproc.GetEntries(); i++)
  {
  DefineOutput(Proc(i)->GetOutputSlotNumber(),TList::Class());
  }
}

// ---------------------------------------  Setters ------------------

  void AliAnalysisTaskLRC::SetMaxPtLimit(Double_t MaxPtLimit)
  {
   //Sets  Max Pt filter
     fMaxPtLimit=MaxPtLimit;
  }
  void AliAnalysisTaskLRC::SetMinPtLimit(Double_t MinPtLimit)
  {
     //Sets  Min Pt filter
  fMinPtLimit=MinPtLimit;
  }
  AliLRCBase*  AliAnalysisTaskLRC::Proc(Int_t index)
  {
  // Get Processor i
  return (dynamic_cast<AliLRCBase*> (fLRCproc.At(index)));
  }

//________________________________________________________________________
void AliAnalysisTaskLRC::UserCreateOutputObjects()
{
  //Disabling "replacing existing TH2D ...etc" warning

   Bool_t lTH1oldStatus = TH1::AddDirectoryStatus();
   TH1::AddDirectory(kFALSE);

   Bool_t lTH2oldStatus = TH2::AddDirectoryStatus();
   TH2::AddDirectory(kFALSE);

  //LRC processors init
  Int_t lLrcNum=fLRCproc.GetEntries();

  for(Int_t i=0; i < lLrcNum; i++)
  {
    AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->InitDataMembers();
    else continue;
  }

    // --------- Output list

  fOutList = new TList();

  fOutList->Add( fEsdTrackCuts );

  //Event level QA
  fHistEventCutStats = new TH1D("fHistEventCutStats","Event statistics;;N_{events}", 7,-0.5,6.5);
  TString gEventCutBinNames[7] = {"Total","No trigger","No vertex","Bad vertex position","HighMult cut","LowMult cut","Analyzed"};
  for(Int_t i = 1; i <= 7; i++)fHistEventCutStats->GetXaxis()->SetBinLabel(i,gEventCutBinNames[i-1].Data());
  fOutList->Add(fHistEventCutStats);

  //Track level QA
  fHistTrackCutStats = new TH1D("fHistTrackCutStats","Event statistics;;N_{events}", 5,-0.5,4.5);
  TString gTrackCutBinNames[5] = {"Total","AliESDtrackCuts","HighPt cut","LowPt cut","Good"};
  for(Int_t i = 1; i <= 5; i++)fHistTrackCutStats->GetXaxis()->SetBinLabel(i,gTrackCutBinNames[i-1].Data());
  fOutList->Add(fHistTrackCutStats);

  //Vertex distributions
  fHistVx = new TH1D("fHistVx","Primary vertex distribution - x coordinate;V_{x} (cm);Entries",100,-0.5,0.5);
  fOutList->Add(fHistVx);
  fHistVy = new TH1D("fHistVy","Primary vertex distribution - y coordinate;V_{y} (cm);Entries",100,-0.5,0.5);
  fOutList->Add(fHistVy);
  fHistVz = new TH1D("fHistVz","Primary vertex distribution - z coordinate;V_{z} (cm);Entries",100,-20.,20.);
  fOutList->Add(fHistVz);

  //Eta vs Zv
  fHistEtaVsZvCoverage = new TH2D("fHistEtaVsZvCoverage","TPC tracks ETA vs Zv;V_{z} (cm);ETA",100,-20,20,50,-2,2);
  fHistEtaVsZvCoverageAcepted = new TH2D("fHistEtaVsZvCoverage","Acepted TPC tracks ETA vs Zv;V_{z} (cm);ETA",100,-20,20,50,-2,2);
  fOutList->Add(fHistEtaVsZvCoverage);
  fOutList->Add(fHistEtaVsZvCoverageAcepted);

  fHistAceptedMult = new TH1D("fHistAceptedMult","N_{ch} - accepted tracks;N_{ch} acepted;Entries",401,-0.5,400.5);
  fOutList->Add(fHistAceptedMult);

  // Returning TH1,TH2 AddDirectory status
  TH1::AddDirectory(lTH1oldStatus);
  TH2::AddDirectory(lTH2oldStatus);

}

//________________________________________________________________________
void AliAnalysisTaskLRC::UserExec(Option_t *)
{
  // Main loop
  // Called for each event

   AliVEvent *event = InputEvent();
   AliESDEvent *fESD = 0x0;
   fESD=dynamic_cast<AliESDEvent*> (event) ;
   AliStack *stack = 0x0;
   AliMCEvent *eventMC = 0x0;
   if( fRunKine )
   {
	eventMC=MCEvent();
	stack=eventMC->Stack();
	Printf("Number of primaries: %d",stack->GetNprimary());
   }

  if (!event) {
     Printf("ERROR: Could not retrieve event");
     return;
  }
  if((fESD)&&(!fEsdTrackCuts)){ AliDebug(AliLog::kError, "No ESD track cuts avalible"); return;}

   // Numbrt of processors attached
   Int_t lLrcNum=fLRCproc.GetEntries();

// Processing event selection
fHistEventCutStats->Fill(0);

Bool_t lTrigger=kTRUE;
Bool_t lVertexPresent=kTRUE;
Bool_t lVertexAceptable=kTRUE;

//Trigger
   if(fESD){
	if(fShowEventStats)Printf("Trigger classes: %s:", fESD->GetFiredTriggerClasses().Data());

   	lTrigger=((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected();
   	if(!lTrigger){
   		if(fShowEventStats)Printf("Rejected!");
		fHistEventCutStats->Fill(1);
 		PostData(1, fOutList);
		return;
	}
   }

// Vertex present
const AliESDVertex *vertex = fESD->GetPrimaryVertex();
 if(vertex) {
   lVertexPresent=((vertex)&&(vertex->GetNContributors() > 0)&&(vertex->GetZRes() != 0));
   if((!lVertexPresent)&&fCheckForkVtx)
     {if(fShowEventStats)Printf("No vertex");
       fHistEventCutStats->Fill(2);
       PostData(1, fOutList);
       return;
     }

   // Vertex in range
   lVertexAceptable=(TMath::Abs(vertex->GetXv()) < fVxMax) && (TMath::Abs(vertex->GetYv()) < fVyMax);
   if(lVertexAceptable) {
     if(fVzMax>0)   //   fVzMax < 0 -> select Zv outside selected range
       { lVertexAceptable = (TMath::Abs(vertex->GetZv()) < fVzMax);}
     else
       { lVertexAceptable = (TMath::Abs(vertex->GetZv()) > -fVzMax);}
   }
   if((!lVertexAceptable) && fCheckForVtxPosition)
     {if(fShowEventStats)Printf("Vertex out of range");
       fHistEventCutStats->Fill(3);
       PostData(1, fOutList);
       return;
     }

   fHistVx->Fill(vertex->GetXv());
   fHistVy->Fill(vertex->GetYv());
   fHistVz->Fill(vertex->GetZv());

int lNchTrigger=0;
// Pre event loop
if(fESD &&  !fRunKine )
	for (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++)
		if(fEsdTrackCuts->AcceptTrack(fESD->GetTrack(iTracks)))lNchTrigger++;

//if(fRunKine)lNchTrigger=eventMC->GetNumberOfPrimaries();

// Nch bins cut

if( (lNchTrigger > fMaxAceptedTracksCut) && (fMaxAceptedTracksCut != 0))
	{
	fHistEventCutStats->Fill(4);
 	PostData(1, fOutList);
	return;
	}

if(lNchTrigger < fMinAceptedTracksCut)
	{
	fHistEventCutStats->Fill(5);
	 PostData(1, fOutList);
	return;
	}
fHistAceptedMult->Fill(lNchTrigger);
fHistEventCutStats->Fill(6);

  //Track variables
  double lPt;   // Temp Pt
  double lEta;	  // Temp ETA
  double lPhi;    // Temp Phi

  //Track selection counters
  int lNaccept=0;
  int lPtOver=0;
  int lPtUnder=0;
  int lNoCharge=0;
  int lCutfail=0;
  int lDecay=0;

 for(Int_t i=0; i < lLrcNum; i++)
  {
    AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->StartEvent();
    else continue;
  }

    // Track loop -----------------------------------------------------------------
  for (Int_t iTracks = 0; iTracks < event->GetNumberOfTracks(); iTracks++) {

    AliVParticle* track = event->GetTrack(iTracks);
    if (!track) {
      Printf("ERROR: Could not receive track %d", iTracks);
      continue;
    }

    fHistTrackCutStats->Fill(0);
    fHistEtaVsZvCoverage->Fill(vertex->GetZv(),track->Eta());

    lPt=track->Pt();
    lEta=track->Eta();
    lPhi=track->Phi();

    // ESD track cuts
    if(fESD &&  !fRunKine )
    {
    	AliESDtrack* lESDtarck= fESD->GetTrack(iTracks);
	if(fShowPerTrackStats)printf("ESD Track N%d , Eta=%f, Pt=%f , TPC Nclusters =%d Sigma=%f ",  iTracks , lEta , lPt, lESDtarck-> GetTPCNcls(),fEsdTrackCuts->GetSigmaToVertex( lESDtarck) );
	if(!fEsdTrackCuts->AcceptTrack(lESDtarck))
		{
		lCutfail++;
		if(fShowPerTrackStats)Printf("Rejected by cuts");
		fHistTrackCutStats->Fill(1);
		continue;
		}
	else
		{
		if(fShowPerTrackStats)Printf("OK");
		}

    }
    // end of ESD tack cuts

      if(lPt>fMaxPtLimit)
	{lPtOver++;
	fHistTrackCutStats->Fill(2);
	continue;}     // Dropping traks with hi Pt

	if(lPt<fMinPtLimit)
	{lPtUnder++;
	fHistTrackCutStats->Fill(3);
	continue;}   // Dropping traks with lo Pt

	fHistTrackCutStats->Fill(4);

      for(Int_t i=0; i < lLrcNum; i++)
  {
    AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->AddTrackPtEta(lPt,lEta,lPhi);
    else continue;
  }

    lNaccept++;
    fHistEtaVsZvCoverageAcepted->Fill(vertex->GetZv(),track->Eta());

  } //end of track loop

   for(Int_t i=0; i < lLrcNum; i++)
  {
      AliLRCBase *lrcBase = dynamic_cast<AliLRCBase*> (fLRCproc.At(i));
    if(lrcBase)
      lrcBase->FinishEvent();
    else continue;
  }

  //Debuging output of track filter
  if(fShowPerTrackStats)Printf("NofTracks= %d , accepted %d , LowPt %d, HighPt %d, LowCharge %d,  ESD cut fail %d , Decay Filer %d", event->GetNumberOfTracks(), lNaccept, lPtUnder, lPtOver ,lNoCharge , lCutfail  , lDecay);

   // Post output data.

  PostData(1, fOutList);

  for(Int_t i=0; i < fLRCproc.GetEntries(); i++)
  {
  PostData(Proc(i)->GetOutputSlotNumber(),Proc(i)->CreateOutput());
  }

 }//vertex

}

//________________________________________________________________________
void AliAnalysisTaskLRC::Terminate(Option_t *)
{
  // Draw result to the screen
  // Called once at the end of the query
//fOutList = dynamic_cast<TList*> (GetOutputData(0));

//fEsdTrackCuts->DrawHistograms();

}

void AliAnalysisTaskLRC::AddLRCProcess(AliLRCBase *newProc)
{
// Add new AliLRCBase (Main LRC processor per ETA window) to the processing list
// Used to add new ETA window to AnalysisTask
if(!newProc)
{Printf("ERROR:No AliLRCBase object -  NULL pointer!");
return;
}

fLRCproc.Add(newProc);
newProc->SetOutputSlotNumber(fLRCproc.GetEntries()+1);
DefineOutput(newProc->GetOutputSlotNumber(),TList::Class());
return ;
}

<|endoftext|>