<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_OPTIONAL_INL
#define IOX_HOOFS_CXX_OPTIONAL_INL

#include "iceoryx_hoofs/cxx/attributes.hpp"
#include "iceoryx_hoofs/cxx/optional.hpp"

namespace iox
{
namespace cxx
{
// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const nullopt_t& noVal IOX_MAYBE_UNUSED) noexcept
{
}

// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional() noexcept
    : optional(nullopt_t())
{
}

// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(T&& value) noexcept
{
    construct_value(std::forward<T>(value));
}

// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const T& value) noexcept
{
    construct_value(value);
}

// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const optional& rhs) noexcept
{
    if (rhs.m_hasValue)
    {
        construct_value(rhs.value());
    }
}

// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(optional&& rhs) noexcept
{
    if (rhs.m_hasValue)
    {
        construct_value(std::move(rhs.value()));
        rhs.destruct_value();
    }
}

// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
template <typename... Targs>
// NOLINTNEXTLINE(readability-named-parameter, hicpp-named-parameter) justification in header
inline optional<T>::optional(in_place_t, Targs&&... args) noexcept
{
    construct_value(std::forward<Targs>(args)...);
}

template <typename T>
inline optional<T>& optional<T>::operator=(const optional& rhs) noexcept
{
    if (this != &rhs)
    {
        if (!rhs.m_hasValue && m_hasValue)
        {
            destruct_value();
        }
        else if (rhs.m_hasValue && m_hasValue)
        {
            value() = rhs.value();
        }
        else if (rhs.m_hasValue && !m_hasValue)
        {
            construct_value(rhs.value());
        }
    }
    return *this;
}

template <typename T>
inline optional<T>& optional<T>::operator=(optional&& rhs) noexcept
{
    if (this != &rhs)
    {
        if (!rhs.m_hasValue && m_hasValue)
        {
            destruct_value();
        }
        else if (rhs.m_hasValue && m_hasValue)
        {
            value() = std::move(rhs.value());
        }
        else if (rhs.m_hasValue && !m_hasValue)
        {
            construct_value(std::move(rhs.value()));
        }
        if (rhs.m_hasValue)
        {
            rhs.destruct_value();
        }
    }
    return *this;
}

template <typename T>
inline optional<T>::~optional() noexcept
{
    if (m_hasValue)
    {
        destruct_value();
    }
}

// NOLINTNEXTLINE(cppcoreguidelines-c-copy-assignment-signature) justification in header
template <typename T>
template <typename U>
inline typename std::enable_if<!std::is_same<U, optional<T>&>::value, optional<T>>::type&
optional<T>::operator=(U&& newValue) noexcept
{
    if (m_hasValue)
    {
/// @todo broken msvc compiler, see:
///  https://developercommunity.visualstudio.com/content/problem/858688/stdforward-none-of-these-2-overloads-could-convert.html
/// remove this as soon as it is fixed;
#ifdef _WIN32
        value() = newValue;
#else
        value() = std::forward<T>(newValue);
#endif
    }
    else
    {
/// @todo again broken msvc compiler
#ifdef _WIN32
        construct_value(newValue);
#else
        construct_value(std::forward<T>(newValue));
#endif
    }
    return *this;
}

template <typename T>
constexpr inline bool optional<T>::operator==(const optional<T>& rhs) const noexcept
{
    return (!m_hasValue && !rhs.m_hasValue) || ((m_hasValue && rhs.m_hasValue) && (value() == rhs.value()));
}

template <typename T>
constexpr inline bool optional<T>::operator==(const nullopt_t& rhs IOX_MAYBE_UNUSED) const noexcept
{
    return !m_hasValue;
}

template <typename T>
constexpr inline bool optional<T>::operator!=(const optional<T>& rhs) const noexcept
{
    return !(*this == rhs);
}

template <typename T>
constexpr inline bool optional<T>::operator!=(const nullopt_t& rhs) const noexcept
{
    return !(*this == rhs);
}

template <typename T>
inline const T* optional<T>::operator->() const noexcept
{
    return &value();
}

template <typename T>
inline const T& optional<T>::operator*() const noexcept
{
    return value();
}

template <typename T>
inline T* optional<T>::operator->() noexcept
{
    return &value();
}

template <typename T>
inline T& optional<T>::operator*() noexcept
{
    return value();
}

template <typename T>
inline constexpr optional<T>::operator bool() const noexcept
{
    return m_hasValue;
}

template <typename T>
template <typename... Targs>
inline T& optional<T>::emplace(Targs&&... args) noexcept
{
    if (m_hasValue)
    {
        destruct_value();
    }

    construct_value(std::forward<Targs>(args)...);
    return value();
}

template <typename T>
inline constexpr bool optional<T>::has_value() const noexcept
{
    return m_hasValue;
}

template <typename T>
inline void optional<T>::reset() noexcept
{
    if (m_hasValue)
    {
        destruct_value();
    }
}

template <typename T>
inline T& optional<T>::value() & noexcept
{
    Expects(has_value());
    return *static_cast<T*>(static_cast<void*>(m_data));
}

template <typename T>
inline const T& optional<T>::value() const& noexcept
{
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
    return const_cast<optional<T>*>(this)->value();
}

template <typename T>
inline T&& optional<T>::value() && noexcept
{
    Expects(has_value());
    return std::move(*static_cast<T*>(static_cast<void*>(m_data)));
}

template <typename T>
inline const T&& optional<T>::value() const&& noexcept
{
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
    return std::move(*const_cast<optional<T>*>(this)->value());
}

template <typename T>
template <typename... Targs>
inline void optional<T>::construct_value(Targs&&... args) noexcept
{
    new (static_cast<T*>(static_cast<void*>(m_data))) T(std::forward<Targs>(args)...);
    m_hasValue = true;
}

template <typename T>
inline void optional<T>::destruct_value() noexcept
{
    value().~T();
    m_hasValue = false;
}

template <typename OptionalBaseType, typename... Targs>
inline optional<OptionalBaseType> make_optional(Targs&&... args) noexcept
{
    optional<OptionalBaseType> returnValue = nullopt_t();
    returnValue.emplace(std::forward<Targs>(args)...);
    return returnValue;
}
} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_OPTIONAL_INL
<commit_msg>iox-#1638 Correct access of m_data in optional<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_OPTIONAL_INL
#define IOX_HOOFS_CXX_OPTIONAL_INL

#include "iceoryx_hoofs/cxx/attributes.hpp"
#include "iceoryx_hoofs/cxx/optional.hpp"

namespace iox
{
namespace cxx
{
// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const nullopt_t& noVal IOX_MAYBE_UNUSED) noexcept
{
}

// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional() noexcept
    : optional(nullopt_t())
{
}

// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(T&& value) noexcept
{
    construct_value(std::forward<T>(value));
}

// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const T& value) noexcept
{
    construct_value(value);
}

// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const optional& rhs) noexcept
{
    if (rhs.m_hasValue)
    {
        construct_value(rhs.value());
    }
}

// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(optional&& rhs) noexcept
{
    if (rhs.m_hasValue)
    {
        construct_value(std::move(rhs.value()));
        rhs.destruct_value();
    }
}

// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
template <typename... Targs>
// NOLINTNEXTLINE(readability-named-parameter, hicpp-named-parameter) justification in header
inline optional<T>::optional(in_place_t, Targs&&... args) noexcept
{
    construct_value(std::forward<Targs>(args)...);
}

template <typename T>
inline optional<T>& optional<T>::operator=(const optional& rhs) noexcept
{
    if (this != &rhs)
    {
        if (!rhs.m_hasValue && m_hasValue)
        {
            destruct_value();
        }
        else if (rhs.m_hasValue && m_hasValue)
        {
            value() = rhs.value();
        }
        else if (rhs.m_hasValue && !m_hasValue)
        {
            construct_value(rhs.value());
        }
    }
    return *this;
}

template <typename T>
inline optional<T>& optional<T>::operator=(optional&& rhs) noexcept
{
    if (this != &rhs)
    {
        if (!rhs.m_hasValue && m_hasValue)
        {
            destruct_value();
        }
        else if (rhs.m_hasValue && m_hasValue)
        {
            value() = std::move(rhs.value());
        }
        else if (rhs.m_hasValue && !m_hasValue)
        {
            construct_value(std::move(rhs.value()));
        }
        if (rhs.m_hasValue)
        {
            rhs.destruct_value();
        }
    }
    return *this;
}

template <typename T>
inline optional<T>::~optional() noexcept
{
    if (m_hasValue)
    {
        destruct_value();
    }
}

// NOLINTNEXTLINE(cppcoreguidelines-c-copy-assignment-signature) justification in header
template <typename T>
template <typename U>
inline typename std::enable_if<!std::is_same<U, optional<T>&>::value, optional<T>>::type&
optional<T>::operator=(U&& newValue) noexcept
{
    if (m_hasValue)
    {
/// @todo broken msvc compiler, see:
///  https://developercommunity.visualstudio.com/content/problem/858688/stdforward-none-of-these-2-overloads-could-convert.html
/// remove this as soon as it is fixed;
#ifdef _WIN32
        value() = newValue;
#else
        value() = std::forward<T>(newValue);
#endif
    }
    else
    {
/// @todo again broken msvc compiler
#ifdef _WIN32
        construct_value(newValue);
#else
        construct_value(std::forward<T>(newValue));
#endif
    }
    return *this;
}

template <typename T>
constexpr inline bool optional<T>::operator==(const optional<T>& rhs) const noexcept
{
    return (!m_hasValue && !rhs.m_hasValue) || ((m_hasValue && rhs.m_hasValue) && (value() == rhs.value()));
}

template <typename T>
constexpr inline bool optional<T>::operator==(const nullopt_t& rhs IOX_MAYBE_UNUSED) const noexcept
{
    return !m_hasValue;
}

template <typename T>
constexpr inline bool optional<T>::operator!=(const optional<T>& rhs) const noexcept
{
    return !(*this == rhs);
}

template <typename T>
constexpr inline bool optional<T>::operator!=(const nullopt_t& rhs) const noexcept
{
    return !(*this == rhs);
}

template <typename T>
inline const T* optional<T>::operator->() const noexcept
{
    return &value();
}

template <typename T>
inline const T& optional<T>::operator*() const noexcept
{
    return value();
}

template <typename T>
inline T* optional<T>::operator->() noexcept
{
    return &value();
}

template <typename T>
inline T& optional<T>::operator*() noexcept
{
    return value();
}

template <typename T>
inline constexpr optional<T>::operator bool() const noexcept
{
    return m_hasValue;
}

template <typename T>
template <typename... Targs>
inline T& optional<T>::emplace(Targs&&... args) noexcept
{
    if (m_hasValue)
    {
        destruct_value();
    }

    construct_value(std::forward<Targs>(args)...);
    return value();
}

template <typename T>
inline constexpr bool optional<T>::has_value() const noexcept
{
    return m_hasValue;
}

template <typename T>
inline void optional<T>::reset() noexcept
{
    if (m_hasValue)
    {
        destruct_value();
    }
}

template <typename T>
inline T& optional<T>::value() & noexcept
{
    Expects(has_value());
    return *static_cast<T*>(static_cast<void*>(&m_data));
}

template <typename T>
inline const T& optional<T>::value() const& noexcept
{
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
    return const_cast<optional<T>*>(this)->value();
}

template <typename T>
inline T&& optional<T>::value() && noexcept
{
    Expects(has_value());
    return std::move(*static_cast<T*>(static_cast<void*>(&m_data)));
}

template <typename T>
inline const T&& optional<T>::value() const&& noexcept
{
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
    return std::move(*const_cast<optional<T>*>(this)->value());
}

template <typename T>
template <typename... Targs>
inline void optional<T>::construct_value(Targs&&... args) noexcept
{
    new (static_cast<T*>(static_cast<void*>(&m_data))) T(std::forward<Targs>(args)...);
    m_hasValue = true;
}

template <typename T>
inline void optional<T>::destruct_value() noexcept
{
    value().~T();
    m_hasValue = false;
}

template <typename OptionalBaseType, typename... Targs>
inline optional<OptionalBaseType> make_optional(Targs&&... args) noexcept
{
    optional<OptionalBaseType> returnValue = nullopt_t();
    returnValue.emplace(std::forward<Targs>(args)...);
    return returnValue;
}
} // namespace cxx
} // namespace iox

#endif // IOX_HOOFS_CXX_OPTIONAL_INL
<|endoftext|>


<commit_before>#include <stdio.h>

#include <spikehw.h>

SpikeHw *spikeHw;

int main(int argc, const char **argv)
{
    spikeHw = new SpikeHw();
    // not needed yet
    //spikeHw->setupDma(memfd);

    // query mmcm and interrupt status
    spikeHw->status();

    // read boot rom
    uint32_t firstword;
    spikeHw->read(0x000000 + 0x000, (uint8_t *)&firstword);
    fprintf(stderr, "First word of boot ROM %08x (expected %08x)\n", firstword, 0x00001137);

    // read ethernet identification register
    uint32_t id;
    spikeHw->read(0x180000 + 0x4f8, (uint8_t *)&id);
    fprintf(stderr, "AXI Ethernet Identification %08x (expected %08x)\n", id, 0x09000000);

    // put flash in query mode
    spikeHw->setFlashParameters(50); // divides clock by 50
    uint32_t values[4] = { 0x98 };
    spikeHw->writeFlash(0x00aa, (uint8_t *)&values[0]);
    spikeHw->readFlash(0x0020, (uint8_t *)&values[1]);
    spikeHw->readFlash(0x0022, (uint8_t *)&values[2]);
    spikeHw->readFlash(0x0024, (uint8_t *)&values[3]);
    fprintf(stderr, "Query flash %02x.%02x.%02x %c%c%c (expected QRY)\n", values[1], values[2], values[3], values[1], values[2], values[3]);

    return 0;
}
<commit_msg>read and verify 8 32-bit words of boot ROM<commit_after>#include <stdio.h>

#include <spikehw.h>

SpikeHw *spikeHw;

int main(int argc, const char **argv)
{
    spikeHw = new SpikeHw();
    // not needed yet
    //spikeHw->setupDma(memfd);

    // query mmcm and interrupt status
    spikeHw->status();

    // read boot rom
    uint32_t word = 0;
    uint32_t expected[] = {
	0x00001137,
	0x010000ef,
	0x20000513,
	0x00050067,
	0x0000006f,
	0x040007b7,
	0x40078793,
	0xfc0005b7
    };
    for (int i = 0; i < 8; i++){
	spikeHw->read(0x000000 + i*4, (uint8_t *)&word);
	fprintf(stderr, "word %04x of boot ROM %08x (expected %08x)\n", i*4, word, expected[i]);
    }

    // read ethernet identification register
    uint32_t id;
    spikeHw->read(0x180000 + 0x4f8, (uint8_t *)&id);
    fprintf(stderr, "AXI Ethernet Identification %08x (expected %08x)\n", id, 0x09000000);

    // put flash in query mode
    spikeHw->setFlashParameters(50); // divides clock by 50
    uint32_t values[4] = { 0x98 };
    spikeHw->writeFlash(0x00aa, (uint8_t *)&values[0]);
    spikeHw->readFlash(0x0020, (uint8_t *)&values[1]);
    spikeHw->readFlash(0x0022, (uint8_t *)&values[2]);
    spikeHw->readFlash(0x0024, (uint8_t *)&values[3]);
    fprintf(stderr, "Query flash %02x.%02x.%02x %c%c%c (expected QRY)\n", values[1], values[2], values[3], values[1], values[2], values[3]);

    return 0;
}
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include "colormap_editor.h"
#include "ui_colormap_editor.h"
#include "PlotJuggler/svg_util.h"
#include <QSettings>
#include <QInputDialog>
#include <QMessageBox>
#include "stylesheet.h"
#include "color_map.h"

ColorMapEditor::ColorMapEditor(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::colormap_editor)
{
  ui->setupUi(this);

  QSettings settings;

  ui->functionText->setHighlighter( new QLuaHighlighter );
  ui->functionText->setCompleter(new QLuaCompleter);

  auto theme = settings.value("StyleSheet::theme", "light").toString();
  on_stylesheetChanged(theme);

  for(const auto& it: ColorMapLibrary())
  {
    ui->listWidget->addItem(it.first);
  }
}

ColorMapEditor::~ColorMapEditor()
{
  SaveColorMapToSettings();
  delete ui;
}

void ColorMapEditor::on_stylesheetChanged(QString theme)
{
  ui->buttonDelete->setIcon(LoadSvg(":/resources/svg/trash.svg", theme));
  ui->functionText->setSyntaxStyle( GetLuaSyntaxStyle(theme) );
}

void ColorMapEditor::on_buttonSave_clicked()
{
  bool ok;

  auto colormap = std::make_shared<ColorMap>();

  auto res = colormap->setScrip(ui->functionText->toPlainText());
  if (!res.valid())
  {
    QMessageBox::warning(this, "Error in the Lua Script", colormap->getError(res), QMessageBox::Cancel);
    return;
  }

  QString default_name;
  auto selected = ui->listWidget->selectedItems();
  if( selected.size() == 1 )
  {
    default_name = selected.front()->text();
  }

  QString name = QInputDialog::getText(this, tr("ColorMap Name"),
                                       tr("Name of the function:"), QLineEdit::Normal,
                                       default_name, &ok);
  if (!ok || name.isEmpty())
  {
    return;
  }
  bool overwrite = false;

  if( !ui->listWidget->findItems(name, Qt::MatchExactly).empty() )
  {
    auto reply = QMessageBox::question(this, "Confirm overwrite",
                                       "A ColorMap with the same name exist already. "
                                       "Do you want to ovewrite it?",
                                       QMessageBox::Yes|QMessageBox::No);
    if (reply == QMessageBox::No)
    {
      return;
    }
    overwrite = true;
  }

  ColorMapLibrary()[name] = colormap;

  if( !overwrite )
  {
    ui->listWidget->addItem(name);
    selectRow(ui->listWidget->count() - 1);
  }
}

void ColorMapEditor::on_buttonDelete_clicked()
{
  for(auto item: ui->listWidget->selectedItems())
  {
    auto it = ColorMapLibrary().find(item->text());
    if( it != ColorMapLibrary().end() )
    {
      if( !it->second->script().isEmpty() )
      {
        auto reply = QMessageBox::question(this, "Delete ColorMap", "Are you sure?",
                                           QMessageBox::Yes|QMessageBox::No);
        if (reply == QMessageBox::No)
        {
          return;
        }
      }
      ColorMapLibrary().erase( it );
    }
    delete ui->listWidget->takeItem( ui->listWidget->row( item ) );
  }
}

void ColorMapEditor::selectRow(int row)
{
  ui->listWidget->clearSelection();
  ui->listWidget->selectionModel()->setCurrentIndex(ui->listWidget->model()->index(row,0),
                                                    QItemSelectionModel::SelectionFlag::Select );
}

void ColorMapEditor::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
  auto it = ColorMapLibrary().find(item->text());
  if( it != ColorMapLibrary().end() )
  {
    auto colormap = it->second;
    ui->functionText->setText( colormap->script() );
  }
}
<commit_msg>Fix typo in ColorMap warning (#693)<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#include "colormap_editor.h"
#include "ui_colormap_editor.h"
#include "PlotJuggler/svg_util.h"
#include <QSettings>
#include <QInputDialog>
#include <QMessageBox>
#include "stylesheet.h"
#include "color_map.h"

ColorMapEditor::ColorMapEditor(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::colormap_editor)
{
  ui->setupUi(this);

  QSettings settings;

  ui->functionText->setHighlighter( new QLuaHighlighter );
  ui->functionText->setCompleter(new QLuaCompleter);

  auto theme = settings.value("StyleSheet::theme", "light").toString();
  on_stylesheetChanged(theme);

  for(const auto& it: ColorMapLibrary())
  {
    ui->listWidget->addItem(it.first);
  }
}

ColorMapEditor::~ColorMapEditor()
{
  SaveColorMapToSettings();
  delete ui;
}

void ColorMapEditor::on_stylesheetChanged(QString theme)
{
  ui->buttonDelete->setIcon(LoadSvg(":/resources/svg/trash.svg", theme));
  ui->functionText->setSyntaxStyle( GetLuaSyntaxStyle(theme) );
}

void ColorMapEditor::on_buttonSave_clicked()
{
  bool ok;

  auto colormap = std::make_shared<ColorMap>();

  auto res = colormap->setScrip(ui->functionText->toPlainText());
  if (!res.valid())
  {
    QMessageBox::warning(this, "Error in the Lua Script", colormap->getError(res), QMessageBox::Cancel);
    return;
  }

  QString default_name;
  auto selected = ui->listWidget->selectedItems();
  if( selected.size() == 1 )
  {
    default_name = selected.front()->text();
  }

  QString name = QInputDialog::getText(this, tr("ColorMap Name"),
                                       tr("Name of the function:"), QLineEdit::Normal,
                                       default_name, &ok);
  if (!ok || name.isEmpty())
  {
    return;
  }
  bool overwrite = false;

  if( !ui->listWidget->findItems(name, Qt::MatchExactly).empty() )
  {
    auto reply = QMessageBox::question(this, "Confirm overwrite",
                                       "A ColorMap with the same name exist already. "
                                       "Do you want to overwrite it?",
                                       QMessageBox::Yes|QMessageBox::No);
    if (reply == QMessageBox::No)
    {
      return;
    }
    overwrite = true;
  }

  ColorMapLibrary()[name] = colormap;

  if( !overwrite )
  {
    ui->listWidget->addItem(name);
    selectRow(ui->listWidget->count() - 1);
  }
}

void ColorMapEditor::on_buttonDelete_clicked()
{
  for(auto item: ui->listWidget->selectedItems())
  {
    auto it = ColorMapLibrary().find(item->text());
    if( it != ColorMapLibrary().end() )
    {
      if( !it->second->script().isEmpty() )
      {
        auto reply = QMessageBox::question(this, "Delete ColorMap", "Are you sure?",
                                           QMessageBox::Yes|QMessageBox::No);
        if (reply == QMessageBox::No)
        {
          return;
        }
      }
      ColorMapLibrary().erase( it );
    }
    delete ui->listWidget->takeItem( ui->listWidget->row( item ) );
  }
}

void ColorMapEditor::selectRow(int row)
{
  ui->listWidget->clearSelection();
  ui->listWidget->selectionModel()->setCurrentIndex(ui->listWidget->model()->index(row,0),
                                                    QItemSelectionModel::SelectionFlag::Select );
}

void ColorMapEditor::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
  auto it = ColorMapLibrary().find(item->text());
  if( it != ColorMapLibrary().end() )
  {
    auto colormap = it->second;
    ui->functionText->setText( colormap->script() );
  }
}
<|endoftext|>


<commit_before>// http://redd.it/29od55
// Challenge 169-Intermediate - Home-row Spell Check
// Usage: aliensp
//    Spell check and correct alien input.
//    aliensp < file.in
// Built using g++: g++ -std=c++0x -Wall -o alien_trans chal169.cpp
//
#include <iostream>

#include "alien_translator.h"
#include "string_utils.h"

int main() {

    //  For each word, check if it's a real word as opposed to gooblygook. If
    //  it's a real word, print it. Otherwise try to guess what the word could
    //  be and print the guesses. If there are no guesses, then print the
    //  original gooblygook.

    Alien_translator translator;

    std::istream_iterator<std::string> word_iter(std::cin);
    std::istream_iterator<std::string> end_iter;

    for(; word_iter != end_iter; ++word_iter) {
        std::string word = string_utils::remove_punctuation(*word_iter);

        if(translator.is_gooblygook(word)) {
            auto guesses = translator.guess(word);
            if(guesses.size() > 0)
                std::cout << '{' << string_utils::fmt_as_list(guesses) << "} ";
            else
                std::cout << word << ' ';
        }
        else
            std::cout << word << ' ';
    }

    return 0;
}
<commit_msg>Correct usage comment<commit_after>// http://redd.it/29od55
// Challenge 169-Intermediate - Home-row Spell Check
// Usage: alien_trans
//    Spell check and correct alien input.
//    alien_trans < file.in
// Built using g++: g++ -std=c++0x -Wall -o alien_trans chal169.cpp
//
#include <iostream>

#include "alien_translator.h"
#include "string_utils.h"

int main() {

    //  For each word, check if it's a real word as opposed to gooblygook. If
    //  it's a real word, print it. Otherwise try to guess what the word could
    //  be and print the guesses. If there are no guesses, then print the
    //  original gooblygook.

    Alien_translator translator;

    std::istream_iterator<std::string> word_iter(std::cin);
    std::istream_iterator<std::string> end_iter;

    for(; word_iter != end_iter; ++word_iter) {
        std::string word = string_utils::remove_punctuation(*word_iter);

        if(translator.is_gooblygook(word)) {
            auto guesses = translator.guess(word);
            if(guesses.size() > 0)
                std::cout << '{' << string_utils::fmt_as_list(guesses) << "} ";
            else
                std::cout << word << ' ';
        }
        else
            std::cout << word << ' ';
    }

    return 0;
}
<|endoftext|>


<commit_before>

#include <pcap.h>
#include <stdio.h>
#include <poll.h>

#include <vector>
#include <queue>
#include <algorithm>

#include <slankdev/util.h>
#include <slankdev/ncurses.h>
#include <slankdev/exception.h>
#include <slankdev/net/protocol.h>

class Packet {
public:
    uint8_t buf[2000];
    size_t   len;
    uint64_t time;
    size_t   number;

    Packet(const void* p, size_t l, uint64_t t, size_t n) :
        len(l), time(t), number(n)
    {
        memcpy(buf, p, len);
    }
    std::string line()
    {
        using namespace slankdev;
        std::string source;
        std::string dest;
        std::string proto;

        ether* eth = reinterpret_cast<ether*>(buf);

        char str[1000];
        sprintf(str, "%5zd %-13ld %-20s %-20s %6s %5zd %-10s" , number, time,
                eth->src.to_string().c_str(),
                eth->dst.to_string().c_str(),
                "protocol", len, "summry");
        return str;
    }
};

class pane {
protected:
    size_t current_x;
    size_t current_y;
    slankdev::ncurses& screen;
public:
    const size_t x;
    const size_t y;
    const size_t w;
    const size_t h;
    pane(size_t ix, size_t iy, size_t iw, size_t ih, slankdev::ncurses& scr) :
        x(ix), y(iy), w(iw), h(ih), current_x(ix), current_y(iy), screen(scr) {}
    template <class... Arg>
    void println(const char* fmt, Arg... arg)
    {
        screen.mvprintw(current_y++, current_x, fmt, arg...);
        current_x = x;
    }
    template <class... Arg>
    void println_hl(const char* fmt, Arg... arg)
    {
        attron(A_REVERSE);
        screen.mvprintw(current_y++, current_x, fmt, arg...);
        current_x = x;
        attroff(A_REVERSE);
    }
    template <class... Arg>
    void print(const char* fmt, Arg... arg)
    {
        char str[1000];
        sprintf(str, fmt, arg...);
        size_t len = strlen(str);
        screen.mvprintw(current_y, current_x+=len, fmt, arg...);
    }
    void putc(char c)
    {
        if (c == '\n') {
            current_y ++ ;
            current_x = x;
        } else {
            screen.mvprintw(current_y, current_x++, "%c", c);
        }
    }
};

class Pane_list : public pane {
    ssize_t cursor_index;
    size_t  list_start_index;
public:
    std::vector<Packet> packets;
    ssize_t get_cursor() { return cursor_index; }
    void dec_cursor()
    {
        if (cursor_index-1 < list_start_index) scroll_up();
        if (get_cursor()-1 >= 0) cursor_index--;
    }
    void inc_cursor()
    {
        if (cursor_index+1-list_start_index >= h) scroll_down();
        if (get_cursor()+1 < packets.size()) cursor_index++;
    }
    void scroll_up()   { list_start_index --; }
    void scroll_down() { list_start_index ++; }
    Pane_list(size_t ix, size_t iy, size_t iw, size_t ih,
            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr),
            cursor_index(0), list_start_index(0) {}
    void push_packet(const void* packet, struct pcap_pkthdr* hdr)
    {
        static int number = 0;
        packets.emplace_back(packet, hdr->len, hdr->ts.tv_sec, number++);
    }
    void refresh()
    {
        current_x = x;
        current_y = y;
        println("%-5s %-13s %-20s %-20s %-6s %-5s %-10s",
                "No.", "Time", "Source", "Destination",
                "Protocol", "Len", "Info");

        size_t start_idx = list_start_index;
        for (size_t i=start_idx, c=0; i<packets.size() && c<h; i++, c++) {
            if (i == get_cursor())
                println_hl(packets[i].line().c_str());
            else
                println(packets[i].line().c_str());
        }
    }
};

class Pane_detail : public pane {
public:
    Pane_detail(size_t ix, size_t iy, size_t iw, size_t ih,
            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
    void print_packet_detail(Packet* packet)
    {
        current_x = x;
        current_y = y;
        println("Packet Detail");
        println(" + number : %zd ", packet->number);
        println(" + pointer: %p", packet->buf);
        println(" + length : %zd", packet->len);
        println(" + time   : %ld", packet->time);
    }
    void refresh() {}
};

class Pane_binary : public pane {
    ssize_t cursor_index;
    size_t  list_start_index;
public:
    std::vector<std::string> lines;

    ssize_t get_cursor() { return cursor_index; }
    void dec_cursor()
    {
        if (cursor_index-1 < list_start_index) scroll_up();
        if (get_cursor()-1 >= 0) cursor_index--;
    }
    void inc_cursor()
    {
        if (cursor_index+1-list_start_index >= h) scroll_down();
        if (get_cursor()+1 < lines.size()) cursor_index++;
    }
    void scroll_up()   { list_start_index --; }
    void scroll_down() { list_start_index ++; }

    Pane_binary(size_t ix, size_t iy, size_t iw, size_t ih,
            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
    void hex(Packet* packet)
    {
        lines.clear();

        const void* buffer = packet->buf;
        size_t bufferlen   = packet->len;
        char str[1000];

        const uint8_t *data = reinterpret_cast<const uint8_t*>(buffer);
        size_t row = 0;
        std::string line;
        while (bufferlen > 0) {
            line.clear();

            sprintf(str, " %04zx:   ", row);
            line += str;

            size_t n;
            if (bufferlen < 16) n = bufferlen;
            else                n = 16;

            for (size_t i = 0; i < n; i++) {
                if (i == 8) { line += " "; }
                sprintf(str, " %02x", data[i]);
                line += str;
            }
            for (size_t i = n; i < 16; i++) { line += "   "; }
            line += "   ";
            for (size_t i = 0; i < n; i++) {
                if (i == 8) { line += "  "; }
                uint8_t c = data[i];
                if (!(0x20 <= c && c <= 0x7e)) c = '.';
                sprintf(str, "%c", c);
                line += str;
            }
            println("");
            lines.push_back(line);
            bufferlen -= n;
            data += n;
            row  += n;
        }
    }
    void refresh()
    {
        current_x = x;
        current_y = y;
        for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {
            if (i == get_cursor())
                println_hl("%s", lines[i].c_str());
            else
                println("%s", lines[i].c_str());
        }
        for (size_t i=0; i<h-lines.size(); i++) {
            for (size_t c=0; c<w; c++) print(" ");
            println("");
        }
    }
};

enum cursor_state {
    LIST,
    DETAIL,
    BINARY,
};

class Statusline {
    const size_t x;
    const size_t y;
    const size_t w;
    const cursor_state& state;
public:
    Statusline(size_t ix, size_t iy, size_t iw, cursor_state& c)
        : x(ix), y(iy), w(iw), state(c) {}
    const char* state2str(cursor_state s)
    {
        switch (s) {
            case LIST:   return "LIST   ";
            case DETAIL: return "DETAIL ";
            case BINARY: return "BINARY ";
            default :    return "UNKNOWN";
        }
    }
    void refresh()
    {
        mvprintw(y, x, "[CUISHARK] pane=%s", state2str(state));
    }
};

size_t a(size_t h) { return (h-1) % 3; }
size_t m(size_t h) { return ((h-1)-((h-1)%3))/3; }
#define H screen.geth()

class display {
    slankdev::ncurses screen;
    pcap_t *handle;
    cursor_state cstate;
public:
    Pane_list   pane_list;
    Pane_detail pane_detail;
    Pane_binary pane_binary;
    Statusline statusline;

    display() :
        cstate(LIST),
        pane_list  (0, 0          , screen.getw(), a(H)+m(H), screen),
        pane_detail(0, a(H)+m(H)  , screen.getw(), m(H)     , screen),
        pane_binary(0, a(H)+2*m(H), screen.getw(), m(H)     , screen),
        statusline (0, a(H)+3*m(H), screen.getw(), cstate)
    {
        char errbuf[PCAP_ERRBUF_SIZE];
        handle = pcap_open_live("lo", BUFSIZ, 0, 0, errbuf);
        // handle = pcap_open_offline("in.pcap", errbuf);
        if (handle == NULL) {
            throw slankdev::exception("pcap_open_live");
        }
        noecho();
        screen.refresh();
    }
    ~display() { pcap_close(handle); }
    void charnge_cstate()
    {
        switch (cstate) {
            case LIST:
                cstate = DETAIL;
                break;
            case DETAIL:
                cstate = BINARY;
                break;
            case BINARY:
                cstate = LIST;
                break;
            default :
                throw slankdev::exception("UNKNOWN state");
                break;
        }
    }
    void press_j()
    {
        switch (cstate) {
            case LIST:
                pane_list.inc_cursor();
                break;
            case DETAIL:
                break;
            case BINARY:
                pane_binary.inc_cursor();
                break;
            defaut:
                throw slankdev::exception("UNknown state");
                break;

        }
    }
    void press_k()
    {
        switch (cstate) {
            case LIST:
                pane_list.dec_cursor();
                break;
            case DETAIL:
                break;
            case BINARY:
                pane_binary.dec_cursor();
                break;
            defaut:
                throw slankdev::exception("UNknown state");
                break;

        }
    }
    void press_enter()
    {
        switch (cstate) {
            case LIST:
            {
                if (pane_list.packets.empty()) return;
                Packet* pack = &pane_list.packets[pane_list.get_cursor()];
                pane_detail.print_packet_detail(pack);
                pane_binary.hex(pack);
                break;
            }
            case DETAIL:
                break;
            case BINARY:
                break;
            defaut:
                throw slankdev::exception("UNknown state");
                break;

        }
    }
    void view_help()
    {
        size_t x = 0;
        size_t y = 0;
        screen.mvprintw(y++, x, "                                                    ");
        screen.mvprintw(y++, x, "    CuiShark version 0.0                            ");
        screen.mvprintw(y++, x, "    Copyright 2017-2020 Hiroki SHIROKURA.           ");
        screen.mvprintw(y++, x, "                                                    ");
        screen.mvprintw(y++, x, "    Avalable Keyboard commands are below.           ");
        screen.mvprintw(y++, x, "    These are Vi-like key-bind because I'm vimmer.  ");
        screen.mvprintw(y++, x, "                                                    ");
        screen.mvprintw(y++, x, "    Commands                                        ");
        screen.mvprintw(y++, x, "    j      :  down                                  ");
        screen.mvprintw(y++, x, "    k      :  up                                    ");
        screen.mvprintw(y++, x, "    tab    :  switch pane                           ");
        screen.mvprintw(y++, x, "    enter  :  select                                ");
        screen.mvprintw(y++, x, "    ?      :  view help                             ");
        screen.mvprintw(y++, x, "    C-c    :  exit                                  ");
        screen.mvprintw(y++, x, "                                                    ");
        screen.getchar();
    }
    void dispatch()
    {
        struct pollfd fds[2];
        fds[0].fd = pcap_get_selectable_fd(handle);
        fds[0].events = POLLIN;
        fds[1].fd = fileno(stdin);
        fds[1].events = POLLIN;
        while (1) {
            if (poll(fds, 2, 100)) {

                if (fds[0].revents & POLLIN) {
                    struct pcap_pkthdr header;
                    const u_char *packet;
                    packet = pcap_next(handle, &header);
                    pane_list.push_packet(packet, &header);
                }

                if (fds[1].revents & POLLIN) {
                    int c = screen.getchar();
                    switch (c) {
                        case 'j':
                            press_j();
                            break;
                        case 'k':
                            press_k();
                            break;
                        case '\t':
                            charnge_cstate();
                            break;
                        case '\n':
                            press_enter();
                            break;
                        case '?':
                            view_help();
                            break;
                    }
                }
            }
            refresh();
        }
    }
    void refresh()
    {
        pane_list.refresh();
        pane_detail.refresh();
        pane_binary.refresh();
        statusline.refresh();
        screen.refresh();
    }
};

int main(int argc, char *argv[])
{
    display dsp0;
    dsp0.dispatch();
}

<commit_msg>Support: scroll on detail-pane<commit_after>

#include <pcap.h>
#include <stdio.h>
#include <poll.h>

#include <vector>
#include <queue>
#include <algorithm>

#include <slankdev/util.h>
#include <slankdev/ncurses.h>
#include <slankdev/exception.h>
#include <slankdev/net/protocol.h>

class Packet {
public:
    uint8_t buf[2000];
    size_t   len;
    uint64_t time;
    size_t   number;

    Packet(const void* p, size_t l, uint64_t t, size_t n) :
        len(l), time(t), number(n)
    {
        memcpy(buf, p, len);
    }
    std::string line()
    {
        using namespace slankdev;
        std::string source;
        std::string dest;
        std::string proto;

        ether* eth = reinterpret_cast<ether*>(buf);

        char str[1000];
        sprintf(str, "%5zd %-13ld %-20s %-20s %6s %5zd %-10s" , number, time,
                eth->src.to_string().c_str(),
                eth->dst.to_string().c_str(),
                "protocol", len, "summry");
        return str;
    }
};

class pane {
protected:
    size_t current_x;
    size_t current_y;
    slankdev::ncurses& screen;
public:
    const size_t x;
    const size_t y;
    const size_t w;
    const size_t h;
    pane(size_t ix, size_t iy, size_t iw, size_t ih, slankdev::ncurses& scr) :
        x(ix), y(iy), w(iw), h(ih), current_x(ix), current_y(iy), screen(scr) {}
    template <class... Arg>
    void println(const char* fmt, Arg... arg)
    {
        screen.mvprintw(current_y++, current_x, fmt, arg...);
        current_x = x;
    }
    template <class... Arg>
    void println_hl(const char* fmt, Arg... arg)
    {
        attron(A_REVERSE);
        screen.mvprintw(current_y++, current_x, fmt, arg...);
        current_x = x;
        attroff(A_REVERSE);
    }
    template <class... Arg>
    void print(const char* fmt, Arg... arg)
    {
        char str[1000];
        sprintf(str, fmt, arg...);
        size_t len = strlen(str);
        screen.mvprintw(current_y, current_x+=len, fmt, arg...);
    }
    void putc(char c)
    {
        if (c == '\n') {
            current_y ++ ;
            current_x = x;
        } else {
            screen.mvprintw(current_y, current_x++, "%c", c);
        }
    }
};

class Pane_list : public pane {
    ssize_t cursor_index;
    size_t  list_start_index;
public:
    std::vector<Packet> packets;
    ssize_t get_cursor() { return cursor_index; }
    void dec_cursor()
    {
        if (cursor_index-1 < list_start_index) scroll_up();
        if (get_cursor()-1 >= 0) cursor_index--;
    }
    void inc_cursor()
    {
        if (cursor_index+1-list_start_index >= h) scroll_down();
        if (get_cursor()+1 < packets.size()) cursor_index++;
    }
    void scroll_up()   { list_start_index --; }
    void scroll_down() { list_start_index ++; }
    Pane_list(size_t ix, size_t iy, size_t iw, size_t ih,
            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr),
            cursor_index(0), list_start_index(0) {}
    void push_packet(const void* packet, struct pcap_pkthdr* hdr)
    {
        static int number = 0;
        packets.emplace_back(packet, hdr->len, hdr->ts.tv_sec, number++);
    }
    void refresh()
    {
        current_x = x;
        current_y = y;
        println("%-5s %-13s %-20s %-20s %-6s %-5s %-10s",
                "No.", "Time", "Source", "Destination",
                "Protocol", "Len", "Info");

        size_t start_idx = list_start_index;
        for (size_t i=start_idx, c=0; i<packets.size() && c<h; i++, c++) {
            if (i == get_cursor())
                println_hl(packets[i].line().c_str());
            else
                println(packets[i].line().c_str());
        }
    }
};

class Pane_detail : public pane {
    ssize_t cursor_index;
    size_t  list_start_index;
public:
    std::vector<std::string> lines;

    ssize_t get_cursor() { return cursor_index; }
    void dec_cursor()
    {
        if (cursor_index-1 < list_start_index) scroll_up();
        if (get_cursor()-1 >= 0) cursor_index--;
    }
    void inc_cursor()
    {
        if (cursor_index+1-list_start_index >= h) scroll_down();
        if (get_cursor()+1 < lines.size()) cursor_index++;
    }
    void scroll_up()   { list_start_index --; }
    void scroll_down() { list_start_index ++; }

    Pane_detail(size_t ix, size_t iy, size_t iw, size_t ih,
            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
    void print_packet_detail(Packet* packet)
    {
        char str[1000];
        sprintf(str, "Packet Detail");
        lines.push_back(str);
        sprintf(str, " + number : %zd ", packet->number);
        lines.push_back(str);
        sprintf(str, " + pointer: %p", packet->buf);
        lines.push_back(str);
        sprintf(str, " + length : %zd", packet->len);
        lines.push_back(str);
        sprintf(str, " + time   : %ld", packet->time);
        lines.push_back(str);
    }
    void refresh()
    {
        current_x = x;
        current_y = y;
        println("Detail pane");
        for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {
            if (i == get_cursor())
                println_hl("%s", lines[i].c_str());
            else
                println("%s", lines[i].c_str());
        }
        for (size_t i=0; i<h-lines.size(); i++) {
            for (size_t c=0; c<w; c++) print(" ");
            println("");
        }
    }
};

class Pane_binary : public pane {
    ssize_t cursor_index;
    size_t  list_start_index;
public:
    std::vector<std::string> lines;

    ssize_t get_cursor() { return cursor_index; }
    void dec_cursor()
    {
        if (cursor_index-1 < list_start_index) scroll_up();
        if (get_cursor()-1 >= 0) cursor_index--;
    }
    void inc_cursor()
    {
        if (cursor_index+1-list_start_index >= h) scroll_down();
        if (get_cursor()+1 < lines.size()) cursor_index++;
    }
    void scroll_up()   { list_start_index --; }
    void scroll_down() { list_start_index ++; }

    Pane_binary(size_t ix, size_t iy, size_t iw, size_t ih,
            slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
    void hex(Packet* packet)
    {
        lines.clear();

        const void* buffer = packet->buf;
        size_t bufferlen   = packet->len;
        char str[1000];

        const uint8_t *data = reinterpret_cast<const uint8_t*>(buffer);
        size_t row = 0;
        std::string line;
        while (bufferlen > 0) {
            line.clear();

            sprintf(str, " %04zx:   ", row);
            line += str;

            size_t n;
            if (bufferlen < 16) n = bufferlen;
            else                n = 16;

            for (size_t i = 0; i < n; i++) {
                if (i == 8) { line += " "; }
                sprintf(str, " %02x", data[i]);
                line += str;
            }
            for (size_t i = n; i < 16; i++) { line += "   "; }
            line += "   ";
            for (size_t i = 0; i < n; i++) {
                if (i == 8) { line += "  "; }
                uint8_t c = data[i];
                if (!(0x20 <= c && c <= 0x7e)) c = '.';
                sprintf(str, "%c", c);
                line += str;
            }
            println("");
            lines.push_back(line);
            bufferlen -= n;
            data += n;
            row  += n;
        }
    }
    void refresh()
    {
        current_x = x;
        current_y = y;
        for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {
            if (i == get_cursor())
                println_hl("%s", lines[i].c_str());
            else
                println("%s", lines[i].c_str());
        }
        for (size_t i=0; i<h-lines.size(); i++) {
            for (size_t c=0; c<w; c++) print(" ");
            println("");
        }
    }
};

enum cursor_state {
    LIST,
    DETAIL,
    BINARY,
};

class Statusline {
    const size_t x;
    const size_t y;
    const size_t w;
    const cursor_state& state;
public:
    Statusline(size_t ix, size_t iy, size_t iw, cursor_state& c)
        : x(ix), y(iy), w(iw), state(c) {}
    const char* state2str(cursor_state s)
    {
        switch (s) {
            case LIST:   return "LIST   ";
            case DETAIL: return "DETAIL ";
            case BINARY: return "BINARY ";
            default :    return "UNKNOWN";
        }
    }
    void refresh()
    {
        mvprintw(y, x, "[CUISHARK] pane=%s", state2str(state));
    }
};

size_t a(size_t h) { return (h-1) % 3; }
size_t m(size_t h) { return ((h-1)-((h-1)%3))/3; }
#define H screen.geth()

class display {
    slankdev::ncurses screen;
    pcap_t *handle;
    cursor_state cstate;
public:
    Pane_list   pane_list;
    Pane_detail pane_detail;
    Pane_binary pane_binary;
    Statusline statusline;

    display() :
        cstate(LIST),
        pane_list  (0, 0          , screen.getw(), a(H)+m(H), screen),
        pane_detail(0, a(H)+m(H)  , screen.getw(), m(H)     , screen),
        pane_binary(0, a(H)+2*m(H), screen.getw(), m(H)     , screen),
        statusline (0, a(H)+3*m(H), screen.getw(), cstate)
    {
        char errbuf[PCAP_ERRBUF_SIZE];
        handle = pcap_open_live("lo", BUFSIZ, 0, 0, errbuf);
        // handle = pcap_open_offline("in.pcap", errbuf);
        if (handle == NULL) {
            throw slankdev::exception("pcap_open_live");
        }
        noecho();
        screen.refresh();
    }
    ~display() { pcap_close(handle); }
    void charnge_cstate()
    {
        switch (cstate) {
            case LIST  : cstate = DETAIL; break;
            case DETAIL: cstate = BINARY; break;
            case BINARY: cstate = LIST  ; break;
            default : throw slankdev::exception("UNKNOWN state");
        }
    }
    void press_j()
    {
        switch (cstate) {
            case LIST  : pane_list.inc_cursor()  ; break;
            case DETAIL: pane_detail.inc_cursor(); break;
            case BINARY: pane_binary.inc_cursor(); break;
            defaut: throw slankdev::exception("UNknown state");
        }
    }
    void press_k()
    {
        switch (cstate) {
            case LIST  : pane_list.dec_cursor()  ; break;
            case DETAIL: pane_detail.dec_cursor(); break;
            case BINARY: pane_binary.dec_cursor(); break;
            defaut: throw slankdev::exception("UNknown state");
        }
    }
    void press_enter()
    {
        switch (cstate) {
            case LIST:
            {
                if (pane_list.packets.empty()) return;
                Packet* pack = &pane_list.packets[pane_list.get_cursor()];
                pane_detail.print_packet_detail(pack);
                pane_binary.hex(pack);
                break;
            }
            case DETAIL:
                break;
            case BINARY:
                break;
            defaut:
                throw slankdev::exception("UNknown state");
                break;

        }
    }
    void view_help()
    {
        size_t x = 0;
        size_t y = 0;
        screen.mvprintw(y++, x, "                                                    ");
        screen.mvprintw(y++, x, "    CuiShark version 0.0                            ");
        screen.mvprintw(y++, x, "    Copyright 2017-2020 Hiroki SHIROKURA.           ");
        screen.mvprintw(y++, x, "                                                    ");
        screen.mvprintw(y++, x, "    Avalable Keyboard commands are below.           ");
        screen.mvprintw(y++, x, "    These are Vi-like key-bind because I'm vimmer.  ");
        screen.mvprintw(y++, x, "                                                    ");
        screen.mvprintw(y++, x, "    Commands                                        ");
        screen.mvprintw(y++, x, "    j      :  down                                  ");
        screen.mvprintw(y++, x, "    k      :  up                                    ");
        screen.mvprintw(y++, x, "    tab    :  switch pane                           ");
        screen.mvprintw(y++, x, "    enter  :  select                                ");
        screen.mvprintw(y++, x, "    ?      :  view help                             ");
        screen.mvprintw(y++, x, "    C-c    :  exit                                  ");
        screen.mvprintw(y++, x, "                                                    ");
        screen.getchar();
    }
    void dispatch()
    {
        struct pollfd fds[2];
        fds[0].fd = pcap_get_selectable_fd(handle);
        fds[0].events = POLLIN;
        fds[1].fd = fileno(stdin);
        fds[1].events = POLLIN;
        while (1) {
            if (poll(fds, 2, 100)) {

                if (fds[0].revents & POLLIN) {
                    struct pcap_pkthdr header;
                    const u_char *packet;
                    packet = pcap_next(handle, &header);
                    pane_list.push_packet(packet, &header);
                }

                if (fds[1].revents & POLLIN) {
                    int c = screen.getchar();
                    switch (c) {
                        case 'j':
                            press_j();
                            break;
                        case 'k':
                            press_k();
                            break;
                        case '\t':
                            charnge_cstate();
                            break;
                        case '\n':
                            press_enter();
                            break;
                        case '?':
                            view_help();
                            break;
                    }
                }
            }
            refresh();
        }
    }
    void refresh()
    {
        pane_list.refresh();
        pane_detail.refresh();
        pane_binary.refresh();
        statusline.refresh();
        screen.refresh();
    }
};

int main(int argc, char *argv[])
{
    display dsp0;
    dsp0.dispatch();
}

<|endoftext|>


<commit_before>#include <cstdlib>

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

#include "fasta_parser.h"
#include "sa_is.h"

struct suffix {
  unsigned int index;
  std::string suffix_string;
};

bool compare(suffix i, suffix j) {
  return i.suffix_string < j.suffix_string ;
}

// Creates a sufix array for the given string using a simple and slow method
void suffix_array(std::string str, std::vector<int> &sa) {
  std::vector<suffix> suffixes;

  for (unsigned int i = 0; i < str.size(); ++i) {
    suffix *s = new suffix;
    s->index = i;
    s->suffix_string = str.substr(i);
    suffixes.push_back(*s);
    delete s;
  }

  std::sort(suffixes.begin(), suffixes.end(), compare);
  for (unsigned int i = 0; i < suffixes.size(); ++i) {
    sa.push_back(suffixes[i].index);
  }
}

int main(int argc, char *argv[]) {

  if(argc != 5) {
    std::cerr << "Usage: " << argv[1] << " <file containing reference string>" << std::endl;
		std::cerr << "Usage: " << argv[2] << " <file containing query string>" << std::endl;
		std::cerr << "Usage: " << argv[3] << " <index level of sparseSA, K-SA>" << std::endl;
		std::cerr << "Usage: " << argv[4] << " <size of minimal match>" << std::endl;

    exit(-1);
  }

  std::ifstream ref_file(argv[1]);
	std::ifstream query_file(argv[2]);

  if(!ref_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[1] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

  if(!query_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[2] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

	std::string ref_string;
	std::vector<string> refdescr;
	std::vector<long> startpos;

	fasta_parser(argv[1], ref_string, refdescr, startpos);

	std::int K = atoi(argv[3]);
  std::int L = atoi(argv[4]);
  std::int N = ref_string;

	std::string query_string;
  std::getline(query_file, query_string);
  std::cout << "Query: " << query_string << std::endl;

  std::vector<int> sa;
  sa.reserve(ref_string.size());
  bool *types = new bool[ref_string.size()];

  suffix_array(ref_string, sa);
  type_array(ref_string.c_str(), types, ref_string.size(), sizeof(char));

  for (unsigned int i = 0; i < sa.size(); ++i) {
    std::cout << "[" << i << "]\t" << sa[i] << (types[sa[i]] ? "\tS\t" : "\tL\t")
    << ref_string.substr(sa[i]) << std::endl;
  }

  int *SA = new int[N];
  int *sparseSA = new int[N / K];
  int *ISA = new int[N];

  // Creates Suffix Array using SA_IS algorithm
  sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));

  // Create
  // Creates Invese SA
  for ( int i = 0; i < N; ++i) {;}

  for (int i = 0; i < N); ++i) {
    printf("%d ", SA[i]);
    if (SA[i] != sa[i]) {
      std::cout << "<-!!! ";
    }
  }
  printf("\n");

  return 0;
}
<commit_msg>ISA, LCP, SSA<commit_after>#include <cstdlib>

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

#include "fasta_parser.h"
#include "sa_is.h"

struct suffix {
  unsigned int index;
  std::string suffix_string;
};

bool compare(suffix i, suffix j) {
  return i.suffix_string < j.suffix_string ;
}

// Creates a sufix array for the given string using a simple and slow method
void suffix_array(std::string str, std::vector<int> &sa) {
  std::vector<suffix> suffixes;

  for (unsigned int i = 0; i < str.size(); ++i) {
    suffix *s = new suffix;
    s->index = i;
    s->suffix_string = str.substr(i);
    suffixes.push_back(*s);
    delete s;
  }

  std::sort(suffixes.begin(), suffixes.end(), compare);
  for (unsigned int i = 0; i < suffixes.size(); ++i) {
    sa.push_back(suffixes[i].index);
  }
}

int main(int argc, char *argv[]) {

  if(argc != 5) {
    std::cerr << "Usage: " << argv[1] << " <file containing reference string>" << std::endl;
		std::cerr << "Usage: " << argv[2] << " <file containing query string>" << std::endl;
		std::cerr << "Usage: " << argv[3] << " <index level of sparseSA, K-SA>" << std::endl;
		std::cerr << "Usage: " << argv[4] << " <size of minimal match>" << std::endl;

    exit(-1);
  }

  std::ifstream ref_file(argv[1]);
	std::ifstream query_file(argv[2]);

  if(!ref_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[1] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

  if(!query_file.is_open()) {
    std::cerr << "There was a problem openning the file \"" << argv[2] << "\"!\nAborting." << std::endl;
    exit(-2);
  }

	std::string ref_string;
	std::vector<string> refdescr;
	std::vector<long> startpos;

	fasta_parser(argv[1], ref_string, refdescr, startpos);

	int K = atoi(argv[3]);
  int L = atoi(argv[4]);
  int N = ref_string.length();

	std::string query_string;
  std::getline(query_file, query_string);
  std::cout << "Query: " << query_string << std::endl;

  std::vector<int> sa;
  sa.reserve(ref_string.size());
  bool *types = new bool[ref_string.size()];

  suffix_array(ref_string, sa);
  type_array(ref_string.c_str(), types, ref_string.size(), sizeof(char));

  for (unsigned int i = 0; i < sa.size(); ++i) {
    std::cout << "[" << i << "]\t" << sa[i] << (types[sa[i]] ? "\tS\t" : "\tL\t")
    << ref_string.substr(sa[i]) << std::endl;
  }

  int *SA = new int[N];
  int *sparseSA = new int[N / K];
  int *ISA = new int[N];
  int *LCP = new int[N / K];

  // Creates Suffix Array using SA_IS algorithm
  sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));

  // Generate Sparse Suffix Array
  for (int i = 0; i < N / K; ++i) {
    sparseSA[i] = SA[i * K];
  }

  // Generate ISA
  for(long i = 0; i < N/K; i++) {
    ISA[SA[i]/K] = i;
  }

  int h = 0;
  for(int i = 0; i < N; i+=K) {
    int m = ISA[i/K];
    if(m==0) {
      LCP[m] = 0;
    }
    else {
      int j = SA[m-1];
      while(i+h < N && j+h < N && ref_string[i+h] == ref_string[j+h]) {
        h++;
      }
      LCP[m] = h;
    }
    h = std::max(0, h - K);
  }

  for (int i = 0; i < N; ++i) {
    printf("%d ", SA[i]);
    if (SA[i] != sa[i]) {
      std::cout << "<-!!! ";
    }
  }
  printf("\n");

  return 0;
}
<|endoftext|>


<commit_before>#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdbool.h>
#include <new>

typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
typedef uintptr_t size_t;
typedef unsigned int uint;

extern "C" void start64() __attribute__((noreturn));

#define STRING_INL_LINKAGE static
#include "string.c"

#define S_(X) #X
#define S(X) S_(X)
#define assert(X) \
	do { if (!(X)) { assert_failed(__FILE__ ":" S(__LINE__), #X); } } while (0)

namespace {

void assert_failed(const char* file, const char* line, const char* msg) __attribute__((noreturn));

static const intptr_t kernel_base = -(1 << 30);

static constexpr void* PhysAddr(uintptr_t phys) {
	return (void*)(phys + kernel_base);
}

static void memset16(u16* dest, u16 value, size_t n) {
	if (/* constant(value) && */ (value >> 8) == (value & 0xff)) {
		memset(dest, value, n * 2);
	} else {
		// rep movsw
		while (n--) *dest++ = value;
	}
}

namespace Console {
	static u16* const buffer = (u16*)PhysAddr(0xb80a0);
	static u16 pos;
	static const u8 width = 80, height = 24;

	void clear() {
		pos = 0;
		memset16(buffer, 0, width * height);
	}

	void write(char c) {
		if (c == '\n') {
			u8 fill = width - (pos % width);
			while(fill--) write(' ');
		} else {
			buffer[pos++] = 0x0700 | c;
		}
	}

	void write(const char *s) {
		while (char c = *s++) write(c);
	}
};

void assert_failed(const char* fileline, const char* msg) {
	using Console::write;
	write(fileline); write(": ASSERT FAILED: "); write(msg);
	for(;;);
}

} // namespace

using Console::write;

void start64() {
	write("Hello world\n");
	assert(!"Testing the assert");
	for(;;);
}
<commit_msg>Add support for qemu/bochs debug console<commit_after>#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdbool.h>
#include <new>

typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
typedef uintptr_t size_t;
typedef unsigned int uint;

extern "C" void start64() __attribute__((noreturn));

#define DEBUGCON 1

#define STRING_INL_LINKAGE static
#include "string.c"

#define S_(X) #X
#define S(X) S_(X)
#define assert(X) \
	do { if (!(X)) { assert_failed(__FILE__ ":" S(__LINE__), #X "\n"); } } while (0)

namespace {

void assert_failed(const char* file, const char* line, const char* msg) __attribute__((noreturn));

static const intptr_t kernel_base = -(1 << 30);

static constexpr void* PhysAddr(uintptr_t phys) {
	return (void*)(phys + kernel_base);
}

static void memset16(u16* dest, u16 value, size_t n) {
	if (/* constant(value) && */ (value >> 8) == (value & 0xff)) {
		memset(dest, value, n * 2);
	} else {
		// rep movsw
		while (n--) *dest++ = value;
	}
}

static void debugcon_putc(char c) {
#if DEBUGCON
	asm("outb %0,%1"::"a"(c),"d"((u16)0xe9));
#endif
}

namespace Console {
	static u16* const buffer = (u16*)PhysAddr(0xb80a0);
	static u16 pos;
	static const u8 width = 80, height = 24;

	void clear() {
		pos = 0;
		memset16(buffer, 0, width * height);
	}

	void write(char c) {
		if (c == '\n') {
			u8 fill = width - (pos % width);
			while(fill--) buffer[pos++] = 0;
		} else {
			buffer[pos++] = 0x0700 | c;
		}
		debugcon_putc(c);
	}

	void write(const char *s) {
		while (char c = *s++) write(c);
	}
};

void assert_failed(const char* fileline, const char* msg) {
	using Console::write;
	write(fileline); write(": ASSERT FAILED: "); write(msg);
	for(;;);
}

} // namespace

using Console::write;

void start64() {
	write("Hello world\n");
	assert(!"Testing the assert");
	for(;;);
}
<|endoftext|>


<commit_before>#include <GL/glew.h>
#define GLM_SWIZZLE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "SDL.h"
#undef main
#include <list>
#include <algorithm>
#include <functional>

#include "RenderingContext.h"
#include "scene/GraphNode.h"
#include "scene/Skybox.h"
#include "scene/Terrain.h"
#include "scene/Mech.h"
#include "animations/Animation.h"

static SDL_Window *win;
static SDL_GLContext context;
bool conf_enable_msaa;

GraphNode *scene = NULL;
RenderingContext *rc;
std::list<Animation*> animations;
int move_forward = 0;

class TestSceneRotation : public Animation
{
private:
	GraphNode* subject;

public:
	TestSceneRotation(GraphNode* subject) : subject(subject)
	{
		rotation = 0;
		y = 0;
	};

	virtual void update(float timestep)
	{
		glm::vec4 cam_pos =
			subject->getWorldCoordinates(
				glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) *
				glm::vec4(0.0f, y, 3.0f, 1.0f));
		rc->setCamera(cam_pos.xyz(), subject);
		while (rotation > 360.0f) rotation -= 360.0f;
	};

	float y;
	float rotation;
} *scene_rot;

class MechWalk : public Animation
{
private:
	Mech* subject;
	Terrain* terrain;
	float leg_bend;
	int leg_state;

public:
	MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain)
	{
		leg_state = 0;
		leg_bend = 90.0f;
	};

	virtual void update(float timestep)
	{
		if (move_forward) {
			subject->bendLeg(0, 35.0f + leg_bend);
			subject->bendLeg(1, 95.0f - leg_bend);
			subject->bendLeg(2, 35.0f + leg_bend);
			subject->bendLeg(3, 95.0f - leg_bend);
			if (leg_state) {
				leg_bend--;
				if (leg_bend <= 0.0f) leg_state = 0;
			} else {
				leg_bend++;
				if (leg_bend >= 60.0f) leg_state = 1;
			}
		}

		glm::vec4 current_pos = subject->getWorldCoordinates();
		current_pos.z += move_forward * timestep;
		glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z) + subject->getDistanceToGround(), current_pos.z);
		subject->setPosition(new_pos.x, new_pos.y, new_pos.z);

	}
};

void reshape(int width, int height)
{
	glViewport(0, 0, (GLint) width, (GLint) height);
	rc->reshape(width, height);
}

/// Sets up rendering and creates the initial scene graph.
void init_scene()
{
	static GLfloat pos[4] =
	{3000.0, 1000.0, -3000.0, 0.0};
	glLightfv(GL_LIGHT0, GL_POSITION, pos);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_TEXTURE_2D);
	//glEnable(GL_MULTISAMPLE);

	scene = new GraphNode;
	scene->addMember(new Skybox);

	Mech *mech = new Mech();
	scene->addMember(mech);
	//mech->setVisibility(false);

	Terrain *terrain = new Terrain("textures/heightmap.bmp", 20.0f);
	scene->addMember(terrain);

	rc = new RenderingContext(scene);
	rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech);

	scene_rot = new TestSceneRotation(mech);
	animations.push_back(scene_rot);
	animations.push_back(new MechWalk(mech, terrain));
}

/// Sets up a new frame and renders the scene.
void draw_scene()
{
	rc->update();
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
		puts((const char*)gluErrorString(error));

	glFlush();
	SDL_GL_SwapWindow(win);
}

/// Updates scene state
void update_scene(float timestep)
{
	std::for_each(
			animations.begin(),
			animations.end(),
			std::bind2nd(std::mem_fun(&Animation::update), timestep));
}

int main(int argc, char const *argv[])
{
#ifdef WIN32
	conf_enable_msaa = true;
#else
	conf_enable_msaa = false;
#endif

	while(*++argv) {
		if (!strcmp(*argv, "--enable-msaa"))
			conf_enable_msaa = true;
		else if (!strcmp(*argv, "--disable-msaa"))
			conf_enable_msaa = false;
	}

	Uint8 *keys;
	int w = 800, h = 600;

	printf("Hello!\n");

	if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1;

	// Set up an OpenGL window
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);

	if (conf_enable_msaa) {
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	}

	win = SDL_CreateWindow("Mech",
			SDL_WINDOWPOS_CENTERED,
			SDL_WINDOWPOS_CENTERED,
			w, h,
			SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

	if ( ! win ) {
		puts(SDL_GetError());
		SDL_Quit();
		exit(2);
	}

	context = SDL_GL_CreateContext(win);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		printf("glewInit error: %s\n", glewGetErrorString(err));
	}
	printf("Using GLEW %s\n", glewGetString(GLEW_VERSION));

	printf("OpenGL version: %s\n", glGetString(GL_VERSION));
	init_scene();
	reshape(w, h);

	Uint32 previous_ticks = SDL_GetTicks();
	Uint32 fps_prev_t = previous_ticks, frames = 0;

	int done = 0;
	SDL_Event event;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			switch(event.type) {
				case SDL_WINDOWEVENT:
					if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
						w = event.window.data1;
						h = event.window.data2;
						reshape(w,h);
					}
					break;

				case SDL_MOUSEMOTION:
					scene_rot->y = 4.0f * (float)(event.motion.y) / (float)(h) - 2.0f;
					scene_rot->rotation = -360.0f * (float)(event.motion.x) / (float)(w);
					break;

				case SDL_QUIT:
					done = 1;
					break;
			}
		}
		keys = SDL_GetKeyboardState(NULL);

		if (keys[SDL_SCANCODE_ESCAPE]) {
			done = 1;
		}

		if (keys[SDL_SCANCODE_W])
			move_forward = 1;
		else if (keys[SDL_SCANCODE_S])
			move_forward = -1;
		else
			move_forward = 0;

		// update
		Uint32 t = SDL_GetTicks();
		update_scene((float)(t - previous_ticks) / 1000.0f);
		previous_ticks = t;

		// count FPS
		frames++;
		if (fps_prev_t + 5000 < t) {
			printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f));
			fps_prev_t = t;
			frames = 0;
		}

		// render
		draw_scene();
	}
	SDL_Quit();
	delete scene;
	return 0;
}
<commit_msg>Change the beginning of the walk animation.<commit_after>#include <GL/glew.h>
#define GLM_SWIZZLE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "SDL.h"
#undef main
#include <list>
#include <algorithm>
#include <functional>

#include "RenderingContext.h"
#include "scene/GraphNode.h"
#include "scene/Skybox.h"
#include "scene/Terrain.h"
#include "scene/Mech.h"
#include "animations/Animation.h"

static SDL_Window *win;
static SDL_GLContext context;
bool conf_enable_msaa;

GraphNode *scene = NULL;
RenderingContext *rc;
std::list<Animation*> animations;
int move_forward = 0;

class TestSceneRotation : public Animation
{
private:
	GraphNode* subject;

public:
	TestSceneRotation(GraphNode* subject) : subject(subject)
	{
		rotation = 0;
		y = 0;
	};

	virtual void update(float timestep)
	{
		glm::vec4 cam_pos =
			subject->getWorldCoordinates(
				glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) *
				glm::vec4(0.0f, y, 3.0f, 1.0f));
		rc->setCamera(cam_pos.xyz(), subject);
		while (rotation > 360.0f) rotation -= 360.0f;
	};

	float y;
	float rotation;
} *scene_rot;

class MechWalk : public Animation
{
private:
	Mech* subject;
	Terrain* terrain;
	float leg_bend;
	int leg_state;

public:
	MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain)
	{
		leg_state = 0;
		leg_bend = 30.0f;
	};

	virtual void update(float timestep)
	{
		subject->bendLeg(0, 35.0f + leg_bend);
		subject->bendLeg(1, 95.0f - leg_bend);
		subject->bendLeg(2, 35.0f + leg_bend);
		subject->bendLeg(3, 95.0f - leg_bend);

		if (move_forward) {
			if (leg_state) {
				leg_bend--;
				if (leg_bend <= 0.0f) leg_state = 0;
			} else {
				leg_bend++;
				if (leg_bend >= 60.0f) leg_state = 1;
			}
		} else {
			leg_state = 0;
			leg_bend = 30.0f;
		}

		glm::vec4 current_pos = subject->getWorldCoordinates();
		current_pos.z += move_forward * timestep;
		glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z) + subject->getDistanceToGround(), current_pos.z);
		subject->setPosition(new_pos.x, new_pos.y, new_pos.z);

	}
};

void reshape(int width, int height)
{
	glViewport(0, 0, (GLint) width, (GLint) height);
	rc->reshape(width, height);
}

/// Sets up rendering and creates the initial scene graph.
void init_scene()
{
	static GLfloat pos[4] =
	{3000.0, 1000.0, -3000.0, 0.0};
	glLightfv(GL_LIGHT0, GL_POSITION, pos);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
	glEnable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_TEXTURE_2D);
	//glEnable(GL_MULTISAMPLE);

	scene = new GraphNode;
	scene->addMember(new Skybox);

	Mech *mech = new Mech();
	scene->addMember(mech);
	//mech->setVisibility(false);

	Terrain *terrain = new Terrain("textures/heightmap.bmp", 20.0f);
	scene->addMember(terrain);

	rc = new RenderingContext(scene);
	rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech);

	scene_rot = new TestSceneRotation(mech);
	animations.push_back(scene_rot);
	animations.push_back(new MechWalk(mech, terrain));
}

/// Sets up a new frame and renders the scene.
void draw_scene()
{
	rc->update();
	GLenum error = glGetError();
	if (error != GL_NO_ERROR)
		puts((const char*)gluErrorString(error));

	glFlush();
	SDL_GL_SwapWindow(win);
}

/// Updates scene state
void update_scene(float timestep)
{
	std::for_each(
			animations.begin(),
			animations.end(),
			std::bind2nd(std::mem_fun(&Animation::update), timestep));
}

int main(int argc, char const *argv[])
{
#ifdef WIN32
	conf_enable_msaa = true;
#else
	conf_enable_msaa = false;
#endif

	while(*++argv) {
		if (!strcmp(*argv, "--enable-msaa"))
			conf_enable_msaa = true;
		else if (!strcmp(*argv, "--disable-msaa"))
			conf_enable_msaa = false;
	}

	Uint8 *keys;
	int w = 800, h = 600;

	printf("Hello!\n");

	if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1;

	// Set up an OpenGL window
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);

	if (conf_enable_msaa) {
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	}

	win = SDL_CreateWindow("Mech",
			SDL_WINDOWPOS_CENTERED,
			SDL_WINDOWPOS_CENTERED,
			w, h,
			SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

	if ( ! win ) {
		puts(SDL_GetError());
		SDL_Quit();
		exit(2);
	}

	context = SDL_GL_CreateContext(win);

	GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		printf("glewInit error: %s\n", glewGetErrorString(err));
	}
	printf("Using GLEW %s\n", glewGetString(GLEW_VERSION));

	printf("OpenGL version: %s\n", glGetString(GL_VERSION));
	init_scene();
	reshape(w, h);

	Uint32 previous_ticks = SDL_GetTicks();
	Uint32 fps_prev_t = previous_ticks, frames = 0;

	int done = 0;
	SDL_Event event;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			switch(event.type) {
				case SDL_WINDOWEVENT:
					if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
						w = event.window.data1;
						h = event.window.data2;
						reshape(w,h);
					}
					break;

				case SDL_MOUSEMOTION:
					scene_rot->y = 4.0f * (float)(event.motion.y) / (float)(h) - 2.0f;
					scene_rot->rotation = -360.0f * (float)(event.motion.x) / (float)(w);
					break;

				case SDL_QUIT:
					done = 1;
					break;
			}
		}
		keys = SDL_GetKeyboardState(NULL);

		if (keys[SDL_SCANCODE_ESCAPE]) {
			done = 1;
		}

		if (keys[SDL_SCANCODE_W])
			move_forward = 1;
		else if (keys[SDL_SCANCODE_S])
			move_forward = -1;
		else
			move_forward = 0;

		// update
		Uint32 t = SDL_GetTicks();
		update_scene((float)(t - previous_ticks) / 1000.0f);
		previous_ticks = t;

		// count FPS
		frames++;
		if (fps_prev_t + 5000 < t) {
			printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f));
			fps_prev_t = t;
			frames = 0;
		}

		// render
		draw_scene();
	}
	SDL_Quit();
	delete scene;
	return 0;
}
<|endoftext|>


<commit_before>/** @file
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

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

  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 "slice.h"

#include "Config.h"
#include "Data.h"
#include "HttpHeader.h"
#include "intercept.h"

#include "ts/remap.h"
#include "ts/ts.h"

#include <netinet/in.h>

namespace
{
Config globalConfig;

bool
read_request(TSHttpTxn txnp, Config *const config)
{
  DEBUG_LOG("slice read_request");
  TxnHdrMgr hdrmgr;
  hdrmgr.populateFrom(txnp, TSHttpTxnClientReqGet);
  HttpHeader const header(hdrmgr.m_buffer, hdrmgr.m_lochdr);

  if (TS_HTTP_METHOD_GET == header.method()) {
    static int const SLICER_MIME_LEN_INFO = strlen(SLICER_MIME_FIELD_INFO);
    if (!header.hasKey(SLICER_MIME_FIELD_INFO, SLICER_MIME_LEN_INFO)) {
      // turn off any and all transaction caching (shouldn't matter)
      TSHttpTxnServerRespNoStoreSet(txnp, 1);
      TSHttpTxnRespCacheableSet(txnp, 0);
      TSHttpTxnReqCacheableSet(txnp, 0);

      DEBUG_LOG("slice accepting and slicing");
      // connection back into ATS
      sockaddr const *const ip = TSHttpTxnClientAddrGet(txnp);
      if (nullptr == ip) {
        return false;
      }

      TSAssert(nullptr != config);
      Data *const data = new Data(config);

      // set up feedback connect
      if (AF_INET == ip->sa_family) {
        memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in));
      } else if (AF_INET6 == ip->sa_family) {
        memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in6));
      } else {
        delete data;
        return false;
      }

      // need to reset the HOST field for global plugin
      data->m_hostlen = sizeof(data->m_hostname) - 1;
      if (!header.valueForKey(TS_MIME_FIELD_HOST, TS_MIME_LEN_HOST, data->m_hostname, &data->m_hostlen)) {
        DEBUG_LOG("Unable to get hostname from header");
        delete data;
        return false;
      }

      // is the plugin configured to use a remap host?
      std::string const &newhost = config->m_remaphost;
      if (newhost.empty()) {
        TSMBuffer urlbuf;
        TSMLoc urlloc;
        TSReturnCode rcode = TSHttpTxnPristineUrlGet(txnp, &urlbuf, &urlloc);

        if (TS_SUCCESS == rcode) {
          TSMBuffer const newbuf = TSMBufferCreate();
          TSMLoc newloc          = nullptr;
          rcode                  = TSUrlClone(newbuf, urlbuf, urlloc, &newloc);
          TSHandleMLocRelease(urlbuf, TS_NULL_MLOC, urlloc);

          if (TS_SUCCESS != rcode) {
            ERROR_LOG("Error cloning pristine url");
            TSMBufferDestroy(newbuf);
            delete data;
            return false;
          }

          data->m_urlbuf = newbuf;
          data->m_urlloc = newloc;
        }
      } else { // grab the effective url, swap out the host and zero the port
        int len            = 0;
        char *const effstr = TSHttpTxnEffectiveUrlStringGet(txnp, &len);

        if (nullptr != effstr) {
          TSMBuffer const newbuf = TSMBufferCreate();
          TSMLoc newloc          = nullptr;
          bool okay              = false;

          if (TS_SUCCESS == TSUrlCreate(newbuf, &newloc)) {
            char const *start = effstr;
            if (TS_PARSE_DONE == TSUrlParse(newbuf, newloc, &start, start + len)) {
              if (TS_SUCCESS == TSUrlHostSet(newbuf, newloc, newhost.c_str(), newhost.size()) &&
                  TS_SUCCESS == TSUrlPortSet(newbuf, newloc, 0)) {
                okay = true;
              }
            }
          }

          TSfree(effstr);

          if (!okay) {
            ERROR_LOG("Error cloning effective url");
            if (nullptr != newloc) {
              TSHandleMLocRelease(newbuf, nullptr, newloc);
            }
            TSMBufferDestroy(newbuf);
            delete data;
            return false;
          }

          data->m_urlbuf = newbuf;
          data->m_urlloc = newloc;
        }
      }

      if (TSIsDebugTagSet(PLUGIN_NAME)) {
        int len            = 0;
        char *const urlstr = TSUrlStringGet(data->m_urlbuf, data->m_urlloc, &len);
        DEBUG_LOG("slice url: %.*s", len, urlstr);
        TSfree(urlstr);
      }

      // we'll intercept this GET and do it ourselves
      TSCont const icontp(TSContCreate(intercept_hook, TSMutexCreate()));
      TSContDataSet(icontp, (void *)data);
      TSHttpTxnIntercept(icontp, txnp);
      return true;
    } else {
      DEBUG_LOG("slice passing GET request through to next plugin");
    }
  }

  return false;
}

int
global_read_request_hook(TSCont // contp
                         ,
                         TSEvent // event
                         ,
                         void *edata)
{
  TSHttpTxn const txnp = static_cast<TSHttpTxn>(edata);
  read_request(txnp, &globalConfig);
  TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
  return 0;
}

} // namespace

///// remap plugin engine

SLICE_EXPORT
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri)
{
  Config *const config = static_cast<Config *>(ih);

  if (read_request(txnp, config)) {
    return TSREMAP_DID_REMAP_STOP;
  } else {
    return TSREMAP_NO_REMAP;
  }
}

///// remap plugin setup and teardown
SLICE_EXPORT
void
TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type)
{
}

SLICE_EXPORT
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int /* errbuf_size */)
{
  Config *const config = new Config;
  if (2 < argc) {
    config->fromArgs(argc - 2, argv + 2);
  }
  *ih = static_cast<void *>(config);
  return TS_SUCCESS;
}

SLICE_EXPORT
void
TSRemapDeleteInstance(void *ih)
{
  if (nullptr != ih) {
    Config *const config = static_cast<Config *>(ih);
    delete config;
  }
}

SLICE_EXPORT
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbug, int errbuf_size)
{
  DEBUG_LOG("slice remap is successfully initialized.");
  return TS_SUCCESS;
}

///// global plugin
SLICE_EXPORT
void
TSPluginInit(int argc, char const *argv[])
{
  TSPluginRegistrationInfo info;
  info.plugin_name   = (char *)PLUGIN_NAME;
  info.vendor_name   = (char *)"Apache Software Foundation";
  info.support_email = (char *)"dev@trafficserver.apache.org";

  if (TS_SUCCESS != TSPluginRegister(&info)) {
    ERROR_LOG("Plugin registration failed.\n");
    ERROR_LOG("Unable to initialize plugin (disabled).");
    return;
  }

  if (1 < argc) {
    globalConfig.fromArgs(argc - 1, argv + 1);
  }

  TSCont const contp(TSContCreate(global_read_request_hook, nullptr));

  // Called immediately after the request header is read from the client
  TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
}
<commit_msg>if transaction status nonzero, bypass the slice plugin (#6417)<commit_after>/** @file
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

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

  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 "slice.h"

#include "Config.h"
#include "Data.h"
#include "HttpHeader.h"
#include "intercept.h"

#include "ts/remap.h"
#include "ts/ts.h"

#include <netinet/in.h>

namespace
{
Config globalConfig;

bool
read_request(TSHttpTxn txnp, Config *const config)
{
  DEBUG_LOG("slice read_request");
  TxnHdrMgr hdrmgr;
  hdrmgr.populateFrom(txnp, TSHttpTxnClientReqGet);
  HttpHeader const header(hdrmgr.m_buffer, hdrmgr.m_lochdr);

  if (TS_HTTP_METHOD_GET == header.method()) {
    static int const SLICER_MIME_LEN_INFO = strlen(SLICER_MIME_FIELD_INFO);
    if (!header.hasKey(SLICER_MIME_FIELD_INFO, SLICER_MIME_LEN_INFO)) {
      // check if any previous plugin has monkeyed with the transaction status
      TSHttpStatus const txnstat = TSHttpTxnStatusGet(txnp);
      if (0 != (int)txnstat) {
        DEBUG_LOG("slice: txn status change detected (%d), skipping plugin\n", (int)txnstat);
        return false;
      }

      // turn off any and all transaction caching (shouldn't matter)
      TSHttpTxnServerRespNoStoreSet(txnp, 1);
      TSHttpTxnRespCacheableSet(txnp, 0);
      TSHttpTxnReqCacheableSet(txnp, 0);

      DEBUG_LOG("slice accepting and slicing");
      // connection back into ATS
      sockaddr const *const ip = TSHttpTxnClientAddrGet(txnp);
      if (nullptr == ip) {
        return false;
      }

      TSAssert(nullptr != config);
      Data *const data = new Data(config);

      // set up feedback connect
      if (AF_INET == ip->sa_family) {
        memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in));
      } else if (AF_INET6 == ip->sa_family) {
        memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in6));
      } else {
        delete data;
        return false;
      }

      // need to reset the HOST field for global plugin
      data->m_hostlen = sizeof(data->m_hostname) - 1;
      if (!header.valueForKey(TS_MIME_FIELD_HOST, TS_MIME_LEN_HOST, data->m_hostname, &data->m_hostlen)) {
        DEBUG_LOG("Unable to get hostname from header");
        delete data;
        return false;
      }

      // is the plugin configured to use a remap host?
      std::string const &newhost = config->m_remaphost;
      if (newhost.empty()) {
        TSMBuffer urlbuf;
        TSMLoc urlloc;
        TSReturnCode rcode = TSHttpTxnPristineUrlGet(txnp, &urlbuf, &urlloc);

        if (TS_SUCCESS == rcode) {
          TSMBuffer const newbuf = TSMBufferCreate();
          TSMLoc newloc          = nullptr;
          rcode                  = TSUrlClone(newbuf, urlbuf, urlloc, &newloc);
          TSHandleMLocRelease(urlbuf, TS_NULL_MLOC, urlloc);

          if (TS_SUCCESS != rcode) {
            ERROR_LOG("Error cloning pristine url");
            TSMBufferDestroy(newbuf);
            delete data;
            return false;
          }

          data->m_urlbuf = newbuf;
          data->m_urlloc = newloc;
        }
      } else { // grab the effective url, swap out the host and zero the port
        int len            = 0;
        char *const effstr = TSHttpTxnEffectiveUrlStringGet(txnp, &len);

        if (nullptr != effstr) {
          TSMBuffer const newbuf = TSMBufferCreate();
          TSMLoc newloc          = nullptr;
          bool okay              = false;

          if (TS_SUCCESS == TSUrlCreate(newbuf, &newloc)) {
            char const *start = effstr;
            if (TS_PARSE_DONE == TSUrlParse(newbuf, newloc, &start, start + len)) {
              if (TS_SUCCESS == TSUrlHostSet(newbuf, newloc, newhost.c_str(), newhost.size()) &&
                  TS_SUCCESS == TSUrlPortSet(newbuf, newloc, 0)) {
                okay = true;
              }
            }
          }

          TSfree(effstr);

          if (!okay) {
            ERROR_LOG("Error cloning effective url");
            if (nullptr != newloc) {
              TSHandleMLocRelease(newbuf, nullptr, newloc);
            }
            TSMBufferDestroy(newbuf);
            delete data;
            return false;
          }

          data->m_urlbuf = newbuf;
          data->m_urlloc = newloc;
        }
      }

      if (TSIsDebugTagSet(PLUGIN_NAME)) {
        int len            = 0;
        char *const urlstr = TSUrlStringGet(data->m_urlbuf, data->m_urlloc, &len);
        DEBUG_LOG("slice url: %.*s", len, urlstr);
        TSfree(urlstr);
      }

      // we'll intercept this GET and do it ourselves
      TSCont const icontp(TSContCreate(intercept_hook, TSMutexCreate()));
      TSContDataSet(icontp, (void *)data);
      TSHttpTxnIntercept(icontp, txnp);
      return true;
    } else {
      DEBUG_LOG("slice passing GET request through to next plugin");
    }
  }

  return false;
}

int
global_read_request_hook(TSCont // contp
                         ,
                         TSEvent // event
                         ,
                         void *edata)
{
  TSHttpTxn const txnp = static_cast<TSHttpTxn>(edata);
  read_request(txnp, &globalConfig);
  TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
  return 0;
}

} // namespace

///// remap plugin engine

SLICE_EXPORT
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri)
{
  Config *const config = static_cast<Config *>(ih);

  if (read_request(txnp, config)) {
    return TSREMAP_DID_REMAP_STOP;
  } else {
    return TSREMAP_NO_REMAP;
  }
}

///// remap plugin setup and teardown
SLICE_EXPORT
void
TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type)
{
}

SLICE_EXPORT
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int /* errbuf_size */)
{
  Config *const config = new Config;
  if (2 < argc) {
    config->fromArgs(argc - 2, argv + 2);
  }
  *ih = static_cast<void *>(config);
  return TS_SUCCESS;
}

SLICE_EXPORT
void
TSRemapDeleteInstance(void *ih)
{
  if (nullptr != ih) {
    Config *const config = static_cast<Config *>(ih);
    delete config;
  }
}

SLICE_EXPORT
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbug, int errbuf_size)
{
  DEBUG_LOG("slice remap is successfully initialized.");
  return TS_SUCCESS;
}

///// global plugin
SLICE_EXPORT
void
TSPluginInit(int argc, char const *argv[])
{
  TSPluginRegistrationInfo info;
  info.plugin_name   = (char *)PLUGIN_NAME;
  info.vendor_name   = (char *)"Apache Software Foundation";
  info.support_email = (char *)"dev@trafficserver.apache.org";

  if (TS_SUCCESS != TSPluginRegister(&info)) {
    ERROR_LOG("Plugin registration failed.\n");
    ERROR_LOG("Unable to initialize plugin (disabled).");
    return;
  }

  if (1 < argc) {
    globalConfig.fromArgs(argc - 1, argv + 1);
  }

  TSCont const contp(TSContCreate(global_read_request_hook, nullptr));

  // Called immediately after the request header is read from the client
  TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
}
<|endoftext|>