<commit_before>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*/

#include "titlebar.h"
#include "messageformatter.h"
#include <QStyleOptionHeader>
#include <QStylePainter>
#include <IrcTextFormat>
#include <QApplication>
#include <QMouseEvent>
#include <QHeaderView>
#include <IrcCommand>
#include <IrcChannel>
#include <QTreeView>
#include <QStyle>
#include <QMenu>

TitleBar::TitleBar(QWidget* parent) : QLabel(parent)
{
    d.buffer = 0;
    d.editor = new QTextEdit(this);
    d.formatter = new MessageFormatter(this);

    setWordWrap(true);
    setOpenExternalLinks(true);
    setTextFormat(Qt::RichText);

#ifdef Q_OS_MAC
    QFont font;
    font.setPointSize(11.0);
    setFont(font);
#endif

    d.editor->setVisible(false);
    d.editor->setAcceptRichText(false);
    d.editor->setTabChangesFocus(true);
    d.editor->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d.editor->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d.editor->installEventFilter(this);

    d.menuButton = new QToolButton(this);
    d.menuButton->setObjectName("menu");
    d.menuButton->setMenu(new QMenu(d.menuButton));
    d.menuButton->setPopupMode(QToolButton::InstantPopup);
    d.menuButton->adjustSize();
}

QMenu* TitleBar::menu() const
{
    return d.menuButton->menu();
}

QSize TitleBar::minimumSizeHint() const
{
    // QMacStyle wants a QHeaderView that is a child of QTreeView :/
    QTreeView tree;
    QStyleOptionHeader option;
    return style()->sizeFromContents(QStyle::CT_HeaderSection, &option, QSize(), tree.header());
}

int TitleBar::heightForWidth(int width) const
{
    return qMax(minimumSizeHint().height(), QLabel::heightForWidth(width));
}

IrcBuffer* TitleBar::buffer() const
{
    return d.buffer;
}

void TitleBar::setBuffer(IrcBuffer* buffer)
{
    if (d.buffer != buffer) {
        if (d.buffer) {
            IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
            if (channel) {
                disconnect(channel, SIGNAL(destroyed(IrcChannel*)), this, SLOT(cleanup()));
                disconnect(channel, SIGNAL(topicChanged(QString)), this, SLOT(refresh()));
                disconnect(channel, SIGNAL(modeChanged(QString)), this, SLOT(refresh()));
            } else {
                disconnect(d.buffer, SIGNAL(destroyed(IrcBuffer*)), this, SLOT(cleanup()));
            }
            disconnect(d.buffer, SIGNAL(titleChanged(QString)), this, SLOT(refresh()));
        }
        d.buffer = buffer;
        if (d.buffer) {
            IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
            if (channel) {
                connect(channel, SIGNAL(destroyed(IrcChannel*)), this, SLOT(cleanup()));
                connect(channel, SIGNAL(topicChanged(QString)), this, SLOT(refresh()));
                connect(channel, SIGNAL(modeChanged(QString)), this, SLOT(refresh()));
            } else {
                connect(d.buffer, SIGNAL(destroyed(IrcBuffer*)), this, SLOT(cleanup()));
            }
            connect(d.buffer, SIGNAL(titleChanged(QString)), this, SLOT(refresh()));
        }
        refresh();
    }
}

QString TitleBar::topic() const
{
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    if (channel)
        return channel->topic();
    return QString();
}

void TitleBar::setTopic(const QString& topic)
{
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    if (channel) {
        if (channel->topic() != topic)
            channel->sendCommand(IrcCommand::createTopic(channel->title(), topic));
    }
}

bool TitleBar::event(QEvent* event)
{
    if (event->type() == QEvent::ActionAdded)
        d.menuButton->menu()->addAction(static_cast<QActionEvent*>(event)->action());
    else if (event->type() == QEvent::ActionRemoved)
        d.menuButton->menu()->removeAction(static_cast<QActionEvent*>(event)->action());
    return QLabel::event(event);
}

bool TitleBar::eventFilter(QObject* object, QEvent* event)
{
    Q_UNUSED(object);
    switch (event->type()) {
    case QEvent::FocusOut:
        d.editor->hide();
        break;
    case QEvent::KeyPress: {
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) {
            setTopic(d.editor->toPlainText());
            d.editor->hide();
        } else if (keyEvent->key() == Qt::Key_Escape) {
            d.editor->hide();
        }
        break;
    }
    default:
        break;
    }
    return false;
}

void TitleBar::mouseDoubleClickEvent(QMouseEvent* event)
{
    edit();
    d.editor->setTextCursor(d.editor->cursorForPosition(event->pos()));
}

void TitleBar::paintEvent(QPaintEvent* event)
{
    QStyleOptionHeader option;
    option.init(this);
#ifdef Q_OS_WIN
    option.rect.adjust(0, 0, 0, 1);
#endif
    option.state = (QStyle::State_Raised | QStyle::State_Horizontal);
    option.position = QStyleOptionHeader::OnlyOneSection;
    QStylePainter painter(this);
    painter.drawControl(QStyle::CE_HeaderSection, option);

    QLabel::paintEvent(event);
}

void TitleBar::resizeEvent(QResizeEvent* event)
{
    QRect r = d.menuButton->rect();
    r.moveTopRight(rect().topRight());
    d.menuButton->setGeometry(r);

    QStyleOptionHeader option;
    option.initFrom(this);
    option.rect.setRight(r.left() - 1);
    QRect ser = style()->subElementRect(QStyle::SE_HeaderLabel, &option, this);
    setContentsMargins(ser.x(), ser.y(), width() - ser.x() - ser.width(), height() - ser.y() - ser.height());

    QLabel::resizeEvent(event);
}

void TitleBar::cleanup()
{
    d.buffer = 0;
    refresh();
}

void TitleBar::refresh()
{
    QString title = d.buffer ? d.buffer->title() : QString();
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    QString topic = channel ? channel->topic() : QString();
    if (!topic.isEmpty())
        title = tr("%1: %2").arg(title, d.formatter->formatContent(topic));
    setText(title);
}

void TitleBar::edit()
{
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    if (channel) {
        d.editor->setPlainText(channel->topic());

        // keep the text visually in place...
        d.editor->document()->setIndentWidth(3);
        d.editor->document()->setDocumentMargin(1);
        QTextCursor cursor(d.editor->document());
        QTextBlockFormat format = cursor.blockFormat();
        format.setIndent(1);
        cursor.setBlockFormat(format);

        d.editor->resize(size()); // TODO: layout?
        d.editor->setFocus();
        d.editor->show();
    }
}
<commit_msg>Right align the app menu<commit_after>/*
* Copyright (C) 2008-2014 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*/

#include "titlebar.h"
#include "messageformatter.h"
#include <QStyleOptionHeader>
#include <QStylePainter>
#include <IrcTextFormat>
#include <QApplication>
#include <QMouseEvent>
#include <QHeaderView>
#include <IrcCommand>
#include <IrcChannel>
#include <QTreeView>
#include <QStyle>
#include <QMenu>

class TitleMenu : public QMenu
{
public:
    TitleMenu(QWidget* parent) : QMenu(parent) { }

protected:
    void moveEvent(QMoveEvent*)
    {
        // TODO: looks scary - any better ideas?
        if (QWidget* parent = parentWidget()) {
            QRect rect = geometry();
            rect.moveTopRight(parent->mapToGlobal(parent->rect().bottomRight()));
            setGeometry(rect);
        }
    }
};

TitleBar::TitleBar(QWidget* parent) : QLabel(parent)
{
    d.buffer = 0;
    d.editor = new QTextEdit(this);
    d.formatter = new MessageFormatter(this);

    setWordWrap(true);
    setOpenExternalLinks(true);
    setTextFormat(Qt::RichText);

#ifdef Q_OS_MAC
    QFont font;
    font.setPointSize(11.0);
    setFont(font);
#endif

    d.editor->setVisible(false);
    d.editor->setAcceptRichText(false);
    d.editor->setTabChangesFocus(true);
    d.editor->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d.editor->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    d.editor->installEventFilter(this);

    d.menuButton = new QToolButton(this);
    d.menuButton->setObjectName("menu");
    d.menuButton->setMenu(new TitleMenu(d.menuButton));
    d.menuButton->setPopupMode(QToolButton::InstantPopup);
    d.menuButton->adjustSize();
}

QMenu* TitleBar::menu() const
{
    return d.menuButton->menu();
}

QSize TitleBar::minimumSizeHint() const
{
    // QMacStyle wants a QHeaderView that is a child of QTreeView :/
    QTreeView tree;
    QStyleOptionHeader option;
    return style()->sizeFromContents(QStyle::CT_HeaderSection, &option, QSize(), tree.header());
}

int TitleBar::heightForWidth(int width) const
{
    return qMax(minimumSizeHint().height(), QLabel::heightForWidth(width));
}

IrcBuffer* TitleBar::buffer() const
{
    return d.buffer;
}

void TitleBar::setBuffer(IrcBuffer* buffer)
{
    if (d.buffer != buffer) {
        if (d.buffer) {
            IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
            if (channel) {
                disconnect(channel, SIGNAL(destroyed(IrcChannel*)), this, SLOT(cleanup()));
                disconnect(channel, SIGNAL(topicChanged(QString)), this, SLOT(refresh()));
                disconnect(channel, SIGNAL(modeChanged(QString)), this, SLOT(refresh()));
            } else {
                disconnect(d.buffer, SIGNAL(destroyed(IrcBuffer*)), this, SLOT(cleanup()));
            }
            disconnect(d.buffer, SIGNAL(titleChanged(QString)), this, SLOT(refresh()));
        }
        d.buffer = buffer;
        if (d.buffer) {
            IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
            if (channel) {
                connect(channel, SIGNAL(destroyed(IrcChannel*)), this, SLOT(cleanup()));
                connect(channel, SIGNAL(topicChanged(QString)), this, SLOT(refresh()));
                connect(channel, SIGNAL(modeChanged(QString)), this, SLOT(refresh()));
            } else {
                connect(d.buffer, SIGNAL(destroyed(IrcBuffer*)), this, SLOT(cleanup()));
            }
            connect(d.buffer, SIGNAL(titleChanged(QString)), this, SLOT(refresh()));
        }
        refresh();
    }
}

QString TitleBar::topic() const
{
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    if (channel)
        return channel->topic();
    return QString();
}

void TitleBar::setTopic(const QString& topic)
{
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    if (channel) {
        if (channel->topic() != topic)
            channel->sendCommand(IrcCommand::createTopic(channel->title(), topic));
    }
}

bool TitleBar::event(QEvent* event)
{
    if (event->type() == QEvent::ActionAdded)
        d.menuButton->menu()->addAction(static_cast<QActionEvent*>(event)->action());
    else if (event->type() == QEvent::ActionRemoved)
        d.menuButton->menu()->removeAction(static_cast<QActionEvent*>(event)->action());
    return QLabel::event(event);
}

bool TitleBar::eventFilter(QObject* object, QEvent* event)
{
    Q_UNUSED(object);
    switch (event->type()) {
    case QEvent::FocusOut:
        d.editor->hide();
        break;
    case QEvent::KeyPress: {
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
        if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) {
            setTopic(d.editor->toPlainText());
            d.editor->hide();
        } else if (keyEvent->key() == Qt::Key_Escape) {
            d.editor->hide();
        }
        break;
    }
    default:
        break;
    }
    return false;
}

void TitleBar::mouseDoubleClickEvent(QMouseEvent* event)
{
    edit();
    d.editor->setTextCursor(d.editor->cursorForPosition(event->pos()));
}

void TitleBar::paintEvent(QPaintEvent* event)
{
    QStyleOptionHeader option;
    option.init(this);
#ifdef Q_OS_WIN
    option.rect.adjust(0, 0, 0, 1);
#endif
    option.state = (QStyle::State_Raised | QStyle::State_Horizontal);
    option.position = QStyleOptionHeader::OnlyOneSection;
    QStylePainter painter(this);
    painter.drawControl(QStyle::CE_HeaderSection, option);

    QLabel::paintEvent(event);
}

void TitleBar::resizeEvent(QResizeEvent* event)
{
    QRect r = d.menuButton->rect();
    r.moveTopRight(rect().topRight());
    d.menuButton->setGeometry(r);

    QStyleOptionHeader option;
    option.initFrom(this);
    option.rect.setRight(r.left() - 1);
    QRect ser = style()->subElementRect(QStyle::SE_HeaderLabel, &option, this);
    setContentsMargins(ser.x(), ser.y(), width() - ser.x() - ser.width(), height() - ser.y() - ser.height());

    QLabel::resizeEvent(event);
}

void TitleBar::cleanup()
{
    d.buffer = 0;
    refresh();
}

void TitleBar::refresh()
{
    QString title = d.buffer ? d.buffer->title() : QString();
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    QString topic = channel ? channel->topic() : QString();
    if (!topic.isEmpty())
        title = tr("%1: %2").arg(title, d.formatter->formatContent(topic));
    setText(title);
}

void TitleBar::edit()
{
    IrcChannel* channel = qobject_cast<IrcChannel*>(d.buffer);
    if (channel) {
        d.editor->setPlainText(channel->topic());

        // keep the text visually in place...
        d.editor->document()->setIndentWidth(3);
        d.editor->document()->setDocumentMargin(1);
        QTextCursor cursor(d.editor->document());
        QTextBlockFormat format = cursor.blockFormat();
        format.setIndent(1);
        cursor.setBlockFormat(format);

        d.editor->resize(size()); // TODO: layout?
        d.editor->setFocus();
        d.editor->show();
    }
}
<|endoftext|>


<commit_before>///
///Revise the loop that printed the first paragraph in text
///to instead change the elements in text that correspond
///to the first paragraph to all uppercase.
///After you’ve updated text, print its contents.
///

#include <iostream>
#include <vector>
#include <string>
#include <iterator>

using std::vector; using std::string; using std::cout; using std::cin; using std::endl;

int main()
{
  vector<string> text;
  for (string line; getline(cin, line); )
    text.push_back(line);

  for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) {
    for (auto &c : *it)
      c = toupper(c);
    cout << *it << endl;
  }

  return 0;
}
<commit_msg>Update ex3_22.cpp<commit_after>///
///Revise the loop that printed the first paragraph in text
///to instead change the elements in text that correspond
///to the first paragraph to all uppercase.
///After you’ve updated text, print its contents.
///

#include <iostream>
#include <vector>
#include <string>
#include <iterator>

using std::vector; using std::string; using std::cout; using std::cin; using std::endl;

int main()
{
    vector<string> text;
    for (string line; getline(cin, line); text.push_back(line));

    for (auto it = text.begin(); it != text.end() && !it->empty(); ++it)
    {
        for (auto &c : *it) c = toupper(c);
        cout << *it << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
using std::cin; using std::cout; using std::endl;

int main()
{
    unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
    char ch;
    while (cin >> ch)
        switch (tolower(ch))
        {
            case 'a':
                ++aCnt;
                break;
            case 'e':
                ++eCnt;
                break;
            case 'i':
                ++iCnt;
                break;
            case 'o':
                ++oCnt;
                break;
            case 'u':
                ++uCnt;
                break;
        }

    cout << "Number of vowel a(A): \t" << aCnt << '\n'
         << "Number of vowel e(E): \t" << eCnt << '\n'
         << "Number of vowel i(I): \t" << iCnt << '\n'
         << "Number of vowel o(O): \t" << oCnt << '\n'
         << "Number of vowel u(U): \t" << uCnt << endl;

    return 0;
}
<commit_msg>ex5_10:default switch behavior<commit_after>#include <iostream>
using std::cin; using std::cout; using std::endl;

int main()
{
    unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
    char ch;
    while (cin >> ch)
        switch (ch)
        {
            case 'a':
            case 'A':
                ++aCnt;
                break;
            case 'e':
            case 'E':
                ++eCnt;
                break;
            case 'i':
            case 'I':
                ++iCnt;
                break;
            case 'o':
            case 'O':
                ++oCnt;
                break;
            case 'u':
            case 'U':
                ++uCnt;
                break;
        }

    cout << "Number of vowel a(A): \t" << aCnt << '\n'
         << "Number of vowel e(E): \t" << eCnt << '\n'
         << "Number of vowel i(I): \t" << iCnt << '\n'
         << "Number of vowel o(O): \t" << oCnt << '\n'
         << "Number of vowel u(U): \t" << uCnt << endl;

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
using std::vector;

void insertDoubleValue(vector<int> &iv, int some_val)
{
    auto cursor = iv.size() / 2;
    auto iter = iv.begin(), mid = iv.begin() + cursor;
    while (iter != mid) {
        if (*iter == some_val) {
            iter = iv.insert(iter, 2 * some_val);
            ++iter;
            ++cursor;
            mid = iv.begin() + cursor;
        }
        ++iter;
    }
}

void print(const vector<int> &iv)
{
    for (auto i : iv) std::cout << i << " ";
    std::cout << std::endl;
}

int main()
{
    vector<int> iv = {1, 1, 1, 1, 1, 7, 1, 9};
    insertDoubleValue(iv, 1);
    print(iv);
}
<commit_msg>Update ex9_22.cpp<commit_after>#include <iostream>
#include <vector>
using namespace std;

void insertDoubleValue(vector<int> &iv, int some_val)
{
    auto cursor = iv.size() / 2;
    auto iter = iv.begin(), mid = iv.begin() + cursor;
    while (iter != mid) {
        if (*iter == some_val) {
            iter = iv.insert(iter, 2 * some_val);
            ++iter;
            ++cursor;
            mid = iv.begin() + cursor;
        }
        ++iter;
    }
}

void print(const vector<int> &iv)
{
    for (auto i : iv)
        cout << i << " ";
    cout << endl;
}

int main()
{
    vector<int> iv = {1, 1, 1, 1, 1, 7, 1, 9};
    insertDoubleValue(iv, 1);
    print(iv);
}
<|endoftext|>


<commit_before>/// @file
/// @author uentity
/// @date 20.11.2017
/// @brief Symbolic link implementation
/// @copyright
/// 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 <bs/log.h>
#include <bs/tree/tree.h>
#include <bs/tree/errors.h>
#include <bs/kernel/config.h>
#include <bs/kernel/tools.h>

#include <bs/serialize/tree.h>
#include <bs/serialize/cafbind.h>

#include "link_actor.h"

NAMESPACE_BEGIN(blue_sky::tree)
///////////////////////////////////////////////////////////////////////////////
//  actor + impl
//

// actor
struct sym_link_actor : public link_actor {
	using super = link_actor;

	using super::super;

	auto target() const -> link_or_err {
		return static_cast<sym_link_impl&>(impl).target();
	}

	template<typename R, typename... Args>
	auto delegate_target(Args&&... args)
	-> std::enable_if_t<tl::detail::is_expected<R>::value, caf::result<R>> {
		if(auto p = target())
			return delegate(link::actor(p.value()), std::forward<Args>(args)...);
		else
			return R{ tl::unexpect, p.error() };
	}

	template<typename R, typename... Args>
	auto delegate_target(R errval, Args&&... args)
	-> std::enable_if_t<!tl::detail::is_expected<R>::value, caf::result<R>> {
		if(auto p = target())
			return delegate(link::actor(p.value()), std::forward<Args>(args)...);
		else
			return errval;
	}

	// delegate name, OID, etc requests to source link
	auto make_behavior() -> caf::behavior override {
		return caf::message_handler({

			[this](a_lnk_oid) -> caf::result<std::string> {
				return delegate_target<std::string>(nil_otid, a_lnk_oid());
			},

			[this](a_lnk_otid) -> caf::result<std::string> {
				return delegate_target<std::string>(nil_otid, a_lnk_otid());
			},

			[this](a_home_id) -> caf::result< std::string > {
				return delegate_target< std::string >(nil_oid, a_home_id());
			},

			[this](a_lnk_inode) -> caf::result< result_or_errbox<inodeptr> > {
				return delegate_target< result_or_errbox<inodeptr> >(a_lnk_inode());
			},

		}).or_else(super::make_behavior());
	}
};

// impl
sym_link_impl::sym_link_impl(std::string name, std::string path, Flags f)
	: super(std::move(name), f), path_(std::move(path))
{}

sym_link_impl::sym_link_impl()
	: super()
{}

auto sym_link_impl::target() const -> link_or_err {
	const auto parent = owner();
	if(!parent) return unexpected_err_quiet(Error::UnboundSymLink);

	link src_link;
	if(auto er = error::eval_safe([&] { src_link = deref_path(path_, parent); }); er)
		return tl::make_unexpected(std::move(er));
	else if(src_link)
		return src_link;
	return unexpected_err_quiet(Error::LinkExpired);
}

auto sym_link_impl::data() -> obj_or_err {
	auto res = target().and_then([](const link& src_link) {
		return src_link.data_ex();
	});
#if defined(_DEBUG)
	if(!res) {
		auto& er = res.error();
		std::cout << ">>> " << to_string(id_) << ' ' << er.what() << std::endl;
		//std::cout << kernel::tools::get_backtrace(16) << std::endl;
	}
#endif
	return res;
}

auto sym_link_impl::data(unsafe_t) const -> sp_obj {
	return target().map([](const link& src_link) {
		return src_link.data(unsafe);
	}).value_or(nullptr);
}

auto sym_link_impl::spawn_actor(sp_limpl limpl) const -> caf::actor {
	return spawn_lactor<sym_link_actor>(std::move(limpl));
}

auto sym_link_impl::clone(bool deep) const -> sp_limpl {
	// no deep copy support for symbolic link
	return std::make_shared<sym_link_impl>(name_, path_, flags_);
}

auto sym_link_impl::propagate_handle() -> node_or_err {
	// sym link cannot be a node's handle
	return target().and_then([](const link& src_link) {
		return src_link.data_node_ex();
	});
}

///////////////////////////////////////////////////////////////////////////////
//  class
//

#define SIMPL static_cast<sym_link_impl&>(*super::pimpl())

/// ctor -- pointee is specified by string path
sym_link::sym_link(std::string name, std::string path, Flags f)
	: link(std::make_shared<sym_link_impl>(std::move(name), std::move(path), f))
{}
/// ctor -- pointee is specified directly - absolute path will be stored
sym_link::sym_link(std::string name, const link& src, Flags f)
	: sym_link(std::move(name), abspath(src), f)
{}

sym_link::sym_link()
	: super(std::make_shared<sym_link_impl>(), false)
{}

bool sym_link::check_alive() {
	auto res = bool(deref_path(SIMPL.path_, owner()));
	auto S = res ? ReqStatus::OK : ReqStatus::Error;
	rs_reset_if_neq(Req::Data, S, S);
	return res;
}

auto sym_link::target() const -> link_or_err {
	return SIMPL.target();
}

/// return stored pointee path
std::string sym_link::target_path(bool human_readable) const {
	auto res = std::string(SIMPL.path_);
	if(human_readable) {
		if(const auto parent = owner())
			res = convert_path(res, parent.handle());
	}
	return res;
}

LINK_CONVERT_TO(sym_link)
LINK_TYPE_DEF(sym_link, sym_link_impl, "sym_link")

NAMESPACE_END(blue_sky::tree)
<commit_msg>tree/sym_link: immediately return error from `propagate_handle()`<commit_after>/// @file
/// @author uentity
/// @date 20.11.2017
/// @brief Symbolic link implementation
/// @copyright
/// 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 <bs/log.h>
#include <bs/tree/tree.h>
#include <bs/tree/errors.h>
#include <bs/kernel/config.h>
#include <bs/kernel/tools.h>

#include <bs/serialize/tree.h>
#include <bs/serialize/cafbind.h>

#include "link_actor.h"

NAMESPACE_BEGIN(blue_sky::tree)
///////////////////////////////////////////////////////////////////////////////
//  sym_link actor
//
struct sym_link_actor : public link_actor {
	using super = link_actor;

	using super::super;

	auto target() const -> link_or_err {
		return static_cast<sym_link_impl&>(impl).target();
	}

	template<typename R, typename... Args>
	auto delegate_target(Args&&... args)
	-> std::enable_if_t<tl::detail::is_expected<R>::value, caf::result<R>> {
		if(auto p = target())
			return delegate(link::actor(p.value()), std::forward<Args>(args)...);
		else
			return R{ tl::unexpect, p.error() };
	}

	template<typename R, typename... Args>
	auto delegate_target(R errval, Args&&... args)
	-> std::enable_if_t<!tl::detail::is_expected<R>::value, caf::result<R>> {
		if(auto p = target())
			return delegate(link::actor(p.value()), std::forward<Args>(args)...);
		else
			return errval;
	}

	// delegate name, OID, etc requests to source link
	auto make_behavior() -> caf::behavior override {
		return caf::message_handler({

			[this](a_lnk_oid) -> caf::result<std::string> {
				return delegate_target<std::string>(nil_otid, a_lnk_oid());
			},

			[this](a_lnk_otid) -> caf::result<std::string> {
				return delegate_target<std::string>(nil_otid, a_lnk_otid());
			},

			[this](a_home_id) -> caf::result< std::string > {
				return delegate_target< std::string >(nil_oid, a_home_id());
			},

			[this](a_lnk_inode) -> caf::result< result_or_errbox<inodeptr> > {
				return delegate_target< result_or_errbox<inodeptr> >(a_lnk_inode());
			},

		}).or_else(super::make_behavior());
	}
};

///////////////////////////////////////////////////////////////////////////////
//  sym_link impl
//
sym_link_impl::sym_link_impl(std::string name, std::string path, Flags f)
	: super(std::move(name), f), path_(std::move(path))
{}

sym_link_impl::sym_link_impl()
	: super()
{}

auto sym_link_impl::target() const -> link_or_err {
	const auto parent = owner();
	if(!parent) return unexpected_err_quiet(Error::UnboundSymLink);

	link src_link;
	if(auto er = error::eval_safe([&] { src_link = deref_path(path_, parent); }); er)
		return tl::make_unexpected(std::move(er));
	else if(src_link)
		return src_link;
	return unexpected_err_quiet(Error::LinkExpired);
}

auto sym_link_impl::data() -> obj_or_err {
	auto res = target().and_then([](const link& src_link) {
		return src_link.data_ex();
	});
#if defined(_DEBUG)
	if(!res) {
		auto& er = res.error();
		std::cout << ">>> " << to_string(id_) << ' ' << er.what() << std::endl;
		//std::cout << kernel::tools::get_backtrace(16) << std::endl;
	}
#endif
	return res;
}

auto sym_link_impl::data(unsafe_t) const -> sp_obj {
	return target().map([](const link& src_link) {
		return src_link.data(unsafe);
	}).value_or(nullptr);
}

auto sym_link_impl::spawn_actor(sp_limpl limpl) const -> caf::actor {
	return spawn_lactor<sym_link_actor>(std::move(limpl));
}

auto sym_link_impl::clone(bool deep) const -> sp_limpl {
	// no deep copy support for symbolic link
	return std::make_shared<sym_link_impl>(name_, path_, flags_);
}

auto sym_link_impl::propagate_handle() -> node_or_err {
	// sym link cannot be a node's handle and also must make tree query here, so just return error
	return unexpected_err_quiet(Error::EmptyData);
}

///////////////////////////////////////////////////////////////////////////////
//  class
//

#define SIMPL static_cast<sym_link_impl&>(*super::pimpl())

/// ctor -- pointee is specified by string path
sym_link::sym_link(std::string name, std::string path, Flags f)
	: link(std::make_shared<sym_link_impl>(std::move(name), std::move(path), f))
{}
/// ctor -- pointee is specified directly - absolute path will be stored
sym_link::sym_link(std::string name, const link& src, Flags f)
	: sym_link(std::move(name), abspath(src), f)
{}

sym_link::sym_link()
	: super(std::make_shared<sym_link_impl>(), false)
{}

bool sym_link::check_alive() {
	auto res = bool(deref_path(SIMPL.path_, owner()));
	auto S = res ? ReqStatus::OK : ReqStatus::Error;
	rs_reset_if_neq(Req::Data, S, S);
	return res;
}

auto sym_link::target() const -> link_or_err {
	return SIMPL.target();
}

/// return stored pointee path
std::string sym_link::target_path(bool human_readable) const {
	auto res = std::string(SIMPL.path_);
	if(human_readable) {
		if(const auto parent = owner())
			res = convert_path(res, parent.handle());
	}
	return res;
}

LINK_CONVERT_TO(sym_link)
LINK_TYPE_DEF(sym_link, sym_link_impl, "sym_link")

NAMESPACE_END(blue_sky::tree)
<|endoftext|>


<commit_before>#ifndef TEST_UNIT_MATH_ODE_HARMONIC_OSCILLATOR
#define TEST_UNIT_MATH_ODE_HARMONIC_OSCILLATOR

#include <stan/math/prim.hpp>
#include <stdexcept>
#include <vector>

struct harm_osc_ode_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(y_in.at(1));
    res.push_back(-y_in.at(0) - theta.at(0) * y_in.at(1));

    return res;
  }
};

struct harm_osc_ode_fun_eigen {
  template <typename T0, typename T1, typename T2>
  inline auto operator()(const T0& t_in,
                         const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y_in,
                         std::ostream* msgs, const std::vector<T2>& theta,
                         const std::vector<double>& x,
                         const std::vector<int>& x_int) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    Eigen::Matrix<stan::return_type_t<T1, T2>, Eigen::Dynamic, 1> res(2);
    res(0) = y_in(1);
    res(1) = -y_in(0) - theta[0] * y_in(1);

    return res;
  }
};

struct harm_osc_ode_data_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(x.at(0) * y_in.at(1) + x_int.at(0));
    res.push_back(-x.at(1) * y_in.at(0) - x.at(2) * theta.at(0) * y_in.at(1)
                  + x_int.at(1));

    return res;
  }
};

struct harm_osc_ode_data_fun_eigen {
  template <typename T0, typename T1, typename T2>
  inline auto operator()(const T0& t_in,
                         const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y_in,
                         std::ostream* msgs, const std::vector<T2>& theta,
                         const std::vector<double>& x,
                         const std::vector<int>& x_int) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    const T2& p = theta.at(0);

    Eigen::Matrix<stan::return_type_t<T1, T2>, -1, 1> res(2);
    res << (x.at(0) * y_in(1) + x_int.at(0)),
        (-x.at(1) * y_in(0) - x.at(2) * p * y_in(1) + x_int.at(1));

    return res;
  }
};

struct harm_osc_ode_wrong_size_1_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(y_in.at(1));
    res.push_back(-y_in.at(0) - theta.at(0) * y_in.at(1));
    res.push_back(0);

    return res;
  }
};

struct harm_osc_ode_wrong_size_2_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(0);

    return res;
  }
};

#endif
<commit_msg>make Eigen inputs expression compatible<commit_after>#ifndef TEST_UNIT_MATH_ODE_HARMONIC_OSCILLATOR
#define TEST_UNIT_MATH_ODE_HARMONIC_OSCILLATOR

#include <stan/math/prim.hpp>
#include <stdexcept>
#include <vector>

struct harm_osc_ode_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(y_in.at(1));
    res.push_back(-y_in.at(0) - theta.at(0) * y_in.at(1));

    return res;
  }
};

struct harm_osc_ode_fun_eigen {
  template <typename T0, typename T1, typename T2>
  inline auto operator()(const T0& t_in,
                         const T1& y_in,
                         std::ostream* msgs, const std::vector<T2>& theta,
                         const std::vector<double>& x,
                         const std::vector<int>& x_int) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    Eigen::Matrix<stan::return_type_t<T1, T2>, Eigen::Dynamic, 1> res(2);
    res(0) = y_in(1);
    res(1) = -y_in(0) - theta[0] * y_in(1);

    return res;
  }
};

struct harm_osc_ode_data_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(x.at(0) * y_in.at(1) + x_int.at(0));
    res.push_back(-x.at(1) * y_in.at(0) - x.at(2) * theta.at(0) * y_in.at(1)
                  + x_int.at(1));

    return res;
  }
};

struct harm_osc_ode_data_fun_eigen {
  template <typename T0, typename T1, typename T2>
  inline auto operator()(const T0& t_in,
                         const T1& y_in,
                         std::ostream* msgs, const std::vector<T2>& theta,
                         const std::vector<double>& x,
                         const std::vector<int>& x_int) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    const T2& p = theta.at(0);

    Eigen::Matrix<stan::return_type_t<T1, T2>, -1, 1> res(2);
    res << (x.at(0) * y_in(1) + x_int.at(0)),
        (-x.at(1) * y_in(0) - x.at(2) * p * y_in(1) + x_int.at(1));

    return res;
  }
};

struct harm_osc_ode_wrong_size_1_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(y_in.at(1));
    res.push_back(-y_in.at(0) - theta.at(0) * y_in.at(1));
    res.push_back(0);

    return res;
  }
};

struct harm_osc_ode_wrong_size_2_fun {
  template <typename T0, typename T1, typename T2>
  inline std::vector<stan::return_type_t<T1, T2>>
  // initial time
  // initial positions
  // parameters
  // double data
  // integer data
  operator()(const T0& t_in, const std::vector<T1>& y_in,
             const std::vector<T2>& theta, const std::vector<double>& x,
             const std::vector<int>& x_int, std::ostream* msgs) const {
    if (y_in.size() != 2)
      throw std::domain_error(
          "this function was called with inconsistent state");

    std::vector<stan::return_type_t<T1, T2>> res;
    res.push_back(0);

    return res;
  }
};

#endif
<|endoftext|>


<commit_before>/*
 * Asynchronous input stream API, utilities for istream
 * implementations.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef ISTREAM_BUCKET_HXX
#define ISTREAM_BUCKET_HXX

#include "util/ConstBuffer.hxx"
#include "util/StaticArray.hxx"

class IstreamBucket {
public:
    enum class Type {
        BUFFER,
    };

private:
    Type type;

    union {
        ConstBuffer<void> buffer;
    };

public:
    IstreamBucket() = default;

    Type GetType() const {
        return type;
    }

    ConstBuffer<void> GetBuffer() const {
        assert(type == Type::BUFFER);

        return buffer;
    }

    void Set(ConstBuffer<void> _buffer) {
        type = Type::BUFFER;
        buffer = _buffer;
    }
};

class IstreamBucketList {
    typedef StaticArray<IstreamBucket, 64> List;
    List list;

    bool more = false;

public:
    IstreamBucketList() = default;

    IstreamBucketList(const IstreamBucketList &) = delete;
    IstreamBucketList &operator=(const IstreamBucketList &) = delete;

    void SetMore() {
        more = true;
    }

    bool HasMore() const {
        return more;
    }

    bool IsEmpty() const {
        return list.empty();
    }

    bool IsFull() const {
        return list.full();
    }

    void Clear() {
        list.clear();
    }

    void Push(const IstreamBucket &bucket) {
        if (IsFull()) {
            SetMore();
            return;
        }

        list.append(bucket);
    }

    void Push(ConstBuffer<void> buffer) {
        if (IsFull())
            return;

        list.append().Set(buffer);
    }

    List::const_iterator begin() const {
        return list.begin();
    }

    List::const_iterator end() const {
        return list.end();
    }

    gcc_pure
    bool HasNonBuffer() const {
        for (const auto &bucket : list)
            if (bucket.GetType() != IstreamBucket::Type::BUFFER)
                return true;
        return false;
    }

    gcc_pure
    size_t GetTotalBufferSize() const {
        size_t size = 0;
        for (const auto &bucket : list)
            if (bucket.GetType() == IstreamBucket::Type::BUFFER)
                size += bucket.GetBuffer().size;
        return size;
    }

    gcc_pure
    bool IsDepleted(size_t consumed) const {
        return !HasMore() && consumed == GetTotalBufferSize();
    }

    void SpliceBuffersFrom(IstreamBucketList &src, size_t max_size) {
        if (src.HasMore())
            SetMore();

        for (const auto &bucket : src) {
            if (bucket.GetType() != IstreamBucket::Type::BUFFER)
                max_size = 0;

            if (max_size == 0) {
                SetMore();
                break;
            }

            auto buffer = bucket.GetBuffer();
            if (buffer.size > max_size) {
                buffer.size = max_size;
                SetMore();
            }

            Push(buffer);
            max_size -= buffer.size;
        }
    }

    /**
     * Move buffer buckets from the given list, stopping at the first
     * no-buffer bucket.
     *
     * @return the number of bytes in all moved buffers
     */
    size_t SpliceBuffersFrom(IstreamBucketList &src) {
        if (src.HasMore())
            SetMore();

        size_t total_size = 0;
        for (const auto &bucket : src) {
            if (bucket.GetType() != IstreamBucket::Type::BUFFER) {
                SetMore();
                break;
            }

            auto buffer = bucket.GetBuffer();
            Push(bucket.GetBuffer());
            total_size += buffer.size;
        }

        return total_size;
    }
};

#endif
<commit_msg>istream/Bucket: set the "more" flag in Push(ConstBuffer)<commit_after>/*
 * Asynchronous input stream API, utilities for istream
 * implementations.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef ISTREAM_BUCKET_HXX
#define ISTREAM_BUCKET_HXX

#include "util/ConstBuffer.hxx"
#include "util/StaticArray.hxx"

class IstreamBucket {
public:
    enum class Type {
        BUFFER,
    };

private:
    Type type;

    union {
        ConstBuffer<void> buffer;
    };

public:
    IstreamBucket() = default;

    Type GetType() const {
        return type;
    }

    ConstBuffer<void> GetBuffer() const {
        assert(type == Type::BUFFER);

        return buffer;
    }

    void Set(ConstBuffer<void> _buffer) {
        type = Type::BUFFER;
        buffer = _buffer;
    }
};

class IstreamBucketList {
    typedef StaticArray<IstreamBucket, 64> List;
    List list;

    bool more = false;

public:
    IstreamBucketList() = default;

    IstreamBucketList(const IstreamBucketList &) = delete;
    IstreamBucketList &operator=(const IstreamBucketList &) = delete;

    void SetMore() {
        more = true;
    }

    bool HasMore() const {
        return more;
    }

    bool IsEmpty() const {
        return list.empty();
    }

    bool IsFull() const {
        return list.full();
    }

    void Clear() {
        list.clear();
    }

    void Push(const IstreamBucket &bucket) {
        if (IsFull()) {
            SetMore();
            return;
        }

        list.append(bucket);
    }

    void Push(ConstBuffer<void> buffer) {
        if (IsFull()) {
            SetMore();
            return;
        }

        list.append().Set(buffer);
    }

    List::const_iterator begin() const {
        return list.begin();
    }

    List::const_iterator end() const {
        return list.end();
    }

    gcc_pure
    bool HasNonBuffer() const {
        for (const auto &bucket : list)
            if (bucket.GetType() != IstreamBucket::Type::BUFFER)
                return true;
        return false;
    }

    gcc_pure
    size_t GetTotalBufferSize() const {
        size_t size = 0;
        for (const auto &bucket : list)
            if (bucket.GetType() == IstreamBucket::Type::BUFFER)
                size += bucket.GetBuffer().size;
        return size;
    }

    gcc_pure
    bool IsDepleted(size_t consumed) const {
        return !HasMore() && consumed == GetTotalBufferSize();
    }

    void SpliceBuffersFrom(IstreamBucketList &src, size_t max_size) {
        if (src.HasMore())
            SetMore();

        for (const auto &bucket : src) {
            if (bucket.GetType() != IstreamBucket::Type::BUFFER)
                max_size = 0;

            if (max_size == 0) {
                SetMore();
                break;
            }

            auto buffer = bucket.GetBuffer();
            if (buffer.size > max_size) {
                buffer.size = max_size;
                SetMore();
            }

            Push(buffer);
            max_size -= buffer.size;
        }
    }

    /**
     * Move buffer buckets from the given list, stopping at the first
     * no-buffer bucket.
     *
     * @return the number of bytes in all moved buffers
     */
    size_t SpliceBuffersFrom(IstreamBucketList &src) {
        if (src.HasMore())
            SetMore();

        size_t total_size = 0;
        for (const auto &bucket : src) {
            if (bucket.GetType() != IstreamBucket::Type::BUFFER) {
                SetMore();
                break;
            }

            auto buffer = bucket.GetBuffer();
            Push(bucket.GetBuffer());
            total_size += buffer.size;
        }

        return total_size;
    }
};

#endif
<|endoftext|>


<commit_before>// Extensions to typedef u64 and s64 until that support is added into
// Armadillo.  We only need to typedef s64 on Armadillo >= 1.2.0
/*
#if   (ARMA_VERSION_MAJOR >= 1) && \
      (ARMA_VERSION_MINOR >= 2) && \
      (ARMA_VERSION_PATCH >= 0)
  // We only need to typedef s64.
  #if   ULONG_MAX >= 0xffffffffffffffff
    typedef          long s64;
  #elif ULLONG_MAX >= 0xffffffffffffffff
    typedef          long s64;
  #else
    #error "don't know how to typedef 's64' on this system"
  #endif
#else
*/
  // We must typedef both u64 and s64.
  #if   ULONG_MAX >= 0xffffffffffffffff
    typedef unsigned long u64;
    typedef          long s64;
  #elif ULLONG_MAX >= 0xffffffffffffffff
    typedef unsigned long long u64;
    typedef          long long s64;
  #else
    #error "don't know how to typedef 'u64' on this system"
  #endif
//#endif
<commit_msg>Actually, the issue is that the header file exists but Armadillo does not include it by default.  So we'll include it manually to typedef u64 right.<commit_after>// Extensions to typedef u64 and s64 until that support is added into
// Armadillo.  We only need to typedef s64 on Armadillo >= 1.2.0

#if   (ARMA_VERSION_MAJOR >= 1) && \
      (ARMA_VERSION_MINOR >= 2) && \
      (ARMA_VERSION_PATCH >= 0)
  // An unincluded header file typedefs u64 for us.
  namespace arma {
    #include <armadillo_bits/typedef_u64.hpp>
  };

  // We only need to typedef s64.
  #if   ULONG_MAX >= 0xffffffffffffffff
    typedef          long s64;
  #elif ULLONG_MAX >= 0xffffffffffffffff
    typedef          long s64;
  #else
    #error "don't know how to typedef 's64' on this system"
  #endif
#else

  // We must typedef both u64 and s64.
  #if   ULONG_MAX >= 0xffffffffffffffff
    typedef unsigned long u64;
    typedef          long s64;
  #elif ULLONG_MAX >= 0xffffffffffffffff
    typedef unsigned long long u64;
    typedef          long long s64;
  #else
    #error "don't know how to typedef 'u64' on this system"
  #endif

#endif
<|endoftext|>


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

/**
*@author Grégory Van den Borre
*/

#include "../includes/JniShader.h"
#include "../includes/JniUtil.h"

JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createFragmentShader(
    JNIEnv* env, jobject o, jstring jname, jstring jpath) {
    JniStringWrapper name = JniStringWrapper(env, jname);
    JniStringWrapper path = JniStringWrapper(env, jpath);
    Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
        name.getValue(),
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
        "glsl",
        Ogre::GPT_FRAGMENT_PROGRAM).get();
    shader->setSourceFile(path.getValue());
    return reinterpret_cast<jlong>(shader);
    }

JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createVertexShader(
    JNIEnv* env, jobject o, jstring jname, jstring jpath) {
    JniStringWrapper name = JniStringWrapper(env, jname);
    JniStringWrapper path = JniStringWrapper(env, jpath);
    Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
        name.getValue(),
        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
        "glsl",
        Ogre::GPT_VERTEX_PROGRAM).get();
    shader->setSourceFile(path.getValue());
    return reinterpret_cast<jlong>(shader);
    }

JNIEXPORT void JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_setParameter(
    JNIEnv* env, jobject o, jlong pointer, jstring jname, jstring jvalue) {
        JniStringWrapper name = JniStringWrapper(env, jname);
        JniStringWrapper value = JniStringWrapper(env, jvalue);
        Ogre::GpuProgram* shader = reinterpret_cast<Ogre::GpuProgram*>(pointer);
        shader->setParameter(name.getValue(), value.getValue());
    }

JNIEXPORT void JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_load(
    JNIEnv* env, jobject o, jlong pointer) {
        reinterpret_cast<Ogre::GpuProgram*>(pointer)->load();
    }
<commit_msg>[NO-JIRA] Throw exception instead of ogre crash.<commit_after>/*
 * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)
 *
 * Copyright (c) 2017 Grégory Van den Borre
 *
 * More infos available: https://www.yildiz-games.be
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.
 */

/**
*@author Grégory Van den Borre
*/

#include "../includes/JniShader.h"
#include "../includes/JniUtil.h"

JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createFragmentShader(
    JNIEnv* env, jobject o, jstring jname, jstring jpath) {
    try {
        JniStringWrapper name = JniStringWrapper(env, jname);
        JniStringWrapper path = JniStringWrapper(env, jpath);
        Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
            name.getValue(),
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
            "glsl",
            Ogre::GPT_FRAGMENT_PROGRAM).get();
        shader->setSourceFile(path.getValue());
        return reinterpret_cast<jlong>(shader);
    } catch (std::exception& e) {
        throwException(env, e.what());
        return -1L;
    }
}

JNIEXPORT jlong JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_createVertexShader(
    JNIEnv* env, jobject o, jstring jname, jstring jpath) {
    try {
        JniStringWrapper name = JniStringWrapper(env, jname);
        JniStringWrapper path = JniStringWrapper(env, jpath);
        Ogre::GpuProgram* shader = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(
            name.getValue(),
            Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
            "glsl",
            Ogre::GPT_VERTEX_PROGRAM).get();
        shader->setSourceFile(path.getValue());
        return reinterpret_cast<jlong>(shader);
    } catch (std::exception& e) {
        throwException(env, e.what());
        return -1L;
    }
}

JNIEXPORT void JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_setParameter(
    JNIEnv* env, jobject o, jlong pointer, jstring jname, jstring jvalue) {
    try {
        JniStringWrapper name = JniStringWrapper(env, jname);
        JniStringWrapper value = JniStringWrapper(env, jvalue);
        Ogre::GpuProgram* shader = reinterpret_cast<Ogre::GpuProgram*>(pointer);
        shader->setParameter(name.getValue(), value.getValue());
    } catch (std::exception& e) {
        throwException(env, e.what());
    }
}

JNIEXPORT void JNICALL Java_be_yildiz_module_graphic_ogre_OgreShader_load(
    JNIEnv* env, jobject o, jlong pointer) {
    try {
        reinterpret_cast<Ogre::GpuProgram*>(pointer)->load();
    } catch (std::exception& e) {
        throwException(env, e.what());
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: saxparser.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: ihi $ $Date: 2008-02-04 13:47:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"

#include <stdio.h>
#include <string.h>
#include <stack>

#include "sal/main.h"

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

#include <vos/diagnose.hxx>

#include "LocaleNode.hxx"

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

/************
 * Sequence of bytes -> InputStream
 ************/
class OInputStream : public WeakImplHelper1 < XInputStream >
{
public:
    OInputStream( const Sequence< sal_Int8 >&seq ) :
        nPos( 0 ),
        m_seq( seq )
        {}

public:
    virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            nBytesToRead = (nBytesToRead > m_seq.getLength() - nPos ) ?
                m_seq.getLength() - nPos :
                nBytesToRead;
            aData = Sequence< sal_Int8 > ( &(m_seq.getConstArray()[nPos]) , nBytesToRead );
            nPos += nBytesToRead;
            return nBytesToRead;
        }
    virtual sal_Int32 SAL_CALL readSomeBytes(
        ::com::sun::star::uno::Sequence< sal_Int8 >& aData,
        sal_Int32 nMaxBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            return readBytes( aData, nMaxBytesToRead );
        }
    virtual void SAL_CALL skipBytes( sal_Int32 /*nBytesToSkip*/ )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            // not implemented
        }
    virtual sal_Int32 SAL_CALL available(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            return m_seq.getLength() - nPos;
        }
    virtual void SAL_CALL closeInput(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            // not needed
        }
    sal_Int32 nPos;
    Sequence< sal_Int8> m_seq;
};

//-------------------------------
// Helper : create an input stream from a file
//------------------------------
Reference< XInputStream > createStreamFromFile(
    const char *pcFile )
{
    FILE *f = fopen( pcFile , "rb" );
    Reference<  XInputStream >  r;

    if( f ) {
        fseek( f , 0 , SEEK_END );
        int nLength = ftell( f );
        fseek( f , 0 , SEEK_SET );

        Sequence<sal_Int8> seqIn(nLength);
        fread( seqIn.getArray() , nLength , 1 , f );

        r = Reference< XInputStream > ( new OInputStream( seqIn ) );
        fclose( f );
    }
    return r;
}

class TestDocumentHandler :
    public WeakImplHelper3< XExtendedDocumentHandler , XEntityResolver , XErrorHandler >
{
public:
    TestDocumentHandler(const char* locale, const char* outFile ) :
      rootNode(0), nError(0), nbOfCurrencies(0), nbOfCalendars(0), nbOfFormatElements(0),
      nbOfTransliterations(0), nbOfCollations(0), nbOfDays(50), nbOfMonths(50), nbOfEras(10),
      flag(-1), of(outFile, locale), isStartDayOfWeek(false), foundDefaultName(false),
      foundVariant(false), openElement(false)
    {
        strncpy( theLocale, locale, sizeof(theLocale) );
        theLocale[sizeof(theLocale)-1] = 0;
    }

    ~TestDocumentHandler(  )
    {
        of.closeOutput();
    }

public: // Error handler
    virtual void SAL_CALL error(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        ++nError;
        printf( "Error !\n" );
        throw  SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("error from error handler")) ,
            Reference < XInterface >() ,
            aSAXParseException );
    }
    virtual void SAL_CALL fatalError(const Any& /*aSAXParseException*/) throw (SAXException, RuntimeException)
    {
        ++nError;
        printf( "Fatal Error !\n" );
    }
    virtual void SAL_CALL warning(const Any& /*aSAXParseException*/) throw (SAXException, RuntimeException)
    {
        printf( "Warning !\n" );
    }

public: // ExtendedDocumentHandler

    stack<LocaleNode *> currentNode ;
    sal_Bool  fElement ;
    LocaleNode * rootNode;

    virtual void SAL_CALL startDocument(void) throw (SAXException, RuntimeException)
    {
    printf( "parsing document %s started\n", theLocale);
    of.writeAsciiString("#include <sal/types.h>\n\n\n");
    of.writeAsciiString("#include <stdio.h> // debug printfs\n\n");
    of.writeAsciiString("extern \"C\" {\n\n");
    }

    virtual void SAL_CALL endDocument(void) throw (SAXException, RuntimeException)
    {
        if (rootNode)
        {
            rootNode->generateCode(of);
            int err = rootNode->getError();
            if (err)
            {
                printf( "Error: in data for %s: %d\n", theLocale, err);
                nError += err;
            }
        }
        else
        {
            ++nError;
            printf( "Error: no data for %s\n", theLocale);
        }
        printf( "parsing document %s finished\n", theLocale);

        of.writeAsciiString("} // extern \"C\"\n\n");
        of.closeOutput();
    }

    virtual void SAL_CALL startElement(const OUString& aName,
                              const Reference< XAttributeList > & xAttribs)
        throw (SAXException,RuntimeException)
    {

        LocaleNode * l =  LocaleNode::createNode (aName, xAttribs);
        if (!currentNode.empty() ) {
            LocaleNode * ln = (LocaleNode *) currentNode . top();
            ln->addChild(l);
        } else {
            rootNode = l;
        }
        currentNode . push (l);
    }

    virtual void SAL_CALL endElement(const OUString& /*aName*/) throw (SAXException,RuntimeException)
    {
        currentNode . pop();
    }

    virtual void SAL_CALL characters(const OUString& aChars) throw (SAXException,RuntimeException)
    {

        LocaleNode * l = currentNode . top();
        l->setValue (aChars);
        ::rtl::OUString str(aChars);
        sal_Unicode nonBreakSPace[2]= {0xa, 0x0};
        if(!openElement || str.equals(nonBreakSPace))
          return;
    }

    virtual void SAL_CALL ignorableWhitespace(const OUString& /*aWhitespaces*/) throw (SAXException,RuntimeException)
    {
    }

    virtual void SAL_CALL processingInstruction(const OUString& /*aTarget*/, const OUString& /*aData*/) throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual void SAL_CALL setDocumentLocator(const Reference< XLocator> & /*xLocator*/)
        throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual InputSource SAL_CALL resolveEntity(
        const OUString& sPublicId,
        const OUString& sSystemId)
        throw (RuntimeException)
    {
        InputSource source;
        source.sSystemId = sSystemId;
        source.sPublicId = sPublicId;

        source.aInputStream = createStreamFromFile(
            OUStringToOString( sSystemId , RTL_TEXTENCODING_ASCII_US) );

        return source;
    }

    virtual void SAL_CALL startCDATA(void) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL endCDATA(void) throw (RuntimeException)
    {
    }
    virtual void SAL_CALL comment(const OUString& /*sComment*/) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL unknown(const OUString& /*sString*/) throw (SAXException,RuntimeException)
    {
    }

    virtual void SAL_CALL allowLineBreak( void) throw (SAXException, RuntimeException )
    {

    }

public:
    int nError;
    ::rtl::OUString currentElement;
    sal_Int16 nbOfCurrencies;
    sal_Int16 nbOfCalendars;
    sal_Int16 nbOfFormatElements;
    sal_Int16 nbOfTransliterations;
    sal_Int16 nbOfCollations;
    Sequence<sal_Int16> nbOfDays;
    Sequence<sal_Int16> nbOfMonths;
    Sequence<sal_Int16> nbOfEras;
    sal_Char *elementTag;
    sal_Char theLocale[50];
    sal_Int16 flag;
    OFileWriter of;
    sal_Bool isStartDayOfWeek;
    sal_Bool foundDefaultName;
    sal_Bool foundVariant;
        sal_Bool openElement;
};

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{

    if( argc < 6) {
        printf( "usage : %s <locaLe> <XML inputfile> <destination file> <services.rdb location> <types.rdb location>\n", argv[0] );
        exit( 1 );
    }

    // create service manager
    Reference< XMultiServiceFactory > xSMgr;
    try
    {
        xSMgr = createRegistryServiceFactory(
            ::rtl::OUString::createFromAscii(argv[4]),
            ::rtl::OUString::createFromAscii(argv[5]) );
    }
    catch ( Exception& )
    {
        printf( "Exception on createRegistryServiceFactory\n" );
        exit(1);
    }

    Reference < XImplementationRegistration > xReg;
    try
    {
        // Create registration service
        Reference < XInterface > x = xSMgr->createInstance(
            OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
        xReg = Reference<  XImplementationRegistration > ( x , UNO_QUERY );
    }
    catch( Exception & ) {
        printf( "Couldn't create ImplementationRegistration service\n" );
        exit(1);
    }

    OString sTestName;
    try
    {
        // Load dll for the tested component
        OUString aDllName =
            OUString::createFromAscii( "sax.uno" SAL_DLLEXTENSION );
        xReg->registerImplementation(
            OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
            aDllName,
            Reference< XSimpleRegistry > ()  );
    }
    catch( Exception &e ) {
        printf( "Couldn't raise sax.uno library!\n" );
        printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );

        exit(1);
    }

    //--------------------------------
    // parser demo
    // read xml from a file and count elements
    //--------------------------------
    Reference< XInterface > x = xSMgr->createInstance(
        OUString::createFromAscii( "com.sun.star.xml.sax.Parser" ) );
    int nError = 0;
    if( x.is() )
    {
        Reference< XParser > rParser( x , UNO_QUERY );

        // create and connect the document handler to the parser
        TestDocumentHandler *pDocHandler = new TestDocumentHandler( argv[1], argv[3]);

        Reference < XDocumentHandler >  rDocHandler( (XDocumentHandler *) pDocHandler );
        Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler );

        rParser->setDocumentHandler( rDocHandler );
        rParser->setEntityResolver( rEntityResolver );

        // create the input stream
        InputSource source;
        source.aInputStream = createStreamFromFile( argv[2] );
        source.sSystemId    = OUString::createFromAscii( argv[2] );

        try
        {
            // start parsing
            rParser->parseStream( source );
        }

        catch( Exception & e )
        {
            OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 );
            printf( "Exception during parsing : %s\n" ,  o1.getStr() );
            exit(1);
        }
        nError = pDocHandler->nError;
    }
    else
    {
        printf( "couln't create sax-parser component\n" );
        exit(1);
    }

    return nError;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.14.10); FILE MERGED 2008/03/31 16:01:26 rt 1.14.10.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: saxparser.cxx,v $
 * $Revision: 1.15 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"

#include <stdio.h>
#include <string.h>
#include <stack>

#include "sal/main.h"

#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#include <com/sun/star/xml/sax/SAXParseException.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase3.hxx>

#include <vos/diagnose.hxx>

#include "LocaleNode.hxx"

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::com::sun::star::xml::sax;
using namespace ::com::sun::star::io;

/************
 * Sequence of bytes -> InputStream
 ************/
class OInputStream : public WeakImplHelper1 < XInputStream >
{
public:
    OInputStream( const Sequence< sal_Int8 >&seq ) :
        nPos( 0 ),
        m_seq( seq )
        {}

public:
    virtual sal_Int32 SAL_CALL readBytes( Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            nBytesToRead = (nBytesToRead > m_seq.getLength() - nPos ) ?
                m_seq.getLength() - nPos :
                nBytesToRead;
            aData = Sequence< sal_Int8 > ( &(m_seq.getConstArray()[nPos]) , nBytesToRead );
            nPos += nBytesToRead;
            return nBytesToRead;
        }
    virtual sal_Int32 SAL_CALL readSomeBytes(
        ::com::sun::star::uno::Sequence< sal_Int8 >& aData,
        sal_Int32 nMaxBytesToRead )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            return readBytes( aData, nMaxBytesToRead );
        }
    virtual void SAL_CALL skipBytes( sal_Int32 /*nBytesToSkip*/ )
        throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)
        {
            // not implemented
        }
    virtual sal_Int32 SAL_CALL available(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            return m_seq.getLength() - nPos;
        }
    virtual void SAL_CALL closeInput(  )
        throw(NotConnectedException, IOException, RuntimeException)
        {
            // not needed
        }
    sal_Int32 nPos;
    Sequence< sal_Int8> m_seq;
};

//-------------------------------
// Helper : create an input stream from a file
//------------------------------
Reference< XInputStream > createStreamFromFile(
    const char *pcFile )
{
    FILE *f = fopen( pcFile , "rb" );
    Reference<  XInputStream >  r;

    if( f ) {
        fseek( f , 0 , SEEK_END );
        int nLength = ftell( f );
        fseek( f , 0 , SEEK_SET );

        Sequence<sal_Int8> seqIn(nLength);
        fread( seqIn.getArray() , nLength , 1 , f );

        r = Reference< XInputStream > ( new OInputStream( seqIn ) );
        fclose( f );
    }
    return r;
}

class TestDocumentHandler :
    public WeakImplHelper3< XExtendedDocumentHandler , XEntityResolver , XErrorHandler >
{
public:
    TestDocumentHandler(const char* locale, const char* outFile ) :
      rootNode(0), nError(0), nbOfCurrencies(0), nbOfCalendars(0), nbOfFormatElements(0),
      nbOfTransliterations(0), nbOfCollations(0), nbOfDays(50), nbOfMonths(50), nbOfEras(10),
      flag(-1), of(outFile, locale), isStartDayOfWeek(false), foundDefaultName(false),
      foundVariant(false), openElement(false)
    {
        strncpy( theLocale, locale, sizeof(theLocale) );
        theLocale[sizeof(theLocale)-1] = 0;
    }

    ~TestDocumentHandler(  )
    {
        of.closeOutput();
    }

public: // Error handler
    virtual void SAL_CALL error(const Any& aSAXParseException) throw (SAXException, RuntimeException)
    {
        ++nError;
        printf( "Error !\n" );
        throw  SAXException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("error from error handler")) ,
            Reference < XInterface >() ,
            aSAXParseException );
    }
    virtual void SAL_CALL fatalError(const Any& /*aSAXParseException*/) throw (SAXException, RuntimeException)
    {
        ++nError;
        printf( "Fatal Error !\n" );
    }
    virtual void SAL_CALL warning(const Any& /*aSAXParseException*/) throw (SAXException, RuntimeException)
    {
        printf( "Warning !\n" );
    }

public: // ExtendedDocumentHandler

    stack<LocaleNode *> currentNode ;
    sal_Bool  fElement ;
    LocaleNode * rootNode;

    virtual void SAL_CALL startDocument(void) throw (SAXException, RuntimeException)
    {
    printf( "parsing document %s started\n", theLocale);
    of.writeAsciiString("#include <sal/types.h>\n\n\n");
    of.writeAsciiString("#include <stdio.h> // debug printfs\n\n");
    of.writeAsciiString("extern \"C\" {\n\n");
    }

    virtual void SAL_CALL endDocument(void) throw (SAXException, RuntimeException)
    {
        if (rootNode)
        {
            rootNode->generateCode(of);
            int err = rootNode->getError();
            if (err)
            {
                printf( "Error: in data for %s: %d\n", theLocale, err);
                nError += err;
            }
        }
        else
        {
            ++nError;
            printf( "Error: no data for %s\n", theLocale);
        }
        printf( "parsing document %s finished\n", theLocale);

        of.writeAsciiString("} // extern \"C\"\n\n");
        of.closeOutput();
    }

    virtual void SAL_CALL startElement(const OUString& aName,
                              const Reference< XAttributeList > & xAttribs)
        throw (SAXException,RuntimeException)
    {

        LocaleNode * l =  LocaleNode::createNode (aName, xAttribs);
        if (!currentNode.empty() ) {
            LocaleNode * ln = (LocaleNode *) currentNode . top();
            ln->addChild(l);
        } else {
            rootNode = l;
        }
        currentNode . push (l);
    }

    virtual void SAL_CALL endElement(const OUString& /*aName*/) throw (SAXException,RuntimeException)
    {
        currentNode . pop();
    }

    virtual void SAL_CALL characters(const OUString& aChars) throw (SAXException,RuntimeException)
    {

        LocaleNode * l = currentNode . top();
        l->setValue (aChars);
        ::rtl::OUString str(aChars);
        sal_Unicode nonBreakSPace[2]= {0xa, 0x0};
        if(!openElement || str.equals(nonBreakSPace))
          return;
    }

    virtual void SAL_CALL ignorableWhitespace(const OUString& /*aWhitespaces*/) throw (SAXException,RuntimeException)
    {
    }

    virtual void SAL_CALL processingInstruction(const OUString& /*aTarget*/, const OUString& /*aData*/) throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual void SAL_CALL setDocumentLocator(const Reference< XLocator> & /*xLocator*/)
        throw (SAXException,RuntimeException)
    {
        // ignored
    }

    virtual InputSource SAL_CALL resolveEntity(
        const OUString& sPublicId,
        const OUString& sSystemId)
        throw (RuntimeException)
    {
        InputSource source;
        source.sSystemId = sSystemId;
        source.sPublicId = sPublicId;

        source.aInputStream = createStreamFromFile(
            OUStringToOString( sSystemId , RTL_TEXTENCODING_ASCII_US) );

        return source;
    }

    virtual void SAL_CALL startCDATA(void) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL endCDATA(void) throw (RuntimeException)
    {
    }
    virtual void SAL_CALL comment(const OUString& /*sComment*/) throw (SAXException,RuntimeException)
    {
    }
    virtual void SAL_CALL unknown(const OUString& /*sString*/) throw (SAXException,RuntimeException)
    {
    }

    virtual void SAL_CALL allowLineBreak( void) throw (SAXException, RuntimeException )
    {

    }

public:
    int nError;
    ::rtl::OUString currentElement;
    sal_Int16 nbOfCurrencies;
    sal_Int16 nbOfCalendars;
    sal_Int16 nbOfFormatElements;
    sal_Int16 nbOfTransliterations;
    sal_Int16 nbOfCollations;
    Sequence<sal_Int16> nbOfDays;
    Sequence<sal_Int16> nbOfMonths;
    Sequence<sal_Int16> nbOfEras;
    sal_Char *elementTag;
    sal_Char theLocale[50];
    sal_Int16 flag;
    OFileWriter of;
    sal_Bool isStartDayOfWeek;
    sal_Bool foundDefaultName;
    sal_Bool foundVariant;
        sal_Bool openElement;
};

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{

    if( argc < 6) {
        printf( "usage : %s <locaLe> <XML inputfile> <destination file> <services.rdb location> <types.rdb location>\n", argv[0] );
        exit( 1 );
    }

    // create service manager
    Reference< XMultiServiceFactory > xSMgr;
    try
    {
        xSMgr = createRegistryServiceFactory(
            ::rtl::OUString::createFromAscii(argv[4]),
            ::rtl::OUString::createFromAscii(argv[5]) );
    }
    catch ( Exception& )
    {
        printf( "Exception on createRegistryServiceFactory\n" );
        exit(1);
    }

    Reference < XImplementationRegistration > xReg;
    try
    {
        // Create registration service
        Reference < XInterface > x = xSMgr->createInstance(
            OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" ) );
        xReg = Reference<  XImplementationRegistration > ( x , UNO_QUERY );
    }
    catch( Exception & ) {
        printf( "Couldn't create ImplementationRegistration service\n" );
        exit(1);
    }

    OString sTestName;
    try
    {
        // Load dll for the tested component
        OUString aDllName =
            OUString::createFromAscii( "sax.uno" SAL_DLLEXTENSION );
        xReg->registerImplementation(
            OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),
            aDllName,
            Reference< XSimpleRegistry > ()  );
    }
    catch( Exception &e ) {
        printf( "Couldn't raise sax.uno library!\n" );
        printf( "%s\n" , OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).getStr() );

        exit(1);
    }

    //--------------------------------
    // parser demo
    // read xml from a file and count elements
    //--------------------------------
    Reference< XInterface > x = xSMgr->createInstance(
        OUString::createFromAscii( "com.sun.star.xml.sax.Parser" ) );
    int nError = 0;
    if( x.is() )
    {
        Reference< XParser > rParser( x , UNO_QUERY );

        // create and connect the document handler to the parser
        TestDocumentHandler *pDocHandler = new TestDocumentHandler( argv[1], argv[3]);

        Reference < XDocumentHandler >  rDocHandler( (XDocumentHandler *) pDocHandler );
        Reference< XEntityResolver > rEntityResolver( (XEntityResolver *) pDocHandler );

        rParser->setDocumentHandler( rDocHandler );
        rParser->setEntityResolver( rEntityResolver );

        // create the input stream
        InputSource source;
        source.aInputStream = createStreamFromFile( argv[2] );
        source.sSystemId    = OUString::createFromAscii( argv[2] );

        try
        {
            // start parsing
            rParser->parseStream( source );
        }

        catch( Exception & e )
        {
            OString o1 = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8 );
            printf( "Exception during parsing : %s\n" ,  o1.getStr() );
            exit(1);
        }
        nError = pDocHandler->nError;
    }
    else
    {
        printf( "couln't create sax-parser component\n" );
        exit(1);
    }

    return nError;
}
<|endoftext|>