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

#include "DebugMessageView.h"
#include <QAction>
#include <QMenu>
#include "Code/QRDUtils.h"
#include "ui_DebugMessageView.h"

static const int EIDRole = Qt::UserRole + 1;
static const int SortDataRole = Qt::UserRole + 2;

class DebugMessageItemModel : public QAbstractItemModel
{
public:
  DebugMessageItemModel(ICaptureContext &ctx, QObject *parent)
      : QAbstractItemModel(parent), m_Ctx(ctx)
  {
  }

  void refresh()
  {
    emit beginResetModel();
    emit endResetModel();
  }

  QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override
  {
    if(row < 0 || row >= rowCount())
      return QModelIndex();

    return createIndex(row, column);
  }

  QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); }
  int rowCount(const QModelIndex &parent = QModelIndex()) const override
  {
    return m_Ctx.DebugMessages().count();
  }
  int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 6; }
  Qt::ItemFlags flags(const QModelIndex &index) const override
  {
    if(!index.isValid())
      return 0;

    return QAbstractItemModel::flags(index);
  }

  QVariant headerData(int section, Qt::Orientation orientation, int role) const override
  {
    if(orientation == Qt::Horizontal && role == Qt::DisplayRole)
    {
      switch(section)
      {
        case 0: return lit("EID");
        case 1: return lit("Source");
        case 2: return lit("Severity");
        case 3: return lit("Category");
        case 4: return lit("ID");
        case 5: return lit("Description");
        default: break;
      }
    }

    return QVariant();
  }

  QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
  {
    if(index.isValid() && (role == Qt::DisplayRole || role == SortDataRole))
    {
      bool sort = (role == SortDataRole);

      int row = index.row();
      int col = index.column();

      if(col >= 0 && col < columnCount() && row < rowCount())
      {
        const DebugMessage &msg = m_Ctx.DebugMessages()[row];

        switch(col)
        {
          case 0: return msg.eventId;
          case 1: return ToQStr(msg.source);
          case 2: return sort ? QVariant((uint32_t)msg.severity) : QVariant(ToQStr(msg.severity));
          case 3: return ToQStr(msg.category);
          case 4: return msg.messageID;
          case 5:
          {
            QVariant desc = msg.description;
            RichResourceTextInitialise(desc);
            return desc;
          }
          default: break;
        }
      }
    }

    if(index.isValid() && role == EIDRole && index.row() >= 0 &&
       index.row() < m_Ctx.DebugMessages().count())
      return m_Ctx.DebugMessages()[index.row()].eventId;

    return QVariant();
  }

private:
  ICaptureContext &m_Ctx;
};

class DebugMessageFilterModel : public QSortFilterProxyModel
{
public:
  DebugMessageFilterModel(ICaptureContext &ctx, QObject *parent)
      : QSortFilterProxyModel(parent), m_Ctx(ctx)
  {
  }

  typedef QPair<QPair<MessageSource, MessageCategory>, uint32_t> MessageType;
  static MessageType makeType(const DebugMessage &msg)
  {
    return qMakePair(qMakePair(msg.source, msg.category), msg.messageID);
  }

  QList<MessageSource> m_HiddenSources;
  QList<MessageCategory> m_HiddenCategories;
  QList<MessageSeverity> m_HiddenSeverities;
  QList<MessageType> m_HiddenTypes;

  bool showHidden = false;

  void refresh() { invalidateFilter(); }
  QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
  {
    if(role == Qt::FontRole && !isVisibleRow(mapToSource(index).row()))
    {
      QFont font;
      font.setItalic(true);
      return font;
    }

    return QSortFilterProxyModel::data(index, role);
  }

protected:
  bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override
  {
    if(showHidden)
      return true;

    return isVisibleRow(sourceRow);
  }

  bool isVisibleRow(int sourceRow) const
  {
    const DebugMessage &msg = m_Ctx.DebugMessages()[sourceRow];

    if(m_HiddenSources.contains(msg.source))
      return false;

    if(m_HiddenCategories.contains(msg.category))
      return false;

    if(m_HiddenSeverities.contains(msg.severity))
      return false;

    if(m_HiddenTypes.contains(makeType(msg)))
      return false;

    return true;
  }

  bool lessThan(const QModelIndex &left, const QModelIndex &right) const override
  {
    return sourceModel()->data(left, SortDataRole) < sourceModel()->data(right, SortDataRole);
  }

private:
  ICaptureContext &m_Ctx;
};

DebugMessageView::DebugMessageView(ICaptureContext &ctx, QWidget *parent)
    : QFrame(parent), ui(new Ui::DebugMessageView), m_Ctx(ctx)
{
  ui->setupUi(this);

  m_ItemModel = new DebugMessageItemModel(m_Ctx, this);
  m_FilterModel = new DebugMessageFilterModel(m_Ctx, this);

  m_FilterModel->setSourceModel(m_ItemModel);
  ui->messages->setModel(m_FilterModel);

  ui->messages->setSortingEnabled(true);
  ui->messages->sortByColumn(0, Qt::AscendingOrder);

  ui->messages->setMouseTracking(true);
  ui->messages->setAutoScroll(false);

  ui->messages->horizontalHeader()->setStretchLastSection(false);

  ui->messages->setContextMenuPolicy(Qt::CustomContextMenu);
  QObject::connect(ui->messages, &QWidget::customContextMenuRequested, this,
                   &DebugMessageView::messages_contextMenu);

  ui->messages->setFont(Formatter::PreferredFont());

  m_ContextMenu = new QMenu(this);

  m_ShowHidden = new QAction(tr("Show hidden rows"), this);
  m_ToggleSource = new QAction(QString(), this);
  m_ToggleSeverity = new QAction(QString(), this);
  m_ToggleCategory = new QAction(QString(), this);
  m_ToggleMessageType = new QAction(QString(), this);

  m_ShowHidden->setCheckable(true);

  m_ContextMenu->addAction(m_ShowHidden);
  m_ContextMenu->addSeparator();
  m_ContextMenu->addAction(m_ToggleSource);
  m_ContextMenu->addAction(m_ToggleSeverity);
  m_ContextMenu->addAction(m_ToggleCategory);
  m_ContextMenu->addAction(m_ToggleMessageType);

  QObject::connect(m_ShowHidden, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleSource, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleSeverity, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleCategory, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleMessageType, &QAction::triggered, this,
                   &DebugMessageView::messages_toggled);

  RefreshMessageList();

  m_Ctx.AddCaptureViewer(this);
}

DebugMessageView::~DebugMessageView()
{
  m_Ctx.BuiltinWindowClosed(this);

  m_Ctx.RemoveCaptureViewer(this);
  delete ui;
}

void DebugMessageView::OnCaptureClosed()
{
  m_FilterModel->showHidden = false;
  RefreshMessageList();
}

void DebugMessageView::OnCaptureLoaded()
{
  m_FilterModel->showHidden = false;
  RefreshMessageList();
}

void DebugMessageView::RefreshMessageList()
{
  m_ItemModel->refresh();

  ui->messages->resizeColumnsToContents();

  if(m_Ctx.UnreadMessageCount() > 0)
    setWindowTitle(tr("(%1) Errors and Warnings").arg(m_Ctx.UnreadMessageCount()));
  else
    setWindowTitle(tr("Errors and Warnings"));
}

void DebugMessageView::on_messages_doubleClicked(const QModelIndex &index)
{
  QVariant var = m_FilterModel->data(index, EIDRole);

  if(var.isValid())
  {
    uint32_t eid = var.toUInt();
    m_Ctx.SetEventID({}, eid, eid);
  }
}

void DebugMessageView::messages_toggled()
{
  QAction *action = qobject_cast<QAction *>(QObject::sender());

  if(action == m_ShowHidden)
  {
    m_FilterModel->showHidden = !m_FilterModel->showHidden;
    m_ShowHidden->setChecked(m_FilterModel->showHidden);
  }
  else if(action == m_ToggleSource)
  {
    if(m_FilterModel->m_HiddenSources.contains(m_ContextMessage.source))
      m_FilterModel->m_HiddenSources.removeOne(m_ContextMessage.source);
    else
      m_FilterModel->m_HiddenSources.push_back(m_ContextMessage.source);
  }
  else if(action == m_ToggleSeverity)
  {
    if(m_FilterModel->m_HiddenSeverities.contains(m_ContextMessage.severity))
      m_FilterModel->m_HiddenSeverities.removeOne(m_ContextMessage.severity);
    else
      m_FilterModel->m_HiddenSeverities.push_back(m_ContextMessage.severity);
  }
  else if(action == m_ToggleCategory)
  {
    if(m_FilterModel->m_HiddenCategories.contains(m_ContextMessage.category))
      m_FilterModel->m_HiddenCategories.removeOne(m_ContextMessage.category);
    else
      m_FilterModel->m_HiddenCategories.push_back(m_ContextMessage.category);
  }
  else if(action == m_ToggleMessageType)
  {
    auto type = DebugMessageFilterModel::makeType(m_ContextMessage);
    if(m_FilterModel->m_HiddenTypes.contains(type))
      m_FilterModel->m_HiddenTypes.removeOne(type);
    else
      m_FilterModel->m_HiddenTypes.push_back(type);
  }

  m_FilterModel->refresh();
}

void DebugMessageView::messages_contextMenu(const QPoint &pos)
{
  if(!m_Ctx.IsCaptureLoaded())
    return;

  QModelIndex index = ui->messages->indexAt(pos);

  if(index.isValid())
  {
    index = m_FilterModel->mapToSource(index);

    m_ToggleSource->setVisible(true);
    m_ToggleSeverity->setVisible(true);
    m_ToggleCategory->setVisible(true);
    m_ToggleMessageType->setVisible(true);

    const DebugMessage &msg = m_Ctx.DebugMessages()[index.row()];

    QString hide = tr("Hide");
    QString show = tr("Show");

    bool hidden = m_FilterModel->m_HiddenSources.contains(msg.source);
    m_ToggleSource->setText(tr("%1 Source: %2").arg(hidden ? show : hide).arg(ToQStr(msg.source)));

    hidden = m_FilterModel->m_HiddenSeverities.contains(msg.severity);
    m_ToggleSeverity->setText(
        tr("%1 Severity: %2").arg(hidden ? show : hide).arg(ToQStr(msg.severity)));

    hidden = m_FilterModel->m_HiddenCategories.contains(msg.category);
    m_ToggleCategory->setText(
        tr("%1 Category: %2").arg(hidden ? show : hide).arg(ToQStr(msg.category)));

    hidden = m_FilterModel->m_HiddenTypes.contains(DebugMessageFilterModel::makeType(msg));
    m_ToggleMessageType->setText(tr("%1 Message Type").arg(hidden ? show : hide));

    m_ContextMessage = msg;
  }
  else
  {
    m_ToggleSource->setVisible(false);
    m_ToggleSeverity->setVisible(false);
    m_ToggleCategory->setVisible(false);
    m_ToggleMessageType->setVisible(false);
  }

  QString showHidden = tr("Show hidden rows");
  QString hideHidden = tr("Stop showing hidden rows");

  m_ShowHidden->setText(m_FilterModel->showHidden ? hideHidden : showHidden);

  RDDialog::show(m_ContextMenu, ui->messages->viewport()->mapToGlobal(pos));
}

void DebugMessageView::paintEvent(QPaintEvent *e)
{
  if(m_Ctx.UnreadMessageCount() > 0)
  {
    m_Ctx.MarkMessagesRead();
    RefreshMessageList();
  }

  QFrame::paintEvent(e);
}
<commit_msg>Keep "Show hidden rows" text constant now that checkbox appears<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2017-2019 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "DebugMessageView.h"
#include <QAction>
#include <QMenu>
#include "Code/QRDUtils.h"
#include "ui_DebugMessageView.h"

static const int EIDRole = Qt::UserRole + 1;
static const int SortDataRole = Qt::UserRole + 2;

class DebugMessageItemModel : public QAbstractItemModel
{
public:
  DebugMessageItemModel(ICaptureContext &ctx, QObject *parent)
      : QAbstractItemModel(parent), m_Ctx(ctx)
  {
  }

  void refresh()
  {
    emit beginResetModel();
    emit endResetModel();
  }

  QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override
  {
    if(row < 0 || row >= rowCount())
      return QModelIndex();

    return createIndex(row, column);
  }

  QModelIndex parent(const QModelIndex &index) const override { return QModelIndex(); }
  int rowCount(const QModelIndex &parent = QModelIndex()) const override
  {
    return m_Ctx.DebugMessages().count();
  }
  int columnCount(const QModelIndex &parent = QModelIndex()) const override { return 6; }
  Qt::ItemFlags flags(const QModelIndex &index) const override
  {
    if(!index.isValid())
      return 0;

    return QAbstractItemModel::flags(index);
  }

  QVariant headerData(int section, Qt::Orientation orientation, int role) const override
  {
    if(orientation == Qt::Horizontal && role == Qt::DisplayRole)
    {
      switch(section)
      {
        case 0: return lit("EID");
        case 1: return lit("Source");
        case 2: return lit("Severity");
        case 3: return lit("Category");
        case 4: return lit("ID");
        case 5: return lit("Description");
        default: break;
      }
    }

    return QVariant();
  }

  QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
  {
    if(index.isValid() && (role == Qt::DisplayRole || role == SortDataRole))
    {
      bool sort = (role == SortDataRole);

      int row = index.row();
      int col = index.column();

      if(col >= 0 && col < columnCount() && row < rowCount())
      {
        const DebugMessage &msg = m_Ctx.DebugMessages()[row];

        switch(col)
        {
          case 0: return msg.eventId;
          case 1: return ToQStr(msg.source);
          case 2: return sort ? QVariant((uint32_t)msg.severity) : QVariant(ToQStr(msg.severity));
          case 3: return ToQStr(msg.category);
          case 4: return msg.messageID;
          case 5:
          {
            QVariant desc = msg.description;
            RichResourceTextInitialise(desc);
            return desc;
          }
          default: break;
        }
      }
    }

    if(index.isValid() && role == EIDRole && index.row() >= 0 &&
       index.row() < m_Ctx.DebugMessages().count())
      return m_Ctx.DebugMessages()[index.row()].eventId;

    return QVariant();
  }

private:
  ICaptureContext &m_Ctx;
};

class DebugMessageFilterModel : public QSortFilterProxyModel
{
public:
  DebugMessageFilterModel(ICaptureContext &ctx, QObject *parent)
      : QSortFilterProxyModel(parent), m_Ctx(ctx)
  {
  }

  typedef QPair<QPair<MessageSource, MessageCategory>, uint32_t> MessageType;
  static MessageType makeType(const DebugMessage &msg)
  {
    return qMakePair(qMakePair(msg.source, msg.category), msg.messageID);
  }

  QList<MessageSource> m_HiddenSources;
  QList<MessageCategory> m_HiddenCategories;
  QList<MessageSeverity> m_HiddenSeverities;
  QList<MessageType> m_HiddenTypes;

  bool showHidden = false;

  void refresh() { invalidateFilter(); }
  QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
  {
    if(role == Qt::FontRole && !isVisibleRow(mapToSource(index).row()))
    {
      QFont font;
      font.setItalic(true);
      return font;
    }

    return QSortFilterProxyModel::data(index, role);
  }

protected:
  bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override
  {
    if(showHidden)
      return true;

    return isVisibleRow(sourceRow);
  }

  bool isVisibleRow(int sourceRow) const
  {
    const DebugMessage &msg = m_Ctx.DebugMessages()[sourceRow];

    if(m_HiddenSources.contains(msg.source))
      return false;

    if(m_HiddenCategories.contains(msg.category))
      return false;

    if(m_HiddenSeverities.contains(msg.severity))
      return false;

    if(m_HiddenTypes.contains(makeType(msg)))
      return false;

    return true;
  }

  bool lessThan(const QModelIndex &left, const QModelIndex &right) const override
  {
    return sourceModel()->data(left, SortDataRole) < sourceModel()->data(right, SortDataRole);
  }

private:
  ICaptureContext &m_Ctx;
};

DebugMessageView::DebugMessageView(ICaptureContext &ctx, QWidget *parent)
    : QFrame(parent), ui(new Ui::DebugMessageView), m_Ctx(ctx)
{
  ui->setupUi(this);

  m_ItemModel = new DebugMessageItemModel(m_Ctx, this);
  m_FilterModel = new DebugMessageFilterModel(m_Ctx, this);

  m_FilterModel->setSourceModel(m_ItemModel);
  ui->messages->setModel(m_FilterModel);

  ui->messages->setSortingEnabled(true);
  ui->messages->sortByColumn(0, Qt::AscendingOrder);

  ui->messages->setMouseTracking(true);
  ui->messages->setAutoScroll(false);

  ui->messages->horizontalHeader()->setStretchLastSection(false);

  ui->messages->setContextMenuPolicy(Qt::CustomContextMenu);
  QObject::connect(ui->messages, &QWidget::customContextMenuRequested, this,
                   &DebugMessageView::messages_contextMenu);

  ui->messages->setFont(Formatter::PreferredFont());

  m_ContextMenu = new QMenu(this);

  m_ShowHidden = new QAction(tr("Show hidden rows"), this);
  m_ToggleSource = new QAction(QString(), this);
  m_ToggleSeverity = new QAction(QString(), this);
  m_ToggleCategory = new QAction(QString(), this);
  m_ToggleMessageType = new QAction(QString(), this);

  m_ShowHidden->setCheckable(true);

  m_ContextMenu->addAction(m_ShowHidden);
  m_ContextMenu->addSeparator();
  m_ContextMenu->addAction(m_ToggleSource);
  m_ContextMenu->addAction(m_ToggleSeverity);
  m_ContextMenu->addAction(m_ToggleCategory);
  m_ContextMenu->addAction(m_ToggleMessageType);

  QObject::connect(m_ShowHidden, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleSource, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleSeverity, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleCategory, &QAction::triggered, this, &DebugMessageView::messages_toggled);
  QObject::connect(m_ToggleMessageType, &QAction::triggered, this,
                   &DebugMessageView::messages_toggled);

  RefreshMessageList();

  m_Ctx.AddCaptureViewer(this);
}

DebugMessageView::~DebugMessageView()
{
  m_Ctx.BuiltinWindowClosed(this);

  m_Ctx.RemoveCaptureViewer(this);
  delete ui;
}

void DebugMessageView::OnCaptureClosed()
{
  m_FilterModel->showHidden = false;
  RefreshMessageList();
}

void DebugMessageView::OnCaptureLoaded()
{
  m_FilterModel->showHidden = false;
  RefreshMessageList();
}

void DebugMessageView::RefreshMessageList()
{
  m_ItemModel->refresh();

  ui->messages->resizeColumnsToContents();

  if(m_Ctx.UnreadMessageCount() > 0)
    setWindowTitle(tr("(%1) Errors and Warnings").arg(m_Ctx.UnreadMessageCount()));
  else
    setWindowTitle(tr("Errors and Warnings"));
}

void DebugMessageView::on_messages_doubleClicked(const QModelIndex &index)
{
  QVariant var = m_FilterModel->data(index, EIDRole);

  if(var.isValid())
  {
    uint32_t eid = var.toUInt();
    m_Ctx.SetEventID({}, eid, eid);
  }
}

void DebugMessageView::messages_toggled()
{
  QAction *action = qobject_cast<QAction *>(QObject::sender());

  if(action == m_ShowHidden)
  {
    m_FilterModel->showHidden = !m_FilterModel->showHidden;
    m_ShowHidden->setChecked(m_FilterModel->showHidden);
  }
  else if(action == m_ToggleSource)
  {
    if(m_FilterModel->m_HiddenSources.contains(m_ContextMessage.source))
      m_FilterModel->m_HiddenSources.removeOne(m_ContextMessage.source);
    else
      m_FilterModel->m_HiddenSources.push_back(m_ContextMessage.source);
  }
  else if(action == m_ToggleSeverity)
  {
    if(m_FilterModel->m_HiddenSeverities.contains(m_ContextMessage.severity))
      m_FilterModel->m_HiddenSeverities.removeOne(m_ContextMessage.severity);
    else
      m_FilterModel->m_HiddenSeverities.push_back(m_ContextMessage.severity);
  }
  else if(action == m_ToggleCategory)
  {
    if(m_FilterModel->m_HiddenCategories.contains(m_ContextMessage.category))
      m_FilterModel->m_HiddenCategories.removeOne(m_ContextMessage.category);
    else
      m_FilterModel->m_HiddenCategories.push_back(m_ContextMessage.category);
  }
  else if(action == m_ToggleMessageType)
  {
    auto type = DebugMessageFilterModel::makeType(m_ContextMessage);
    if(m_FilterModel->m_HiddenTypes.contains(type))
      m_FilterModel->m_HiddenTypes.removeOne(type);
    else
      m_FilterModel->m_HiddenTypes.push_back(type);
  }

  m_FilterModel->refresh();
}

void DebugMessageView::messages_contextMenu(const QPoint &pos)
{
  if(!m_Ctx.IsCaptureLoaded())
    return;

  QModelIndex index = ui->messages->indexAt(pos);

  if(index.isValid())
  {
    index = m_FilterModel->mapToSource(index);

    m_ToggleSource->setVisible(true);
    m_ToggleSeverity->setVisible(true);
    m_ToggleCategory->setVisible(true);
    m_ToggleMessageType->setVisible(true);

    const DebugMessage &msg = m_Ctx.DebugMessages()[index.row()];

    QString hide = tr("Hide");
    QString show = tr("Show");

    bool hidden = m_FilterModel->m_HiddenSources.contains(msg.source);
    m_ToggleSource->setText(tr("%1 Source: %2").arg(hidden ? show : hide).arg(ToQStr(msg.source)));

    hidden = m_FilterModel->m_HiddenSeverities.contains(msg.severity);
    m_ToggleSeverity->setText(
        tr("%1 Severity: %2").arg(hidden ? show : hide).arg(ToQStr(msg.severity)));

    hidden = m_FilterModel->m_HiddenCategories.contains(msg.category);
    m_ToggleCategory->setText(
        tr("%1 Category: %2").arg(hidden ? show : hide).arg(ToQStr(msg.category)));

    hidden = m_FilterModel->m_HiddenTypes.contains(DebugMessageFilterModel::makeType(msg));
    m_ToggleMessageType->setText(tr("%1 Message Type").arg(hidden ? show : hide));

    m_ContextMessage = msg;
  }
  else
  {
    m_ToggleSource->setVisible(false);
    m_ToggleSeverity->setVisible(false);
    m_ToggleCategory->setVisible(false);
    m_ToggleMessageType->setVisible(false);
  }

  RDDialog::show(m_ContextMenu, ui->messages->viewport()->mapToGlobal(pos));
}

void DebugMessageView::paintEvent(QPaintEvent *e)
{
  if(m_Ctx.UnreadMessageCount() > 0)
  {
    m_Ctx.MarkMessagesRead();
    RefreshMessageList();
  }

  QFrame::paintEvent(e);
}
<|endoftext|>


<commit_before>#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>

#include <syslog.h>

#include <zmq.hpp>

#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>

#include <magic.h>

#include <Magick++.h>

#include "io.hpp"
#include "thumq.pb.h"

namespace protobuf = google::protobuf;

using namespace thumq;

namespace {

static magic_t magic_cookie;

static bool decode_request(zmq::message_t &message, Request &request)
{
	protobuf::io::ArrayInputStream array(message.data(), message.size());
	protobuf::io::CodedInputStream coded(&array);

	return request.MergePartialFromCodedStream(&coded);
}

static void encode_response(const Response &response, zmq::message_t &message)
{
	message.rebuild(response.ByteSize());

	protobuf::io::ArrayOutputStream array(message.data(), message.size());
	protobuf::io::CodedOutputStream coded(&array);

	response.SerializeWithCachedSizes(&coded);
}

static void convert_image(Magick::Image &image, int scale, Request::Crop crop)
{
	switch (atoi(image.attribute("EXIF:Orientation").c_str())) {
	case Magick::TopLeftOrientation:
		break;

	case Magick::TopRightOrientation:
		image.flop();
		break;

	case Magick::BottomRightOrientation:
		image.rotate(180);
		break;

	case Magick::BottomLeftOrientation:
		image.flip();
		break;

	case Magick::LeftTopOrientation:
		image.rotate(90);
		image.flop();
		break;

	case Magick::RightTopOrientation:
		image.rotate(90);
		break;

	case Magick::RightBottomOrientation:
		image.rotate(270);
		image.flop();
		break;

	case Magick::LeftBottomOrientation:
		image.rotate(270);
		break;
	}

	Magick::Geometry size = image.size();
	int width = size.width();
	int height = size.height();

	switch (crop) {
	case Request::NO_CROP:
		break;

	case Request::TOP_SQUARE:
		if (width < height) {
			image.crop(Magick::Geometry(width, width));
			height = width;
		} else {
			image.crop(Magick::Geometry(height, height, (width - height) / 2, 0));
			width = height;
		}
		break;
	}

	if (width > scale || height > scale)
		image.scale(Magick::Geometry(scale, scale));

	image.strip();
}

static void free_blob_data(void *, void *hint)
{
	Magick::Blob *blob = reinterpret_cast<Magick::Blob *> (hint);
	delete blob;

}

static void write_jpeg(Magick::Image &image, zmq::message_t &data)
{
	std::unique_ptr<Magick::Blob> blob(new Magick::Blob);
	image.write(blob.get(), "JPEG");
	data.rebuild(const_cast<void *> (blob->data()), blob->length(), free_blob_data, blob.get());
	blob.release();
}

} // namespace

int main(int argc, char **argv)
{
	if (argc < 2) {
		fprintf(stderr, "Usage: %s ADDRESS...\n", argv[0]);
		return 2;
	}

	const char *progname = strrchr(argv[0], '/');
	if (progname)
		progname++;
	else
		progname = argv[0];

	openlog(progname, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER);

	magic_cookie = magic_open(MAGIC_MIME_TYPE);
	if (magic_load(magic_cookie, nullptr) < 0) {
		syslog(LOG_CRIT, "magic: %s", strerror(errno));
		return 1;
	}

	Magick::InitializeMagick(argv[0]);

	zmq::context_t context(1);
	zmq::socket_t socket(context, ZMQ_REP);

	try {
		for (int i = 1; i < argc; i++)
			socket.bind(argv[i]);

		while (true) {
			IO io(socket);

			if (!io.receive()) {
				syslog(LOG_ERR, "request message was too short");
				continue;
			}

			Request request;
			Response response;

			if (!decode_request(io.request.first, request)) {
				syslog(LOG_ERR, "could not decode request header");
				continue;
			}

			const char *mimetype = magic_buffer(magic_cookie, io.request.second.data(), io.request.second.size());

			response.set_source_type(mimetype);

			if (mimetype && (strcmp(mimetype, "image/bmp") == 0 ||
			                 strcmp(mimetype, "image/gif") == 0 ||
			                 strcmp(mimetype, "image/jpeg") == 0 ||
			                 strcmp(mimetype, "image/png") == 0)) {
				try {
					Magick::Blob blob(io.request.second.data(), io.request.second.size());
					Magick::Image image(blob);

					convert_image(image, request.scale(), request.crop());
					response.set_nail_width(image.size().width());
					response.set_nail_height(image.size().height());
					write_jpeg(image, io.response.second);
				} catch (const Magick::Exception &e) {
					syslog(LOG_ERR, "magick: %s", e.what());
					continue;
				}
			}

			encode_response(response, io.response.first);
			io.handled = true;
		}
	} catch (const zmq::error_t &e) {
		syslog(LOG_CRIT, "zmq: %s", e.what());
	}

	return 1;
}
<commit_msg>silence protobuf enum switch warning<commit_after>#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>

#include <syslog.h>

#include <zmq.hpp>

#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>

#include <magic.h>

#include <Magick++.h>

#include "io.hpp"
#include "thumq.pb.h"

namespace protobuf = google::protobuf;

using namespace thumq;

namespace {

static magic_t magic_cookie;

static bool decode_request(zmq::message_t &message, Request &request)
{
	protobuf::io::ArrayInputStream array(message.data(), message.size());
	protobuf::io::CodedInputStream coded(&array);

	return request.MergePartialFromCodedStream(&coded);
}

static void encode_response(const Response &response, zmq::message_t &message)
{
	message.rebuild(response.ByteSize());

	protobuf::io::ArrayOutputStream array(message.data(), message.size());
	protobuf::io::CodedOutputStream coded(&array);

	response.SerializeWithCachedSizes(&coded);
}

static void convert_image(Magick::Image &image, int scale, Request::Crop crop)
{
	switch (atoi(image.attribute("EXIF:Orientation").c_str())) {
	case Magick::TopLeftOrientation:
		break;

	case Magick::TopRightOrientation:
		image.flop();
		break;

	case Magick::BottomRightOrientation:
		image.rotate(180);
		break;

	case Magick::BottomLeftOrientation:
		image.flip();
		break;

	case Magick::LeftTopOrientation:
		image.rotate(90);
		image.flop();
		break;

	case Magick::RightTopOrientation:
		image.rotate(90);
		break;

	case Magick::RightBottomOrientation:
		image.rotate(270);
		image.flop();
		break;

	case Magick::LeftBottomOrientation:
		image.rotate(270);
		break;
	}

	Magick::Geometry size = image.size();
	int width = size.width();
	int height = size.height();

	switch (crop) {
	case Request::NO_CROP:
		break;

	case Request::TOP_SQUARE:
		if (width < height) {
			image.crop(Magick::Geometry(width, width));
			height = width;
		} else {
			image.crop(Magick::Geometry(height, height, (width - height) / 2, 0));
			width = height;
		}
		break;

	default: // Avoid warning caused by generated protobuf code.
		break;
	}

	if (width > scale || height > scale)
		image.scale(Magick::Geometry(scale, scale));

	image.strip();
}

static void free_blob_data(void *, void *hint)
{
	Magick::Blob *blob = reinterpret_cast<Magick::Blob *> (hint);
	delete blob;

}

static void write_jpeg(Magick::Image &image, zmq::message_t &data)
{
	std::unique_ptr<Magick::Blob> blob(new Magick::Blob);
	image.write(blob.get(), "JPEG");
	data.rebuild(const_cast<void *> (blob->data()), blob->length(), free_blob_data, blob.get());
	blob.release();
}

} // namespace

int main(int argc, char **argv)
{
	if (argc < 2) {
		fprintf(stderr, "Usage: %s ADDRESS...\n", argv[0]);
		return 2;
	}

	const char *progname = strrchr(argv[0], '/');
	if (progname)
		progname++;
	else
		progname = argv[0];

	openlog(progname, LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER);

	magic_cookie = magic_open(MAGIC_MIME_TYPE);
	if (magic_load(magic_cookie, nullptr) < 0) {
		syslog(LOG_CRIT, "magic: %s", strerror(errno));
		return 1;
	}

	Magick::InitializeMagick(argv[0]);

	zmq::context_t context(1);
	zmq::socket_t socket(context, ZMQ_REP);

	try {
		for (int i = 1; i < argc; i++)
			socket.bind(argv[i]);

		while (true) {
			IO io(socket);

			if (!io.receive()) {
				syslog(LOG_ERR, "request message was too short");
				continue;
			}

			Request request;
			Response response;

			if (!decode_request(io.request.first, request)) {
				syslog(LOG_ERR, "could not decode request header");
				continue;
			}

			const char *mimetype = magic_buffer(magic_cookie, io.request.second.data(), io.request.second.size());

			response.set_source_type(mimetype);

			if (mimetype && (strcmp(mimetype, "image/bmp") == 0 ||
			                 strcmp(mimetype, "image/gif") == 0 ||
			                 strcmp(mimetype, "image/jpeg") == 0 ||
			                 strcmp(mimetype, "image/png") == 0)) {
				try {
					Magick::Blob blob(io.request.second.data(), io.request.second.size());
					Magick::Image image(blob);

					convert_image(image, request.scale(), request.crop());
					response.set_nail_width(image.size().width());
					response.set_nail_height(image.size().height());
					write_jpeg(image, io.response.second);
				} catch (const Magick::Exception &e) {
					syslog(LOG_ERR, "magick: %s", e.what());
					continue;
				}
			}

			encode_response(response, io.response.first);
			io.handled = true;
		}
	} catch (const zmq::error_t &e) {
		syslog(LOG_CRIT, "zmq: %s", e.what());
	}

	return 1;
}
<|endoftext|>


<commit_before>// Copyright 2016 Google Inc.
//
// 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 <grpc++/grpc++.h>
#include <unistd.h>

#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

#include "parse_arguments.h"
#include "google/cloud/speech/v1/cloud_speech.grpc.pb.h"
#include "google/longrunning/operations.grpc.pb.h"

using google::cloud::speech::v1::RecognitionConfig;
using google::cloud::speech::v1::Speech;
using google::cloud::speech::v1::LongRunningRecognizeRequest;
using google::cloud::speech::v1::LongRunningRecognizeResponse;

static const char usage[] =
    "Usage:\n"
    "   async_transcribe [--bitrate N] gs://bucket/audio.(raw|ulaw|flac|amr|awb)\n";

int main(int argc, char** argv) {
  // [START speech_async_recognize]
  // Create a Speech stub connected to the speech service.
  auto creds = grpc::GoogleDefaultCredentials();
  auto channel = grpc::CreateChannel("speech.googleapis.com", creds);
  std::unique_ptr<Speech::Stub> speech(Speech::NewStub(channel));
  // Create a long operations stub so we can check the progress of the async
  // request.
  std::unique_ptr<google::longrunning::Operations::Stub> long_operations(
      google::longrunning::Operations::NewStub(channel));
  // Parse command line arguments.
  LongRunningRecognizeRequest request;
  char* file_path =
      ParseArguments(argc, argv, request.mutable_config());
  if (nullptr == file_path) {
    std::cerr << usage;
    return -1;
  }
  // Pass the Google Cloud Storage URI to the request.
  request.mutable_audio()->set_uri(file_path);
  // Call LongRunningRecognize().
  grpc::ClientContext context;
  google::longrunning::Operation op;
  grpc::Status rpc_status = speech->
        LongRunningRecognize(&context, request, &op);
  if (!rpc_status.ok()) {
    // Report the RPC failure.
    std::cerr << rpc_status.error_message() << std::endl;
    return -1;
  }
  // Wait for the operation to complete.  Check the status once per second.
  std::cout << "Waiting for operation " << op.name() << " to complete.";
  google::longrunning::GetOperationRequest get_op_request;
  get_op_request.set_name(op.name());
  while (!op.done()) {
    std::cout << "." << std::flush;
    sleep(1);
    grpc::ClientContext op_context;
    rpc_status = long_operations->
        GetOperation(&op_context, get_op_request, &op);
    if (!rpc_status.ok()) {
      // Report the RPC failure.
      std::cerr << rpc_status.error_message() << std::endl;
      return -1;
    }
  }
  std::cout << std::endl;
  // Unpack the response.
  if (!op.response().Is<LongRunningRecognizeResponse>()) {
    std::cerr << "The operation completed, but did not contain a "
              << "LongRunningRecognizeResponse.";
    return -1;
  }
  LongRunningRecognizeResponse response;
  op.response().UnpackTo(&response);
  // Dump the transcript of all the results.
  for (int r = 0; r < response.results_size(); ++r) {
    auto result = response.results(r);
    for (int a = 0; a < result.alternatives_size(); ++a) {
      auto alternative = result.alternatives(a);
      std::cout << alternative.confidence() << "\t"
                << alternative.transcript() << std::endl;
    }
  }
  // [END speech_async_recognize]
  return 0;
}
<commit_msg>speech_async_recognize -> speech_async_recognize_gcs<commit_after>// Copyright 2016 Google Inc.
//
// 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 <grpc++/grpc++.h>
#include <unistd.h>

#include <fstream>
#include <iostream>
#include <iterator>
#include <string>

#include "parse_arguments.h"
#include "google/cloud/speech/v1/cloud_speech.grpc.pb.h"
#include "google/longrunning/operations.grpc.pb.h"

using google::cloud::speech::v1::RecognitionConfig;
using google::cloud::speech::v1::Speech;
using google::cloud::speech::v1::LongRunningRecognizeRequest;
using google::cloud::speech::v1::LongRunningRecognizeResponse;

static const char usage[] =
    "Usage:\n"
    "   async_transcribe [--bitrate N] gs://bucket/audio.(raw|ulaw|flac|amr|awb)\n";

int main(int argc, char** argv) {
  // [START speech_async_recognize_gcs]
  // Create a Speech stub connected to the speech service.
  auto creds = grpc::GoogleDefaultCredentials();
  auto channel = grpc::CreateChannel("speech.googleapis.com", creds);
  std::unique_ptr<Speech::Stub> speech(Speech::NewStub(channel));
  // Create a long operations stub so we can check the progress of the async
  // request.
  std::unique_ptr<google::longrunning::Operations::Stub> long_operations(
      google::longrunning::Operations::NewStub(channel));
  // Parse command line arguments.
  LongRunningRecognizeRequest request;
  char* file_path =
      ParseArguments(argc, argv, request.mutable_config());
  if (nullptr == file_path) {
    std::cerr << usage;
    return -1;
  }
  // Pass the Google Cloud Storage URI to the request.
  request.mutable_audio()->set_uri(file_path);
  // Call LongRunningRecognize().
  grpc::ClientContext context;
  google::longrunning::Operation op;
  grpc::Status rpc_status = speech->
        LongRunningRecognize(&context, request, &op);
  if (!rpc_status.ok()) {
    // Report the RPC failure.
    std::cerr << rpc_status.error_message() << std::endl;
    return -1;
  }
  // Wait for the operation to complete.  Check the status once per second.
  std::cout << "Waiting for operation " << op.name() << " to complete.";
  google::longrunning::GetOperationRequest get_op_request;
  get_op_request.set_name(op.name());
  while (!op.done()) {
    std::cout << "." << std::flush;
    sleep(1);
    grpc::ClientContext op_context;
    rpc_status = long_operations->
        GetOperation(&op_context, get_op_request, &op);
    if (!rpc_status.ok()) {
      // Report the RPC failure.
      std::cerr << rpc_status.error_message() << std::endl;
      return -1;
    }
  }
  std::cout << std::endl;
  // Unpack the response.
  if (!op.response().Is<LongRunningRecognizeResponse>()) {
    std::cerr << "The operation completed, but did not contain a "
              << "LongRunningRecognizeResponse.";
    return -1;
  }
  LongRunningRecognizeResponse response;
  op.response().UnpackTo(&response);
  // Dump the transcript of all the results.
  for (int r = 0; r < response.results_size(); ++r) {
    auto result = response.results(r);
    for (int a = 0; a < result.alternatives_size(); ++a) {
      auto alternative = result.alternatives(a);
      std::cout << alternative.confidence() << "\t"
                << alternative.transcript() << std::endl;
    }
  }
  // [END speech_async_recognize_gcs]
  return 0;
}
<|endoftext|>


<commit_before>#include <avr/interrupt.h>
#include "UART.h"
#include "UARTsettings.h"

static volatile uint8_t tx_buffer[SERIAL_BUFFER_SIZE];
static volatile uint8_t rx_buffer[SERIAL_BUFFER_SIZE];

static volatile uint8_t rx_buffer_head = 0;
static volatile uint8_t rx_buffer_tail = 0;

static volatile uint8_t tx_buffer_head = 0;
static volatile uint8_t tx_buffer_tail = 0;

bool    rxEnabled,
        txEnabled;

//isr functions

ISR(USART1_RX_vect) {

    uint8_t data, bufferIndex;

    data = UDR1;
    bufferIndex = rx_buffer_head + 1;

    if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;

    if (bufferIndex != rx_buffer_tail) {

        rx_buffer[bufferIndex] = data;
        rx_buffer_head = bufferIndex;

    }

}

ISR(USART1_UDRE_vect)   {

    uint8_t bufferIndex;

    if (tx_buffer_head == tx_buffer_tail) {

        // buffer is empty, disable transmit interrupt
        if (!rxEnabled)
            UCSR1B = (1<<TXCIE1) | (1<<TXEN1);
        else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);

    } else {

        bufferIndex = tx_buffer_tail + 1;
        if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;
        UDR1 = tx_buffer[bufferIndex];
        tx_buffer_tail = bufferIndex;

    }

}

UART::UART()  {

    //default constructor

}

int8_t UART::read(void)   {

    uint8_t data, bufferIndex;

    if (rx_buffer_head == rx_buffer_tail) return -1;
    bufferIndex = rx_buffer_tail + 1;
    if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;
    data = rx_buffer[bufferIndex];
    rx_buffer_tail = bufferIndex;
    return data;

}

void UART::write(uint8_t data)  {

    if (!txEnabled) return;

    uint8_t bufferIndex;

    if (!(UCSR1B & (1<<TXEN1))) return;

    bufferIndex = tx_buffer_head + 1;

    if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;

    while (tx_buffer_tail == bufferIndex); // wait until space in buffer

    tx_buffer[bufferIndex] = data;

    tx_buffer_head = bufferIndex;

    if (!rxEnabled)
        UCSR1B = (1<<TXCIE1) | (1<<TXEN1) | (1<<UDRIE1);
    else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1) | (1<<UDRIE1);

}

void UART::begin(uint32_t baudRate, bool enableRX, bool enableTX)   {

    rxEnabled = enableRX;
    txEnabled = enableTX;

    int16_t baud_count = ((F_CPU / 8) + (baudRate / 2)) / baudRate;

    if ((baud_count & 1) && baud_count <= 4096) {

        UCSR1A = (1<<U2X1); //double speed uart
        UBRR1 = baud_count - 1;

    }   else {

        UCSR1A = 0;
        UBRR1 = (baud_count >> 1) - 1;

    }

    if (!(UCSR1B & (1<<TXEN1))) {

        rx_buffer_head = 0;
        rx_buffer_tail = 0;
        tx_buffer_head = 0;
        tx_buffer_tail = 0;

        UCSR1C = (1<<UCSZ11) | (1<<UCSZ10); //8 bit, no parity, 1 stop bit

        if (enableRX && enableTX)   //enable both rx and tx
            UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);
        else if (enableRX && !enableTX) //enable only receive
            UCSR1B = (1<<RXEN1) | (1<<RXCIE1);
        else if (enableTX & !enableRX)  //enable only transmit
            UCSR1B = (1<<TXCIE1) | (1<<TXEN1);

    }

}

uint8_t UART::available()    {

    //return available number of bytes in incoming buffer

    uint8_t head, tail;

    head = rx_buffer_head;
    tail = rx_buffer_tail;

    if (head >= tail) return head - tail;
    return SERIAL_BUFFER_SIZE + head - tail;

}

UART uart;<commit_msg>define USART1_TX_vect interrupt<commit_after>#include <avr/interrupt.h>
#include "UART.h"
#include "UARTsettings.h"

static volatile uint8_t tx_buffer[SERIAL_BUFFER_SIZE];
static volatile uint8_t rx_buffer[SERIAL_BUFFER_SIZE];

static volatile uint8_t rx_buffer_head = 0;
static volatile uint8_t rx_buffer_tail = 0;

static volatile uint8_t tx_buffer_head = 0;
static volatile uint8_t tx_buffer_tail = 0;

bool    rxEnabled,
        txEnabled;

//isr functions

ISR(USART1_RX_vect) {

    uint8_t data, bufferIndex;

    data = UDR1;
    bufferIndex = rx_buffer_head + 1;

    if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;

    if (bufferIndex != rx_buffer_tail) {

        rx_buffer[bufferIndex] = data;
        rx_buffer_head = bufferIndex;

    }

}

ISR(USART1_UDRE_vect)   {

    uint8_t bufferIndex;

    if (tx_buffer_head == tx_buffer_tail) {

        // buffer is empty, disable transmit interrupt
        if (!rxEnabled)
            UCSR1B = (1<<TXCIE1) | (1<<TXEN1);
        else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);

    } else {

        bufferIndex = tx_buffer_tail + 1;
        if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;
        UDR1 = tx_buffer[bufferIndex];
        tx_buffer_tail = bufferIndex;

    }

}

ISR(USART1_TX_vect) {}

UART::UART()  {

    //default constructor

}

int8_t UART::read(void)   {

    uint8_t data, bufferIndex;

    if (rx_buffer_head == rx_buffer_tail) return -1;
    bufferIndex = rx_buffer_tail + 1;
    if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;
    data = rx_buffer[bufferIndex];
    rx_buffer_tail = bufferIndex;
    return data;

}

void UART::write(uint8_t data)  {

    if (!txEnabled) return;

    uint8_t bufferIndex;

    if (!(UCSR1B & (1<<TXEN1))) return;

    bufferIndex = tx_buffer_head + 1;

    if (bufferIndex >= SERIAL_BUFFER_SIZE) bufferIndex = 0;

    while (tx_buffer_tail == bufferIndex); // wait until space in buffer

    tx_buffer[bufferIndex] = data;

    tx_buffer_head = bufferIndex;

    if (!rxEnabled)
        UCSR1B = (1<<TXCIE1) | (1<<TXEN1) | (1<<UDRIE1);
    else UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1) | (1<<UDRIE1);

}

void UART::begin(uint32_t baudRate, bool enableRX, bool enableTX)   {

    rxEnabled = enableRX;
    txEnabled = enableTX;

    int16_t baud_count = ((F_CPU / 8) + (baudRate / 2)) / baudRate;

    if ((baud_count & 1) && baud_count <= 4096) {

        UCSR1A = (1<<U2X1); //double speed uart
        UBRR1 = baud_count - 1;

    }   else {

        UCSR1A = 0;
        UBRR1 = (baud_count >> 1) - 1;

    }

    if (!(UCSR1B & (1<<TXEN1))) {

        rx_buffer_head = 0;
        rx_buffer_tail = 0;
        tx_buffer_head = 0;
        tx_buffer_tail = 0;

        UCSR1C = (1<<UCSZ11) | (1<<UCSZ10); //8 bit, no parity, 1 stop bit

        if (enableRX && enableTX)   //enable both rx and tx
            UCSR1B = (1<<RXEN1) | (1<<TXCIE1) | (1<<TXEN1) | (1<<RXCIE1);
        else if (enableRX && !enableTX) //enable only receive
            UCSR1B = (1<<RXEN1) | (1<<RXCIE1);
        else if (enableTX & !enableRX)  //enable only transmit
            UCSR1B = (1<<TXCIE1) | (1<<TXEN1);

    }

}

uint8_t UART::available()    {

    //return available number of bytes in incoming buffer

    uint8_t head, tail;

    head = rx_buffer_head;
    tail = rx_buffer_tail;

    if (head >= tail) return head - tail;
    return SERIAL_BUFFER_SIZE + head - tail;

}

UART uart;<|endoftext|>


<commit_before>/*
	Dashel
	A cross-platform DAta Stream Helper Encapsulation Library
	Copyright (C) 2007 -- 2009:

		Stephane Magnenat <stephane at magnenat dot net>
			(http://stephane.magnenat.net)
		Mobots group - Laboratory of Robotics Systems, EPFL, Lausanne
			(http://mobots.epfl.ch)

		Sebastian Gerlach
		Kenzan Technologies
			(http://www.kenzantech.com)

	All rights reserved.

	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.
		* Neither the names of "Mobots", "Laboratory of Robotics Systems", "EPFL",
		  "Kenzan Technologies" nor the names of the contributors may be used to
		  endorse or promote products derived from this software without specific
		  prior written permission.

	THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ``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 COPYRIGHT HOLDERS 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.
*/

#include "dashel.h"
#include "dashel-private.h"
#include <algorithm>

#include <ostream>
#include <sstream>
#ifndef WIN32
	#include <netdb.h>
	#include <sys/socket.h>
	#include <arpa/inet.h>
#else
	#include <winsock2.h>
#endif

/*!	\file dashel-commong.cpp
	\brief Implementation of Dashel, A cross-platform DAta Stream Helper Encapsulation Library
*/

namespace Dashel
{
	using namespace std;

	// frome dashe-private.h
	ExpandableBuffer::ExpandableBuffer(size_t size) :
		_data((unsigned char*)malloc(size)),
		_size(size),
		_pos(0)
	{
	}

	ExpandableBuffer::~ExpandableBuffer()
	{
		free(_data);
	}

	void ExpandableBuffer::clear()
	{
		_pos = 0;
	}

	void ExpandableBuffer::add(const void* data, const size_t size)
	{
		if (_pos + size > _size)
		{
			_size = max(_size * 2, _size + size);
			_data = (unsigned char*)realloc(_data, _size);
		}
		memcpy(_data + _pos, (unsigned char *)data, size);
		_pos += size;
	}

	// frome dashel.h
	DashelException::DashelException(Source s, int se, const char *reason, Stream* stream) :
		std::runtime_error(reason),
		source(s),
		sysError(se),
		stream(stream)
	{

	}

	IPV4Address::IPV4Address(unsigned addr, unsigned short prt)
	{
		address = addr;
		port = prt;
	}

	IPV4Address::IPV4Address(const std::string& name, unsigned short port) :
		port(port)
	{
		hostent *he = gethostbyname(name.c_str());

		if (he == NULL)
		{
			#ifndef WIN32
			struct in_addr addr;
			if (inet_aton(name.c_str(), &addr))
			{
				address = ntohl(addr.s_addr);
			}
			else
			{
				address = INADDR_ANY;
			}
			#else // WIN32
			unsigned long addr = inet_addr(name.c_str());
			if(addr != INADDR_NONE)
				address = addr;
			else
				address = INADDR_ANY;
			#endif // WIN32
		}
		else
		{
			#ifndef WIN32
			address = ntohl(*((unsigned *)he->h_addr));
			#else
			address = ntohl(*((unsigned *)he->h_addr));
			#endif
		}
	}

	bool IPV4Address::operator==(const IPV4Address& o) const
	{
		return address==o.address && port==o.port;
	}

	bool IPV4Address::operator<(const IPV4Address& o) const
	{
		return address<o.address || (address==o.address && port<o.port);
	}

	std::string IPV4Address::hostname() const
	{
		unsigned a2 = htonl(address);
		struct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);

		if (he == NULL)
		{
			struct in_addr addr;
			addr.s_addr = a2;
			return std::string(inet_ntoa(addr));
		}
		else
		{
			return std::string(he->h_name);
		}
	}

	std::string IPV4Address::format() const
	{
		std::ostringstream buf;
		unsigned a2 = htonl(address);
		struct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);

		if (he == NULL)
		{
			struct in_addr addr;
			addr.s_addr = a2;
			buf << "tcp:host=" << inet_ntoa(addr) << ";port=" << port;
		}
		else
		{
			buf << "tcp:host=" << he->h_name << ";port=" << port;
		}

		return buf.str();
	}

	void ParameterSet::add(const char *line)
	{
		char *lc = strdup(line);
		int spc = 0;
		char *param;
		bool storeParams = (params.size() == 0);
		char *protocolName = strtok(lc, ":");

		// Do nothing with this.
		assert(protocolName);

		while((param = strtok(NULL, ";")) != NULL)
		{
			char *sep = strchr(param, '=');
			if(sep)
			{
				*sep++ = 0;
				values[param] = sep;
				if (storeParams)
					params.push_back(param);
			}
			else
			{
				if (storeParams)
					params.push_back(param);
				values[params[spc]] = param;
			}
			++spc;
		}

		free(lc);
	}

	void ParameterSet::addParam(const char *param, const char *value, bool atStart)
	{
		if (atStart)
			params.insert(params.begin(), 1, param);
		else
			params.push_back(param);

		if (value)
			values[param] = value;
	}

	bool ParameterSet::isSet(const char *key) const
	{
		return (values.find(key) != values.end());
	}

	const std::string& ParameterSet::get(const char *key) const
	{
		std::map<std::string, std::string>::const_iterator it = values.find(key);
		if(it == values.end())
		{
			std::string r = std::string("Parameter missing: ").append(key);
			throw DashelException(DashelException::InvalidTarget, 0, r.c_str());
		}
		return it->second;
	}

	std::string ParameterSet::getString() const
	{
		std::ostringstream oss;
		std::vector<std::string>::const_iterator i = params.begin();
		while (true)
		{
			oss << *i << "=" << values.find(*i)->second;
			if (++i == params.end())
				break;
			oss << ";";
		}
		return oss.str();
	}

	void ParameterSet::erase(const char *key)
	{
		std::vector<std::string>::iterator i = std::find(params.begin(), params.end(), key);
		if (i != params.end())
			params.erase(i);

		std::map<std::string, std::string>::iterator j = values.find(key);
		if (j != values.end())
			values.erase(j);
	}

	void MemoryPacketStream::write(const void *data, const size_t size)
	{
		sendBuffer.add(data, size);
	}

	void MemoryPacketStream::read(void *data, size_t size)
	{
		if (size > receptionBuffer.size())
			fail(DashelException::IOError, 0, "Attempt to read past available data");

		unsigned char* ptr = (unsigned char*)data;
		std::copy(receptionBuffer.begin(), receptionBuffer.begin() + size, ptr);
		receptionBuffer.erase(receptionBuffer.begin(), receptionBuffer.begin() + size);
	}

	void Hub::closeStream(Stream* stream)
	{
		streams.erase(stream);
		dataStreams.erase(stream);
		delete stream;
	}
}

<commit_msg>Fixed trash when target has no arguments<commit_after>/*
	Dashel
	A cross-platform DAta Stream Helper Encapsulation Library
	Copyright (C) 2007 -- 2009:

		Stephane Magnenat <stephane at magnenat dot net>
			(http://stephane.magnenat.net)
		Mobots group - Laboratory of Robotics Systems, EPFL, Lausanne
			(http://mobots.epfl.ch)

		Sebastian Gerlach
		Kenzan Technologies
			(http://www.kenzantech.com)

	All rights reserved.

	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.
		* Neither the names of "Mobots", "Laboratory of Robotics Systems", "EPFL",
		  "Kenzan Technologies" nor the names of the contributors may be used to
		  endorse or promote products derived from this software without specific
		  prior written permission.

	THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS ``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 COPYRIGHT HOLDERS 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.
*/

#include "dashel.h"
#include "dashel-private.h"
#include <algorithm>

#include <ostream>
#include <sstream>
#ifndef WIN32
	#include <netdb.h>
	#include <sys/socket.h>
	#include <arpa/inet.h>
#else
	#include <winsock2.h>
#endif

/*!	\file dashel-commong.cpp
	\brief Implementation of Dashel, A cross-platform DAta Stream Helper Encapsulation Library
*/

namespace Dashel
{
	using namespace std;

	// frome dashe-private.h
	ExpandableBuffer::ExpandableBuffer(size_t size) :
		_data((unsigned char*)malloc(size)),
		_size(size),
		_pos(0)
	{
	}

	ExpandableBuffer::~ExpandableBuffer()
	{
		free(_data);
	}

	void ExpandableBuffer::clear()
	{
		_pos = 0;
	}

	void ExpandableBuffer::add(const void* data, const size_t size)
	{
		if (_pos + size > _size)
		{
			_size = max(_size * 2, _size + size);
			_data = (unsigned char*)realloc(_data, _size);
		}
		memcpy(_data + _pos, (unsigned char *)data, size);
		_pos += size;
	}

	// frome dashel.h
	DashelException::DashelException(Source s, int se, const char *reason, Stream* stream) :
		std::runtime_error(reason),
		source(s),
		sysError(se),
		stream(stream)
	{

	}

	IPV4Address::IPV4Address(unsigned addr, unsigned short prt)
	{
		address = addr;
		port = prt;
	}

	IPV4Address::IPV4Address(const std::string& name, unsigned short port) :
		port(port)
	{
		hostent *he = gethostbyname(name.c_str());

		if (he == NULL)
		{
			#ifndef WIN32
			struct in_addr addr;
			if (inet_aton(name.c_str(), &addr))
			{
				address = ntohl(addr.s_addr);
			}
			else
			{
				address = INADDR_ANY;
			}
			#else // WIN32
			unsigned long addr = inet_addr(name.c_str());
			if(addr != INADDR_NONE)
				address = addr;
			else
				address = INADDR_ANY;
			#endif // WIN32
		}
		else
		{
			#ifndef WIN32
			address = ntohl(*((unsigned *)he->h_addr));
			#else
			address = ntohl(*((unsigned *)he->h_addr));
			#endif
		}
	}

	bool IPV4Address::operator==(const IPV4Address& o) const
	{
		return address==o.address && port==o.port;
	}

	bool IPV4Address::operator<(const IPV4Address& o) const
	{
		return address<o.address || (address==o.address && port<o.port);
	}

	std::string IPV4Address::hostname() const
	{
		unsigned a2 = htonl(address);
		struct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);

		if (he == NULL)
		{
			struct in_addr addr;
			addr.s_addr = a2;
			return std::string(inet_ntoa(addr));
		}
		else
		{
			return std::string(he->h_name);
		}
	}

	std::string IPV4Address::format() const
	{
		std::ostringstream buf;
		unsigned a2 = htonl(address);
		struct hostent *he = gethostbyaddr((const char *)&a2, 4, AF_INET);

		if (he == NULL)
		{
			struct in_addr addr;
			addr.s_addr = a2;
			buf << "tcp:host=" << inet_ntoa(addr) << ";port=" << port;
		}
		else
		{
			buf << "tcp:host=" << he->h_name << ";port=" << port;
		}

		return buf.str();
	}

	void ParameterSet::add(const char *line)
	{
		char *lc = strdup(line);
		int spc = 0;
		char *param;
		bool storeParams = (params.size() == 0);
		char *protocolName = strtok(lc, ":");

		// Do nothing with this.
		assert(protocolName);

		while((param = strtok(NULL, ";")) != NULL)
		{
			char *sep = strchr(param, '=');
			if(sep)
			{
				*sep++ = 0;
				values[param] = sep;
				if (storeParams)
					params.push_back(param);
			}
			else
			{
				if (storeParams)
					params.push_back(param);
				values[params[spc]] = param;
			}
			++spc;
		}

		free(lc);
	}

	void ParameterSet::addParam(const char *param, const char *value, bool atStart)
	{
		if (atStart)
			params.insert(params.begin(), 1, param);
		else
			params.push_back(param);

		if (value)
			values[param] = value;
	}

	bool ParameterSet::isSet(const char *key) const
	{
		return (values.find(key) != values.end());
	}

	const std::string& ParameterSet::get(const char *key) const
	{
		std::map<std::string, std::string>::const_iterator it = values.find(key);
		if(it == values.end())
		{
			std::string r = std::string("Parameter missing: ").append(key);
			throw DashelException(DashelException::InvalidTarget, 0, r.c_str());
		}
		return it->second;
	}

	std::string ParameterSet::getString() const
	{
		std::ostringstream oss;
		std::vector<std::string>::const_iterator i = params.begin();
		while (i != params.end())
		{
			oss << *i << "=" << values.find(*i)->second;
			if (++i == params.end())
				break;
			oss << ";";
		}
		return oss.str();
	}

	void ParameterSet::erase(const char *key)
	{
		std::vector<std::string>::iterator i = std::find(params.begin(), params.end(), key);
		if (i != params.end())
			params.erase(i);

		std::map<std::string, std::string>::iterator j = values.find(key);
		if (j != values.end())
			values.erase(j);
	}

	void MemoryPacketStream::write(const void *data, const size_t size)
	{
		sendBuffer.add(data, size);
	}

	void MemoryPacketStream::read(void *data, size_t size)
	{
		if (size > receptionBuffer.size())
			fail(DashelException::IOError, 0, "Attempt to read past available data");

		unsigned char* ptr = (unsigned char*)data;
		std::copy(receptionBuffer.begin(), receptionBuffer.begin() + size, ptr);
		receptionBuffer.erase(receptionBuffer.begin(), receptionBuffer.begin() + size);
	}

	void Hub::closeStream(Stream* stream)
	{
		streams.erase(stream);
		dataStreams.erase(stream);
		delete stream;
	}
}

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  MemoryMapWindow.cc
//------------------------------------------------------------------------------
#include "MemoryMapWindow.h"
#include "IMUI/IMUI.h"
#include "Core/String/StringBuilder.h"

OryolClassImpl(MemoryMapWindow);

using namespace Oryol;
using namespace yakc;

//------------------------------------------------------------------------------
void
MemoryMapWindow::Setup(kc85& kc) {
    this->setName("Memory Map");
}

//------------------------------------------------------------------------------
MemoryMapWindow::pageInfo
MemoryMapWindow::getPageInfo(kc85& kc, int layer_index, int page_index) const {
    pageInfo info;
    unsigned int addr = page_index * memory::page::size;
    if (0 == layer_index) {
        if (kc.model() == kc85_model::kc85_3) {
            if (addr < 0x4000) {
                info.name = "RAM0";
                info.addr = 0x0000;
                info.size = 0x4000;
            }
            else if ((addr >= 0x8000) && (addr < 0xC000)) {
                info.name = "IRM";
                info.addr = 0x8000;
                info.size = 0x4000;
            }
            else if ((addr >= 0xC000) && (addr < 0xE000)) {
                info.name = "BASIC ROM";
                info.addr = 0xC000;
                info.size = 0x2000;
            }
            else if ((addr >= 0xE000) && (addr < 0x10000)){
                info.name = "CAOS ROM";
                info.addr = 0xE000;
                info.size = 0x2000;
            }
        }
        else if (kc.model() == kc85_model::kc85_4) {
            if (addr < 0x4000) {
                info.name = "RAM0";
                info.addr = 0x0000;
                info.size = 0x4000;
            }
            else if ((addr >= 0x4000) && (addr < 0x8000)) {
                info.name = "RAM4";
                info.addr = 0x4000;
                info.size = 0x4000;
            }
            else if ((addr >= 0xE000) && (addr < 0x10000)){
                info.name = "CAOS ROM E";
                info.addr = 0xE000;
                info.size = 0x2000;
            }
        }
    }
    else if (1 == layer_index) {
        // base device module slot 08
        if (kc.exp.slot_occupied(0x08)) {
            const auto& slot = kc.exp.slot_by_addr(0x08);
            if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {
                info.name = slot.mod.name;
                info.addr = slot.addr;
                info.size = slot.mod.mem_size;
            }
        }
    }
    else if (2 == layer_index) {
        // base device module slot 0C
        if (kc.exp.slot_occupied(0x0C)) {
            const auto& slot = kc.exp.slot_by_addr(0x0C);
            if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {
                info.name = slot.mod.name;
                info.addr = slot.addr;
                info.size = slot.mod.mem_size;
            }
        }
    }
    return info;
}

//------------------------------------------------------------------------------
bool
MemoryMapWindow::Draw(kc85& kc) {
    StringBuilder strBuilder;
    static const ImVec4 grey(0.25f, 0.25f, 0.25f, 1.0f);
    static const ImVec4 light_green(0.0f, 1.0f, 0.0f, 1.0f);
    static const ImVec4 dark_green(0.0f, 0.5f, 0.0f, 1.0f);
    static const ImVec2 page_size(12, 0);
    ImGui::SetNextWindowSize(ImVec2(512, 100), ImGuiSetCond_Once);
    if (ImGui::Begin(this->title.AsCStr(), &this->Visible, ImGuiWindowFlags_NoResize)) {
        static const int num_layers = 3;
        static const char* layer_name[num_layers] = { "BUILT-IN", "SLOT 08", "SLOT 0C" };
        for (int layer=0; layer<num_layers; layer++) {
            ImGui::Text(layer_name[layer]);
            for (int page=0; page<memory::num_pages; page++) {
                ImGui::SameLine(72 + page*(page_size.x));
                bool is_mapped = false;
                if (kc.cpu.mem.layers[layer][page].ptr) {
                    is_mapped = true;
                    if (kc.cpu.mem.get_mapped_layer_index(page) == layer) {
                        ImGui::PushStyleColor(ImGuiCol_Button, light_green);
                        ImGui::PushStyleColor(ImGuiCol_ButtonHovered, light_green);
                    }
                    else {
                        ImGui::PushStyleColor(ImGuiCol_Button, dark_green);
                        ImGui::PushStyleColor(ImGuiCol_ButtonHovered, dark_green);
                    }
                }
                else {
                    ImGui::PushStyleColor(ImGuiCol_Button, grey);
                    ImGui::PushStyleColor(ImGuiCol_ButtonHovered, grey);
                }
                ImGui::Button("",page_size);
                if (ImGui::IsItemHovered()) {
                    pageInfo info = this->getPageInfo(kc, layer, page);
                    if (info.name) {
                        strBuilder.Format(48, "%s\n(%04X-%04X)", info.name, info.addr, (info.addr + info.size) - 1);
                        ImGui::SetTooltip(strBuilder.AsCStr());
                    }
                }
                ImGui::PopStyleColor();
                ImGui::PopStyleColor();
            }
        }
    }
    ImGui::End();
    return this->Visible;
}
<commit_msg>Reminder to fix memory map window for 85/2 and 85/4<commit_after>//------------------------------------------------------------------------------
//  MemoryMapWindow.cc
//------------------------------------------------------------------------------
#include "MemoryMapWindow.h"
#include "IMUI/IMUI.h"
#include "Core/String/StringBuilder.h"

OryolClassImpl(MemoryMapWindow);

using namespace Oryol;
using namespace yakc;

//------------------------------------------------------------------------------
void
MemoryMapWindow::Setup(kc85& kc) {
    this->setName("Memory Map (FIXME!)");
}

//------------------------------------------------------------------------------
MemoryMapWindow::pageInfo
MemoryMapWindow::getPageInfo(kc85& kc, int layer_index, int page_index) const {
    pageInfo info;
    unsigned int addr = page_index * memory::page::size;
    if (0 == layer_index) {
        if (kc.model() == kc85_model::kc85_3) {
            if (addr < 0x4000) {
                info.name = "RAM0";
                info.addr = 0x0000;
                info.size = 0x4000;
            }
            else if ((addr >= 0x8000) && (addr < 0xC000)) {
                info.name = "IRM";
                info.addr = 0x8000;
                info.size = 0x4000;
            }
            else if ((addr >= 0xC000) && (addr < 0xE000)) {
                info.name = "BASIC ROM";
                info.addr = 0xC000;
                info.size = 0x2000;
            }
            else if ((addr >= 0xE000) && (addr < 0x10000)){
                info.name = "CAOS ROM";
                info.addr = 0xE000;
                info.size = 0x2000;
            }
        }
        else if (kc.model() == kc85_model::kc85_4) {
            if (addr < 0x4000) {
                info.name = "RAM0";
                info.addr = 0x0000;
                info.size = 0x4000;
            }
            else if ((addr >= 0x4000) && (addr < 0x8000)) {
                info.name = "RAM4";
                info.addr = 0x4000;
                info.size = 0x4000;
            }
            else if ((addr >= 0xE000) && (addr < 0x10000)){
                info.name = "CAOS ROM E";
                info.addr = 0xE000;
                info.size = 0x2000;
            }
        }
    }
    else if (1 == layer_index) {
        // base device module slot 08
        if (kc.exp.slot_occupied(0x08)) {
            const auto& slot = kc.exp.slot_by_addr(0x08);
            if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {
                info.name = slot.mod.name;
                info.addr = slot.addr;
                info.size = slot.mod.mem_size;
            }
        }
    }
    else if (2 == layer_index) {
        // base device module slot 0C
        if (kc.exp.slot_occupied(0x0C)) {
            const auto& slot = kc.exp.slot_by_addr(0x0C);
            if ((addr >= slot.addr) && (addr < (slot.addr + slot.mod.mem_size))) {
                info.name = slot.mod.name;
                info.addr = slot.addr;
                info.size = slot.mod.mem_size;
            }
        }
    }
    return info;
}

//------------------------------------------------------------------------------
bool
MemoryMapWindow::Draw(kc85& kc) {
    StringBuilder strBuilder;
    static const ImVec4 grey(0.25f, 0.25f, 0.25f, 1.0f);
    static const ImVec4 light_green(0.0f, 1.0f, 0.0f, 1.0f);
    static const ImVec4 dark_green(0.0f, 0.5f, 0.0f, 1.0f);
    static const ImVec2 page_size(12, 0);
    ImGui::SetNextWindowSize(ImVec2(512, 100), ImGuiSetCond_Once);
    if (ImGui::Begin(this->title.AsCStr(), &this->Visible, ImGuiWindowFlags_NoResize)) {
        static const int num_layers = 3;
        static const char* layer_name[num_layers] = { "BUILT-IN", "SLOT 08", "SLOT 0C" };
        for (int layer=0; layer<num_layers; layer++) {
            ImGui::Text(layer_name[layer]);
            for (int page=0; page<memory::num_pages; page++) {
                ImGui::SameLine(72 + page*(page_size.x));
                bool is_mapped = false;
                if (kc.cpu.mem.layers[layer][page].ptr) {
                    is_mapped = true;
                    if (kc.cpu.mem.get_mapped_layer_index(page) == layer) {
                        ImGui::PushStyleColor(ImGuiCol_Button, light_green);
                        ImGui::PushStyleColor(ImGuiCol_ButtonHovered, light_green);
                    }
                    else {
                        ImGui::PushStyleColor(ImGuiCol_Button, dark_green);
                        ImGui::PushStyleColor(ImGuiCol_ButtonHovered, dark_green);
                    }
                }
                else {
                    ImGui::PushStyleColor(ImGuiCol_Button, grey);
                    ImGui::PushStyleColor(ImGuiCol_ButtonHovered, grey);
                }
                ImGui::Button("",page_size);
                if (ImGui::IsItemHovered()) {
                    pageInfo info = this->getPageInfo(kc, layer, page);
                    if (info.name) {
                        strBuilder.Format(48, "%s\n(%04X-%04X)", info.name, info.addr, (info.addr + info.size) - 1);
                        ImGui::SetTooltip(strBuilder.AsCStr());
                    }
                }
                ImGui::PopStyleColor();
                ImGui::PopStyleColor();
            }
        }
    }
    ImGui::End();
    return this->Visible;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx
#define itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx

#include <fstream>
#include <iostream>
#include <sstream>

#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"

namespace itk
{
namespace BlockMatching
{

template< typename TMultiResolutionMethod >
MultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >
::MultiResolutionSearchRegionWriterCommand()
{
  m_SearchRegionImageComponent  = SearchRegionImageComponentType::New();
  m_SearchRegionComponentWriter = SearchRegionComponentWriterType::New();
  m_SearchRegionComponentWriter->SetInput( m_SearchRegionImageComponent );
}

template< typename TMultiResolutionMethod >
MultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >
::~MultiResolutionSearchRegionWriterCommand()
{
}

template< typename TMultiResolutionMethod >
void
MultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >
::Execute( const itk::Object * object , const itk::EventObject & event )
{
  Superclass::Execute( object, event );

  const unsigned long level = this->m_MultiResolutionMethod->GetCurrentLevel();

  this->m_SearchRegionImageSource->UpdateLargestPossibleRegion();
  typename SearchRegionImageType::ConstPointer searchRegionImage = this->m_SearchRegionImageSource->GetOutput();
  m_SearchRegionImageComponent->CopyInformation( searchRegionImage );
  m_SearchRegionImageComponent->SetRegions( searchRegionImage->GetBufferedRegion() );
  m_SearchRegionImageComponent->Allocate();

  std::cout << "Writing SearchRegionImage images..." << std::endl;

  if( m_OutputFilePrefix.size() == 0 )
    {
    itkExceptionMacro( << "OutputFilePrefix is not set." );
    }

  std::ostringstream ostr;
  itk::ImageRegionConstIterator< SearchRegionImageType > regionIt( searchRegionImage,
    searchRegionImage->GetBufferedRegion() );
  itk::ImageRegionIterator< SearchRegionImageComponentType > compIt( m_SearchRegionImageComponent,
    m_SearchRegionImageComponent->GetBufferedRegion() );
  for( unsigned int dim = 0; dim < 2; ++dim )
    {
    for( regionIt.GoToBegin(), compIt.GoToBegin();
         !regionIt.IsAtEnd();
         ++regionIt, ++compIt )
      {
      compIt.Set( regionIt.Get().GetSize()[dim] );
      }

    ostr.str( "" );
    ostr << m_OutputFilePrefix << "_Level_" << level << "_SearchRegionImageComponent" << dim << ".mha";
    m_SearchRegionComponentWriter->SetFileName( ostr.str() );
    m_SearchRegionComponentWriter->Update();
    }
}

}
}

#endif
<commit_msg>COMP: Add missing itkBlockMatchingMultiResolutionSearchRegionWriterCommand.h include<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx
#define itkBlockMatchingMultiResolutionSearchRegionWriterCommand_hxx

#include "itkBlockMatchingMultiResolutionSearchRegionWriterCommand.h"

#include <fstream>
#include <iostream>
#include <sstream>

#include "itkImageRegionConstIterator.h"
#include "itkImageRegionIterator.h"

namespace itk
{
namespace BlockMatching
{

template< typename TMultiResolutionMethod >
MultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >
::MultiResolutionSearchRegionWriterCommand()
{
  m_SearchRegionImageComponent  = SearchRegionImageComponentType::New();
  m_SearchRegionComponentWriter = SearchRegionComponentWriterType::New();
  m_SearchRegionComponentWriter->SetInput( m_SearchRegionImageComponent );
}

template< typename TMultiResolutionMethod >
MultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >
::~MultiResolutionSearchRegionWriterCommand()
{
}

template< typename TMultiResolutionMethod >
void
MultiResolutionSearchRegionWriterCommand< TMultiResolutionMethod >
::Execute( const itk::Object * object , const itk::EventObject & event )
{
  Superclass::Execute( object, event );

  const unsigned long level = this->m_MultiResolutionMethod->GetCurrentLevel();

  this->m_SearchRegionImageSource->UpdateLargestPossibleRegion();
  typename SearchRegionImageType::ConstPointer searchRegionImage = this->m_SearchRegionImageSource->GetOutput();
  m_SearchRegionImageComponent->CopyInformation( searchRegionImage );
  m_SearchRegionImageComponent->SetRegions( searchRegionImage->GetBufferedRegion() );
  m_SearchRegionImageComponent->Allocate();

  std::cout << "Writing SearchRegionImage images..." << std::endl;

  if( m_OutputFilePrefix.size() == 0 )
    {
    itkExceptionMacro( << "OutputFilePrefix is not set." );
    }

  std::ostringstream ostr;
  itk::ImageRegionConstIterator< SearchRegionImageType > regionIt( searchRegionImage,
    searchRegionImage->GetBufferedRegion() );
  itk::ImageRegionIterator< SearchRegionImageComponentType > compIt( m_SearchRegionImageComponent,
    m_SearchRegionImageComponent->GetBufferedRegion() );
  for( unsigned int dim = 0; dim < 2; ++dim )
    {
    for( regionIt.GoToBegin(), compIt.GoToBegin();
         !regionIt.IsAtEnd();
         ++regionIt, ++compIt )
      {
      compIt.Set( regionIt.Get().GetSize()[dim] );
      }

    ostr.str( "" );
    ostr << m_OutputFilePrefix << "_Level_" << level << "_SearchRegionImageComponent" << dim << ".mha";
    m_SearchRegionComponentWriter->SetFileName( ostr.str() );
    m_SearchRegionComponentWriter->Update();
    }
}

} // end namespace BlockMatching
} // end namespace itk

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: storagehelper.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _COMPHELPER_STORAGEHELPER_HXX
#define _COMPHELPER_STORAGEHELPER_HXX

#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XStream.hpp>
#include "comphelper/comphelperdllapi.h"

#define PACKAGE_STORAGE_FORMAT_STRING   ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PackageFormat" ) )
#define ZIP_STORAGE_FORMAT_STRING       ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ZipFormat" ) )
#define OFOPXML_STORAGE_FORMAT_STRING   ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OFOPXMLFormat" ) )

namespace comphelper {

class COMPHELPER_DLLPUBLIC OStorageHelper
{
public:
    static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
        GetStorageFactory(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetTemporaryStorage(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageFromURL(
            const ::rtl::OUString& aURL,
            sal_Int32 nStorageMode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageFromInputStream(
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageFromStream(
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,
            sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static void CopyInputToOutput(
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput,
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutput )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >
        GetInputStreamFromURL(
            const ::rtl::OUString& aURL,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static void SetCommonStoragePassword(
            const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage,
            const ::rtl::OUString& aPass )
        throw ( ::com::sun::star::uno::Exception );

    // the following method supports only storages of OOo formats
    static sal_Int32 GetXStorageFormat(
            const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage )
        throw ( ::com::sun::star::uno::Exception );

    // The followin methods are related to creation of a storage of specified format
    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetTemporaryStorageOfFormat(
            const ::rtl::OUString& aFormat,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageOfFormatFromURL(
            const ::rtl::OUString& aFormat,
            const ::rtl::OUString& aURL,
            sal_Int32 nStorageMode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageOfFormatFromInputStream(
            const ::rtl::OUString& aFormat,
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageOfFormatFromStream(
            const ::rtl::OUString& aFormat,
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,
            sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

};

}

#endif

<commit_msg>INTEGRATION: CWS odfmetadata (1.7.34); FILE MERGED 2008/06/11 16:26:59 mst 1.7.34.1: - comphelper/inc/comphelper/storagehelper.hxx,   comphelper/source/misc/storagehelper.cxx:   + new static methods GetFileSystemStorageFactory, GetStorageFromURL2<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: storagehelper.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _COMPHELPER_STORAGEHELPER_HXX
#define _COMPHELPER_STORAGEHELPER_HXX

#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XStream.hpp>
#include "comphelper/comphelperdllapi.h"

#define PACKAGE_STORAGE_FORMAT_STRING   ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PackageFormat" ) )
#define ZIP_STORAGE_FORMAT_STRING       ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ZipFormat" ) )
#define OFOPXML_STORAGE_FORMAT_STRING   ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "OFOPXMLFormat" ) )

namespace comphelper {

class COMPHELPER_DLLPUBLIC OStorageHelper
{
public:
    static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
        GetStorageFactory(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory >
        GetFileSystemStorageFactory(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xSF
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetTemporaryStorage(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    /// this one will only return Storage
    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageFromURL(
            const ::rtl::OUString& aURL,
            sal_Int32 nStorageMode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    /// this one will return either Storage or FileSystemStorage
    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageFromURL2(
            const ::rtl::OUString& aURL,
            sal_Int32 nStorageMode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )

        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageFromInputStream(
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageFromStream(
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,
            sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static void CopyInputToOutput(
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput,
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& xOutput )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >
        GetInputStreamFromURL(
            const ::rtl::OUString& aURL,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static void SetCommonStoragePassword(
            const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage,
            const ::rtl::OUString& aPass )
        throw ( ::com::sun::star::uno::Exception );

    // the following method supports only storages of OOo formats
    static sal_Int32 GetXStorageFormat(
            const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage )
        throw ( ::com::sun::star::uno::Exception );

    // The followin methods are related to creation of a storage of specified format
    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetTemporaryStorageOfFormat(
            const ::rtl::OUString& aFormat,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageOfFormatFromURL(
            const ::rtl::OUString& aFormat,
            const ::rtl::OUString& aURL,
            sal_Int32 nStorageMode,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageOfFormatFromInputStream(
            const ::rtl::OUString& aFormat,
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XInputStream >& xStream,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

    static ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >
        GetStorageOfFormatFromStream(
            const ::rtl::OUString& aFormat,
            const ::com::sun::star::uno::Reference < ::com::sun::star::io::XStream >& xStream,
            sal_Int32 nStorageMode = ::com::sun::star::embed::ElementModes::READWRITE,
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory
                            = ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >() )
        throw ( ::com::sun::star::uno::Exception );

};

}

#endif

<|endoftext|>