<commit_before>#include <QtGui>
#include <QHeaderView>
#include <QDesktopServices>
#include <QEvent>
#include <QShowEvent>
#include <QHideEvent>

#include "QtAwesome.h"
#include "utils/utils.h"
#include "seafile-applet.h"
#include "rpc/rpc-client.h"
#include "rpc/local-repo.h"
#include "download-repo-dialog.h"
#include "clone-tasks-dialog.h"
#include "cloud-view.h"
#include "repo-item.h"
#include "repo-item-delegate.h"
#include "repo-tree-model.h"
#include "repo-tree-view.h"
#include "repo-detail-dialog.h"

RepoTreeView::RepoTreeView(CloudView *cloud_view, QWidget *parent)
    : QTreeView(parent),
      cloud_view_(cloud_view)
{
    header()->hide();
    createActions();

    // We draw the indicator ourselves
    setIndentation(0);
    // We handle the click oursevles
    setExpandsOnDoubleClick(false);

    connect(this, SIGNAL(clicked(const QModelIndex&)),
            this, SLOT(onItemClicked(const QModelIndex&)));

    connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
            this, SLOT(onItemDoubleClicked(const QModelIndex&)));
}

void RepoTreeView::contextMenuEvent(QContextMenuEvent *event)
{
    QPoint pos = event->pos();
    QModelIndex index = indexAt(pos);
    if (!index.isValid()) {
        // Not clicked at a repo item
        return;
    }

    QStandardItem *item = getRepoItem(index);
    if (!item || item->type() != REPO_ITEM_TYPE) {
        return;
    }
    updateRepoActions();
    QMenu *menu = prepareContextMenu((RepoItem *)item);
    pos = viewport()->mapToGlobal(pos);
    menu->exec(pos);
}

QMenu* RepoTreeView::prepareContextMenu(const RepoItem *item)
{
    QMenu *menu = new QMenu(this);
    if (item->localRepo().isValid()) {
        menu->addAction(open_local_folder_action_);
    }

    if (item->repoDownloadable()) {
        menu->addAction(download_action_);
    }

    menu->addAction(view_on_web_action_);

    if (item->localRepo().isValid()) {
        menu->addSeparator();
        menu->addAction(toggle_auto_sync_action_);
        menu->addAction(sync_now_action_);
        menu->addSeparator();
    }

    menu->addAction(show_detail_action_);

    if (item->cloneTask().isCancelable()) {
        menu->addAction(cancel_download_action_);
    }
    if (item->localRepo().isValid()) {
        menu->addAction(unsync_action_);
    }

    return menu;
}

void RepoTreeView::updateRepoActions()
{
    RepoItem *item = NULL;
    QItemSelection selected = selectionModel()->selection();
    QModelIndexList indexes = selected.indexes();
    if (indexes.size() != 0) {
        const QModelIndex& index = indexes.at(0);
        QStandardItem *it = ((RepoTreeModel *)model())->itemFromIndex(index);
        if (it && it->type() == REPO_ITEM_TYPE) {
            item = (RepoItem *)it;
        }
    }

    if (!item) {
        // No repo item is selected
        download_action_->setEnabled(false);
        sync_now_action_->setEnabled(false);
        open_local_folder_action_->setEnabled(false);
        unsync_action_->setEnabled(false);
        toggle_auto_sync_action_->setEnabled(false);
        view_on_web_action_->setEnabled(false);
        show_detail_action_->setEnabled(false);
        return;
    }

    LocalRepo r;
    seafApplet->rpcClient()->getLocalRepo(item->repo().id, &r);
    item->setLocalRepo(r);

    if (item->localRepo().isValid()) {
        const LocalRepo& local_repo = item->localRepo();
        download_action_->setEnabled(false);

        sync_now_action_->setEnabled(true);
        sync_now_action_->setData(QVariant::fromValue(local_repo));

        open_local_folder_action_->setData(QVariant::fromValue(local_repo));
        open_local_folder_action_->setEnabled(true);

        unsync_action_->setData(QVariant::fromValue(local_repo));
        unsync_action_->setEnabled(true);

        toggle_auto_sync_action_->setData(QVariant::fromValue(local_repo));
        toggle_auto_sync_action_->setEnabled(true);
        if (local_repo.auto_sync) {
            toggle_auto_sync_action_->setText(tr("Disable auto sync"));
            toggle_auto_sync_action_->setToolTip(tr("Disable auto sync"));
            toggle_auto_sync_action_->setIcon(QIcon(":/images/pause.png"));
        } else {
            toggle_auto_sync_action_->setText(tr("Enable auto sync"));
            toggle_auto_sync_action_->setToolTip(tr("Enable auto sync"));
            toggle_auto_sync_action_->setIcon(QIcon(":/images/play.png"));
        }

    } else {
        if (item->repoDownloadable()) {
            download_action_->setEnabled(true);
            download_action_->setData(QVariant::fromValue(item->repo()));
        } else {
            download_action_->setEnabled(false);
        }

        sync_now_action_->setEnabled(false);

        open_local_folder_action_->setEnabled(false);
        unsync_action_->setEnabled(false);
        toggle_auto_sync_action_->setEnabled(false);
    }

    view_on_web_action_->setEnabled(true);
    view_on_web_action_->setData(item->repo().id);
    show_detail_action_->setEnabled(true);
    show_detail_action_->setData(QVariant::fromValue(item->repo()));

    if (item->cloneTask().isCancelable()) {
        cancel_download_action_->setEnabled(true);
        cancel_download_action_->setData(QVariant::fromValue(item->repo()));
    } else {
        cancel_download_action_->setEnabled(false);
    }
}

QStandardItem* RepoTreeView::getRepoItem(const QModelIndex &index) const
{
    if (!index.isValid()) {
        return NULL;
    }
    const RepoTreeModel *model = (const RepoTreeModel*)index.model();
    QStandardItem *item = model->itemFromIndex(index);
    if (item->type() != REPO_ITEM_TYPE &&
        item->type() != REPO_CATEGORY_TYPE) {
        return NULL;
    }
    return item;
}

void RepoTreeView::createActions()
{
    show_detail_action_ = new QAction(tr("&Show details"), this);
    show_detail_action_->setIcon(QIcon(":/images/info.png"));
    show_detail_action_->setStatusTip(tr("Download this library"));
    show_detail_action_->setIconVisibleInMenu(true);
    connect(show_detail_action_, SIGNAL(triggered()), this, SLOT(showRepoDetail()));

    download_action_ = new QAction(tr("&Download this library"), this);
    download_action_->setIcon(QIcon(":/images/download.png"));
    download_action_->setStatusTip(tr("Download this library"));
    download_action_->setIconVisibleInMenu(true);
    connect(download_action_, SIGNAL(triggered()), this, SLOT(downloadRepo()));

    sync_now_action_ = new QAction(tr("&Sync now"), this);
    sync_now_action_->setIcon(QIcon(":/images/sync_now.png"));
    sync_now_action_->setStatusTip(tr("Sync this library immediately"));
    sync_now_action_->setIconVisibleInMenu(true);
    connect(sync_now_action_, SIGNAL(triggered()), this, SLOT(syncRepoImmediately()));

    cancel_download_action_ = new QAction(tr("&Cancel download"), this);
    cancel_download_action_->setIcon(QIcon(":/images/remove.png"));
    cancel_download_action_->setStatusTip(tr("Cancel download of this library"));
    cancel_download_action_->setIconVisibleInMenu(true);
    connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(cancelDownload()));

    open_local_folder_action_ = new QAction(tr("&Open folder"), this);
    open_local_folder_action_->setIcon(QIcon(":/images/folder-open.png"));
    open_local_folder_action_->setStatusTip(tr("open local folder"));
    open_local_folder_action_->setIconVisibleInMenu(true);
    connect(open_local_folder_action_, SIGNAL(triggered()), this, SLOT(openLocalFolder()));

    unsync_action_ = new QAction(tr("&Unsync"), this);
    unsync_action_->setStatusTip(tr("unsync this library"));
    unsync_action_->setIcon(QIcon(":/images/minus.png"));
    unsync_action_->setIconVisibleInMenu(true);
    connect(unsync_action_, SIGNAL(triggered()), this, SLOT(unsyncRepo()));

    toggle_auto_sync_action_ = new QAction(tr("Enable auto sync"), this);
    toggle_auto_sync_action_->setStatusTip(tr("Enable auto sync"));
    toggle_auto_sync_action_->setIconVisibleInMenu(true);
    connect(toggle_auto_sync_action_, SIGNAL(triggered()), this, SLOT(toggleRepoAutoSync()));

    view_on_web_action_ = new QAction(tr("&View on cloud"), this);
    view_on_web_action_->setIcon(QIcon(":/images/cloud.png"));
    view_on_web_action_->setStatusTip(tr("view this library on seahub"));
    view_on_web_action_->setIconVisibleInMenu(true);

    connect(view_on_web_action_, SIGNAL(triggered()), this, SLOT(viewRepoOnWeb()));
}

void RepoTreeView::downloadRepo()
{
    ServerRepo repo = qvariant_cast<ServerRepo>(download_action_->data());
    DownloadRepoDialog dialog(cloud_view_->currentAccount(), repo, this);

    updateRepoActions();
}

void RepoTreeView::showRepoDetail()
{
    ServerRepo repo = qvariant_cast<ServerRepo>(show_detail_action_->data());
    RepoDetailDialog dialog(repo, this);
    dialog.exec();
}

void RepoTreeView::openLocalFolder()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(open_local_folder_action_->data());
    QDesktopServices::openUrl(QUrl::fromLocalFile(repo.worktree));
}

void RepoTreeView::toggleRepoAutoSync()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data());

    seafApplet->rpcClient()->setRepoAutoSync(repo.id, !repo.auto_sync);

    updateRepoActions();
}

void RepoTreeView::unsyncRepo()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data());

    QString question = tr("Are you sure to unsync library \"%1\"?").arg(repo.name);

    if (QMessageBox::question(this,
                              tr(SEAFILE_CLIENT_BRAND),
                              question,
                              QMessageBox::Ok | QMessageBox::Cancel,
                              QMessageBox::Cancel) != QMessageBox::Ok) {
        return;
    }

    if (seafApplet->rpcClient()->unsync(repo.id) < 0) {
        QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
                             tr("Failed to unsync library \"%1\"").arg(repo.name),
                             QMessageBox::Ok);
    }

    updateRepoActions();
}

void RepoTreeView::onItemClicked(const QModelIndex& index)
{
    QStandardItem *item = getRepoItem(index);
    if (!item) {
        return;
    }
    if (item->type() == REPO_ITEM_TYPE) {
        return;
    } else {
        // A repo category item
        if (isExpanded(index)) {
            collapse(index);
        } else {
            expand(index);
        }
    }
}

void RepoTreeView::onItemDoubleClicked(const QModelIndex& index)
{
    QStandardItem *item = getRepoItem(index);
    if (!item) {
        return;
    }
    if (item->type() == REPO_ITEM_TYPE) {
        RepoItem *it = (RepoItem *)item;
        const LocalRepo& local_repo = it->localRepo();
        if (local_repo.isValid()) {
            QDesktopServices::openUrl(QUrl::fromLocalFile(local_repo.worktree));
        }
    }
}

void RepoTreeView::viewRepoOnWeb()
{
    QString repo_id = view_on_web_action_->data().toString();
    const Account& account = cloud_view_->currentAccount();
    if (account.isValid()) {
        QUrl url = account.serverUrl;
        url.setPath(url.path() + "/repo/" + repo_id);
        QDesktopServices::openUrl(url);
    }
}

bool RepoTreeView::viewportEvent(QEvent *event)
{
    if (event->type() != QEvent::ToolTip && event->type() != QEvent::WhatsThis) {
        return QTreeView::viewportEvent(event);
    }

    QPoint global_pos = QCursor::pos();
    QPoint viewport_pos = viewport()->mapFromGlobal(global_pos);
    QModelIndex index = indexAt(viewport_pos);
    if (!index.isValid()) {
        return true;
    }

    QStandardItem *item = getRepoItem(index);
    if (!item) {
        return true;
    }

    QRect item_rect = visualRect(index);
    if (item->type() == REPO_ITEM_TYPE) {
        showRepoItemToolTip((RepoItem *)item, global_pos, item_rect);
    } else {
        showRepoCategoryItemToolTip((RepoCategoryItem *)item, global_pos, item_rect);
    }

    return true;
}

void RepoTreeView::showRepoItemToolTip(const RepoItem *item,
                                       const QPoint& pos,
                                       const QRect& rect)
{
    RepoItemDelegate *delegate = (RepoItemDelegate *)itemDelegate();
    delegate->showRepoItemToolTip(item, pos, viewport(), rect);
}

void RepoTreeView::showRepoCategoryItemToolTip(const RepoCategoryItem *item,
                                               const QPoint& pos,
                                               const QRect& rect)
{
    QToolTip::showText(pos, item->name(), viewport(), rect);
    // QToolTip::showText(pos, item->name());
}

std::vector<QAction*> RepoTreeView::getToolBarActions()
{
    std::vector<QAction*> actions;

    actions.push_back(download_action_);
    actions.push_back(open_local_folder_action_);
    actions.push_back(view_on_web_action_);
    actions.push_back(show_detail_action_);
    return actions;
}

void RepoTreeView::selectionChanged(const QItemSelection &selected,
                                    const QItemSelection &deselected)
{
    updateRepoActions();
}

void RepoTreeView::hideEvent(QHideEvent *event)
{
    download_action_->setEnabled(false);
    open_local_folder_action_->setEnabled(false);
    unsync_action_->setEnabled(false);
    toggle_auto_sync_action_->setEnabled(false);
    view_on_web_action_->setEnabled(false);
    show_detail_action_->setEnabled(false);
}

void RepoTreeView::showEvent(QShowEvent *event)
{
    updateRepoActions();
}

void RepoTreeView::syncRepoImmediately()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(sync_now_action_->data());

    seafApplet->rpcClient()->syncRepoImmediately(repo.id);
}

void RepoTreeView::cancelDownload()
{
    ServerRepo repo = qvariant_cast<ServerRepo>(cancel_download_action_->data());

    QString error;
    if (seafApplet->rpcClient()->cancelCloneTask(repo.id, &error) < 0) {
        QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
                             tr("Failed to cancel this task:\n\n %1").arg(error),
                             QMessageBox::Ok);
    } else {
        QMessageBox::information(this, tr(SEAFILE_CLIENT_BRAND),
                                 tr("The download has been canceled"),
                                 QMessageBox::Ok);
    }
}
<commit_msg>fixed a bug<commit_after>#include <QtGui>
#include <QHeaderView>
#include <QDesktopServices>
#include <QEvent>
#include <QShowEvent>
#include <QHideEvent>

#include "QtAwesome.h"
#include "utils/utils.h"
#include "seafile-applet.h"
#include "rpc/rpc-client.h"
#include "rpc/local-repo.h"
#include "download-repo-dialog.h"
#include "clone-tasks-dialog.h"
#include "cloud-view.h"
#include "repo-item.h"
#include "repo-item-delegate.h"
#include "repo-tree-model.h"
#include "repo-tree-view.h"
#include "repo-detail-dialog.h"

RepoTreeView::RepoTreeView(CloudView *cloud_view, QWidget *parent)
    : QTreeView(parent),
      cloud_view_(cloud_view)
{
    header()->hide();
    createActions();

    // We draw the indicator ourselves
    setIndentation(0);
    // We handle the click oursevles
    setExpandsOnDoubleClick(false);

    connect(this, SIGNAL(clicked(const QModelIndex&)),
            this, SLOT(onItemClicked(const QModelIndex&)));

    connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
            this, SLOT(onItemDoubleClicked(const QModelIndex&)));
}

void RepoTreeView::contextMenuEvent(QContextMenuEvent *event)
{
    QPoint pos = event->pos();
    QModelIndex index = indexAt(pos);
    if (!index.isValid()) {
        // Not clicked at a repo item
        return;
    }

    QStandardItem *item = getRepoItem(index);
    if (!item || item->type() != REPO_ITEM_TYPE) {
        return;
    }
    updateRepoActions();
    QMenu *menu = prepareContextMenu((RepoItem *)item);
    pos = viewport()->mapToGlobal(pos);
    menu->exec(pos);
}

QMenu* RepoTreeView::prepareContextMenu(const RepoItem *item)
{
    QMenu *menu = new QMenu(this);
    if (item->localRepo().isValid()) {
        menu->addAction(open_local_folder_action_);
    }

    if (item->repoDownloadable()) {
        menu->addAction(download_action_);
    }

    menu->addAction(view_on_web_action_);

    if (item->localRepo().isValid()) {
        menu->addSeparator();
        menu->addAction(toggle_auto_sync_action_);
        menu->addAction(sync_now_action_);
        menu->addSeparator();
    }

    menu->addAction(show_detail_action_);

    if (item->cloneTask().isCancelable()) {
        menu->addAction(cancel_download_action_);
    }
    if (item->localRepo().isValid()) {
        menu->addAction(unsync_action_);
    }

    return menu;
}

void RepoTreeView::updateRepoActions()
{
    RepoItem *item = NULL;
    QItemSelection selected = selectionModel()->selection();
    QModelIndexList indexes = selected.indexes();
    if (indexes.size() != 0) {
        const QModelIndex& index = indexes.at(0);
        QStandardItem *it = ((RepoTreeModel *)model())->itemFromIndex(index);
        if (it && it->type() == REPO_ITEM_TYPE) {
            item = (RepoItem *)it;
        }
    }

    if (!item) {
        // No repo item is selected
        download_action_->setEnabled(false);
        sync_now_action_->setEnabled(false);
        open_local_folder_action_->setEnabled(false);
        unsync_action_->setEnabled(false);
        toggle_auto_sync_action_->setEnabled(false);
        view_on_web_action_->setEnabled(false);
        show_detail_action_->setEnabled(false);
        return;
    }

    LocalRepo r;
    seafApplet->rpcClient()->getLocalRepo(item->repo().id, &r);
    item->setLocalRepo(r);

    if (item->localRepo().isValid()) {
        const LocalRepo& local_repo = item->localRepo();
        download_action_->setEnabled(false);

        sync_now_action_->setEnabled(true);
        sync_now_action_->setData(QVariant::fromValue(local_repo));

        open_local_folder_action_->setData(QVariant::fromValue(local_repo));
        open_local_folder_action_->setEnabled(true);

        unsync_action_->setData(QVariant::fromValue(local_repo));
        unsync_action_->setEnabled(true);

        toggle_auto_sync_action_->setData(QVariant::fromValue(local_repo));
        toggle_auto_sync_action_->setEnabled(true);
        if (local_repo.auto_sync) {
            toggle_auto_sync_action_->setText(tr("Disable auto sync"));
            toggle_auto_sync_action_->setToolTip(tr("Disable auto sync"));
            toggle_auto_sync_action_->setIcon(QIcon(":/images/pause.png"));
        } else {
            toggle_auto_sync_action_->setText(tr("Enable auto sync"));
            toggle_auto_sync_action_->setToolTip(tr("Enable auto sync"));
            toggle_auto_sync_action_->setIcon(QIcon(":/images/play.png"));
        }

    } else {
        if (item->repoDownloadable()) {
            download_action_->setEnabled(true);
            download_action_->setData(QVariant::fromValue(item->repo()));
        } else {
            download_action_->setEnabled(false);
        }

        sync_now_action_->setEnabled(false);

        open_local_folder_action_->setEnabled(false);
        unsync_action_->setEnabled(false);
        toggle_auto_sync_action_->setEnabled(false);
    }

    view_on_web_action_->setEnabled(true);
    view_on_web_action_->setData(item->repo().id);
    show_detail_action_->setEnabled(true);
    show_detail_action_->setData(QVariant::fromValue(item->repo()));

    if (item->cloneTask().isCancelable()) {
        cancel_download_action_->setEnabled(true);
        cancel_download_action_->setData(QVariant::fromValue(item->repo()));
    } else {
        cancel_download_action_->setEnabled(false);
    }
}

QStandardItem* RepoTreeView::getRepoItem(const QModelIndex &index) const
{
    if (!index.isValid()) {
        return NULL;
    }
    const RepoTreeModel *model = (const RepoTreeModel*)index.model();
    QStandardItem *item = model->itemFromIndex(index);
    if (item->type() != REPO_ITEM_TYPE &&
        item->type() != REPO_CATEGORY_TYPE) {
        return NULL;
    }
    return item;
}

void RepoTreeView::createActions()
{
    show_detail_action_ = new QAction(tr("&Show details"), this);
    show_detail_action_->setIcon(QIcon(":/images/info.png"));
    show_detail_action_->setStatusTip(tr("Download this library"));
    show_detail_action_->setIconVisibleInMenu(true);
    connect(show_detail_action_, SIGNAL(triggered()), this, SLOT(showRepoDetail()));

    download_action_ = new QAction(tr("&Download this library"), this);
    download_action_->setIcon(QIcon(":/images/download.png"));
    download_action_->setStatusTip(tr("Download this library"));
    download_action_->setIconVisibleInMenu(true);
    connect(download_action_, SIGNAL(triggered()), this, SLOT(downloadRepo()));

    sync_now_action_ = new QAction(tr("&Sync now"), this);
    sync_now_action_->setIcon(QIcon(":/images/sync_now.png"));
    sync_now_action_->setStatusTip(tr("Sync this library immediately"));
    sync_now_action_->setIconVisibleInMenu(true);
    connect(sync_now_action_, SIGNAL(triggered()), this, SLOT(syncRepoImmediately()));

    cancel_download_action_ = new QAction(tr("&Cancel download"), this);
    cancel_download_action_->setIcon(QIcon(":/images/remove.png"));
    cancel_download_action_->setStatusTip(tr("Cancel download of this library"));
    cancel_download_action_->setIconVisibleInMenu(true);
    connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(cancelDownload()));

    open_local_folder_action_ = new QAction(tr("&Open folder"), this);
    open_local_folder_action_->setIcon(QIcon(":/images/folder-open.png"));
    open_local_folder_action_->setStatusTip(tr("open local folder"));
    open_local_folder_action_->setIconVisibleInMenu(true);
    connect(open_local_folder_action_, SIGNAL(triggered()), this, SLOT(openLocalFolder()));

    unsync_action_ = new QAction(tr("&Unsync"), this);
    unsync_action_->setStatusTip(tr("unsync this library"));
    unsync_action_->setIcon(QIcon(":/images/minus.png"));
    unsync_action_->setIconVisibleInMenu(true);
    connect(unsync_action_, SIGNAL(triggered()), this, SLOT(unsyncRepo()));

    toggle_auto_sync_action_ = new QAction(tr("Enable auto sync"), this);
    toggle_auto_sync_action_->setStatusTip(tr("Enable auto sync"));
    toggle_auto_sync_action_->setIconVisibleInMenu(true);
    connect(toggle_auto_sync_action_, SIGNAL(triggered()), this, SLOT(toggleRepoAutoSync()));

    view_on_web_action_ = new QAction(tr("&View on cloud"), this);
    view_on_web_action_->setIcon(QIcon(":/images/cloud.png"));
    view_on_web_action_->setStatusTip(tr("view this library on seahub"));
    view_on_web_action_->setIconVisibleInMenu(true);

    connect(view_on_web_action_, SIGNAL(triggered()), this, SLOT(viewRepoOnWeb()));
}

void RepoTreeView::downloadRepo()
{
    ServerRepo repo = qvariant_cast<ServerRepo>(download_action_->data());
    DownloadRepoDialog dialog(cloud_view_->currentAccount(), repo, this);

    dialog.exec();

    updateRepoActions();
}

void RepoTreeView::showRepoDetail()
{
    ServerRepo repo = qvariant_cast<ServerRepo>(show_detail_action_->data());
    RepoDetailDialog dialog(repo, this);
    dialog.exec();
}

void RepoTreeView::openLocalFolder()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(open_local_folder_action_->data());
    QDesktopServices::openUrl(QUrl::fromLocalFile(repo.worktree));
}

void RepoTreeView::toggleRepoAutoSync()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data());

    seafApplet->rpcClient()->setRepoAutoSync(repo.id, !repo.auto_sync);

    updateRepoActions();
}

void RepoTreeView::unsyncRepo()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(toggle_auto_sync_action_->data());

    QString question = tr("Are you sure to unsync library \"%1\"?").arg(repo.name);

    if (QMessageBox::question(this,
                              tr(SEAFILE_CLIENT_BRAND),
                              question,
                              QMessageBox::Ok | QMessageBox::Cancel,
                              QMessageBox::Cancel) != QMessageBox::Ok) {
        return;
    }

    if (seafApplet->rpcClient()->unsync(repo.id) < 0) {
        QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
                             tr("Failed to unsync library \"%1\"").arg(repo.name),
                             QMessageBox::Ok);
    }

    updateRepoActions();
}

void RepoTreeView::onItemClicked(const QModelIndex& index)
{
    QStandardItem *item = getRepoItem(index);
    if (!item) {
        return;
    }
    if (item->type() == REPO_ITEM_TYPE) {
        return;
    } else {
        // A repo category item
        if (isExpanded(index)) {
            collapse(index);
        } else {
            expand(index);
        }
    }
}

void RepoTreeView::onItemDoubleClicked(const QModelIndex& index)
{
    QStandardItem *item = getRepoItem(index);
    if (!item) {
        return;
    }
    if (item->type() == REPO_ITEM_TYPE) {
        RepoItem *it = (RepoItem *)item;
        const LocalRepo& local_repo = it->localRepo();
        if (local_repo.isValid()) {
            QDesktopServices::openUrl(QUrl::fromLocalFile(local_repo.worktree));
        }
    }
}

void RepoTreeView::viewRepoOnWeb()
{
    QString repo_id = view_on_web_action_->data().toString();
    const Account& account = cloud_view_->currentAccount();
    if (account.isValid()) {
        QUrl url = account.serverUrl;
        url.setPath(url.path() + "/repo/" + repo_id);
        QDesktopServices::openUrl(url);
    }
}

bool RepoTreeView::viewportEvent(QEvent *event)
{
    if (event->type() != QEvent::ToolTip && event->type() != QEvent::WhatsThis) {
        return QTreeView::viewportEvent(event);
    }

    QPoint global_pos = QCursor::pos();
    QPoint viewport_pos = viewport()->mapFromGlobal(global_pos);
    QModelIndex index = indexAt(viewport_pos);
    if (!index.isValid()) {
        return true;
    }

    QStandardItem *item = getRepoItem(index);
    if (!item) {
        return true;
    }

    QRect item_rect = visualRect(index);
    if (item->type() == REPO_ITEM_TYPE) {
        showRepoItemToolTip((RepoItem *)item, global_pos, item_rect);
    } else {
        showRepoCategoryItemToolTip((RepoCategoryItem *)item, global_pos, item_rect);
    }

    return true;
}

void RepoTreeView::showRepoItemToolTip(const RepoItem *item,
                                       const QPoint& pos,
                                       const QRect& rect)
{
    RepoItemDelegate *delegate = (RepoItemDelegate *)itemDelegate();
    delegate->showRepoItemToolTip(item, pos, viewport(), rect);
}

void RepoTreeView::showRepoCategoryItemToolTip(const RepoCategoryItem *item,
                                               const QPoint& pos,
                                               const QRect& rect)
{
    QToolTip::showText(pos, item->name(), viewport(), rect);
    // QToolTip::showText(pos, item->name());
}

std::vector<QAction*> RepoTreeView::getToolBarActions()
{
    std::vector<QAction*> actions;

    actions.push_back(download_action_);
    actions.push_back(open_local_folder_action_);
    actions.push_back(view_on_web_action_);
    actions.push_back(show_detail_action_);
    return actions;
}

void RepoTreeView::selectionChanged(const QItemSelection &selected,
                                    const QItemSelection &deselected)
{
    updateRepoActions();
}

void RepoTreeView::hideEvent(QHideEvent *event)
{
    download_action_->setEnabled(false);
    open_local_folder_action_->setEnabled(false);
    unsync_action_->setEnabled(false);
    toggle_auto_sync_action_->setEnabled(false);
    view_on_web_action_->setEnabled(false);
    show_detail_action_->setEnabled(false);
}

void RepoTreeView::showEvent(QShowEvent *event)
{
    updateRepoActions();
}

void RepoTreeView::syncRepoImmediately()
{
    LocalRepo repo = qvariant_cast<LocalRepo>(sync_now_action_->data());

    seafApplet->rpcClient()->syncRepoImmediately(repo.id);
}

void RepoTreeView::cancelDownload()
{
    ServerRepo repo = qvariant_cast<ServerRepo>(cancel_download_action_->data());

    QString error;
    if (seafApplet->rpcClient()->cancelCloneTask(repo.id, &error) < 0) {
        QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),
                             tr("Failed to cancel this task:\n\n %1").arg(error),
                             QMessageBox::Ok);
    } else {
        QMessageBox::information(this, tr(SEAFILE_CLIENT_BRAND),
                                 tr("The download has been canceled"),
                                 QMessageBox::Ok);
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010-2015 Max Kellermann <max@duempel.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef TRIVIAL_ARRAY_HXX
#define TRIVIAL_ARRAY_HXX

#include <array>
#include <algorithm>

#include <assert.h>

/**
 * An array with a maximum size known at compile time.  It keeps track
 * of the actual length at runtime. The clear() function needs to be
 * called to initialize the class properly.
 */
template<class T, unsigned max>
class TrivialArray {
	typedef std::array<T, max> Array;

public:
	typedef unsigned size_type;
	typedef T value_type;
	typedef typename Array::iterator iterator;
	typedef typename Array::const_iterator const_iterator;

protected:
	size_type the_size;
	Array data;

	constexpr
	TrivialArray(size_type _size):the_size(_size) {}

public:
	/**
	 * Non-initialising constructor.
	 */
	TrivialArray() = default;

	TrivialArray(size_type _size, const T &value):the_size(_size) {
		std::fill(begin(), end(), value);
	}

	/**
	 * Initialise the array with values from the iterator range.
	 */
	template<typename I>
	TrivialArray(I _begin, I _end):the_size(0) {
		for (I i = _begin; i != _end; ++i)
			push_back(*i);
	}

	constexpr
	size_type capacity() const { return max; }

	constexpr
	size_type max_size() const {
		return max;
	}

	/**
	 * Forcibly set the specified size, without initialising or
	 * freeing new/excess elements.
	 */
	void resize(size_type new_size) {
		assert(new_size <= max_size());

		the_size = new_size;
	}

	/**
	 * Returns the number of allocated elements.
	 */
	constexpr
	size_type size() const {
		return the_size;
	}

	void shrink(size_type _size) {
		assert(_size <= the_size);

		the_size = _size;
	}

	constexpr
	bool empty() const {
		return the_size == 0;
	}

	constexpr
	bool full() const {
		return the_size == max;
	}

	/**
	 * Empties this array, but does not destruct its elements.
	 */
	void clear() {
		the_size = 0;
	}

	/**
	 * Returns one element.  No bounds checking.
	 */
	T &operator[](size_type i) {
		assert(i < size());

		return data[i];
	}

	/**
	 * Returns one constant element.  No bounds checking.
	 */
	const T &operator[](size_type i) const {
		assert(i < size());

		return data[i];
	}

	iterator begin() {
		return data.begin();
	}

	constexpr const_iterator begin() const {
		return data.begin();
	}

	iterator end() {
		return std::next(data.begin(), the_size);
	}

	constexpr const_iterator end() const {
		return std::next(data.begin(), the_size);
	}

	T &last() {
		assert(the_size > 0);

		return data[the_size - 1];
	}

	const T &last() const {
		assert(the_size > 0);

		return data[the_size - 1];
	}

	bool contains(const T &value) const {
		return std::find(begin(), end(), value) != end();
	}

	/**
	 * Return address of start of data segment.
	 */
	const T* raw() const {
		return &data[0];
	}

	/**
	 * Append an element at the end of the array, increasing the
	 * length by one.  No bounds checking.
	 */
	void append(const T &value) {
		assert(!full());

		data[the_size++] = value;
	}

	/**
	 * Increase the length by one and return a pointer to the new
	 * element, to be modified by the caller.  No bounds checking.
	 */
	T &append() {
		assert(!full());

		return data[the_size++];
	}

	/**
	 * Like append(), but checks if the array is already full
	 * (returns false in this case).
	 */
	bool checked_append(const T &value) {
		if (full())
			return false;

		append(value);
		return true;
	}

	/**
	 * Remove the item at the given index.
	 */
	void remove(size_type i) {
		assert(i < size());

		std::move(std::next(data.begin(), i + 1),
			  std::next(data.begin(), size()),
			  std::next(data.begin(), i));

		--the_size;
	}

	/**
	 * Remove an item by copying the last item over it.
	 */
	void quick_remove(size_type i) {
		assert(i < size());

		if (i < size() - 1)
			data[i] = std::move(data[size() - 1]);

		--the_size;
	}

	/* STL API emulation */

	void push_back(const T &value) {
		append(value);
	}

	T &front() {
		assert(the_size > 0);

		return data.front();
	}

	const T &front() const {
		assert(the_size > 0);

		return data.front();
	}

	T &back() {
		return last();
	}

	const T &back() const {
		return last();
	}
};

#endif
<commit_msg>util/TrivialArray: add method insert()<commit_after>/*
 * Copyright (C) 2010-2015 Max Kellermann <max@duempel.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef TRIVIAL_ARRAY_HXX
#define TRIVIAL_ARRAY_HXX

#include <array>
#include <algorithm>

#include <assert.h>

/**
 * An array with a maximum size known at compile time.  It keeps track
 * of the actual length at runtime. The clear() function needs to be
 * called to initialize the class properly.
 */
template<class T, unsigned max>
class TrivialArray {
	typedef std::array<T, max> Array;

public:
	typedef unsigned size_type;
	typedef T value_type;
	typedef typename Array::iterator iterator;
	typedef typename Array::const_iterator const_iterator;

protected:
	size_type the_size;
	Array data;

	constexpr
	TrivialArray(size_type _size):the_size(_size) {}

public:
	/**
	 * Non-initialising constructor.
	 */
	TrivialArray() = default;

	TrivialArray(size_type _size, const T &value):the_size(_size) {
		std::fill(begin(), end(), value);
	}

	/**
	 * Initialise the array with values from the iterator range.
	 */
	template<typename I>
	TrivialArray(I _begin, I _end):the_size(0) {
		for (I i = _begin; i != _end; ++i)
			push_back(*i);
	}

	constexpr
	size_type capacity() const { return max; }

	constexpr
	size_type max_size() const {
		return max;
	}

	/**
	 * Forcibly set the specified size, without initialising or
	 * freeing new/excess elements.
	 */
	void resize(size_type new_size) {
		assert(new_size <= max_size());

		the_size = new_size;
	}

	/**
	 * Returns the number of allocated elements.
	 */
	constexpr
	size_type size() const {
		return the_size;
	}

	void shrink(size_type _size) {
		assert(_size <= the_size);

		the_size = _size;
	}

	constexpr
	bool empty() const {
		return the_size == 0;
	}

	constexpr
	bool full() const {
		return the_size == max;
	}

	/**
	 * Empties this array, but does not destruct its elements.
	 */
	void clear() {
		the_size = 0;
	}

	/**
	 * Returns one element.  No bounds checking.
	 */
	T &operator[](size_type i) {
		assert(i < size());

		return data[i];
	}

	/**
	 * Returns one constant element.  No bounds checking.
	 */
	const T &operator[](size_type i) const {
		assert(i < size());

		return data[i];
	}

	iterator begin() {
		return data.begin();
	}

	constexpr const_iterator begin() const {
		return data.begin();
	}

	iterator end() {
		return std::next(data.begin(), the_size);
	}

	constexpr const_iterator end() const {
		return std::next(data.begin(), the_size);
	}

	T &last() {
		assert(the_size > 0);

		return data[the_size - 1];
	}

	const T &last() const {
		assert(the_size > 0);

		return data[the_size - 1];
	}

	bool contains(const T &value) const {
		return std::find(begin(), end(), value) != end();
	}

	/**
	 * Return address of start of data segment.
	 */
	const T* raw() const {
		return &data[0];
	}

	/**
	 * Append an element at the end of the array, increasing the
	 * length by one.  No bounds checking.
	 */
	void append(const T &value) {
		assert(!full());

		data[the_size++] = value;
	}

	/**
	 * Increase the length by one and return a pointer to the new
	 * element, to be modified by the caller.  No bounds checking.
	 */
	T &append() {
		assert(!full());

		return data[the_size++];
	}

	/**
	 * Like append(), but checks if the array is already full
	 * (returns false in this case).
	 */
	bool checked_append(const T &value) {
		if (full())
			return false;

		append(value);
		return true;
	}

	/**
	 * Remove the item at the given index.
	 */
	void remove(size_type i) {
		assert(i < size());

		std::move(std::next(data.begin(), i + 1),
			  std::next(data.begin(), size()),
			  std::next(data.begin(), i));

		--the_size;
	}

	/**
	 * Remove an item by copying the last item over it.
	 */
	void quick_remove(size_type i) {
		assert(i < size());

		if (i < size() - 1)
			data[i] = std::move(data[size() - 1]);

		--the_size;
	}

	template<typename I>
	void insert(size_type i, I _begin, I _end) {
		size_type n = std::distance(_begin, _end);
		assert(the_size + n < capacity());

		auto dest_begin = std::next(begin(), i);
		auto dest_end = end();
		the_size += n;

		std::move_backward(dest_begin, dest_end, end());
		std::copy(_begin, _end, dest_begin);
	}

	/* STL API emulation */

	void push_back(const T &value) {
		append(value);
	}

	T &front() {
		assert(the_size > 0);

		return data.front();
	}

	const T &front() const {
		assert(the_size > 0);

		return data.front();
	}

	T &back() {
		return last();
	}

	const T &back() const {
		return last();
	}
};

#endif
<|endoftext|>


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

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#if !defined OS2 && !defined WNT
//#define _BUTTON_HXX
#endif

#define _SETBRW_HXX
#define _STACK_HXX
//#define _STATUS_HXX
#define _STDMENU_HXX
#define _TABBAR_HXX
#define _VCBRW_HXX
#define _VCTRLS_HXX
#define _VCSBX_HXX
#define _VCONT_HXX
#define _VDRWOBJ_HXX

#define _BASE_DLGS_HXX
#define _BIGINT_HXX
#define _CACHESTR_HXX
#define _CONFIG_HXX
#define _CURSOR_HXX
#define _CTRLTOOL_HXX
#define _DLGCFG_HXX
#define _DYNARR_HXX
#define _EXTATTR_HXX
#define _FILDLG_HXX
#define _FONTDLG_HXX
#define _FRM3D_HXX
#define _INTRO_HXX
#define _ISETBWR_HXX
#define _NO_SVRTF_PARSER_HXX
#define _MACRODLG_HXX
#define _MODALDLG_HXX
#define _MOREBUTTON_HXX
#define _OUTLINER_HXX
#define _PASSWD_HXX
//#define _PRNDLG_HXX
//#define _POLY_HXX
#define _PVRWIN_HXX
#define _QUEUE_HXX
#define _RULER_HXX
#define _SCRWIN_HXX
#define _STACK_HXX
#define _SETBRW_HXX
#define _STACK_HXX
//#define _STATUS_HXX
#define _STDMENU_HXX
#define _TABBAR_HXX
#define _VCBRW_HXX
#define _VCTRLS_HXX
#define _VCSBX_HXX
#define _VCONT_HXX
#define _VDRWOBJ_HXX

#define _SVDXOUT_HXX
#define _SVDATTR_HXX
#define _SVDETC_HXX
#define _SVDIO_HXX
#define _SVDRAG_HXX
#define _SVDLAYER_HXX

#define _SFXFILEDLG_HXX
#define _SFX_MACRO_HXX
#define _SFXMNUITEM_HXX
#define _SFXMNUMGR_HXX
#define _SFXMSGPOOL_HXX
#define _SFXMULTISEL_HXX
#define _SFXBASIC_HXX
#define _SFXSTBMGR_HXX
//#define _SFXTBXCTRL_HXX
//#define _SFXTBXMGR_HXX
//#define _SFXIMGMGR_HXX

#define _SI_DLL_HXX
#define _SIDLL_HXX
#define _SI_NOITEMS
#define _SI_NOOTHERFORMS
#define _SI_NOSBXCONTROLS
#define _SINOSBXCONTROLS
#define _SI_NODRW
#define _SI_NOCONTROL

#define _SVX_DAILDLL_HXX
#define _SVX_HYPHEN_HXX
#define _SVX_IMPGRF_HXX
#define _SVX_OPTITEMS_HXX
#define _SVX_OPTGERL_HXX
#define _SVX_OPTSAVE_HXX
#define _SVX_OPTSPELL_HXX
#define _SVX_OPTPATH_HXX
#define _SVX_OPTLINGU_HXX
#define _SVX_RULER_HXX
#define _SVX_RULRITEM_HXX
#define _SVX_SPLWRAP_HXX
#define _SVX_SPLDLG_HXX
#define _SVX_THESDLG_HXX

// INCLUDE ---------------------------------------------------------------

#include "scitems.hxx"
#include <basctl/idetemp.hxx>
#include <svx/imapdlg.hxx>
#include <svx/srchitem.hxx>
#include <offmgr/sbasltid.hrc>
#include <sfx2/templdlg.hxx>

#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "reffact.hxx"
#include "scresid.hxx"
#include "dwfunctr.hxx"
#include "sc.hrc"       // -> SID_TOOL_xxx
#include "drawattr.hxx" // -> SvxDrawToolItem

#define ScTabViewShell
#include "scslots.hxx"

#define SearchSettings
#include <svx/svxslots.hxx>

TYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener);

SFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL))
{
    SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS  | SFX_VISIBILITY_STANDARD |
                                SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,
                                ScResId(RID_OBJECTBAR_TOOLS) );

    SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS);
    SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR);
    SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG);
    SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG);
}

SFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) )
{
    SFX_VIEW_REGISTRATION(ScDocShell);
}

//------------------------------------------------------------------

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

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#if !defined OS2 && !defined WNT
//#define _BUTTON_HXX
#endif

#define _SETBRW_HXX
#define _STACK_HXX
//#define _STATUS_HXX
#define _STDMENU_HXX
#define _TABBAR_HXX
#define _VCBRW_HXX
#define _VCTRLS_HXX
#define _VCSBX_HXX
#define _VCONT_HXX
#define _VDRWOBJ_HXX

#define _BASE_DLGS_HXX
#define _BIGINT_HXX
#define _CACHESTR_HXX
#define _CONFIG_HXX
#define _CURSOR_HXX
#define _CTRLTOOL_HXX
#define _DLGCFG_HXX
#define _DYNARR_HXX
#define _EXTATTR_HXX
#define _FILDLG_HXX
#define _FONTDLG_HXX
#define _FRM3D_HXX
#define _INTRO_HXX
#define _ISETBWR_HXX
#define _NO_SVRTF_PARSER_HXX
#define _MACRODLG_HXX
#define _MODALDLG_HXX
#define _MOREBUTTON_HXX
#define _OUTLINER_HXX
#define _PASSWD_HXX
//#define _PRNDLG_HXX
//#define _POLY_HXX
#define _PVRWIN_HXX
#define _QUEUE_HXX
#define _RULER_HXX
#define _SCRWIN_HXX
#define _STACK_HXX
#define _SETBRW_HXX
#define _STACK_HXX
//#define _STATUS_HXX
#define _STDMENU_HXX
#define _TABBAR_HXX
#define _VCBRW_HXX
#define _VCTRLS_HXX
#define _VCSBX_HXX
#define _VCONT_HXX
#define _VDRWOBJ_HXX

#define _SVDXOUT_HXX
#define _SVDATTR_HXX
#define _SVDETC_HXX
#define _SVDIO_HXX
#define _SVDRAG_HXX
#define _SVDLAYER_HXX

#define _SFXFILEDLG_HXX
#define _SFX_MACRO_HXX
#define _SFXMNUITEM_HXX
#define _SFXMNUMGR_HXX
#define _SFXMSGPOOL_HXX
#define _SFXMULTISEL_HXX
#define _SFXBASIC_HXX
#define _SFXSTBMGR_HXX
//#define _SFXTBXCTRL_HXX
//#define _SFXTBXMGR_HXX
//#define _SFXIMGMGR_HXX

#define _SI_DLL_HXX
#define _SIDLL_HXX
#define _SI_NOITEMS
#define _SI_NOOTHERFORMS
#define _SI_NOSBXCONTROLS
#define _SINOSBXCONTROLS
#define _SI_NODRW
#define _SI_NOCONTROL

#define _SVX_DAILDLL_HXX
#define _SVX_HYPHEN_HXX
#define _SVX_IMPGRF_HXX
#define _SVX_OPTITEMS_HXX
#define _SVX_OPTGERL_HXX
#define _SVX_OPTSAVE_HXX
#define _SVX_OPTSPELL_HXX
#define _SVX_OPTPATH_HXX
#define _SVX_OPTLINGU_HXX
#define _SVX_RULER_HXX
#define _SVX_RULRITEM_HXX
#define _SVX_SPLWRAP_HXX
#define _SVX_SPLDLG_HXX
#define _SVX_THESDLG_HXX

// INCLUDE ---------------------------------------------------------------

#include "scitems.hxx"
#include <svx/imapdlg.hxx>
#include <svx/srchitem.hxx>
#include <offmgr/sbasltid.hrc>
#include <sfx2/templdlg.hxx>

#include "tabvwsh.hxx"
#include "docsh.hxx"
#include "reffact.hxx"
#include "scresid.hxx"
#include "dwfunctr.hxx"
#include "sc.hrc"       // -> SID_TOOL_xxx
#include "drawattr.hxx" // -> SvxDrawToolItem

#define ScTabViewShell
#include "scslots.hxx"

#define SearchSettings
#include <svx/svxslots.hxx>

TYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener);

SFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL))
{
    SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS  | SFX_VISIBILITY_STANDARD |
                                SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,
                                ScResId(RID_OBJECTBAR_TOOLS) );

    SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS);
    SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR);
    SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId());
    SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG);
    SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG);
}

SFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) )
{
    SFX_VIEW_REGISTRATION(ScDocShell);
}

//------------------------------------------------------------------

<|endoftext|>


<commit_before>/*
    Copyright (c) 2011 <chrigi_1@fastmail.fm>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

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

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

#include "note.h"

#include <Akonadi/EntityDisplayAttribute>
#include <akonadi/notes/noteutils.h>

#include <KMime/Message>

Note::Note(QObject *parent)
:   AbstractPimItem(parent)
{
    //init payload, mimetype, and displayattribute
    commitData();
}
/*
Note::Note(const Note &note)
:   AbstractPimItem(note.getItem())
{
    m_text = note.m_text;
    m_title = note.m_title;
    m_creationDate = note.m_creationDate;
}*/

Note::Note(const Akonadi::Item &item, QObject *parent)
:   AbstractPimItem(item, parent)
{
    fetchData();
}

Note::Note(AbstractPimItem &item, QObject* parent)
:   AbstractPimItem(item, parent)
{
    commitData();
}

bool Note::hasValidPayload()
{
    if (m_item.hasPayload<KMime::Message::Ptr>()) {
        return true;
    }
    return false;
}

void Note::commitData()
{
    m_item.setMimeType(Akonadi::NoteUtils::noteMimeType());
    Akonadi::NoteUtils::NoteMessageWrapper messageWrapper;
    messageWrapper.setTitle(m_title);
    messageWrapper.setText(m_text, m_textIsRich ? Qt::RichText : Qt::PlainText);
    messageWrapper.setCreationDate(m_creationDate);
    messageWrapper.setFrom(QString::fromLatin1( "NoteTaker@kde4" )); //FIXME shouldn't be hardcoded
    m_item.setPayload(messageWrapper.message());

    Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute();
    eda->setIconName(getIconName());
    eda->setDisplayName(m_title);
    m_item.addAttribute(eda);
}

void Note::fetchData()
{
    if (m_dataFetched) {
        return;
    }

    if ( !hasValidPayload()) {
        kDebug() << "invalid payload";
        return;
    }

    KMime::Message::Ptr msg = m_item.payload<KMime::Message::Ptr>();
    Q_ASSERT(msg.get());
    Akonadi::NoteUtils::NoteMessageWrapper messageWrapper(msg);
    m_textIsRich = messageWrapper.textFormat() == Qt::RichText;
    m_titleIsRich = false;
    m_title = messageWrapper.title();
    m_text = messageWrapper.text();
    m_creationDate = messageWrapper.creationDate();

    m_dataFetched = true;
}

QString Note::mimeType()
{
    Q_ASSERT(AbstractPimItem::mimeType(AbstractPimItem::Note) == Akonadi::NoteUtils::noteMimeType());
    return AbstractPimItem::mimeType(AbstractPimItem::Note);
}

AbstractPimItem::ItemStatus Note::getStatus() const
{
    return AbstractPimItem::Later;
}

KDateTime Note::getPrimaryDate()
{
    return getLastModifiedDate();
}

QString Note::getIconName()
{
    return Akonadi::NoteUtils::noteIconName();
}

AbstractPimItem::ItemType Note::itemType()
{
    return AbstractPimItem::Note;
}
<commit_msg>set correct application name<commit_after>/*
    Copyright (c) 2011 <chrigi_1@fastmail.fm>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

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

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

#include "note.h"

#include <Akonadi/EntityDisplayAttribute>
#include <akonadi/notes/noteutils.h>

#include <KMime/Message>
#include <QCoreApplication>

Note::Note(QObject *parent)
:   AbstractPimItem(parent)
{
    //init payload, mimetype, and displayattribute
    commitData();
}
/*
Note::Note(const Note &note)
:   AbstractPimItem(note.getItem())
{
    m_text = note.m_text;
    m_title = note.m_title;
    m_creationDate = note.m_creationDate;
}*/

Note::Note(const Akonadi::Item &item, QObject *parent)
:   AbstractPimItem(item, parent)
{
    fetchData();
}

Note::Note(AbstractPimItem &item, QObject* parent)
:   AbstractPimItem(item, parent)
{
    commitData();
}

bool Note::hasValidPayload()
{
    if (m_item.hasPayload<KMime::Message::Ptr>()) {
        return true;
    }
    return false;
}

void Note::commitData()
{
    m_item.setMimeType(Akonadi::NoteUtils::noteMimeType());
    Akonadi::NoteUtils::NoteMessageWrapper messageWrapper;
    messageWrapper.setTitle(m_title);
    messageWrapper.setText(m_text, m_textIsRich ? Qt::RichText : Qt::PlainText);
    messageWrapper.setCreationDate(m_creationDate);
    messageWrapper.setFrom(QCoreApplication::applicationName()+QCoreApplication::applicationVersion());
    m_item.setPayload(messageWrapper.message());

    Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute();
    eda->setIconName(getIconName());
    eda->setDisplayName(m_title);
    m_item.addAttribute(eda);
}

void Note::fetchData()
{
    if (m_dataFetched) {
        return;
    }

    if ( !hasValidPayload()) {
        kDebug() << "invalid payload";
        return;
    }

    KMime::Message::Ptr msg = m_item.payload<KMime::Message::Ptr>();
    Q_ASSERT(msg.get());
    Akonadi::NoteUtils::NoteMessageWrapper messageWrapper(msg);
    m_textIsRich = messageWrapper.textFormat() == Qt::RichText;
    m_titleIsRich = false;
    m_title = messageWrapper.title();
    m_text = messageWrapper.text();
    m_creationDate = messageWrapper.creationDate();

    m_dataFetched = true;
}

QString Note::mimeType()
{
    Q_ASSERT(AbstractPimItem::mimeType(AbstractPimItem::Note) == Akonadi::NoteUtils::noteMimeType());
    return AbstractPimItem::mimeType(AbstractPimItem::Note);
}

AbstractPimItem::ItemStatus Note::getStatus() const
{
    return AbstractPimItem::Later;
}

KDateTime Note::getPrimaryDate()
{
    return getLastModifiedDate();
}

QString Note::getIconName()
{
    return Akonadi::NoteUtils::noteIconName();
}

AbstractPimItem::ItemType Note::itemType()
{
    return AbstractPimItem::Note;
}
<|endoftext|>


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

#include "modules/prediction/prediction.h"

#include <cmath>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"

namespace apollo {
namespace prediction {

using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::common::time::Clock;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;

std::string Prediction::Name() const {
  return FLAGS_prediction_module_name;
}

Status Prediction::Init() {
  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    return OnError("Unable to load prediction conf file: " +
                   FLAGS_prediction_conf_file);
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    return OnError("Unable to load adapter conf file: " +
                   FLAGS_prediction_adapter_config_filename);
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  // Initialization of all managers
  AdapterManager::Init(adapter_conf_);
  ContainerManager::instance()->Init(adapter_conf_);
  EvaluatorManager::instance()->Init(prediction_conf_);
  PredictorManager::instance()->Init(prediction_conf_);

  CHECK(AdapterManager::GetLocalization()) << "Localization is not ready.";
  CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not ready.";

  // Set perception obstacle callback function
  AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);
  // Set localization callback function
  AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);

  return Status::OK();
}

Status Prediction::Start() {
  return Status::OK();
}

void Prediction::Stop() {}

void Prediction::OnLocalization(const LocalizationEstimate& localization) {
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);

  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);

  pose_container->Insert(localization);
  PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
  if (pose_ptr != nullptr) {
    obstacles_container->InsertPerceptionObstacle(
        *(pose_ptr), pose_container->GetTimestamp());
  } else {
    ADEBUG << "Invalid pose found.";
  }

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {
  ADEBUG << "Received a perception message ["
         << perception_obstacles.ShortDebugString() << "].";

  double start_timestamp = Clock::NowInSecond();
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(perception_obstacles);
  EvaluatorManager::instance()->Run(perception_obstacles);
  PredictorManager::instance()->Run(perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSecond());

  Publish(&prediction_obstacles);
}

Status Prediction::OnError(const std::string& error_msg) {
  return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}

bool Prediction::IsValidTrajectoryPoint(
    const TrajectoryPoint& trajectory_point) {
  return (!std::isnan(trajectory_point.path_point().x())) &&
         (!std::isnan(trajectory_point.path_point().y())) &&
         (!std::isnan(trajectory_point.path_point().theta())) &&
         (!std::isnan(trajectory_point.v())) &&
         (!std::isnan(trajectory_point.a())) &&
         (!std::isnan(trajectory_point.relative_time()));
}

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

#include "modules/prediction/prediction.h"

#include <cmath>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/time/time.h"
#include "modules/common/util/file.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"

namespace apollo {
namespace prediction {

using ::apollo::common::ErrorCode;
using ::apollo::common::Status;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::adapter::AdapterManager;
using ::apollo::common::time::Clock;
using ::apollo::localization::LocalizationEstimate;
using ::apollo::perception::PerceptionObstacle;
using ::apollo::perception::PerceptionObstacles;

std::string Prediction::Name() const {
  return FLAGS_prediction_module_name;
}

Status Prediction::Init() {
  // Load prediction conf
  prediction_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,
                                      &prediction_conf_)) {
    return OnError("Unable to load prediction conf file: " +
                   FLAGS_prediction_conf_file);
  } else {
    ADEBUG << "Prediction config file is loaded into: "
           << prediction_conf_.ShortDebugString();
  }

  adapter_conf_.Clear();
  if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
                                      &adapter_conf_)) {
    return OnError("Unable to load adapter conf file: " +
                   FLAGS_prediction_adapter_config_filename);
  } else {
    ADEBUG << "Adapter config file is loaded into: "
           << adapter_conf_.ShortDebugString();
  }

  // Initialization of all managers
  AdapterManager::Init(adapter_conf_);
  ContainerManager::instance()->Init(adapter_conf_);
  EvaluatorManager::instance()->Init(prediction_conf_);
  PredictorManager::instance()->Init(prediction_conf_);

  CHECK(AdapterManager::GetLocalization()) << "Localization is not ready.";
  CHECK(AdapterManager::GetPerceptionObstacles()) << "Perception is not ready.";

  // Set perception obstacle callback function
  AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);
  // Set localization callback function
  AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);

  return Status::OK();
}

Status Prediction::Start() {
  return Status::OK();
}

void Prediction::Stop() {}

void Prediction::OnLocalization(const LocalizationEstimate& localization) {
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);

  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  CHECK_NOTNULL(pose_container);

  pose_container->Insert(localization);
  PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();
  if (pose_ptr != nullptr) {
    obstacles_container->InsertPerceptionObstacle(
        *(pose_ptr), pose_container->GetTimestamp());
  } else {
    ADEBUG << "Invalid pose found.";
  }

  ADEBUG << "Received a localization message ["
         << localization.ShortDebugString() << "].";
}

void Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {
  ADEBUG << "Received a perception message ["
         << perception_obstacles.ShortDebugString() << "].";

  double start_timestamp = Clock::NowInSecond();
  ObstaclesContainer* obstacles_container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  CHECK_NOTNULL(obstacles_container);
  obstacles_container->Insert(perception_obstacles);
  EvaluatorManager::instance()->Run(perception_obstacles);
  PredictorManager::instance()->Run(perception_obstacles);

  auto prediction_obstacles =
      PredictorManager::instance()->prediction_obstacles();
  prediction_obstacles.set_start_timestamp(start_timestamp);
  prediction_obstacles.set_end_timestamp(Clock::NowInSecond());
  Publish(&prediction_obstacles);
  for (auto const& prediction_obstacle :
       prediction_obstacles.prediction_obstacle()) {
    for (auto const& trajectory : prediction_obstacle.trajectory()) {
      for (auto const& trajectory_point : trajectory.trajectory_point()) {
        CHECK(IsValidTrajectoryPoint(trajectory_point));
      }
    }
  }

  ADEBUG << "Received a perception message ["
         << perception_obstacles.ShortDebugString() << "].";
  ADEBUG << "Published a prediction message ["
         << prediction_obstacles.ShortDebugString() << "].";
}

Status Prediction::OnError(const std::string& error_msg) {
  return Status(ErrorCode::PREDICTION_ERROR, error_msg);
}

bool Prediction::IsValidTrajectoryPoint(
    const TrajectoryPoint& trajectory_point) {
  return trajectory_point.has_path_point() &&
         (!std::isnan(trajectory_point.path_point().x())) &&
         (!std::isnan(trajectory_point.path_point().y())) &&
         (!std::isnan(trajectory_point.path_point().theta())) &&
         (!std::isnan(trajectory_point.v())) &&
         (!std::isnan(trajectory_point.a())) &&
         (!std::isnan(trajectory_point.relative_time()));
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>/*
 *  webrtc-echo - A WebRTC echo server
 *  Copyright (C) 2014  Stephan Thamm
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "srtp.h"

#include <node_buffer.h>

#include "helper.h"

using namespace v8;

v8::Persistent<v8::Function> Srtp::constructor;
bool Srtp::initialized = false;

static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {
	srtp_policy_t policy;

	memset(&policy, 0, sizeof(policy));

	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);
	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);

	policy.ssrc.type = direction;
	policy.ssrc.value = 0;

	policy.key = (unsigned char*) key;

	policy.next = NULL;

	int res = srtp_create(session, &policy);

	DEBUG("creating session " << res);
}

Srtp::Srtp(const char *sendKey, const char *recvKey) {
	if(!initialized) {
		DEBUG("initializing srtp");
		srtp_init();
		initialized = true;
	}

	createSession(&_sendSession, sendKey, ssrc_any_outbound);
	createSession(&_recvSession, recvKey, ssrc_any_inbound);
}

Srtp::~Srtp() {
	srtp_dealloc(_sendSession);
	srtp_dealloc(_recvSession);
}

void Srtp::init(v8::Handle<v8::Object> exports) {
	// Prepare constructor template
	Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
	tpl->SetClassName(String::NewSymbol("Srtp"));
	tpl->InstanceTemplate()->SetInternalFieldCount(1);
	// protoype
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp);
	constructor = Persistent<Function>::New(tpl->GetFunction());
	// export
	exports->Set(String::NewSymbol("Srtp"), constructor);
}

v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) {
	HandleScope scope;

	if (args.IsConstructCall()) {
		// Invoked as constructor: `new MyObject(...)`
		if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {
			return ThrowException(Exception::TypeError(String::New("Expected buffers")));
		}

		const char *sendKey = node::Buffer::Data(args[0]);
		const char *recvKey = node::Buffer::Data(args[1]);

		Srtp* obj = new Srtp(sendKey, recvKey);
		obj->Wrap(args.This());

		return args.This();
	} else {
		// Invoked as plain function `MyObject(...)`, turn into construct call.
		const int argc = 1;
		Local<Value> argv[1] = { argv[0] };
		return scope.Close(constructor->NewInstance(argc, argv));
	}
}

v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {
	HandleScope scope;

	// type checking

	if(!node::Buffer::HasInstance(args[0])) {
		return ThrowException(Exception::TypeError(String::New("Expected buffer")));
	}

	// copy buffer for result

	int size = node::Buffer::Length(args[0]);
	char *in_buf = node::Buffer::Data(args[0]);

	Handle<Object> tmp = node::Buffer::New(size + 32)->handle_;
	char *out_buf = node::Buffer::Data(tmp);

	memcpy(out_buf, in_buf, size);

	// actual crypt stuff

	err_status_t err = fun(session, out_buf, &size);

	if(err != err_status_ok) {
		DEBUG("srtp error " << err);
	}

	// return slice of the right size

	Handle<Value> slice_v = tmp->Get(String::New("slice"));

	if(!slice_v->IsFunction()) {
		return ThrowException(Exception::Error(String::New("Buffer does not have a slice function")));
	}

	Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v);

	const int argc = 2;
	Handle<Value> argv[argc] = {
		Integer::New(0),
		Integer::New(size),
	};

	Handle<Value> res = slice_f->Call(tmp, argc, argv);

	return scope.Close(res);
}

v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect);
}

v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect);
}

v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect_rtcp);
}

v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect_rtcp);
}

<commit_msg>Disable srtp replay protection<commit_after>/*
 *  webrtc-echo - A WebRTC echo server
 *  Copyright (C) 2014  Stephan Thamm
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "srtp.h"

#include <node_buffer.h>

#include "helper.h"

using namespace v8;

v8::Persistent<v8::Function> Srtp::constructor;
bool Srtp::initialized = false;

static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {
	srtp_policy_t policy;

	memset(&policy, 0, sizeof(policy));

	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);
	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);

	policy.ssrc.type = direction;
	policy.ssrc.value = 0;

	policy.key = (unsigned char*) key;

	policy.window_size = 0;
	policy.allow_repeat_tx = 1;

	policy.next = NULL;

	srtp_create(session, &policy);
}

Srtp::Srtp(const char *sendKey, const char *recvKey) {
	if(!initialized) {
		DEBUG("initializing srtp");
		srtp_init();
		initialized = true;
	}

	createSession(&_sendSession, sendKey, ssrc_any_outbound);
	createSession(&_recvSession, recvKey, ssrc_any_inbound);
}

Srtp::~Srtp() {
	srtp_dealloc(_sendSession);
	srtp_dealloc(_recvSession);
}

void Srtp::init(v8::Handle<v8::Object> exports) {
	// Prepare constructor template
	Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
	tpl->SetClassName(String::NewSymbol("Srtp"));
	tpl->InstanceTemplate()->SetInternalFieldCount(1);
	// protoype
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp);
	constructor = Persistent<Function>::New(tpl->GetFunction());
	// export
	exports->Set(String::NewSymbol("Srtp"), constructor);
}

v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) {
	HandleScope scope;

	if (args.IsConstructCall()) {
		// Invoked as constructor: `new MyObject(...)`
		if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {
			return ThrowException(Exception::TypeError(String::New("Expected buffers")));
		}

		const char *sendKey = node::Buffer::Data(args[0]);
		const char *recvKey = node::Buffer::Data(args[1]);

		Srtp* obj = new Srtp(sendKey, recvKey);
		obj->Wrap(args.This());

		return args.This();
	} else {
		// Invoked as plain function `MyObject(...)`, turn into construct call.
		const int argc = 1;
		Local<Value> argv[1] = { argv[0] };
		return scope.Close(constructor->NewInstance(argc, argv));
	}
}

v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {
	HandleScope scope;

	// type checking

	if(!node::Buffer::HasInstance(args[0])) {
		return ThrowException(Exception::TypeError(String::New("Expected buffer")));
	}

	// copy buffer for result

	int size = node::Buffer::Length(args[0]);
	char *in_buf = node::Buffer::Data(args[0]);

	Handle<Object> tmp = node::Buffer::New(size + 32)->handle_;
	char *out_buf = node::Buffer::Data(tmp);

	memcpy(out_buf, in_buf, size);

	// actual crypt stuff

	err_status_t err = fun(session, out_buf, &size);

	if(err != err_status_ok) {
		DEBUG("srtp error " << err);
	}

	// return slice of the right size

	Handle<Value> slice_v = tmp->Get(String::New("slice"));

	if(!slice_v->IsFunction()) {
		return ThrowException(Exception::Error(String::New("Buffer does not have a slice function")));
	}

	Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v);

	const int argc = 2;
	Handle<Value> argv[argc] = {
		Integer::New(0),
		Integer::New(size),
	};

	Handle<Value> res = slice_f->Call(tmp, argc, argv);

	return scope.Close(res);
}

v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect);
}

v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect);
}

v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect_rtcp);
}

v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect_rtcp);
}

<|endoftext|>


<commit_before>/*
 *  webrtc-echo - A WebRTC echo server
 *  Copyright (C) 2014  Stephan Thamm
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "srtp.h"

#include <node_buffer.h>

#include "helper.h"

using namespace v8;

v8::Persistent<v8::Function> Srtp::constructor;
bool Srtp::initialized = false;

static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {
	srtp_policy_t policy;

	memset(&policy, 0, sizeof(policy));

	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);
	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);

	policy.ssrc.type = direction;
	policy.ssrc.value = 0;

	policy.key = (unsigned char*) key;

	policy.window_size = 0;
	policy.allow_repeat_tx = 1;

	policy.next = NULL;

	srtp_create(session, &policy);
}

Srtp::Srtp(const char *sendKey, const char *recvKey) {
	if(!initialized) {
		DEBUG("initializing srtp");
		srtp_init();
		initialized = true;
	}

	createSession(&_sendSession, sendKey, ssrc_any_outbound);
	createSession(&_recvSession, recvKey, ssrc_any_inbound);
}

Srtp::~Srtp() {
	srtp_dealloc(_sendSession);
	srtp_dealloc(_recvSession);
}

void Srtp::init(v8::Handle<v8::Object> exports) {
	// Prepare constructor template
	Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
	tpl->SetClassName(String::NewSymbol("Srtp"));
	tpl->InstanceTemplate()->SetInternalFieldCount(1);
	// protoype
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp);
	constructor = Persistent<Function>::New(tpl->GetFunction());
	// export
	exports->Set(String::NewSymbol("Srtp"), constructor);
}

v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) {
	HandleScope scope;

	if (args.IsConstructCall()) {
		// Invoked as constructor: `new MyObject(...)`
		if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {
			return ThrowException(Exception::TypeError(String::New("Expected buffers")));
		}

		const char *sendKey = node::Buffer::Data(args[0]);
		const char *recvKey = node::Buffer::Data(args[1]);

		Srtp* obj = new Srtp(sendKey, recvKey);
		obj->Wrap(args.This());

		return args.This();
	} else {
		// Invoked as plain function `MyObject(...)`, turn into construct call.
		const int argc = 1;
		Local<Value> argv[1] = { argv[0] };
		return scope.Close(constructor->NewInstance(argc, argv));
	}
}

v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {
	HandleScope scope;

	// type checking

	if(!node::Buffer::HasInstance(args[0])) {
		return ThrowException(Exception::TypeError(String::New("Expected buffer")));
	}

	// copy buffer for result

	int size = node::Buffer::Length(args[0]);
	char *in_buf = node::Buffer::Data(args[0]);

	Handle<Object> tmp = node::Buffer::New(size + 32)->handle_;
	char *out_buf = node::Buffer::Data(tmp);

	memcpy(out_buf, in_buf, size);

	// actual crypt stuff

	err_status_t err = fun(session, out_buf, &size);

	if(err != err_status_ok) {
		DEBUG("srtp error " << err);
	}

	// return slice of the right size

	Handle<Value> slice_v = tmp->Get(String::New("slice"));

	if(!slice_v->IsFunction()) {
		return ThrowException(Exception::Error(String::New("Buffer does not have a slice function")));
	}

	Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v);

	const int argc = 2;
	Handle<Value> argv[argc] = {
		Integer::New(0),
		Integer::New(size),
	};

	Handle<Value> res = slice_f->Call(tmp, argc, argv);

	return scope.Close(res);
}

v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect);
}

v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect);
}

v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect_rtcp);
}

v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect_rtcp);
}

<commit_msg>Do not set window size of srtp to zero<commit_after>/*
 *  webrtc-echo - A WebRTC echo server
 *  Copyright (C) 2014  Stephan Thamm
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "srtp.h"

#include <node_buffer.h>

#include "helper.h"

using namespace v8;

v8::Persistent<v8::Function> Srtp::constructor;
bool Srtp::initialized = false;

static void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {
	srtp_policy_t policy;

	memset(&policy, 0, sizeof(policy));

	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);
	crypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);

	policy.ssrc.type = direction;
	policy.ssrc.value = 0;

	policy.key = (unsigned char*) key;

	//policy.window_size = 0;
	policy.allow_repeat_tx = 1;

	policy.next = NULL;

	srtp_create(session, &policy);
}

Srtp::Srtp(const char *sendKey, const char *recvKey) {
	if(!initialized) {
		DEBUG("initializing srtp");
		srtp_init();
		initialized = true;
	}

	createSession(&_sendSession, sendKey, ssrc_any_outbound);
	createSession(&_recvSession, recvKey, ssrc_any_inbound);
}

Srtp::~Srtp() {
	srtp_dealloc(_sendSession);
	srtp_dealloc(_recvSession);
}

void Srtp::init(v8::Handle<v8::Object> exports) {
	// Prepare constructor template
	Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
	tpl->SetClassName(String::NewSymbol("Srtp"));
	tpl->InstanceTemplate()->SetInternalFieldCount(1);
	// protoype
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtp", protectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtp", unprotectRtp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "protectRtcp", protectRtcp);
	NODE_SET_PROTOTYPE_METHOD(tpl, "unprotectRtcp", unprotectRtcp);
	constructor = Persistent<Function>::New(tpl->GetFunction());
	// export
	exports->Set(String::NewSymbol("Srtp"), constructor);
}

v8::Handle<v8::Value> Srtp::New(const v8::Arguments& args) {
	HandleScope scope;

	if (args.IsConstructCall()) {
		// Invoked as constructor: `new MyObject(...)`
		if(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {
			return ThrowException(Exception::TypeError(String::New("Expected buffers")));
		}

		const char *sendKey = node::Buffer::Data(args[0]);
		const char *recvKey = node::Buffer::Data(args[1]);

		Srtp* obj = new Srtp(sendKey, recvKey);
		obj->Wrap(args.This());

		return args.This();
	} else {
		// Invoked as plain function `MyObject(...)`, turn into construct call.
		const int argc = 1;
		Local<Value> argv[1] = { argv[0] };
		return scope.Close(constructor->NewInstance(argc, argv));
	}
}

v8::Handle<v8::Value> Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {
	HandleScope scope;

	// type checking

	if(!node::Buffer::HasInstance(args[0])) {
		return ThrowException(Exception::TypeError(String::New("Expected buffer")));
	}

	// copy buffer for result

	int size = node::Buffer::Length(args[0]);
	char *in_buf = node::Buffer::Data(args[0]);

	Handle<Object> tmp = node::Buffer::New(size + 32)->handle_;
	char *out_buf = node::Buffer::Data(tmp);

	memcpy(out_buf, in_buf, size);

	// actual crypt stuff

	err_status_t err = fun(session, out_buf, &size);

	if(err != err_status_ok) {
		DEBUG("srtp error " << err);
	}

	// return slice of the right size

	Handle<Value> slice_v = tmp->Get(String::New("slice"));

	if(!slice_v->IsFunction()) {
		return ThrowException(Exception::Error(String::New("Buffer does not have a slice function")));
	}

	Handle<v8::Function> slice_f = v8::Handle<v8::Function>::Cast(slice_v);

	const int argc = 2;
	Handle<Value> argv[argc] = {
		Integer::New(0),
		Integer::New(size),
	};

	Handle<Value> res = slice_f->Call(tmp, argc, argv);

	return scope.Close(res);
}

v8::Handle<v8::Value> Srtp::protectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect);
}

v8::Handle<v8::Value> Srtp::unprotectRtp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect);
}

v8::Handle<v8::Value> Srtp::protectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_sendSession, srtp_protect_rtcp);
}

v8::Handle<v8::Value> Srtp::unprotectRtcp(const v8::Arguments& args) {
	Srtp *srtp = node::ObjectWrap::Unwrap<Srtp>(args.This()->ToObject());

	return convert(args, srtp->_recvSession, srtp_unprotect_rtcp);
}

<|endoftext|>


<commit_before>#include "ompu/music/concrete/context.hpp"
#include "ompu/music.hpp"

namespace ompu { namespace music { namespace concrete {

namespace detail {

bool ContextKeyboard::empty() const noexcept
{
    return notes_.empty();
}

void ContextKeyboard::on(Note note) noexcept
{
    notes_.emplace(std::move(note));
}

void ContextKeyboard::off(Note note) noexcept
{
    notes_.erase(note);
}

void ContextKeyboard::clear()
{
    notes_.clear();
}

} // detail

Context::Context()
    : key_(keys::CMaj{})
{}

void Context::set(Key key) noexcept
{
    key_ = std::move(key);
}

std::vector<Chord>
Context::get_closest_chords(std::size_t const limit) const
{
    auto const notes = kb_.notes();

    std::vector<Chord> ret;
    ret.reserve(limit);

    try {
        for (auto possible_root : notes) {
            auto const root_height = possible_root.height();
            Chord chord{std::move(possible_root)};

            for (auto possible_note : notes) {
                if (possible_note.height() == root_height) continue;
                chord.add(std::move(possible_note));
            }

            ret.emplace_back(std::move(chord));
            if (ret.size() >= limit) break;
        }

    } catch (invalid_chord_error const& e) {
        if (logger_) {
            *logger_ << e.what() << std::endl;
        }
    }

    return ret;
}

void Context::add(Note note) noexcept
{
    kb_.on(std::move(note));
}

void Context::remove(Note note) noexcept
{
    kb_.off(std::move(note));
}

void Context::add_or_remove(bool is_add, Note note) noexcept
{
    is_add ? kb_.on(std::move(note)) : kb_.off(std::move(note));
}

void Context::clear_notes()
{
    kb_.clear();
}

}}} // ompu
<commit_msg>Chord detection: auto shrink buffer<commit_after>#include "ompu/music/concrete/context.hpp"
#include "ompu/music.hpp"

namespace ompu { namespace music { namespace concrete {

namespace detail {

bool ContextKeyboard::empty() const noexcept
{
    return notes_.empty();
}

void ContextKeyboard::on(Note note) noexcept
{
    notes_.emplace(std::move(note));
}

void ContextKeyboard::off(Note note) noexcept
{
    notes_.erase(note);
}

void ContextKeyboard::clear()
{
    notes_.clear();
}

} // detail

Context::Context()
    : key_(keys::CMaj{})
{}

void Context::set(Key key) noexcept
{
    key_ = std::move(key);
}

std::vector<Chord>
Context::get_closest_chords(std::size_t const limit) const
{
    auto const notes = kb_.notes();

    std::vector<Chord> ret;
    ret.reserve(limit);

    try {
        for (auto possible_root : notes) {
            auto const root_height = possible_root.height();
            Chord chord{std::move(possible_root)};

            for (auto possible_note : notes) {
                if (possible_note.height() == root_height) continue;
                chord.add(std::move(possible_note));
            }

            ret.emplace_back(std::move(chord));
            if (ret.size() >= limit) break;
        }

    } catch (invalid_chord_error const& e) {
        if (logger_) {
            *logger_ << e.what() << std::endl;
        }
    }

    ret.shrink_to_fit();
    return ret;
}

void Context::add(Note note) noexcept
{
    kb_.on(std::move(note));
}

void Context::remove(Note note) noexcept
{
    kb_.off(std::move(note));
}

void Context::add_or_remove(bool is_add, Note note) noexcept
{
    is_add ? kb_.on(std::move(note)) : kb_.off(std::move(note));
}

void Context::clear_notes()
{
    kb_.clear();
}

}}} // ompu
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <cmath>
#include <stdlib.h>

/* MacLaurin Serie for sin(x), Taylor serie with a = 0
 * sin(x) = (Σn=0, ∞)(((-1 ^ n)/(2n + 1)!)(x^(2n + 1))

 * As the serie converges, the next term of the sum will be
 * smaller than the last one, and also will be alternating
 * signs between + and -, therefore each iteration aproaches
 * the correct value. We need to get a given number of correct
 * digits, so we must make the last term calculated lesser
 * than the required absolute error. */

using namespace std;

double sin(double x, double E);
double maxAbsErr(int cd);
ulong fact(ulong n);

int main(int argc, char* args[]){
  double x;
  int cd;

  if(argc > 2){
    x = atof(args[1]);
    cd = atoi(args[2]);
  }else{
    cout << "Input x and cd:" << endl;
    cin >> x;
    cin >> cd;
  }

  double E = maxAbsErr(cd);

  cout << "sin(" << x << ") = " << setprecision(cd) << sin(x, E)
       << ", E = " << E << ", cd = " << cd << endl;

  return 0;
}

//sin(x) = (Σn=0, ∞)(((-1 ^ n)/(2n + 1)!)(x^(2n + 1))
double sin(double x, double E){

  double sin = 0.0d, term, last;

  int n = 0;
  bool bigger = true;
  while(bigger){
    last = sin;
    term = (pow(-1.0d, n) / fact(2*n + 1)) * pow(x, 2*n + 1);
    if(abs(sin + term - last) > E){
      sin += term;
    }else{
      bigger = false;
    }
    n++;
  }

  return sin;
}

//Emax = 1.0 x 10 ^ -cd, asuming c++ uses floor as round method
double maxAbsErr(int cd) {
  return pow(10.0d, -cd);
}

ulong fact(ulong n){
  if(n <= 1) return 1;
  return n * fact(n - 1);
}
<commit_msg>Cleaned up the repository<commit_after><|endoftext|>