<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "contactlistpage.h"
#ifdef BUILD_VERSIT
#include "qversitreader.h"
#include "qversitcontactimporter.h"
#include "qversitwriter.h"
#include "qversitcontactexporter.h"
#endif

#include <QtGui>

ContactListPage::ContactListPage(QWidget *parent)
        : QWidget(parent)
{
    m_manager = 0;
    m_currentFilter = QContactFilter();

    m_backendsCombo = new QComboBox(this);
    QStringList availableManagers = QContactManager::availableManagers();

    foreach(QString managerName, availableManagers) {

        QMap<QString, QString> params;
        QString managerUri = QContactManager::buildUri(managerName, params);

        // Add some parameters to SIM backend so that we can use
        // all the stores.
        if (managerName == "symbiansim") {
            availableManagers.removeAll("symbiansim");

            availableManagers.append("symbiansim:adn");
            params.insert("store", "ADN");
            managerUri = QContactManager::buildUri(managerName, params);
            m_availableManagers.insert(availableManagers.last(), managerUri);

            availableManagers.append("symbiansim:fdn");
            params.clear();
            params.insert("store", "FDN");
            managerUri = QContactManager::buildUri(managerName, params);
            m_availableManagers.insert(availableManagers.last(), managerUri);

            availableManagers.append("symbiansim:sdn");
            params.clear();
            params.insert("store", "SDN");
            managerUri = QContactManager::buildUri(managerName, params);
            m_availableManagers.insert(availableManagers.last(), managerUri);
        }
        else {
            m_availableManagers.insert(managerName, managerUri);
        }
    }
    m_backendsCombo->addItems(m_availableManagers.keys());
    connect(m_backendsCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(backendSelected()));
    m_filterActiveLabel = new QLabel("Inactive");
    m_filterActiveLabel->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

    m_contactsList = new QListWidget(this);

    QPushButton* m_addContactBtn = new QPushButton("Add", this);
    connect(m_addContactBtn, SIGNAL(clicked()), this, SLOT(addContactClicked()));
    QPushButton* m_editBtn = new QPushButton("Edit", this);
    connect(m_editBtn, SIGNAL(clicked()), this, SLOT(editClicked()));
    QPushButton* m_deleteBtn = new QPushButton("Delete", this);
    connect(m_deleteBtn, SIGNAL(clicked()), this, SLOT(deleteClicked()));
    QPushButton* m_filterBtn = new QPushButton("Filter", this);
    connect(m_filterBtn, SIGNAL(clicked()), this, SLOT(filterClicked()));
    QPushButton* m_importBtn = new QPushButton("Import");
    connect(m_importBtn, SIGNAL(clicked()), this, SLOT(importClicked()));
    QPushButton* m_exportBtn = new QPushButton("Export");
    connect(m_exportBtn, SIGNAL(clicked()), this, SLOT(exportClicked()));

    QFormLayout *backendLayout = new QFormLayout;
    backendLayout->addRow("Store:", m_backendsCombo);
    backendLayout->addRow("Filter:", m_filterActiveLabel);

    QHBoxLayout *btnLayout1 = new QHBoxLayout;
    btnLayout1->addWidget(m_addContactBtn);
    btnLayout1->addWidget(m_editBtn);
    btnLayout1->addWidget(m_deleteBtn);
    btnLayout1->addWidget(m_filterBtn);

    QHBoxLayout *btnLayout2 = new QHBoxLayout;
    btnLayout2->addWidget(m_importBtn);
    btnLayout2->addWidget(m_exportBtn);

    QVBoxLayout *bookLayout = new QVBoxLayout;
    bookLayout->addLayout(backendLayout);
    bookLayout->addWidget(m_contactsList);
    bookLayout->addLayout(btnLayout1);
#ifdef BUILD_VERSIT
    bookLayout->addLayout(btnLayout2);
#endif

    setLayout(bookLayout);

    // force update to backend.
    QTimer::singleShot(0, this, SLOT(backendSelected()));
}

ContactListPage::~ContactListPage()
{
    QList<QContactManager*> initialisedManagers = m_initialisedManagers.values();
    while (!initialisedManagers.isEmpty()) {
        QContactManager *deleteMe = initialisedManagers.takeFirst();
        delete deleteMe;
    }
}

void ContactListPage::backendSelected()
{
    QString managerUri = m_availableManagers.value(m_backendsCombo->currentText());

    // first, check to see if they reselected the same backend.
    if (m_manager && m_manager->managerUri() == managerUri)
        return;

    // the change is real.  update.
    if (m_initialisedManagers.contains(managerUri)) {
        m_manager = m_initialisedManagers.value(managerUri);
    } else {
        m_manager = QContactManager::fromUri(managerUri);
        if (m_manager->error()) {
            QMessageBox::information(this, "Failed!", QString("Failed to open store!\n(error code %1)").arg(m_manager->error()));
            delete m_manager;
            m_manager = 0;
            return;
        }
        m_initialisedManagers.insert(managerUri, m_manager);
    }

    // signal that the manager has changed.
    emit managerChanged(m_manager);

    // and... rebuild the list.
    rebuildList(m_currentFilter);
}

void ContactListPage::rebuildList(const QContactFilter& filter)
{
    // first, check to see whether the filter does anything
    if (filter == QContactFilter())
        m_filterActiveLabel->setText("Inactive");
    else
        m_filterActiveLabel->setText("Active");

    QContact currContact;
    m_currentFilter = filter;
    m_contactsList->clear();
    m_idToListIndex.clear();
    QList<QContactLocalId> contactIds = m_manager->contactIds(m_currentFilter);
    foreach (const QContactLocalId& id, contactIds) {
        QListWidgetItem *currItem = new QListWidgetItem;
        currContact = m_manager->contact(id);
        currItem->setData(Qt::DisplayRole, currContact.displayLabel());
        currItem->setData(Qt::UserRole, currContact.localId()); // also store the id of the contact.
        m_idToListIndex.insert(currContact.localId(), m_contactsList->count());
        m_contactsList->addItem(currItem);
    }
}

void ContactListPage::addContactClicked()
{
    if (m_manager)
        emit showEditorPage(QContactLocalId(0));
}

void ContactListPage::editClicked()
{
    if (m_contactsList->currentItem())
        emit showEditorPage(QContactLocalId(m_contactsList->currentItem()->data(Qt::UserRole).toUInt()));
    // else, nothing selected; ignore.
}

void ContactListPage::filterClicked()
{
    if (m_manager)
        emit showFilterPage(m_currentFilter);
}

void ContactListPage::deleteClicked()
{
    if (!m_manager) {
        qWarning() << "No manager selected; cannot delete.";
        return;
    }

    if (!m_contactsList->currentItem()) {
        qWarning() << "Nothing to delete.";
        return;
    }

    QContactLocalId contactId = QContactLocalId(m_contactsList->currentItem()->data(Qt::UserRole).toUInt());
    bool success = m_manager->removeContact(contactId);
    if (success) {
        delete m_contactsList->takeItem(m_contactsList->currentRow());
        QMessageBox::information(this, "Success!", "Contact deleted successfully!");
    }
    else
        QMessageBox::information(this, "Failed!", "Failed to delete contact!");
}

void ContactListPage::importClicked()
{
#ifdef BUILD_VERSIT
    if (!m_manager) {
        qWarning() << "No manager selected; cannot import";
        return;
    }
    QString fileName = QFileDialog::getOpenFileName(this,
       tr("Select vCard file"), ".", tr("vCard files (*.vcf)"));
    QFile file(fileName);
    file.open(QIODevice::ReadOnly);
    if (file.isReadable()) {
        QVersitReader reader;
        reader.setDevice(&file);
        if (reader.startReading() && reader.waitForFinished()) {
            QVersitContactImporter importer;
            if (importer.importDocuments(reader.results())) {
                QList<QContact> contacts = importer.contacts();
                QMap<int, QContactManager::Error> errorMap;
                m_manager->saveContacts(&contacts, &errorMap);
                rebuildList(m_currentFilter);
            }
        }
    }
#endif
}

void ContactListPage::exportClicked()
{
#ifdef BUILD_VERSIT
    if (!m_manager) {
        qWarning() << "No manager selected; cannot import";
        return;
    }
    QList<QContact> contacts = m_manager->contacts(QList<QContactSortOrder>(), QContactFetchHint());
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save vCard"),
                                                    "./contacts.vcf",
                                                    tr("vCards (*.vcf)"));
    QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    if (file.isWritable()) {
        QVersitContactExporter exporter;
        if(exporter.exportContacts(contacts, QVersitDocument::VCard30Type)) {
            QList<QVersitDocument> documents = exporter.documents();
            QVersitWriter writer;
            writer.setDevice(&file);
            writer.startWriting(documents);
            writer.waitForFinished();
        }
    }
#endif
}
<commit_msg>QTMOBILITY-145:The default manager name always is invalid in samplephonebook.exe<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "contactlistpage.h"
#ifdef BUILD_VERSIT
#include "qversitreader.h"
#include "qversitcontactimporter.h"
#include "qversitwriter.h"
#include "qversitcontactexporter.h"
#endif

#include <QtGui>

ContactListPage::ContactListPage(QWidget *parent)
        : QWidget(parent)
{
    m_manager = 0;
    m_currentFilter = QContactFilter();

    m_backendsCombo = new QComboBox(this);
    QStringList availableManagers = QContactManager::availableManagers();
    availableManagers.removeAll("invalid");
    foreach(QString managerName, availableManagers) {

        QMap<QString, QString> params;
        QString managerUri = QContactManager::buildUri(managerName, params);

        // Add some parameters to SIM backend so that we can use
        // all the stores.
        if (managerName == "symbiansim") {
            availableManagers.removeAll("symbiansim");

            availableManagers.append("symbiansim:adn");
            params.insert("store", "ADN");
            managerUri = QContactManager::buildUri(managerName, params);
            m_availableManagers.insert(availableManagers.last(), managerUri);

            availableManagers.append("symbiansim:fdn");
            params.clear();
            params.insert("store", "FDN");
            managerUri = QContactManager::buildUri(managerName, params);
            m_availableManagers.insert(availableManagers.last(), managerUri);

            availableManagers.append("symbiansim:sdn");
            params.clear();
            params.insert("store", "SDN");
            managerUri = QContactManager::buildUri(managerName, params);
            m_availableManagers.insert(availableManagers.last(), managerUri);
        }
        else {
            m_availableManagers.insert(managerName, managerUri);
        }
    }
    m_backendsCombo->addItems(availableManagers);
    connect(m_backendsCombo, SIGNAL(currentIndexChanged(QString)), this, SLOT(backendSelected()));
    m_filterActiveLabel = new QLabel("Inactive");
    m_filterActiveLabel->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));

    m_contactsList = new QListWidget(this);

    QPushButton* m_addContactBtn = new QPushButton("Add", this);
    connect(m_addContactBtn, SIGNAL(clicked()), this, SLOT(addContactClicked()));
    QPushButton* m_editBtn = new QPushButton("Edit", this);
    connect(m_editBtn, SIGNAL(clicked()), this, SLOT(editClicked()));
    QPushButton* m_deleteBtn = new QPushButton("Delete", this);
    connect(m_deleteBtn, SIGNAL(clicked()), this, SLOT(deleteClicked()));
    QPushButton* m_filterBtn = new QPushButton("Filter", this);
    connect(m_filterBtn, SIGNAL(clicked()), this, SLOT(filterClicked()));
    QPushButton* m_importBtn = new QPushButton("Import");
    connect(m_importBtn, SIGNAL(clicked()), this, SLOT(importClicked()));
    QPushButton* m_exportBtn = new QPushButton("Export");
    connect(m_exportBtn, SIGNAL(clicked()), this, SLOT(exportClicked()));

    QFormLayout *backendLayout = new QFormLayout;
    backendLayout->addRow("Store:", m_backendsCombo);
    backendLayout->addRow("Filter:", m_filterActiveLabel);

    QHBoxLayout *btnLayout1 = new QHBoxLayout;
    btnLayout1->addWidget(m_addContactBtn);
    btnLayout1->addWidget(m_editBtn);
    btnLayout1->addWidget(m_deleteBtn);
    btnLayout1->addWidget(m_filterBtn);

    QHBoxLayout *btnLayout2 = new QHBoxLayout;
    btnLayout2->addWidget(m_importBtn);
    btnLayout2->addWidget(m_exportBtn);

    QVBoxLayout *bookLayout = new QVBoxLayout;
    bookLayout->addLayout(backendLayout);
    bookLayout->addWidget(m_contactsList);
    bookLayout->addLayout(btnLayout1);
#ifdef BUILD_VERSIT
    bookLayout->addLayout(btnLayout2);
#endif

    setLayout(bookLayout);

    // force update to backend.
    QTimer::singleShot(0, this, SLOT(backendSelected()));
}

ContactListPage::~ContactListPage()
{
    QList<QContactManager*> initialisedManagers = m_initialisedManagers.values();
    while (!initialisedManagers.isEmpty()) {
        QContactManager *deleteMe = initialisedManagers.takeFirst();
        delete deleteMe;
    }
}

void ContactListPage::backendSelected()
{
    QString managerUri = m_availableManagers.value(m_backendsCombo->currentText());

    // first, check to see if they reselected the same backend.
    if (m_manager && m_manager->managerUri() == managerUri)
        return;

    // the change is real.  update.
    if (m_initialisedManagers.contains(managerUri)) {
        m_manager = m_initialisedManagers.value(managerUri);
    } else {
        m_manager = QContactManager::fromUri(managerUri);
        if (m_manager->error()) {
            QMessageBox::information(this, "Failed!", QString("Failed to open store!\n(error code %1)").arg(m_manager->error()));
            delete m_manager;
            m_manager = 0;
            return;
        }
        m_initialisedManagers.insert(managerUri, m_manager);
    }

    // signal that the manager has changed.
    emit managerChanged(m_manager);

    // and... rebuild the list.
    rebuildList(m_currentFilter);
}

void ContactListPage::rebuildList(const QContactFilter& filter)
{
    // first, check to see whether the filter does anything
    if (filter == QContactFilter())
        m_filterActiveLabel->setText("Inactive");
    else
        m_filterActiveLabel->setText("Active");

    QContact currContact;
    m_currentFilter = filter;
    m_contactsList->clear();
    m_idToListIndex.clear();
    QList<QContactLocalId> contactIds = m_manager->contactIds(m_currentFilter);
    foreach (const QContactLocalId& id, contactIds) {
        QListWidgetItem *currItem = new QListWidgetItem;
        currContact = m_manager->contact(id);
        currItem->setData(Qt::DisplayRole, currContact.displayLabel());
        currItem->setData(Qt::UserRole, currContact.localId()); // also store the id of the contact.
        m_idToListIndex.insert(currContact.localId(), m_contactsList->count());
        m_contactsList->addItem(currItem);
    }
}

void ContactListPage::addContactClicked()
{
    if (m_manager)
        emit showEditorPage(QContactLocalId(0));
}

void ContactListPage::editClicked()
{
    if (m_contactsList->currentItem())
        emit showEditorPage(QContactLocalId(m_contactsList->currentItem()->data(Qt::UserRole).toUInt()));
    // else, nothing selected; ignore.
}

void ContactListPage::filterClicked()
{
    if (m_manager)
        emit showFilterPage(m_currentFilter);
}

void ContactListPage::deleteClicked()
{
    if (!m_manager) {
        qWarning() << "No manager selected; cannot delete.";
        return;
    }

    if (!m_contactsList->currentItem()) {
        qWarning() << "Nothing to delete.";
        return;
    }

    QContactLocalId contactId = QContactLocalId(m_contactsList->currentItem()->data(Qt::UserRole).toUInt());
    bool success = m_manager->removeContact(contactId);
    if (success) {
        delete m_contactsList->takeItem(m_contactsList->currentRow());
        QMessageBox::information(this, "Success!", "Contact deleted successfully!");
    }
    else
        QMessageBox::information(this, "Failed!", "Failed to delete contact!");
}

void ContactListPage::importClicked()
{
#ifdef BUILD_VERSIT
    if (!m_manager) {
        qWarning() << "No manager selected; cannot import";
        return;
    }
    QString fileName = QFileDialog::getOpenFileName(this,
       tr("Select vCard file"), ".", tr("vCard files (*.vcf)"));
    QFile file(fileName);
    file.open(QIODevice::ReadOnly);
    if (file.isReadable()) {
        QVersitReader reader;
        reader.setDevice(&file);
        if (reader.startReading() && reader.waitForFinished()) {
            QVersitContactImporter importer;
            if (importer.importDocuments(reader.results())) {
                QList<QContact> contacts = importer.contacts();
                QMap<int, QContactManager::Error> errorMap;
                m_manager->saveContacts(&contacts, &errorMap);
                rebuildList(m_currentFilter);
            }
        }
    }
#endif
}

void ContactListPage::exportClicked()
{
#ifdef BUILD_VERSIT
    if (!m_manager) {
        qWarning() << "No manager selected; cannot import";
        return;
    }
    QList<QContact> contacts = m_manager->contacts(QList<QContactSortOrder>(), QContactFetchHint());
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save vCard"),
                                                    "./contacts.vcf",
                                                    tr("vCards (*.vcf)"));
    QFile file(fileName);
    file.open(QIODevice::WriteOnly);
    if (file.isWritable()) {
        QVersitContactExporter exporter;
        if(exporter.exportContacts(contacts, QVersitDocument::VCard30Type)) {
            QList<QVersitDocument> documents = exporter.documents();
            QVersitWriter writer;
            writer.setDevice(&file);
            writer.startWriting(documents);
            writer.waitForFinished();
        }
    }
#endif
}
<|endoftext|>


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

#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"

#include <stdlib.h>
#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "xwalk/application/browser/application_service.h"
#include "xwalk/application/browser/application_system.h"
#include "xwalk/application/common/application.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/experimental/dialog/dialog_extension.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/devtools/remote_debugging_server.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/runtime_registry.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#include "xwalk/runtime/extension/runtime_extension.h"
#include "cc/base/switches.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/result_codes.h"
#include "grit/net_resources.h"
#include "net/base/net_util.h"
#include "net/base/net_module.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/gl/gl_switches.h"

#if defined(OS_ANDROID)
#include "content/public/browser/android/compositor.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/l10n/l10n_util_android.h"
#endif  // defined(OS_ANDROID)

#if defined(OS_TIZEN_MOBILE)
#include "xwalk/application/browser/installer/tizen/package_installer.h"
#endif  // defined(OS_TIZEN_MOBILE)

namespace {

base::StringPiece PlatformResourceProvider(int key) {
  if (key == IDR_DIR_HEADER_HTML) {
    base::StringPiece html_data =
        ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
            IDR_DIR_HEADER_HTML);
    return html_data;
  }
  return base::StringPiece();
}

// FIXME: Compare with method in startup_browser_creator.cc.
static GURL GetURLFromCommandLine(const CommandLine& command_line) {
#if !defined(OS_ANDROID)
  const CommandLine::StringVector& args = command_line.GetArgs();

  if (args.empty())
    return GURL();

  GURL url(args[0]);
  if (url.is_valid() && url.has_scheme()) {
    return url;
  } else {
    base::FilePath path(args[0]);
    if (!path.IsAbsolute())
      path = MakeAbsoluteFilePath(path);
    return url = net::FilePathToFileURL(path);
  }
#endif
  return GURL();
}

}  // namespace

namespace xswitches {
// Redefine settings not exposed by content module.
const char kEnableViewport[] = "enable-viewport";
}

namespace xwalk {

void SetXWalkCommandLineFlags() {
  static bool already_initialized = false;
  if (already_initialized)
    return;
  already_initialized = true;

  CommandLine* command_line = CommandLine::ForCurrentProcess();

#if defined(OS_TIZEN_MOBILE)
  command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);

  const char* gl_name;
  if (base::PathExists(base::FilePath("/usr/lib/xwalk/libosmesa.so")))
    gl_name = gfx::kGLImplementationOSMesaName;
  else if (base::PathExists(base::FilePath("/usr/lib/libGL.so")))
    gl_name = gfx::kGLImplementationDesktopName;
  else
    gl_name = gfx::kGLImplementationEGLName;
  command_line->AppendSwitchASCII(switches::kUseGL, gl_name);
#endif

  // Always use fixed layout and viewport tag.
  command_line->AppendSwitch(switches::kEnableFixedLayout);
  command_line->AppendSwitch(xswitches::kEnableViewport);

  // Show feedback on touch.
  command_line->AppendSwitch(switches::kEnableGestureTapHighlight);

#if defined(OS_ANDROID)
  // Disable ExtensionProcess for Android.
  // External extensions will run in the BrowserProcess (in process mode).
  command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess);
#endif

  // FIXME: Add comment why this is needed on Android and Tizen.
  command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
}

XWalkBrowserMainParts::XWalkBrowserMainParts(
    const content::MainFunctionParams& parameters)
    : BrowserMainParts(),
      startup_url_(content::kAboutBlankURL),
      parameters_(parameters),
      run_default_message_loop_(true) {
}

XWalkBrowserMainParts::~XWalkBrowserMainParts() {
}

#if defined(OS_ANDROID)
void XWalkBrowserMainParts::SetRuntimeContext(RuntimeContext* context) {
  runtime_context_ = context;
}
#endif

void XWalkBrowserMainParts::PreMainMessageLoopStart() {
  SetXWalkCommandLineFlags();

  CommandLine* command_line = CommandLine::ForCurrentProcess();
  startup_url_ = GetURLFromCommandLine(*command_line);

#if defined(OS_MACOSX)
  PreMainMessageLoopStartMac();
#endif
}

void XWalkBrowserMainParts::PostMainMessageLoopStart() {
#if defined(OS_ANDROID)
  base::MessageLoopForUI::current()->Start();
#endif
}

void XWalkBrowserMainParts::PreEarlyInitialization() {
#if defined(OS_ANDROID)
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());

  CommandLine::ForCurrentProcess()->AppendSwitch(
      cc::switches::kCompositeToMailbox);

  // Initialize the Compositor.
  content::Compositor::Initialize();
#endif

#if defined(OS_LINUX)
  // FIXME: We disable the setuid sandbox on Linux because we don't ship
  // the setuid binary. It is important to remember that the seccomp-bpf
  // sandbox is still fully operational if supported by the kernel. See
  // issue #496.
  //
  // switches::kDisableSetuidSandbox is not being used here because it
  // doesn't have the CONTENT_EXPORT macro despite the fact it is exposed by
  // content_switches.h.
  CommandLine::ForCurrentProcess()->AppendSwitch("disable-setuid-sandbox");
#endif
}

int XWalkBrowserMainParts::PreCreateThreads() {
#if defined(OS_ANDROID)
  DCHECK(runtime_context_);
  runtime_context_->InitializeBeforeThreadCreation();
#endif
  return content::RESULT_CODE_NORMAL_EXIT;
}

void XWalkBrowserMainParts::RegisterExternalExtensions() {
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (!cmd_line->HasSwitch(switches::kXWalkExternalExtensionsPath))
    return;

  if (!cmd_line->HasSwitch(
          switches::kXWalkAllowExternalExtensionsForRemoteSources) &&
      !startup_url_.SchemeIsFile()) {
    VLOG(0) << "Unsupported scheme for external extensions: " <<
          startup_url_.scheme();
    return;
  }

  base::FilePath extensions_dir =
      cmd_line->GetSwitchValuePath(switches::kXWalkExternalExtensionsPath);
  if (!base::DirectoryExists(extensions_dir)) {
    LOG(WARNING) << "Ignoring non-existent extension directory: "
                 << extensions_dir.AsUTF8Unsafe();
    return;
  }

  extension_service_->RegisterExternalExtensionsForPath(extensions_dir);
}

void XWalkBrowserMainParts::PreMainMessageLoopRun() {
#if defined(OS_ANDROID)
  net::NetModule::SetResourceProvider(PlatformResourceProvider);
  if (parameters_.ui_task) {
    parameters_.ui_task->Run();
    delete parameters_.ui_task;
    run_default_message_loop_ = false;
  }

  DCHECK(runtime_context_);
  runtime_context_->PreMainMessageLoopRun();
  runtime_registry_.reset(new RuntimeRegistry);
  extension_service_.reset(
      new extensions::XWalkExtensionService());
#else
  runtime_context_.reset(new RuntimeContext);
  runtime_registry_.reset(new RuntimeRegistry);
  extension_service_.reset(
      new extensions::XWalkExtensionService());

  RegisterInternalExtensions();
  RegisterExternalExtensions();

  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
    std::string port_str =
        command_line->GetSwitchValueASCII(switches::kRemoteDebuggingPort);
    int port;
    const char* loopback_ip = "127.0.0.1";
    if (base::StringToInt(port_str, &port) && port > 0 && port < 65535) {
      remote_debugging_server_.reset(
          new RemoteDebuggingServer(runtime_context_.get(),
              loopback_ip, port, std::string()));
    }
  }

  NativeAppWindow::Initialize();

  std::string command_name =
      command_line->GetProgram().BaseName().MaybeAsASCII();

#if defined(OS_TIZEN_MOBILE)
  // On Tizen, applications are launched by a symbolic link
  // named like the application ID.
  if (startup_url_.SchemeIsFile() || command_name.compare("xwalk") != 0) {
#else
  if (startup_url_.SchemeIsFile()) {
#endif  // OS_TIZEN_MOBILE
    xwalk::application::ApplicationSystem* system =
        runtime_context_->GetApplicationSystem();
    xwalk::application::ApplicationService* service =
        system->application_service();

    if (xwalk::application::Application::IsIDValid(command_name)) {
      run_default_message_loop_ = service->Launch(command_name);
      return;
    }

    const CommandLine::StringVector& args = command_line->GetArgs();
    std::string id;
    if (args.size() > 0)
      id = std::string(args[0].begin(), args[0].end());
    if (xwalk::application::Application::IsIDValid(id)) {
      if (command_line->HasSwitch(switches::kUninstall)) {
#if defined(OS_TIZEN_MOBILE)
        scoped_refptr<xwalk::application::PackageInstaller> installer =
            xwalk::application::PackageInstaller::Create(service, id,
                runtime_context_->GetPath());
        if (!installer->Uninstall()) {
          LOG(ERROR) << "[ERR] An error occurred during uninstalling on Tizen.";
          return;
        }
#endif
        if (!service->Uninstall(id))
          LOG(ERROR) << "[ERR] An error occurred during"
                        "uninstalling application "
                     << id;
        else
          LOG(INFO) << "[OK] Application uninstalled successfully: " << id;
        run_default_message_loop_ = false;
      } else {
        run_default_message_loop_ = service->Launch(id);
      }
      return;
    }
    base::FilePath path;
    if (!net::FileURLToFilePath(startup_url_, &path))
      return;
    if (command_line->HasSwitch(switches::kInstall)) {
      if (base::PathExists(path)) {
        std::string id;
        if (service->Install(path, &id)) {
#if defined(OS_TIZEN_MOBILE)
          scoped_refptr<xwalk::application::PackageInstaller> installer =
              xwalk::application::PackageInstaller::Create(service, id,
                  runtime_context_->GetPath());
          if (!installer->Install()) {
            LOG(ERROR) << "[ERR] An error occurred during installing on Tizen.";
            return;
          }
#endif  // OS_TIZEN_MOBILE
          LOG(INFO) << "[OK] Application installed: " << id;
        } else {
          LOG(ERROR) << "[ERR] Application install failure: " << path.value();
        }
      }
      run_default_message_loop_ = false;
      return;
    } else if (base::DirectoryExists(path)) {
      run_default_message_loop_ = service->Launch(path);
      return;
    }
  }

  // The new created Runtime instance will be managed by RuntimeRegistry.
  Runtime::CreateWithDefaultWindow(runtime_context_.get(), startup_url_);

  // If the |ui_task| is specified in main function parameter, it indicates
  // that we will run this UI task instead of running the the default main
  // message loop. See |content::BrowserTestBase::SetUp| for |ui_task| usage
  // case.
  if (parameters_.ui_task) {
    parameters_.ui_task->Run();
    delete parameters_.ui_task;
    run_default_message_loop_ = false;
  }
#endif
}

bool XWalkBrowserMainParts::MainMessageLoopRun(int* result_code) {
  return !run_default_message_loop_;
}

void XWalkBrowserMainParts::PostMainMessageLoopRun() {
#if defined(OS_ANDROID)
  base::MessageLoopForUI::current()->Start();
#else
  runtime_context_.reset();
#endif
}

void XWalkBrowserMainParts::RegisterInternalExtensions() {
  extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
      new RuntimeExtension()));
  extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
      new experimental::DialogExtension(runtime_registry_.get())));
}

}  // namespace xwalk
<commit_msg>[Temp] [Android] A temporary way to enable WebGL for Android port.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/xwalk_browser_main_parts.h"

#include <stdlib.h>
#include <string>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "xwalk/application/browser/application_service.h"
#include "xwalk/application/browser/application_system.h"
#include "xwalk/application/common/application.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/experimental/dialog/dialog_extension.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/devtools/remote_debugging_server.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_context.h"
#include "xwalk/runtime/browser/runtime_registry.h"
#include "xwalk/runtime/common/xwalk_switches.h"
#include "xwalk/runtime/extension/runtime_extension.h"
#include "cc/base/switches.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/result_codes.h"
#include "grit/net_resources.h"
#include "net/base/net_util.h"
#include "net/base/net_module.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"
#include "ui/gl/gl_switches.h"

#if defined(OS_ANDROID)
#include "content/public/browser/android/compositor.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/l10n/l10n_util_android.h"
#endif  // defined(OS_ANDROID)

#if defined(OS_TIZEN_MOBILE)
#include "xwalk/application/browser/installer/tizen/package_installer.h"
#endif  // defined(OS_TIZEN_MOBILE)

namespace {

base::StringPiece PlatformResourceProvider(int key) {
  if (key == IDR_DIR_HEADER_HTML) {
    base::StringPiece html_data =
        ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
            IDR_DIR_HEADER_HTML);
    return html_data;
  }
  return base::StringPiece();
}

// FIXME: Compare with method in startup_browser_creator.cc.
static GURL GetURLFromCommandLine(const CommandLine& command_line) {
#if !defined(OS_ANDROID)
  const CommandLine::StringVector& args = command_line.GetArgs();

  if (args.empty())
    return GURL();

  GURL url(args[0]);
  if (url.is_valid() && url.has_scheme()) {
    return url;
  } else {
    base::FilePath path(args[0]);
    if (!path.IsAbsolute())
      path = MakeAbsoluteFilePath(path);
    return url = net::FilePathToFileURL(path);
  }
#endif
  return GURL();
}

}  // namespace

namespace xswitches {
// Redefine settings not exposed by content module.
const char kEnableViewport[] = "enable-viewport";
}

namespace xwalk {

void SetXWalkCommandLineFlags() {
  static bool already_initialized = false;
  if (already_initialized)
    return;
  already_initialized = true;

  CommandLine* command_line = CommandLine::ForCurrentProcess();

#if defined(OS_TIZEN_MOBILE)
  command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);

  const char* gl_name;
  if (base::PathExists(base::FilePath("/usr/lib/xwalk/libosmesa.so")))
    gl_name = gfx::kGLImplementationOSMesaName;
  else if (base::PathExists(base::FilePath("/usr/lib/libGL.so")))
    gl_name = gfx::kGLImplementationDesktopName;
  else
    gl_name = gfx::kGLImplementationEGLName;
  command_line->AppendSwitchASCII(switches::kUseGL, gl_name);
#endif

  // Always use fixed layout and viewport tag.
  command_line->AppendSwitch(switches::kEnableFixedLayout);
  command_line->AppendSwitch(xswitches::kEnableViewport);

  // Show feedback on touch.
  command_line->AppendSwitch(switches::kEnableGestureTapHighlight);

#if defined(OS_ANDROID)
  // Disable ExtensionProcess for Android.
  // External extensions will run in the BrowserProcess (in process mode).
  command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess);

  // Enable WebGL for Android.
  command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
#endif

  // FIXME: Add comment why this is needed on Android and Tizen.
  command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
}

XWalkBrowserMainParts::XWalkBrowserMainParts(
    const content::MainFunctionParams& parameters)
    : BrowserMainParts(),
      startup_url_(content::kAboutBlankURL),
      parameters_(parameters),
      run_default_message_loop_(true) {
}

XWalkBrowserMainParts::~XWalkBrowserMainParts() {
}

#if defined(OS_ANDROID)
void XWalkBrowserMainParts::SetRuntimeContext(RuntimeContext* context) {
  runtime_context_ = context;
}
#endif

void XWalkBrowserMainParts::PreMainMessageLoopStart() {
  SetXWalkCommandLineFlags();

  CommandLine* command_line = CommandLine::ForCurrentProcess();
  startup_url_ = GetURLFromCommandLine(*command_line);

#if defined(OS_MACOSX)
  PreMainMessageLoopStartMac();
#endif
}

void XWalkBrowserMainParts::PostMainMessageLoopStart() {
#if defined(OS_ANDROID)
  base::MessageLoopForUI::current()->Start();
#endif
}

void XWalkBrowserMainParts::PreEarlyInitialization() {
#if defined(OS_ANDROID)
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());

  CommandLine::ForCurrentProcess()->AppendSwitch(
      cc::switches::kCompositeToMailbox);

  // Initialize the Compositor.
  content::Compositor::Initialize();
#endif

#if defined(OS_LINUX)
  // FIXME: We disable the setuid sandbox on Linux because we don't ship
  // the setuid binary. It is important to remember that the seccomp-bpf
  // sandbox is still fully operational if supported by the kernel. See
  // issue #496.
  //
  // switches::kDisableSetuidSandbox is not being used here because it
  // doesn't have the CONTENT_EXPORT macro despite the fact it is exposed by
  // content_switches.h.
  CommandLine::ForCurrentProcess()->AppendSwitch("disable-setuid-sandbox");
#endif
}

int XWalkBrowserMainParts::PreCreateThreads() {
#if defined(OS_ANDROID)
  DCHECK(runtime_context_);
  runtime_context_->InitializeBeforeThreadCreation();
#endif
  return content::RESULT_CODE_NORMAL_EXIT;
}

void XWalkBrowserMainParts::RegisterExternalExtensions() {
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (!cmd_line->HasSwitch(switches::kXWalkExternalExtensionsPath))
    return;

  if (!cmd_line->HasSwitch(
          switches::kXWalkAllowExternalExtensionsForRemoteSources) &&
      !startup_url_.SchemeIsFile()) {
    VLOG(0) << "Unsupported scheme for external extensions: " <<
          startup_url_.scheme();
    return;
  }

  base::FilePath extensions_dir =
      cmd_line->GetSwitchValuePath(switches::kXWalkExternalExtensionsPath);
  if (!base::DirectoryExists(extensions_dir)) {
    LOG(WARNING) << "Ignoring non-existent extension directory: "
                 << extensions_dir.AsUTF8Unsafe();
    return;
  }

  extension_service_->RegisterExternalExtensionsForPath(extensions_dir);
}

void XWalkBrowserMainParts::PreMainMessageLoopRun() {
#if defined(OS_ANDROID)
  net::NetModule::SetResourceProvider(PlatformResourceProvider);
  if (parameters_.ui_task) {
    parameters_.ui_task->Run();
    delete parameters_.ui_task;
    run_default_message_loop_ = false;
  }

  DCHECK(runtime_context_);
  runtime_context_->PreMainMessageLoopRun();
  runtime_registry_.reset(new RuntimeRegistry);
  extension_service_.reset(
      new extensions::XWalkExtensionService());
#else
  runtime_context_.reset(new RuntimeContext);
  runtime_registry_.reset(new RuntimeRegistry);
  extension_service_.reset(
      new extensions::XWalkExtensionService());

  RegisterInternalExtensions();
  RegisterExternalExtensions();

  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) {
    std::string port_str =
        command_line->GetSwitchValueASCII(switches::kRemoteDebuggingPort);
    int port;
    const char* loopback_ip = "127.0.0.1";
    if (base::StringToInt(port_str, &port) && port > 0 && port < 65535) {
      remote_debugging_server_.reset(
          new RemoteDebuggingServer(runtime_context_.get(),
              loopback_ip, port, std::string()));
    }
  }

  NativeAppWindow::Initialize();

  std::string command_name =
      command_line->GetProgram().BaseName().MaybeAsASCII();

#if defined(OS_TIZEN_MOBILE)
  // On Tizen, applications are launched by a symbolic link
  // named like the application ID.
  if (startup_url_.SchemeIsFile() || command_name.compare("xwalk") != 0) {
#else
  if (startup_url_.SchemeIsFile()) {
#endif  // OS_TIZEN_MOBILE
    xwalk::application::ApplicationSystem* system =
        runtime_context_->GetApplicationSystem();
    xwalk::application::ApplicationService* service =
        system->application_service();

    if (xwalk::application::Application::IsIDValid(command_name)) {
      run_default_message_loop_ = service->Launch(command_name);
      return;
    }

    const CommandLine::StringVector& args = command_line->GetArgs();
    std::string id;
    if (args.size() > 0)
      id = std::string(args[0].begin(), args[0].end());
    if (xwalk::application::Application::IsIDValid(id)) {
      if (command_line->HasSwitch(switches::kUninstall)) {
#if defined(OS_TIZEN_MOBILE)
        scoped_refptr<xwalk::application::PackageInstaller> installer =
            xwalk::application::PackageInstaller::Create(service, id,
                runtime_context_->GetPath());
        if (!installer->Uninstall()) {
          LOG(ERROR) << "[ERR] An error occurred during uninstalling on Tizen.";
          return;
        }
#endif
        if (!service->Uninstall(id))
          LOG(ERROR) << "[ERR] An error occurred during"
                        "uninstalling application "
                     << id;
        else
          LOG(INFO) << "[OK] Application uninstalled successfully: " << id;
        run_default_message_loop_ = false;
      } else {
        run_default_message_loop_ = service->Launch(id);
      }
      return;
    }
    base::FilePath path;
    if (!net::FileURLToFilePath(startup_url_, &path))
      return;
    if (command_line->HasSwitch(switches::kInstall)) {
      if (base::PathExists(path)) {
        std::string id;
        if (service->Install(path, &id)) {
#if defined(OS_TIZEN_MOBILE)
          scoped_refptr<xwalk::application::PackageInstaller> installer =
              xwalk::application::PackageInstaller::Create(service, id,
                  runtime_context_->GetPath());
          if (!installer->Install()) {
            LOG(ERROR) << "[ERR] An error occurred during installing on Tizen.";
            return;
          }
#endif  // OS_TIZEN_MOBILE
          LOG(INFO) << "[OK] Application installed: " << id;
        } else {
          LOG(ERROR) << "[ERR] Application install failure: " << path.value();
        }
      }
      run_default_message_loop_ = false;
      return;
    } else if (base::DirectoryExists(path)) {
      run_default_message_loop_ = service->Launch(path);
      return;
    }
  }

  // The new created Runtime instance will be managed by RuntimeRegistry.
  Runtime::CreateWithDefaultWindow(runtime_context_.get(), startup_url_);

  // If the |ui_task| is specified in main function parameter, it indicates
  // that we will run this UI task instead of running the the default main
  // message loop. See |content::BrowserTestBase::SetUp| for |ui_task| usage
  // case.
  if (parameters_.ui_task) {
    parameters_.ui_task->Run();
    delete parameters_.ui_task;
    run_default_message_loop_ = false;
  }
#endif
}

bool XWalkBrowserMainParts::MainMessageLoopRun(int* result_code) {
  return !run_default_message_loop_;
}

void XWalkBrowserMainParts::PostMainMessageLoopRun() {
#if defined(OS_ANDROID)
  base::MessageLoopForUI::current()->Start();
#else
  runtime_context_.reset();
#endif
}

void XWalkBrowserMainParts::RegisterInternalExtensions() {
  extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
      new RuntimeExtension()));
  extension_service_->RegisterExtension(scoped_ptr<XWalkExtension>(
      new experimental::DialogExtension(runtime_registry_.get())));
}

}  // namespace xwalk
<|endoftext|>


<commit_before>/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   unhandled_exception_count.cpp
 * \author Andrey Semashev
 * \date   05.11.2012
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/libs/log/doc/log.html.
 *
 * The code in this file is based on the implementation by Evgeny Panasyuk:
 *
 * https://github.com/panaseleus/stack_unwinding/blob/master/boost/exception/uncaught_exception_count.hpp
 */

#include <exception>
#include <boost/log/detail/unhandled_exception_count.hpp>
#include <boost/log/detail/header.hpp>

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

BOOST_LOG_ANONYMOUS_NAMESPACE {

#if defined(BOOST_LOG_HAS_CXXABI_H)
// Only GCC 4.7 declares __cxa_get_globals() in cxxabi.h, older compilers do not expose this function but it's there
extern "C" void* __cxa_get_globals();
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define BOOST_LOG_HAS_GETPTD
extern "C" void* _getptd();
#endif

} // namespace

//! Returns the number of currently pending exceptions
BOOST_LOG_API unsigned int unhandled_exception_count() BOOST_NOEXCEPT
{
#if defined(BOOST_LOG_HAS_CXXABI_H)
    // Tested on {clang 3.2,GCC 3.5.6,GCC 4.1.2,GCC 4.4.6,GCC 4.4.7}x{x32,x64}
    return *(reinterpret_cast< const unsigned int* >(static_cast< const char* >(__cxa_get_globals()) + sizeof(void*))); // __cxa_eh_globals::uncaughtExceptions, x32 offset - 0x4, x64 - 0x8
#elif defined(BOOST_LOG_HAS_GETPTD)
    // MSVC specific. Tested on {MSVC2005SP1,MSVC2008SP1,MSVC2010SP1,MSVC2012}x{x32,x64}.
    return *(reinterpret_cast< const unsigned int* >(static_cast< const char* >(_getptd()) + (sizeof(void*) == 8 ? 0x100 : 0x90))); // _tiddata::_ProcessingThrow, x32 offset - 0x90, x64 - 0x100
#else
    return static_cast< unsigned int >(std::unhandled_exception());
#endif
}

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>
<commit_msg>Fall back to portable implementation of unhandled_exception_count() on MinGW GCC 4.4 as it seems to not work the same way as the newer versions of GCC do.<commit_after>/*
 *          Copyright Andrey Semashev 2007 - 2013.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   unhandled_exception_count.cpp
 * \author Andrey Semashev
 * \date   05.11.2012
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/libs/log/doc/log.html.
 *
 * The code in this file is based on the implementation by Evgeny Panasyuk:
 *
 * https://github.com/panaseleus/stack_unwinding/blob/master/boost/exception/uncaught_exception_count.hpp
 */

#include <exception>
#include <boost/log/detail/unhandled_exception_count.hpp>
#include <boost/log/detail/header.hpp>

namespace boost {

BOOST_LOG_OPEN_NAMESPACE

namespace aux {

BOOST_LOG_ANONYMOUS_NAMESPACE {

#if defined(BOOST_LOG_HAS_CXXABI_H)
// MinGW GCC 4.4 seem to not work the same way the newer GCC versions do. As a result, __cxa_get_globals based implementation will always return 0.
// Just disable it for now and fall back to std::unhandled_exception().
#if !defined(__MINGW32__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)))
// Only GCC 4.7 declares __cxa_get_globals() in cxxabi.h, older compilers do not expose this function but it's there
#define BOOST_LOG_HAS_CXA_GET_GLOBALS
extern "C" void* __cxa_get_globals();
#endif
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define BOOST_LOG_HAS_GETPTD
extern "C" void* _getptd();
#endif

} // namespace

//! Returns the number of currently pending exceptions
BOOST_LOG_API unsigned int unhandled_exception_count() BOOST_NOEXCEPT
{
#if defined(BOOST_LOG_HAS_CXA_GET_GLOBALS)
    // Tested on {clang 3.2,GCC 3.5.6,GCC 4.1.2,GCC 4.4.6,GCC 4.4.7}x{x32,x64}
    return *(reinterpret_cast< const unsigned int* >(static_cast< const char* >(__cxa_get_globals()) + sizeof(void*))); // __cxa_eh_globals::uncaughtExceptions, x32 offset - 0x4, x64 - 0x8
#elif defined(BOOST_LOG_HAS_GETPTD)
    // MSVC specific. Tested on {MSVC2005SP1,MSVC2008SP1,MSVC2010SP1,MSVC2012}x{x32,x64}.
    return *(reinterpret_cast< const unsigned int* >(static_cast< const char* >(_getptd()) + (sizeof(void*) == 8 ? 0x100 : 0x90))); // _tiddata::_ProcessingThrow, x32 offset - 0x90, x64 - 0x100
#else
    // Portable implementation. Does not allow to detect multiple nested exceptions.
    return static_cast< unsigned int >(std::unhandled_exception());
#endif
}

} // namespace aux

BOOST_LOG_CLOSE_NAMESPACE // namespace log

} // namespace boost

#include <boost/log/detail/footer.hpp>
<|endoftext|>


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

/*
 * XSEC
 *
 * XSECTXFMInputSource := Transfomer InputSource for Xerces Parser.
 *
 * $Id$
 *
 *
 */

#include "XSECTXFMInputSource.hpp"
#include <xsec/transformers/TXFMBase.hpp>
#include <xsec/utils/XSECBinTXFMInputStream.hpp>
#include <xsec/framework/XSECError.hpp>

#include <xercesc/util/BinInputStream.hpp>

XERCES_CPP_NAMESPACE_USE

// --------------------------------------------------------------------------------
//           Construct/Destruct
// --------------------------------------------------------------------------------

XSECTXFMInputSource::XSECTXFMInputSource(TXFMChain * chain, bool deleteWhenDone) :

mp_chain(chain),
m_deleteWhenDone(deleteWhenDone) {
}

XSECTXFMInputSource::~XSECTXFMInputSource() {
}

// --------------------------------------------------------------------------------
//           Create the stream
// --------------------------------------------------------------------------------

BinInputStream* XSECTXFMInputSource::makeStream() const {

	XSECBinTXFMInputStream * ret;

	// Have to do direct due to strange issues with MSVC++ and DEBUG_NEW
	ret = new XSECBinTXFMInputStream(mp_chain, m_deleteWhenDone);

	return ret;

}

<commit_msg>Local reference to header fails during RPM build.<commit_after>/*
 * Copyright 2002-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * XSEC
 *
 * XSECTXFMInputSource := Transfomer InputSource for Xerces Parser.
 *
 * $Id$
 *
 *
 */

#include <xsec/transformers/TXFMBase.hpp>
#include <xsec/utils/XSECBinTXFMInputStream.hpp>
#include <xsec/utils/XSECTXFMInputSource.hpp>
#include <xsec/framework/XSECError.hpp>

#include <xercesc/util/BinInputStream.hpp>

XERCES_CPP_NAMESPACE_USE

// --------------------------------------------------------------------------------
//           Construct/Destruct
// --------------------------------------------------------------------------------

XSECTXFMInputSource::XSECTXFMInputSource(TXFMChain * chain, bool deleteWhenDone) :

mp_chain(chain),
m_deleteWhenDone(deleteWhenDone) {
}

XSECTXFMInputSource::~XSECTXFMInputSource() {
}

// --------------------------------------------------------------------------------
//           Create the stream
// --------------------------------------------------------------------------------

BinInputStream* XSECTXFMInputSource::makeStream() const {

	XSECBinTXFMInputStream * ret;

	// Have to do direct due to strange issues with MSVC++ and DEBUG_NEW
	ret = new XSECBinTXFMInputStream(mp_chain, m_deleteWhenDone);

	return ret;

}

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <set>

// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>
#include <sys/stat.h>

#include <getopt.h>
#include <unistd.h>
#include <alloca.h>

#include <pcafitter.hpp>
#include <pcaffunctype.hpp>

#define MINDIMLINIT 25

// lstorchi: basic quick code to generate PCA constants

namespace
{
  bool file_exists(const std::string& filename)
  {
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
      return true;

    return false;
  }
}

void usage (char * name)
{
  std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl;
  std::cerr << std::endl;
  std::cerr << " -h, --help                      : display this help and exit" << std::endl;
  std::cerr << " -v, --version                   : print version and exit" << std::endl;
  std::cerr << " -j, --jump-tracks               : generate the constants using only even tracks" << std::endl;
  std::cerr << " -p, --dump-allcoords            : dump all stub coordinates to a file" << std::endl;
  std::cerr << " -z, --rz-plane                  : use rz plane view" << std::endl;
  std::cerr << " -r, --rphi-plane                : use r-phi plane view" << std::endl;
  std::cerr << " -e, --not-use-charge            : do not read charge from coordinatesfile, by default " << std::endl;
  std::cerr << "                                   we will  use it if rphi-plane has been selected" << std::endl;
  std::cerr << " -g, --charge-sign=[+/-]         : use only + particle or - paricle " << std::endl;
  std::cerr << " -t, --eta-range=\"etamin,etamax\" : specify the eta range to use " << std::endl;
  std::cerr << " -x, --exclude-s-module          : exclude S-module (last three layer) so 6 coordinates inseatd of 12 "
    << std::endl;
  std::cerr << " -d, --use-d0                    : use also d0 param in r-phi plane " << std::endl;

  exit(1);
}

void perform_main_computation (const arma::mat & coord, const arma::mat & param,
    const std::string & cfname, const std::string & qfname,
    pca::pcafitter & fitter)
{
  // ordered
  arma::vec eigval;
  // by row or by column ?
  arma::mat eigvec;

  std::cout << "Compute correlation mtx" << std::endl;
  arma::mat coordm = arma::zeros<arma::mat>(fitter.get_coordim());
  arma::mat hca = arma::zeros<arma::mat>(fitter.get_coordim(),
      fitter.get_coordim());
  arma::vec eigvaltmp = arma::zeros<arma::vec>(fitter.get_coordim());

  eigvec = arma::zeros<arma::mat>(fitter.get_coordim(),
      fitter.get_coordim());
  eigval = arma::zeros<arma::vec>(fitter.get_coordim());

  hca = arma::cov(coord);

  std::cout << "Eigensystem" << std::endl;
  arma::eig_sym(eigvaltmp, eigvec, hca);

  for (int i=0; i<fitter.get_coordim(); ++i)
    eigval(i) = eigvaltmp(fitter.get_coordim()-i-1);

  double totval = 0.0e0;
  for (int i=0; i<fitter.get_coordim(); ++i)
    totval += eigval(i);

  std::cout << "Eigenvalues: " << std::endl;
  double totvar = 0.0e0;
  for (int i=0; i<fitter.get_coordim(); ++i)
  {
    if (i < fitter.get_paramdim())
      totvar += 100.0e0*(eigval(i)/totval);

    std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval)
              << "% value: " << eigval(i) <<  std::endl;
  }
  std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl;

  std::cout << fitter.get_paramdim() << " X " << fitter.get_coordim() << std::endl;

  arma::mat cmtx = arma::zeros<arma::mat>(fitter.get_paramdim(),
      fitter.get_coordim());
  arma::rowvec q = arma::zeros<arma::rowvec>(fitter.get_paramdim());

  std::cout << "Compute PCA constants " << std::endl;
  fitter.compute_pca_constants (param,
      coord, cmtx, q);

  std::cout << "Write constant to file" << std::endl;
  pca::write_armmat(cfname.c_str(), cmtx);
  pca::write_armvct(qfname.c_str(), q);
}

int main (int argc, char ** argv)
{
  pca::pcafitter fitter;

  bool useonlyeven = false;
  bool printallcoords = false;
  bool rzplane = false;
  bool rphiplane = false;
  bool usecharge = true;
  bool usealsod0 = false;

  int chargesign = 0;

  double etamin = -1.0e0 * INFINITY, etamax = +1.0e0 * INFINITY;

  std::vector<std::string> tokens;

  bool excludesmodule = false;

  while (1)
  {
    int c, option_index;
    static struct option long_options[] = {
      {"help", 0, NULL, 'h'},
      {"version", 0, NULL, 'v'},
      {"jump-tracks", 0, NULL, 'j'},
      {"dump-allcoords", 0, NULL, 'p'},
      {"rz-plane", 0, NULL, 'z'},
      {"rphi-plane", 0, NULL, 'r'},
      {"not-use-charge", 0, NULL, 'e'},
      {"charge-sign", 1, NULL, 'g'},
      {"eta-range", 1, NULL, 't'},
      {"exclude-s-module", 0, NULL, 'x'},
      {"use-d0", 0, NULL, 'd'},
      {0, 0, 0, 0}
    };

    c = getopt_long (argc, argv, "dxehvjpzrg:t:", long_options, &option_index);

    if (c == -1)
      break;

    switch (c)
    {
      case 'd':
        usealsod0 = true;
        break;
      case 'x':
        excludesmodule = true;
        break;
      case 't':
        pca::tokenize (optarg, tokens, ";");
        if (tokens.size() != 2)
          usage (argv[0]);

        etamin = atof(tokens[0].c_str());
        etamax = atof(tokens[1].c_str());

        break;
      case 'g':
        if (strlen(optarg) > 1)
          usage (argv[0]);

        if (*optarg == '-')
          chargesign = -1;
        else if (*optarg == '+')
          chargesign = +1;
        else
          usage (argv[0]);

        break;
      case 'z':
        rzplane = true;
        break;
      case 'r':
        rphiplane = true;
        break;
      case 'p':
        printallcoords = true;
        break;
      case 'j':
        useonlyeven = true;
        break;
      case 'h':
        usage (argv[0]);
        break;
      case 'v':
        std::cout << "Version: " << pca::pcafitter::get_version_string() << std::endl;
        exit(1);
        break;
      case 'e':
        usecharge = false;
        break;
      default:
        usage (argv[0]);
        break;
    }
  }

  if (optind >= argc)
    usage (argv[0]);

  if ((rzplane && rphiplane) ||
      (!rzplane && !rphiplane))
  {
    std::cerr << "r-phi or r-z plane ?" << std::endl;
    usage (argv[0]);
  }

  // R-z
  if (excludesmodule && rzplane)
    fitter.set_coordim (2*3);
  else
    fitter.set_coordim (2*6);

  if (usealsod0 && rphiplane)
    fitter.set_paramdim(3);
  else
    fitter.set_paramdim(2);

  if (rzplane)
  {
    if (!fitter.set_paramidx(SPLIT_COTTETHAIDX, "cot(tetha)"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
    if (!fitter.set_paramidx(SPLIT_Z0IDX, "z0"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
  }
  else if (rphiplane)
  {
    if (!fitter.set_paramidx(SPLIT_PHIIDX, "phi"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }

    if (usealsod0)
    {
      if (!fitter.set_paramidx(SPLIT_D0IDX, "d0"))
      {
        std::cerr << fitter.get_errmsg() << std::endl;
        return EXIT_FAILURE;
      }
    }

    if (usecharge)
    {
      if (!fitter.set_paramidx(SPLIT_ONEOVERPTIDX, "q/pt"))
      {
        std::cerr << fitter.get_errmsg() << std::endl;
        return EXIT_FAILURE;
      }
    }
    else
    {
      if (!fitter.set_paramidx(SPLIT_ONEOVERPTIDX, "1/pt"))
      {
        std::cerr << fitter.get_errmsg() << std::endl;
        return EXIT_FAILURE;
      }
    }
  }

  char * filename = (char *) alloca (strlen(argv[optind]) + 1);
  strcpy (filename, argv[optind]);

  // leggere file coordinate tracce simulate plus parametri
  if (!file_exists(filename))
  {
    std::cerr << "Inout file does not exist" << std::endl;
    return EXIT_FAILURE;
  }

  int num_of_line = pca::numofline(filename);
  std::cout << "file has " << num_of_line << " line " << std::endl;
  int num_of_ent_read = (num_of_line-1)/ENTDIM;

  int num_of_ent = num_of_ent_read;

  if (useonlyeven)
  {
    if (num_of_ent_read % 2)
      num_of_ent = (num_of_ent_read-1)/2;
    else
      num_of_ent = num_of_ent_read/2;
  }

  std::cout << "file has " << num_of_ent << " entries " << std::endl;

  // non perfomante ma easy to go
  arma::mat coordin, paramin;
  coordin.set_size(num_of_ent, fitter.get_coordim());
  paramin.set_size(num_of_ent, fitter.get_paramdim());

  // leggere file coordinate tracce simulate plus parametri
  std::cout << "Reading data from " << filename << " file " << std::endl;

  if (!pca::reading_from_file_split (fitter, filename, paramin, coordin,
         num_of_ent_read, useonlyeven, false, rzplane, rphiplane,
         etamin, etamax, usecharge, chargesign, excludesmodule,
         usealsod0))
    return EXIT_FAILURE;

  std::cout << "Using " << paramin.n_rows << " tracks" << std::endl;

  std::cout << "Writing parameters to files" << std::endl;

  std::ostringstream cfname, qfname;

  if (rzplane)
  {
    pca::write_to_file("cottetha.txt", paramin, SPLIT_COTTETHAIDX);
    pca::write_to_file("z0.txt", paramin, SPLIT_Z0IDX);
    cfname << "c.rz.bin";
    qfname << "q.rz.bin";

  }
  else if (rphiplane)
  {
    pca::write_to_file("phi.txt", paramin, SPLIT_PHIIDX);
    pca::write_to_file("oneoverpt.txt", paramin, SPLIT_ONEOVERPTIDX);
    cfname << "c.rphi.bin";
    qfname << "q.rphi.bin";
  }

  if (printallcoords)
  {
    std::cout << "Printout coordinates " << std::endl;
    std::ofstream myfilect("allcoords.txt");
    for (int i=0; i<(int)coordin.n_rows; ++i)
      for (int j=0; j<fitter.get_coordim(); j=j+2)
        myfilect << coordin(i, j) << " " <<
                    coordin(i, j+1) << std::endl;
    myfilect.close();
  }

  perform_main_computation (coordin, paramin,
      cfname.str(), qfname.str(), fitter);

  return EXIT_SUCCESS;
}
<commit_msg>minor<commit_after>#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <string>
#include <map>
#include <set>

// Loriano: let's try Armadillo quick code
#include <armadillo>
#include <cassert>
#include <sys/stat.h>

#include <getopt.h>
#include <unistd.h>
#include <alloca.h>

#include <pcafitter.hpp>
#include <pcaffunctype.hpp>

#define MINDIMLINIT 25

// lstorchi: basic quick code to generate PCA constants

namespace
{
  bool file_exists(const std::string& filename)
  {
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
      return true;

    return false;
  }
}

void usage (char * name)
{
  std::cerr << "usage: " << name << " [options] coordinatesfile " << std::endl;
  std::cerr << std::endl;
  std::cerr << " -h, --help                      : display this help and exit" << std::endl;
  std::cerr << " -v, --version                   : print version and exit" << std::endl;
  std::cerr << " -j, --jump-tracks               : generate the constants using only even tracks" << std::endl;
  std::cerr << " -p, --dump-allcoords            : dump all stub coordinates to a file" << std::endl;
  std::cerr << " -z, --rz-plane                  : use rz plane view" << std::endl;
  std::cerr << " -r, --rphi-plane                : use r-phi plane view" << std::endl;
  std::cerr << " -e, --not-use-charge            : do not read charge from coordinatesfile, by default " << std::endl;
  std::cerr << "                                   we will  use it if rphi-plane has been selected" << std::endl;
  std::cerr << " -g, --charge-sign=[+/-]         : use only + particle or - paricle " << std::endl;
  std::cerr << " -t, --eta-range=\"etamin;etamax\" : specify the eta range to use " << std::endl;
  std::cerr << " -x, --exclude-s-module          : exclude S-module (last three layer) so 6 coordinates inseatd of 12 "
    << std::endl;
  std::cerr << " -d, --use-d0                    : use also d0 param in r-phi plane " << std::endl;

  exit(1);
}

void perform_main_computation (const arma::mat & coord, const arma::mat & param,
    const std::string & cfname, const std::string & qfname,
    pca::pcafitter & fitter)
{
  // ordered
  arma::vec eigval;
  // by row or by column ?
  arma::mat eigvec;

  std::cout << "Compute correlation mtx" << std::endl;
  arma::mat coordm = arma::zeros<arma::mat>(fitter.get_coordim());
  arma::mat hca = arma::zeros<arma::mat>(fitter.get_coordim(),
      fitter.get_coordim());
  arma::vec eigvaltmp = arma::zeros<arma::vec>(fitter.get_coordim());

  eigvec = arma::zeros<arma::mat>(fitter.get_coordim(),
      fitter.get_coordim());
  eigval = arma::zeros<arma::vec>(fitter.get_coordim());

  hca = arma::cov(coord);

  std::cout << "Eigensystem" << std::endl;
  arma::eig_sym(eigvaltmp, eigvec, hca);

  for (int i=0; i<fitter.get_coordim(); ++i)
    eigval(i) = eigvaltmp(fitter.get_coordim()-i-1);

  double totval = 0.0e0;
  for (int i=0; i<fitter.get_coordim(); ++i)
    totval += eigval(i);

  std::cout << "Eigenvalues: " << std::endl;
  double totvar = 0.0e0;
  for (int i=0; i<fitter.get_coordim(); ++i)
  {
    if (i < fitter.get_paramdim())
      totvar += 100.0e0*(eigval(i)/totval);

    std::cout << i+1 << " ==> " << 100.0e0*(eigval(i)/totval)
              << "% value: " << eigval(i) <<  std::endl;
  }
  std::cout << "PARAMDIM eigenvalues: " << totvar << std::endl;

  std::cout << fitter.get_paramdim() << " X " << fitter.get_coordim() << std::endl;

  arma::mat cmtx = arma::zeros<arma::mat>(fitter.get_paramdim(),
      fitter.get_coordim());
  arma::rowvec q = arma::zeros<arma::rowvec>(fitter.get_paramdim());

  std::cout << "Compute PCA constants " << std::endl;
  fitter.compute_pca_constants (param,
      coord, cmtx, q);

  std::cout << "Write constant to file" << std::endl;
  pca::write_armmat(cfname.c_str(), cmtx);
  pca::write_armvct(qfname.c_str(), q);
}

int main (int argc, char ** argv)
{
  pca::pcafitter fitter;

  bool useonlyeven = false;
  bool printallcoords = false;
  bool rzplane = false;
  bool rphiplane = false;
  bool usecharge = true;
  bool usealsod0 = false;

  int chargesign = 0;

  double etamin = -1.0e0 * INFINITY, etamax = +1.0e0 * INFINITY;

  std::vector<std::string> tokens;

  bool excludesmodule = false;

  while (1)
  {
    int c, option_index;
    static struct option long_options[] = {
      {"help", 0, NULL, 'h'},
      {"version", 0, NULL, 'v'},
      {"jump-tracks", 0, NULL, 'j'},
      {"dump-allcoords", 0, NULL, 'p'},
      {"rz-plane", 0, NULL, 'z'},
      {"rphi-plane", 0, NULL, 'r'},
      {"not-use-charge", 0, NULL, 'e'},
      {"charge-sign", 1, NULL, 'g'},
      {"eta-range", 1, NULL, 't'},
      {"exclude-s-module", 0, NULL, 'x'},
      {"use-d0", 0, NULL, 'd'},
      {0, 0, 0, 0}
    };

    c = getopt_long (argc, argv, "dxehvjpzrg:t:", long_options, &option_index);

    if (c == -1)
      break;

    switch (c)
    {
      case 'd':
        usealsod0 = true;
        break;
      case 'x':
        excludesmodule = true;
        break;
      case 't':
        pca::tokenize (optarg, tokens, ";");
        if (tokens.size() != 2)
          usage (argv[0]);

        etamin = atof(tokens[0].c_str());
        etamax = atof(tokens[1].c_str());

        break;
      case 'g':
        if (strlen(optarg) > 1)
          usage (argv[0]);

        if (*optarg == '-')
          chargesign = -1;
        else if (*optarg == '+')
          chargesign = +1;
        else
          usage (argv[0]);

        break;
      case 'z':
        rzplane = true;
        break;
      case 'r':
        rphiplane = true;
        break;
      case 'p':
        printallcoords = true;
        break;
      case 'j':
        useonlyeven = true;
        break;
      case 'h':
        usage (argv[0]);
        break;
      case 'v':
        std::cout << "Version: " << pca::pcafitter::get_version_string() << std::endl;
        exit(1);
        break;
      case 'e':
        usecharge = false;
        break;
      default:
        usage (argv[0]);
        break;
    }
  }

  if (optind >= argc)
    usage (argv[0]);

  if ((rzplane && rphiplane) ||
      (!rzplane && !rphiplane))
  {
    std::cerr << "r-phi or r-z plane ?" << std::endl;
    usage (argv[0]);
  }

  // R-z
  if (excludesmodule && rzplane)
    fitter.set_coordim (2*3);
  else
    fitter.set_coordim (2*6);

  if (usealsod0 && rphiplane)
    fitter.set_paramdim(3);
  else
    fitter.set_paramdim(2);

  if (rzplane)
  {
    if (!fitter.set_paramidx(SPLIT_COTTETHAIDX, "cot(tetha)"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
    if (!fitter.set_paramidx(SPLIT_Z0IDX, "z0"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }
  }
  else if (rphiplane)
  {
    if (!fitter.set_paramidx(SPLIT_PHIIDX, "phi"))
    {
      std::cerr << fitter.get_errmsg() << std::endl;
      return EXIT_FAILURE;
    }

    if (usealsod0)
    {
      if (!fitter.set_paramidx(SPLIT_D0IDX, "d0"))
      {
        std::cerr << fitter.get_errmsg() << std::endl;
        return EXIT_FAILURE;
      }
    }

    if (usecharge)
    {
      if (!fitter.set_paramidx(SPLIT_ONEOVERPTIDX, "q/pt"))
      {
        std::cerr << fitter.get_errmsg() << std::endl;
        return EXIT_FAILURE;
      }
    }
    else
    {
      if (!fitter.set_paramidx(SPLIT_ONEOVERPTIDX, "1/pt"))
      {
        std::cerr << fitter.get_errmsg() << std::endl;
        return EXIT_FAILURE;
      }
    }
  }

  char * filename = (char *) alloca (strlen(argv[optind]) + 1);
  strcpy (filename, argv[optind]);

  // leggere file coordinate tracce simulate plus parametri
  if (!file_exists(filename))
  {
    std::cerr << "Inout file does not exist" << std::endl;
    return EXIT_FAILURE;
  }

  int num_of_line = pca::numofline(filename);
  std::cout << "file has " << num_of_line << " line " << std::endl;
  int num_of_ent_read = (num_of_line-1)/ENTDIM;

  int num_of_ent = num_of_ent_read;

  if (useonlyeven)
  {
    if (num_of_ent_read % 2)
      num_of_ent = (num_of_ent_read-1)/2;
    else
      num_of_ent = num_of_ent_read/2;
  }

  std::cout << "file has " << num_of_ent << " entries " << std::endl;

  // non perfomante ma easy to go
  arma::mat coordin, paramin;
  coordin.set_size(num_of_ent, fitter.get_coordim());
  paramin.set_size(num_of_ent, fitter.get_paramdim());

  // leggere file coordinate tracce simulate plus parametri
  std::cout << "Reading data from " << filename << " file " << std::endl;

  if (!pca::reading_from_file_split (fitter, filename, paramin, coordin,
         num_of_ent_read, useonlyeven, false, rzplane, rphiplane,
         etamin, etamax, usecharge, chargesign, excludesmodule,
         usealsod0))
    return EXIT_FAILURE;

  std::cout << "Using " << paramin.n_rows << " tracks" << std::endl;

  std::cout << "Writing parameters to files" << std::endl;

  std::ostringstream cfname, qfname;

  if (rzplane)
  {
    pca::write_to_file("cottetha.txt", paramin, SPLIT_COTTETHAIDX);
    pca::write_to_file("z0.txt", paramin, SPLIT_Z0IDX);
    cfname << "c.rz.bin";
    qfname << "q.rz.bin";

  }
  else if (rphiplane)
  {
    pca::write_to_file("phi.txt", paramin, SPLIT_PHIIDX);
    pca::write_to_file("oneoverpt.txt", paramin, SPLIT_ONEOVERPTIDX);
    cfname << "c.rphi.bin";
    qfname << "q.rphi.bin";
  }

  if (printallcoords)
  {
    std::cout << "Printout coordinates " << std::endl;
    std::ofstream myfilect("allcoords.txt");
    for (int i=0; i<(int)coordin.n_rows; ++i)
      for (int j=0; j<fitter.get_coordim(); j=j+2)
        myfilect << coordin(i, j) << " " <<
                    coordin(i, j+1) << std::endl;
    myfilect.close();
  }

  perform_main_computation (coordin, paramin,
      cfname.str(), qfname.str(), fitter);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>Vulkan: fix clear value list with MSAA.<commit_after><|endoftext|>


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

#include <media/MediaPlayer.h>
#include "PlayerWorker.h"
#include "MediaPlayerImpl.h"

#include <debug.h>
#include "audio/audio_manager.h"

namespace media {
MediaPlayerImpl::MediaPlayerImpl()
{
	mPlayerObserver = nullptr;
	mCurState = PLAYER_STATE_NONE;
	mBuffer = nullptr;
	mInputDataSource = nullptr;

	static int playerId = 1;
	mId = playerId++;
}

player_result_t MediaPlayerImpl::create()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer create\n");
	if (mCurState != PLAYER_STATE_NONE) {
		meddbg("MediaPlayer create fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.startWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);

	mCurState = PLAYER_STATE_IDLE;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::destroy()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer destroy\n");
	if (mCurState != PLAYER_STATE_IDLE) {
		meddbg("MediaPlayer destroy fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);
	mpw.stopWorker();

	PlayerObserverWorker& pow = PlayerObserverWorker::getWorker();
	pow.stopWorker();

	mCurState = PLAYER_STATE_NONE;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::prepare()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer prepare\n");
	if (mCurState != PLAYER_STATE_IDLE) {
		meddbg("MediaPlayer prepare fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);

	if (mInputDataSource == nullptr) {
		meddbg("MediaPlayer prepare fail : mInputDataSource is not set\n");
		return PLAYER_ERROR;
	}

	mInputDataSource->open();
	if (!mInputDataSource->isPrepare()) {
		meddbg("MediaPlayer prepare fail : file open fail\n");
		return PLAYER_ERROR;
	}

	if (set_audio_stream_out(mInputDataSource->getChannels(), mInputDataSource->getSampleRate(),
							 mInputDataSource->getPcmFormat()) != AUDIO_MANAGER_SUCCESS) {
		meddbg("MediaPlayer prepare fail : set_audio_stream_out fail\n");
		return PLAYER_ERROR;
	}

	mBufSize = get_output_frames_byte_size(get_output_frame_count());
	medvdbg("MediaPlayer mBuffer size : %d\n", mBufSize);

	mBuffer = new unsigned char[mBufSize];
	if (!mBuffer) {
		meddbg("MediaPlayer prepare fail : mBuffer allocation fail\n");
		return PLAYER_ERROR;
	}

	mCurState = PLAYER_STATE_READY;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::unprepare()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer unprepare\n");
	if (mCurState == PLAYER_STATE_NONE || mCurState == PLAYER_STATE_IDLE) {
		meddbg("MediaPlayer unprepare fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);

	if (mBuffer) {
		delete[] mBuffer;
		mBuffer = nullptr;
	}
	mBufSize = 0;

	if (reset_audio_stream_out() != AUDIO_MANAGER_SUCCESS) {
		meddbg("MediaPlayer unprepare fail : reset_audio_stream_out fail\n");
		return PLAYER_ERROR;
	}

	if (destroy_audio_stream_out() != AUDIO_MANAGER_SUCCESS) {
		meddbg("MediaPlayer unprepare fail : destroy_audio_stream_out fail\n");
		return PLAYER_ERROR;
	}

	mInputDataSource->close();

	mCurState = PLAYER_STATE_IDLE;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::start()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer start\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&PlayerWorker::startPlayer, &mpw, shared_from_this());

	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::stop()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer stop\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&PlayerWorker::stopPlayer, &mpw, shared_from_this());

	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::pause()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer pause\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&PlayerWorker::pausePlayer, &mpw, shared_from_this());

	return PLAYER_OK;
}

int MediaPlayerImpl::getVolume()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer getVolume\n");
	if (mCurState == PLAYER_STATE_NONE) {
		meddbg("MediaPlayer getVolume fail : wrong state\n");
		return -1;
	}

	return get_audio_volume();
}

player_result_t MediaPlayerImpl::setVolume(int vol)
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer setVolume\n");
	if (mCurState == PLAYER_STATE_NONE) {
		meddbg("MediaPlayer setVolume fail : wrong state\n");
		return PLAYER_ERROR;
	}

	if (vol < 0 || vol > 31) {
		meddbg("MediaPlayer setVolume fail : invalid argument. volume level should be 0(Min) ~ 31(Max)\n");
		return PLAYER_ERROR;
	}

	if (!set_audio_volume(vol)) {
		mCurVolume = vol;
		return PLAYER_OK;
	} else {
		return PLAYER_ERROR;
	}
}

void MediaPlayerImpl::setDataSource(std::unique_ptr<stream::InputDataSource> source)
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer setDataSource\n");
	mInputDataSource = std::move(source);
}

void MediaPlayerImpl::setObserver(std::shared_ptr<MediaPlayerObserverInterface> observer)
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer setObserver\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);
	PlayerObserverWorker& pow = PlayerObserverWorker::getWorker();
	pow.startWorker();
	mPlayerObserver = observer;
}

player_state_t MediaPlayerImpl::getState()
{
	medvdbg("MediaPlayer getState\n");
	return mCurState;
}

player_result_t MediaPlayerImpl::seekTo(int msec)
{
	medvdbg("MediaPlayer seekTo %d msec\n", msec);
	// TODO : implementation of seekTo
	return PLAYER_OK;
}

void MediaPlayerImpl::notifySync()
{
	mSyncCv.notify_one();
}

void MediaPlayerImpl::notifyObserver(player_observer_command_t cmd)
{
	if (mPlayerObserver != nullptr) {
		PlayerObserverWorker& pow = PlayerObserverWorker::getWorker();
		switch (cmd) {
		case PLAYER_OBSERVER_COMMAND_STARTED:
			pow.getQueue().enQueue(&MediaPlayerObserverInterface::onPlaybackStarted, mPlayerObserver, mId);
			break;
		case PLAYER_OBSERVER_COMMAND_FINISHIED:
			pow.getQueue().enQueue(&MediaPlayerObserverInterface::onPlaybackFinished, mPlayerObserver, mId);
			break;
		case PLAYER_OBSERVER_COMMAND_ERROR:
			pow.getQueue().enQueue(&MediaPlayerObserverInterface::onPlaybackError, mPlayerObserver, mId);
			break;
		}
	}
}

int MediaPlayerImpl::playback(int size)
{
	return start_audio_stream_out(mBuffer, get_output_bytes_frame_count(size));
}

MediaPlayerImpl::~MediaPlayerImpl()
{
	player_result_t ret;

	if (mCurState > PLAYER_STATE_IDLE) {
		ret = unprepare();
		if (ret != PLAYER_OK) {
			meddbg("~MediaPlayer fail : unprepare fail\n");
		}
	}

	if (mCurState == PLAYER_STATE_IDLE) {
		ret = destroy();
		if (ret != PLAYER_OK) {
			meddbg("~MediaPlayer fail : destroy fail\n");
		}
	}
}
} // namespace media
<commit_msg>MediaPlayerImpl: Remove duplicated function call<commit_after>/* ****************************************************************
 *
 * Copyright 2018 Samsung Electronics All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************/

#include <media/MediaPlayer.h>
#include "PlayerWorker.h"
#include "MediaPlayerImpl.h"

#include <debug.h>
#include "audio/audio_manager.h"

namespace media {
MediaPlayerImpl::MediaPlayerImpl()
{
	mPlayerObserver = nullptr;
	mCurState = PLAYER_STATE_NONE;
	mBuffer = nullptr;
	mInputDataSource = nullptr;

	static int playerId = 1;
	mId = playerId++;
}

player_result_t MediaPlayerImpl::create()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer create\n");
	if (mCurState != PLAYER_STATE_NONE) {
		meddbg("MediaPlayer create fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.startWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);

	mCurState = PLAYER_STATE_IDLE;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::destroy()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer destroy\n");
	if (mCurState != PLAYER_STATE_IDLE) {
		meddbg("MediaPlayer destroy fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);
	mpw.stopWorker();

	PlayerObserverWorker& pow = PlayerObserverWorker::getWorker();
	pow.stopWorker();

	mCurState = PLAYER_STATE_NONE;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::prepare()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer prepare\n");
	if (mCurState != PLAYER_STATE_IDLE) {
		meddbg("MediaPlayer prepare fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);

	if (mInputDataSource == nullptr) {
		meddbg("MediaPlayer prepare fail : mInputDataSource is not set\n");
		return PLAYER_ERROR;
	}

	if (!mInputDataSource->open()) {
		meddbg("MediaPlayer prepare fail : file open fail\n");
		return PLAYER_ERROR;
	}

	if (set_audio_stream_out(mInputDataSource->getChannels(), mInputDataSource->getSampleRate(),
							 mInputDataSource->getPcmFormat()) != AUDIO_MANAGER_SUCCESS) {
		meddbg("MediaPlayer prepare fail : set_audio_stream_out fail\n");
		return PLAYER_ERROR;
	}

	mBufSize = get_output_frames_byte_size(get_output_frame_count());
	medvdbg("MediaPlayer mBuffer size : %d\n", mBufSize);

	mBuffer = new unsigned char[mBufSize];
	if (!mBuffer) {
		meddbg("MediaPlayer prepare fail : mBuffer allocation fail\n");
		return PLAYER_ERROR;
	}

	mCurState = PLAYER_STATE_READY;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::unprepare()
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer unprepare\n");
	if (mCurState == PLAYER_STATE_NONE || mCurState == PLAYER_STATE_IDLE) {
		meddbg("MediaPlayer unprepare fail : wrong state\n");
		return PLAYER_ERROR;
	}

	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);

	if (mBuffer) {
		delete[] mBuffer;
		mBuffer = nullptr;
	}
	mBufSize = 0;

	if (reset_audio_stream_out() != AUDIO_MANAGER_SUCCESS) {
		meddbg("MediaPlayer unprepare fail : reset_audio_stream_out fail\n");
		return PLAYER_ERROR;
	}

	if (destroy_audio_stream_out() != AUDIO_MANAGER_SUCCESS) {
		meddbg("MediaPlayer unprepare fail : destroy_audio_stream_out fail\n");
		return PLAYER_ERROR;
	}

	mInputDataSource->close();

	mCurState = PLAYER_STATE_IDLE;
	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::start()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer start\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&PlayerWorker::startPlayer, &mpw, shared_from_this());

	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::stop()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer stop\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&PlayerWorker::stopPlayer, &mpw, shared_from_this());

	return PLAYER_OK;
}

player_result_t MediaPlayerImpl::pause()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer pause\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&PlayerWorker::pausePlayer, &mpw, shared_from_this());

	return PLAYER_OK;
}

int MediaPlayerImpl::getVolume()
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer getVolume\n");
	if (mCurState == PLAYER_STATE_NONE) {
		meddbg("MediaPlayer getVolume fail : wrong state\n");
		return -1;
	}

	return get_audio_volume();
}

player_result_t MediaPlayerImpl::setVolume(int vol)
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer setVolume\n");
	if (mCurState == PLAYER_STATE_NONE) {
		meddbg("MediaPlayer setVolume fail : wrong state\n");
		return PLAYER_ERROR;
	}

	if (vol < 0 || vol > 31) {
		meddbg("MediaPlayer setVolume fail : invalid argument. volume level should be 0(Min) ~ 31(Max)\n");
		return PLAYER_ERROR;
	}

	if (!set_audio_volume(vol)) {
		mCurVolume = vol;
		return PLAYER_OK;
	} else {
		return PLAYER_ERROR;
	}
}

void MediaPlayerImpl::setDataSource(std::unique_ptr<stream::InputDataSource> source)
{
	std::lock_guard<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer setDataSource\n");
	mInputDataSource = std::move(source);
}

void MediaPlayerImpl::setObserver(std::shared_ptr<MediaPlayerObserverInterface> observer)
{
	std::unique_lock<std::mutex> lock(mCmdMtx);
	medvdbg("MediaPlayer setObserver\n");
	PlayerWorker& mpw = PlayerWorker::getWorker();
	mpw.getQueue().enQueue(&MediaPlayerImpl::notifySync, shared_from_this());
	mSyncCv.wait(lock);
	PlayerObserverWorker& pow = PlayerObserverWorker::getWorker();
	pow.startWorker();
	mPlayerObserver = observer;
}

player_state_t MediaPlayerImpl::getState()
{
	medvdbg("MediaPlayer getState\n");
	return mCurState;
}

player_result_t MediaPlayerImpl::seekTo(int msec)
{
	medvdbg("MediaPlayer seekTo %d msec\n", msec);
	// TODO : implementation of seekTo
	return PLAYER_OK;
}

void MediaPlayerImpl::notifySync()
{
	mSyncCv.notify_one();
}

void MediaPlayerImpl::notifyObserver(player_observer_command_t cmd)
{
	if (mPlayerObserver != nullptr) {
		PlayerObserverWorker& pow = PlayerObserverWorker::getWorker();
		switch (cmd) {
		case PLAYER_OBSERVER_COMMAND_STARTED:
			pow.getQueue().enQueue(&MediaPlayerObserverInterface::onPlaybackStarted, mPlayerObserver, mId);
			break;
		case PLAYER_OBSERVER_COMMAND_FINISHIED:
			pow.getQueue().enQueue(&MediaPlayerObserverInterface::onPlaybackFinished, mPlayerObserver, mId);
			break;
		case PLAYER_OBSERVER_COMMAND_ERROR:
			pow.getQueue().enQueue(&MediaPlayerObserverInterface::onPlaybackError, mPlayerObserver, mId);
			break;
		}
	}
}

int MediaPlayerImpl::playback(int size)
{
	return start_audio_stream_out(mBuffer, get_output_bytes_frame_count(size));
}

MediaPlayerImpl::~MediaPlayerImpl()
{
	player_result_t ret;

	if (mCurState > PLAYER_STATE_IDLE) {
		ret = unprepare();
		if (ret != PLAYER_OK) {
			meddbg("~MediaPlayer fail : unprepare fail\n");
		}
	}

	if (mCurState == PLAYER_STATE_IDLE) {
		ret = destroy();
		if (ret != PLAYER_OK) {
			meddbg("~MediaPlayer fail : destroy fail\n");
		}
	}
}
} // namespace media
<|endoftext|>