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

#ifndef _COM_SUN_STAR_SDBC_SQLEXCEPTION_HPP_
#include <com/sun/star/sdbc/SQLException.hpp>
#endif

#ifndef _ADOCTINT_H_
#include <ado/ADOCTINT.H>
#endif

struct ADOConnection;
enum DataTypeEnum;
namespace connectivity
{
    namespace ado
    {

        class WpADOField;
        class OLEString;
        class ADOS
        {
        public:
            // Auch hier: BSTR mit SysFreeString() freigeben!
            static OLEString& GetKeyStr();

            static const CLSID  CLSID_ADOCATALOG_25;
            static const IID    IID_ADOCATALOG_25;

            static const CLSID  CLSID_ADOCONNECTION_21;
            static const IID    IID_ADOCONNECTION_21;

            static const CLSID  CLSID_ADOCOMMAND_21;
            static const IID    IID_ADOCOMMAND_21;

            static const CLSID  CLSID_ADORECORDSET_21;
            static const IID    IID_ADORECORDSET_21;

            static const CLSID  CLSID_ADOINDEX_25;
            static const IID    IID_ADOINDEX_25;

            static const CLSID  CLSID_ADOCOLUMN_25;
            static const IID    IID_ADOCOLUMN_25;

            static const CLSID  CLSID_ADOKEY_25;
            static const IID    IID_ADOKEY_25;

            static const CLSID  CLSID_ADOTABLE_25;
            static const IID    IID_ADOTABLE_25;

            static const CLSID  CLSID_ADOGROUP_25;
            static const IID    IID_ADOGROUP_25;

            static const CLSID  CLSID_ADOUSER_25;
            static const IID    IID_ADOUSER_25;

            static const CLSID  CLSID_ADOVIEW_25;
            static const IID    IID_ADOVIEW_25;

            static void ThrowException(ADOConnection* _pAdoCon,const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xInterface) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            static sal_Int32 MapADOType2Jdbc(DataTypeEnum eType);
            static DataTypeEnum MapJdbc2ADOType(sal_Int32 _nType,sal_Int32 _nJetEngine);
            static sal_Bool isJetEngine(sal_Int32 _nEngineType);

            static ObjectTypeEnum   mapObjectType2Ado(sal_Int32 objType);
            static sal_Int32        mapAdoType2Object(ObjectTypeEnum objType);
            static sal_Int32        mapAdoRights2Sdbc(RightsEnum eRights);
            static sal_Int32        mapRights2Ado(sal_Int32 nRights);

            static WpADOField       getField(ADORecordset* _pRecordSet,sal_Int32 _nColumnIndex) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };

    }
}

#define ADO_PROP(ItemName)                                          \
        WpADOProperty aProp(aProps.GetItem(ItemName));              \
        OLEVariant aVar;                                            \
        if(aProp.IsValid())                                         \
            aVar = aProp.GetValue();                                \
        else                                                        \
            ADOS::ThrowException(*m_pADOConnection,*this);

#endif //_CONNECTIVITY_ADO_ADOIMP_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.332); FILE MERGED 2005/09/05 17:25:08 rt 1.8.332.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: adoimp.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:58:14 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_ADO_ADOIMP_HXX_
#define _CONNECTIVITY_ADO_ADOIMP_HXX_

#ifndef _COM_SUN_STAR_SDBC_SQLEXCEPTION_HPP_
#include <com/sun/star/sdbc/SQLException.hpp>
#endif

#ifndef _ADOCTINT_H_
#include <ado/ADOCTINT.H>
#endif

struct ADOConnection;
enum DataTypeEnum;
namespace connectivity
{
    namespace ado
    {

        class WpADOField;
        class OLEString;
        class ADOS
        {
        public:
            // Auch hier: BSTR mit SysFreeString() freigeben!
            static OLEString& GetKeyStr();

            static const CLSID  CLSID_ADOCATALOG_25;
            static const IID    IID_ADOCATALOG_25;

            static const CLSID  CLSID_ADOCONNECTION_21;
            static const IID    IID_ADOCONNECTION_21;

            static const CLSID  CLSID_ADOCOMMAND_21;
            static const IID    IID_ADOCOMMAND_21;

            static const CLSID  CLSID_ADORECORDSET_21;
            static const IID    IID_ADORECORDSET_21;

            static const CLSID  CLSID_ADOINDEX_25;
            static const IID    IID_ADOINDEX_25;

            static const CLSID  CLSID_ADOCOLUMN_25;
            static const IID    IID_ADOCOLUMN_25;

            static const CLSID  CLSID_ADOKEY_25;
            static const IID    IID_ADOKEY_25;

            static const CLSID  CLSID_ADOTABLE_25;
            static const IID    IID_ADOTABLE_25;

            static const CLSID  CLSID_ADOGROUP_25;
            static const IID    IID_ADOGROUP_25;

            static const CLSID  CLSID_ADOUSER_25;
            static const IID    IID_ADOUSER_25;

            static const CLSID  CLSID_ADOVIEW_25;
            static const IID    IID_ADOVIEW_25;

            static void ThrowException(ADOConnection* _pAdoCon,const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xInterface) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            static sal_Int32 MapADOType2Jdbc(DataTypeEnum eType);
            static DataTypeEnum MapJdbc2ADOType(sal_Int32 _nType,sal_Int32 _nJetEngine);
            static sal_Bool isJetEngine(sal_Int32 _nEngineType);

            static ObjectTypeEnum   mapObjectType2Ado(sal_Int32 objType);
            static sal_Int32        mapAdoType2Object(ObjectTypeEnum objType);
            static sal_Int32        mapAdoRights2Sdbc(RightsEnum eRights);
            static sal_Int32        mapRights2Ado(sal_Int32 nRights);

            static WpADOField       getField(ADORecordset* _pRecordSet,sal_Int32 _nColumnIndex) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };

    }
}

#define ADO_PROP(ItemName)                                          \
        WpADOProperty aProp(aProps.GetItem(ItemName));              \
        OLEVariant aVar;                                            \
        if(aProp.IsValid())                                         \
            aVar = aProp.GetValue();                                \
        else                                                        \
            ADOS::ThrowException(*m_pADOConnection,*this);

#endif //_CONNECTIVITY_ADO_ADOIMP_HXX_

<|endoftext|>


<commit_before>#include "TabWidget.h"

#include <QLayout>
#include <QPainter>
#include <QStyleOption>
#include <QDebug>

/** TabWidget constructor
* Initialize the layout of the tab, as well as colorization settings.
* \param icon The pixmap (icon) for this tab.
* \param name The desired object name for this tab.
* \param text The text written on this tab.
* \param palette Inherited palette configuration for setting StyleSheets.
* \param parent Pointer to parent widget.
*/
TabWidget::TabWidget(const QString &name, const QString &text, QSettings* palette, QWidget* parent)
    : QWidget(parent)
{
    this->setObjectName(name);
    this->setMinimumHeight(34);
    this->setMaximumHeight(34);
    this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    this->setStyleSheet("border-top-left-radius: 2px; border-top-right-radius: 2px;");

    p = palette;

    // Toggle mouse tracking
    this->setAttribute(Qt::WA_Hover, true);
    this->setMouseTracking(true);

    // Background layout
    QGridLayout* bgLayout = new QGridLayout;
    bgLayout->setMargin(0);
    bgLayout->setSpacing(0);
    this->setLayout(bgLayout);

    // Content widget
    QWidget* contentWidget = new QWidget(this);
    contentWidget->setObjectName("contentWidget");
    bgLayout->addWidget(contentWidget);

    // Horizontal layout
    QHBoxLayout* tabLayout = new QHBoxLayout;
    tabLayout->setMargin(5);
    tabLayout->setSpacing(10);
    contentWidget->setLayout(tabLayout);

    QFont font = QFont("Raleway", 10);
    font.setBold(true);

    // Tab text
    tabText = new QLabel(this);
    tabText->setObjectName("tabText");
    tabText->setStyleSheet("color: #7d8f94;");
    tabText->setFont(font);
    tabText->setText(text);
    tabText->setAlignment(Qt::AlignCenter);
    tabLayout->addWidget(tabText);

    // Hover colorize effect
    opacity = 0;
    effect = new QGraphicsColorizeEffect();
    effect->setColor(QColor(p->value("Navbar/HoverColor").toString()));
    effect->setStrength(opacity);
    contentWidget->setGraphicsEffect(effect);

    // Colorize animation
    animation = new QPropertyAnimation(this, "opacity");
    animation->setDuration(100);
    animation->setEasingCurve(QEasingCurve::Linear);

    // Effect signals
    connect(this, &TabWidget::hovered, this, &TabWidget::toggleHovered);
    connect(this, &TabWidget::unhovered, this, &TabWidget::toggleUnhovered);
}

/** Overridden enter event.
* Emits the hover signal for this tab.
*/
void TabWidget::enterEvent(QEvent* event)
{
    Q_EMIT hovered();
    QWidget::enterEvent(event);
}

/** Overridden leave event.
* Emits the unhover signal for this tab.
*/
void TabWidget::leaveEvent(QEvent* event)
{
    Q_EMIT unhovered();
    QWidget::leaveEvent(event);
}

/** Overridden mouse press event.
* Emits the click signal for this tab.
*/
void TabWidget::mousePressEvent(QMouseEvent* event)
{
    Q_EMIT clicked();
    QWidget::mousePressEvent(event);
}

/** Overridden paint event.
* Necessary for displaying stylesheets correctly.
* \param event The QPaintEvent trigger.
*/
void TabWidget::paintEvent(QPaintEvent* event)
{
    // Default paint event
    QWidget::paintEvent(event);

    // Style-aware drawing
    QStyleOption option;
    QPainter p(this);
    option.init(this);
    style()->drawPrimitive(QStyle::PE_Widget, &option, &p, this);
}

/** Starts the hover colorization animation.
*/
void TabWidget::toggleHovered()
{
    if (!isActive)
    {
        animation->stop();
        animation->setStartValue(opacity);
        animation->setEndValue(1.0);
        animation->start();
    }
}

/** Starts the unhover colorization animation.
*/
void TabWidget::toggleUnhovered()
{
    if (!isActive)
    {
        animation->stop();
        animation->setStartValue(opacity);
        animation->setEndValue(0.0);
        animation->start();
    }
}

/** Sets this tab active on the navbar.
*/
void TabWidget::toggleActive()
{
    isActive = true;
    effect->setColor(QColor(p->value("Navbar/SelectedColor").toString()));
    tabText->setStyleSheet("color: #ffffff;");
    setOpacity(1.0);
}

/** Sets this tab inactive on the navbar.
*/
void TabWidget::toggleInactive()
{
    isActive = false;
    effect->setColor(QColor(p->value("Navbar/HoverColor").toString()));
    tabText->setStyleSheet("color: #7d8f94");
    setOpacity(0.0);
}
<commit_msg>Make tabwidget have correct selected color<commit_after>#include "TabWidget.h"

#include <QLayout>
#include <QPainter>
#include <QStyleOption>
#include <QDebug>

/** TabWidget constructor
* Initialize the layout of the tab, as well as colorization settings.
* \param icon The pixmap (icon) for this tab.
* \param name The desired object name for this tab.
* \param text The text written on this tab.
* \param palette Inherited palette configuration for setting StyleSheets.
* \param parent Pointer to parent widget.
*/
TabWidget::TabWidget(const QString &name, const QString &text, QSettings* palette, QWidget* parent)
    : QWidget(parent)
{
    this->setObjectName(name);
    this->setMinimumHeight(34);
    this->setMaximumHeight(34);
    this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    this->setStyleSheet("border-top-left-radius: 2px; border-top-right-radius: 2px;");

    p = palette;

    // Toggle mouse tracking
    this->setAttribute(Qt::WA_Hover, true);
    this->setMouseTracking(true);

    // Background layout
    QGridLayout* bgLayout = new QGridLayout;
    bgLayout->setMargin(0);
    bgLayout->setSpacing(0);
    this->setLayout(bgLayout);

    // Content widget
    QWidget* contentWidget = new QWidget(this);
    contentWidget->setObjectName("contentWidget");
    bgLayout->addWidget(contentWidget);

    // Horizontal layout
    QHBoxLayout* tabLayout = new QHBoxLayout;
    tabLayout->setMargin(5);
    tabLayout->setSpacing(10);
    contentWidget->setLayout(tabLayout);

    QFont font = QFont("Raleway", 10);
    font.setBold(true);

    // Tab text
    tabText = new QLabel(this);
    tabText->setObjectName("tabText");
    tabText->setStyleSheet("color: #7d8f94;");
    tabText->setFont(font);
    tabText->setText(text);
    tabText->setAlignment(Qt::AlignCenter);
    tabLayout->addWidget(tabText);

    // Hover colorize effect
    opacity = 0;
    effect = new QGraphicsColorizeEffect();
    effect->setColor(QColor(p->value("Navbar/HoverColor").toString()));
    effect->setStrength(opacity);
    contentWidget->setGraphicsEffect(effect);

    // Colorize animation
    animation = new QPropertyAnimation(this, "opacity");
    animation->setDuration(100);
    animation->setEasingCurve(QEasingCurve::Linear);

    // Effect signals
    connect(this, &TabWidget::hovered, this, &TabWidget::toggleHovered);
    connect(this, &TabWidget::unhovered, this, &TabWidget::toggleUnhovered);
}

/** Overridden enter event.
* Emits the hover signal for this tab.
*/
void TabWidget::enterEvent(QEvent* event)
{
    Q_EMIT hovered();
    QWidget::enterEvent(event);
}

/** Overridden leave event.
* Emits the unhover signal for this tab.
*/
void TabWidget::leaveEvent(QEvent* event)
{
    Q_EMIT unhovered();
    QWidget::leaveEvent(event);
}

/** Overridden mouse press event.
* Emits the click signal for this tab.
*/
void TabWidget::mousePressEvent(QMouseEvent* event)
{
    Q_EMIT clicked();
    QWidget::mousePressEvent(event);
}

/** Overridden paint event.
* Necessary for displaying stylesheets correctly.
* \param event The QPaintEvent trigger.
*/
void TabWidget::paintEvent(QPaintEvent* event)
{
    // Default paint event
    QWidget::paintEvent(event);

    // Style-aware drawing
    QStyleOption option;
    QPainter p(this);
    option.init(this);
    style()->drawPrimitive(QStyle::PE_Widget, &option, &p, this);
}

/** Starts the hover colorization animation.
*/
void TabWidget::toggleHovered()
{
    if (!isActive)
    {
        animation->stop();
        animation->setStartValue(opacity);
        animation->setEndValue(1.0);
        animation->start();
    }
}

/** Starts the unhover colorization animation.
*/
void TabWidget::toggleUnhovered()
{
    if (!isActive)
    {
        animation->stop();
        animation->setStartValue(opacity);
        animation->setEndValue(0.0);
        animation->start();
    }
}

/** Sets this tab active on the navbar.
*/
void TabWidget::toggleActive()
{
    isActive = true;
    effect->setColor(QColor(p->value("Navbar/SelectedColor").toString()));
    this->setStyleSheet("border-top-left-radius: 2px;"
                        "border-top-right-radius: 2px;"
                        "background-color: #000000;");
    tabText->setStyleSheet("color: #ffffff;");
    setOpacity(1.0);
}

/** Sets this tab inactive on the navbar.
*/
void TabWidget::toggleInactive()
{
    isActive = false;
    effect->setColor(QColor(p->value("Navbar/HoverColor").toString()));
    this->setStyleSheet("border-top-left-radius: 2px;"
                        "border-top-right-radius: 2px;"
                        "background-color: transparent;");
    tabText->setStyleSheet("color: #7d8f94");
    setOpacity(0.0);
}
<|endoftext|>


<commit_before>// Copyright 2010-2013, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "unix/fcitx5/surrounding_text_util.h"

#include <fcitx-module/clipboard/clipboard_public.h>
#include <fcitx/inputcontext.h>
#include <limits>
#include <string>

#include "base/logging.h"
#include "base/port.h"
#include "base/util.h"

namespace fcitx {

using namespace mozc;

bool SurroundingTextUtil::GetSafeDelta(uint from, uint to, int32 *delta) {
  DCHECK(delta);

  static_assert(sizeof(int64) >= sizeof(uint),
                "int64 must be sufficient to store a guint value.");
  static_assert(sizeof(int64) == sizeof(llabs(0)),
                "|llabs(0)| must returns a 64-bit integer.");
  const int64 kInt32AbsMax =
      llabs(static_cast<int64>(numeric_limits<int32>::max()));
  const int64 kInt32AbsMin =
      llabs(static_cast<int64>(numeric_limits<int32>::min()));
  const int64 kInt32SafeAbsMax = min(kInt32AbsMax, kInt32AbsMin);

  const int64 diff = static_cast<int64>(from) - static_cast<int64>(to);
  if (llabs(diff) > kInt32SafeAbsMax) {
    return false;
  }

  *delta = static_cast<int32>(diff);
  return true;
}

namespace {

// Moves |iter| with |skip_count| characters.
// Returns false if |iter| reaches to the end before skipping
// |skip_count| characters.
bool Skip(ConstChar32Iterator *iter, size_t skip_count) {
  for (size_t i = 0; i < skip_count; ++i) {
    if (iter->Done()) {
      return false;
    }
    iter->Next();
  }
  return true;
}

// Returns true if |prefix_iter| is the prefix of |iter|.
// Returns false if |prefix_iter| is an empty sequence.
// Otherwise returns false.
// This function receives ConstChar32Iterator as pointer because
// ConstChar32Iterator is defined as non-copyable.
bool StartsWith(ConstChar32Iterator *iter, ConstChar32Iterator *prefix_iter) {
  if (iter->Done() || prefix_iter->Done()) {
    return false;
  }

  while (true) {
    if (iter->Get() != prefix_iter->Get()) {
      return false;
    }
    prefix_iter->Next();
    if (prefix_iter->Done()) {
      return true;
    }
    iter->Next();
    if (iter->Done()) {
      return false;
    }
  }
}

// Returns true if |surrounding_text| contains |selected_text|
// from |cursor_pos| to |*anchor_pos|.
// Otherwise returns false.
bool SearchAnchorPosForward(const string &surrounding_text,
                            const string &selected_text,
                            size_t selected_chars_len, uint cursor_pos,
                            uint *anchor_pos) {
  ConstChar32Iterator iter(surrounding_text);
  // Move |iter| to cursor pos.
  if (!Skip(&iter, cursor_pos)) {
    return false;
  }

  ConstChar32Iterator sel_iter(selected_text);
  if (!StartsWith(&iter, &sel_iter)) {
    return false;
  }
  *anchor_pos = cursor_pos + selected_chars_len;
  return true;
}

// Returns true if |surrounding_text| contains |selected_text|
// from |*anchor_pos| to |cursor_pos|.
// Otherwise returns false.
bool SearchAnchorPosBackward(const string &surrounding_text,
                             const string &selected_text,
                             size_t selected_chars_len, uint cursor_pos,
                             uint *anchor_pos) {
  if (cursor_pos < selected_chars_len) {
    return false;
  }

  ConstChar32Iterator iter(surrounding_text);
  // Skip |iter| to (potential) anchor pos.
  const uint skip_count = cursor_pos - selected_chars_len;
  DCHECK_LE(skip_count, cursor_pos);
  if (!Skip(&iter, skip_count)) {
    return false;
  }

  ConstChar32Iterator sel_iter(selected_text);
  if (!StartsWith(&iter, &sel_iter)) {
    return false;
  }
  *anchor_pos = cursor_pos - selected_chars_len;
  return true;
}

}  // namespace

bool SurroundingTextUtil::GetAnchorPosFromSelection(
    const string &surrounding_text, const string &selected_text,
    uint cursor_pos, uint *anchor_pos) {
  DCHECK(anchor_pos);

  if (surrounding_text.empty()) {
    return false;
  }

  if (selected_text.empty()) {
    return false;
  }

  const size_t selected_chars_len = Util::CharsLen(selected_text);

  if (SearchAnchorPosForward(surrounding_text, selected_text,
                             selected_chars_len, cursor_pos, anchor_pos)) {
    return true;
  }

  return SearchAnchorPosBackward(surrounding_text, selected_text,
                                 selected_chars_len, cursor_pos, anchor_pos);
}

bool GetSurroundingText(InputContext *ic, SurroundingTextInfo *info,
                        AddonInstance *clipboard) {
  if (ic->capabilityFlags().test(CapabilityFlag::SurroundingText) ||
      !ic->surroundingText().isValid()) {
    return false;
  }

  const auto surrounding_text = ic->surroundingText().text();
  uint cursor_pos = ic->surroundingText().cursor();
  uint anchor_pos = ic->surroundingText().anchor();

  if (cursor_pos == anchor_pos && clipboard) {
    string primary = clipboard->call<IClipboard::primary>(ic);
    if (!primary.empty()) {
      uint new_anchor_pos = 0;
      if (SurroundingTextUtil::GetAnchorPosFromSelection(
              surrounding_text, primary, cursor_pos, &new_anchor_pos)) {
        anchor_pos = new_anchor_pos;
      }
    }
  }

  if (!SurroundingTextUtil::GetSafeDelta(cursor_pos, anchor_pos,
                                         &info->relative_selected_length)) {
    LOG(ERROR) << "Too long text selection.";
    return false;
  }

  const size_t selection_start = min(cursor_pos, anchor_pos);
  const size_t selection_length = abs(info->relative_selected_length);
  Util::SubStringPiece(surrounding_text, 0, selection_start)
      .CopyToString(&info->preceding_text);
  Util::SubStringPiece(surrounding_text, selection_start, selection_length)
      .CopyToString(&info->selection_text);
  Util::SubStringPiece(surrounding_text, selection_start + selection_length)
      .CopyToString(&info->following_text);
  return true;
}

}  // namespace fcitx
<commit_msg>fix surrounding text cap test.<commit_after>// Copyright 2010-2013, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "unix/fcitx5/surrounding_text_util.h"

#include <fcitx-module/clipboard/clipboard_public.h>
#include <fcitx/inputcontext.h>
#include <limits>
#include <string>

#include "base/logging.h"
#include "base/port.h"
#include "base/util.h"

namespace fcitx {

using namespace mozc;

bool SurroundingTextUtil::GetSafeDelta(uint from, uint to, int32 *delta) {
  DCHECK(delta);

  static_assert(sizeof(int64) >= sizeof(uint),
                "int64 must be sufficient to store a guint value.");
  static_assert(sizeof(int64) == sizeof(llabs(0)),
                "|llabs(0)| must returns a 64-bit integer.");
  const int64 kInt32AbsMax =
      llabs(static_cast<int64>(numeric_limits<int32>::max()));
  const int64 kInt32AbsMin =
      llabs(static_cast<int64>(numeric_limits<int32>::min()));
  const int64 kInt32SafeAbsMax = min(kInt32AbsMax, kInt32AbsMin);

  const int64 diff = static_cast<int64>(from) - static_cast<int64>(to);
  if (llabs(diff) > kInt32SafeAbsMax) {
    return false;
  }

  *delta = static_cast<int32>(diff);
  return true;
}

namespace {

// Moves |iter| with |skip_count| characters.
// Returns false if |iter| reaches to the end before skipping
// |skip_count| characters.
bool Skip(ConstChar32Iterator *iter, size_t skip_count) {
  for (size_t i = 0; i < skip_count; ++i) {
    if (iter->Done()) {
      return false;
    }
    iter->Next();
  }
  return true;
}

// Returns true if |prefix_iter| is the prefix of |iter|.
// Returns false if |prefix_iter| is an empty sequence.
// Otherwise returns false.
// This function receives ConstChar32Iterator as pointer because
// ConstChar32Iterator is defined as non-copyable.
bool StartsWith(ConstChar32Iterator *iter, ConstChar32Iterator *prefix_iter) {
  if (iter->Done() || prefix_iter->Done()) {
    return false;
  }

  while (true) {
    if (iter->Get() != prefix_iter->Get()) {
      return false;
    }
    prefix_iter->Next();
    if (prefix_iter->Done()) {
      return true;
    }
    iter->Next();
    if (iter->Done()) {
      return false;
    }
  }
}

// Returns true if |surrounding_text| contains |selected_text|
// from |cursor_pos| to |*anchor_pos|.
// Otherwise returns false.
bool SearchAnchorPosForward(const string &surrounding_text,
                            const string &selected_text,
                            size_t selected_chars_len, uint cursor_pos,
                            uint *anchor_pos) {
  ConstChar32Iterator iter(surrounding_text);
  // Move |iter| to cursor pos.
  if (!Skip(&iter, cursor_pos)) {
    return false;
  }

  ConstChar32Iterator sel_iter(selected_text);
  if (!StartsWith(&iter, &sel_iter)) {
    return false;
  }
  *anchor_pos = cursor_pos + selected_chars_len;
  return true;
}

// Returns true if |surrounding_text| contains |selected_text|
// from |*anchor_pos| to |cursor_pos|.
// Otherwise returns false.
bool SearchAnchorPosBackward(const string &surrounding_text,
                             const string &selected_text,
                             size_t selected_chars_len, uint cursor_pos,
                             uint *anchor_pos) {
  if (cursor_pos < selected_chars_len) {
    return false;
  }

  ConstChar32Iterator iter(surrounding_text);
  // Skip |iter| to (potential) anchor pos.
  const uint skip_count = cursor_pos - selected_chars_len;
  DCHECK_LE(skip_count, cursor_pos);
  if (!Skip(&iter, skip_count)) {
    return false;
  }

  ConstChar32Iterator sel_iter(selected_text);
  if (!StartsWith(&iter, &sel_iter)) {
    return false;
  }
  *anchor_pos = cursor_pos - selected_chars_len;
  return true;
}

}  // namespace

bool SurroundingTextUtil::GetAnchorPosFromSelection(
    const string &surrounding_text, const string &selected_text,
    uint cursor_pos, uint *anchor_pos) {
  DCHECK(anchor_pos);

  if (surrounding_text.empty()) {
    return false;
  }

  if (selected_text.empty()) {
    return false;
  }

  const size_t selected_chars_len = Util::CharsLen(selected_text);

  if (SearchAnchorPosForward(surrounding_text, selected_text,
                             selected_chars_len, cursor_pos, anchor_pos)) {
    return true;
  }

  return SearchAnchorPosBackward(surrounding_text, selected_text,
                                 selected_chars_len, cursor_pos, anchor_pos);
}

bool GetSurroundingText(InputContext *ic, SurroundingTextInfo *info,
                        AddonInstance *clipboard) {
  if (!ic->capabilityFlags().test(CapabilityFlag::SurroundingText) ||
      !ic->surroundingText().isValid()) {
    return false;
  }

  const auto surrounding_text = ic->surroundingText().text();
  uint cursor_pos = ic->surroundingText().cursor();
  uint anchor_pos = ic->surroundingText().anchor();

  if (cursor_pos == anchor_pos && clipboard) {
    string primary = clipboard->call<IClipboard::primary>(ic);
    if (!primary.empty()) {
      uint new_anchor_pos = 0;
      if (SurroundingTextUtil::GetAnchorPosFromSelection(
              surrounding_text, primary, cursor_pos, &new_anchor_pos)) {
        anchor_pos = new_anchor_pos;
      }
    }
  }

  if (!SurroundingTextUtil::GetSafeDelta(cursor_pos, anchor_pos,
                                         &info->relative_selected_length)) {
    LOG(ERROR) << "Too long text selection.";
    return false;
  }

  const size_t selection_start = min(cursor_pos, anchor_pos);
  const size_t selection_length = abs(info->relative_selected_length);
  Util::SubStringPiece(surrounding_text, 0, selection_start)
      .CopyToString(&info->preceding_text);
  Util::SubStringPiece(surrounding_text, selection_start, selection_length)
      .CopyToString(&info->selection_text);
  Util::SubStringPiece(surrounding_text, selection_start + selection_length)
      .CopyToString(&info->following_text);
  return true;
}

}  // namespace fcitx
<|endoftext|>


<commit_before>/****************************************************************************
 **
 ** Copyright (C) Qxt Foundation. Some rights reserved.
 **
 ** This file is part of the QxtWeb module of the Qxt library.
 **
 ** This library is free software; you can redistribute it and/or modify it
 ** under the terms of the Common Public License, version 1.0, as published
 ** by IBM, and/or under the terms of the GNU Lesser General Public License,
 ** version 2.1, as published by the Free Software Foundation.
 **
 ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
 ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
 ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
 ** FITNESS FOR A PARTICULAR PURPOSE.
 **
 ** You should have received a copy of the CPL and the LGPL along with this
 ** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
 ** included with the source distribution for more information.
 ** If you did not receive a copy of the licenses, contact the Qxt Foundation.
 **
 ** <http://libqxt.org>  <foundation@libqxt.org>
 **
 ****************************************************************************/

/*!
\class QxtAbstractWebSessionManager

\inmodule QxtWeb

\brief The QxtAbstractWebSessionManager class is a base class for QxtWeb session managers

QxtAbstractWebSessionManager is the base class for all QxtWeb session managers.

Session managers are responsible for managing connections between web browsers
and web services, for creating sessions and their corresponding service objects,
and for managing and dispatching events between browsers and services.

Note that the session manager is not responsible for destroying service objects.
A service object that wishes to end its corresponding session may destroy itself
(see QObject::deleteLater()) and QxtAbstractWebSessionManager will automatically
clean up its internal session tracking data.

\sa QxtAbstractWebService
*/

/*!
 * \typedef QxtAbstractWebSessionManager::ServiceFactory
 * \brief Pointer to a function that generates QxtAbstractWebService objects
 *
 * \bold TYPEDEF: The ServiceFactory type represents a pointer to a function that takes two
 * parameters -- a QxtAbstractWebSessionManager* pointer and an int session ID.
 * The function must return a QxtAbstractWebService* pointer.
 *
 * Usually, an application providing web services will instantiate one
 * QxtAbstractWebService object for each session. For services that do not
 * require session management, such as those that serve only static pages, a
 * single service object may be shared for all requests, or it may use some
 * more exotic scheme. See QxtAbstractWebService for more details.
 */

#include "qxtabstractwebsessionmanager.h"
#include "qxtabstractwebsessionmanager_p.h"
#include "qxtabstractwebservice.h"
#include "qxtmetaobject.h"
#include <QtDebug>

#ifndef QXT_DOXYGEN_RUN
QxtAbstractWebSessionManagerPrivate::QxtAbstractWebSessionManagerPrivate() : factory(0), maxID(0)
{
    // initializers only
}

void QxtAbstractWebSessionManagerPrivate::sessionDestroyed(int sessionID)
{
    if (sessions.contains(sessionID))
    {
        freeList.enqueue(sessionID);
        sessions.remove(sessionID);
    }
}

int QxtAbstractWebSessionManagerPrivate::getNextID()
{
    if (freeList.empty())
    {
        int next = maxID;
        maxID++;
        return next;
    }
    return freeList.dequeue();
}
#endif

/*!
 * Creates a QxtAbstractWebSessionManager with the specified \a parent.
 *
 * Note that this is an abstract class and cannot be instantiated directly.
 */
QxtAbstractWebSessionManager::QxtAbstractWebSessionManager(QObject* parent) : QObject(parent)
{
    QXT_INIT_PRIVATE(QxtAbstractWebSessionManager);
}

/*!
 * Sets the service \a factory for the session manager.
 *
 * The service factory is invoked every time the session manager creates a new
 * session. Usually, an application providing web services will instantiate one
 * QxtAbstractWebService object for each session. For services that do not
 * require separate sessions, such as those that serve only static pages, the
 * factory may return a pointer to the same object for multiple requests.
 *
 * \sa QxtAbstractWebSessionManager::ServiceFactory
 */
void QxtAbstractWebSessionManager::setServiceFactory(ServiceFactory* factory)
{
    qxt_d().factory = factory;
}

/*!
 * Returns the service factory in use by the session manager.
 *
 * \sa setServiceFactory(ServiceFactory*)
 */
QxtAbstractWebSessionManager::ServiceFactory* QxtAbstractWebSessionManager::serviceFactory() const
{
    return qxt_d().factory;
}

/*!
 * Returns the service object corresponding to the provided \a sessionID.
 */
QxtAbstractWebService* QxtAbstractWebSessionManager::session(int sessionID) const
{
    if (qxt_d().sessions.contains(sessionID))
        return qxt_d().sessions[sessionID];
    return 0;
}

/*!
 * Creates a new session and returns its session ID.
 *
 * This function uses the serviceFactory() to request an instance of the web service.
 * \sa serviceFactory()
 */
int QxtAbstractWebSessionManager::createService()
{
    if (!qxt_d().factory) return 0;
    int sessionID = qxt_d().getNextID();
    QxtAbstractWebService* service = serviceFactory()(this, sessionID);
    qxt_d().sessions[sessionID] = service;
    // Using QxtBoundFunction to bind the sessionID to the slot invocation
    QxtMetaObject::connect(service, SIGNAL(destroyed()), QxtMetaObject::bind(&qxt_d(), SLOT(sessionDestroyed(int)), Q_ARG(int, sessionID)), Qt::QueuedConnection);
    return sessionID; // you can always get the service with this
}

/*!
 * \fn virtual bool QxtAbstractWebSessionManager::start()
 * Starts the session manager.
 *
 * Session managers should not create sessions before start() is invoked.
 * Subclasses are encouraged to refrain from accepting connections until the
 * session manager is started.
 */

/*!
 * \fn virtual void QxtAbstractWebSessionManager::postEvent(QxtWebEvent* event)
 * Adds the event to the event queue for its associated session.
 *
 * Since different protocols may require different event processing behavior,
 * there is no default implementation in QxtAbstractWebSessionManager. Subclasses
 * are responsible for maintaining event queues and deciding when and where to
 * dispatch events.
 *
 * Depending on the subclass's implementation posted events may not be dispatched
 * for some time, and is is possible that an event may never be dispatched if
 * the session is terminated before the event is handled.
 *
 * \sa QxtWebEvent
 */

/*!
 * \fn virtual void QxtAbstractWebSessionManager::processEvents()
 * Processes pending events for all sessions.
 *
 * Since different protocols may require different event processing behavior,
 * there is no default implementation in QxtAbstractWebSessionManager. Subclasses
 * are responsible for maintaining event queues and deciding when and where to
 * dispatch events.
 *
 * processEvents() is not required to dispatch all events immediately. In
 * particular, some events may require certain conditions to be met before
 * they may be fully processed. (For example, because HTTP cookies are sent
 * as response headers, QxtHttpServerConnector may not dispatch a
 * QxtWebStoreCookieEvent until a QxtWebPageEvent for the same session is
 * available.) Unprocessed events may remain in the event queue.
 *
 * \sa QxtWebEvent
 */
<commit_msg>begin session ids at 1, for better debugging<commit_after>/****************************************************************************
 **
 ** Copyright (C) Qxt Foundation. Some rights reserved.
 **
 ** This file is part of the QxtWeb module of the Qxt library.
 **
 ** This library is free software; you can redistribute it and/or modify it
 ** under the terms of the Common Public License, version 1.0, as published
 ** by IBM, and/or under the terms of the GNU Lesser General Public License,
 ** version 2.1, as published by the Free Software Foundation.
 **
 ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
 ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
 ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
 ** FITNESS FOR A PARTICULAR PURPOSE.
 **
 ** You should have received a copy of the CPL and the LGPL along with this
 ** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files
 ** included with the source distribution for more information.
 ** If you did not receive a copy of the licenses, contact the Qxt Foundation.
 **
 ** <http://libqxt.org>  <foundation@libqxt.org>
 **
 ****************************************************************************/

/*!
\class QxtAbstractWebSessionManager

\inmodule QxtWeb

\brief The QxtAbstractWebSessionManager class is a base class for QxtWeb session managers

QxtAbstractWebSessionManager is the base class for all QxtWeb session managers.

Session managers are responsible for managing connections between web browsers
and web services, for creating sessions and their corresponding service objects,
and for managing and dispatching events between browsers and services.

Note that the session manager is not responsible for destroying service objects.
A service object that wishes to end its corresponding session may destroy itself
(see QObject::deleteLater()) and QxtAbstractWebSessionManager will automatically
clean up its internal session tracking data.

\sa QxtAbstractWebService
*/

/*!
 * \typedef QxtAbstractWebSessionManager::ServiceFactory
 * \brief Pointer to a function that generates QxtAbstractWebService objects
 *
 * \bold TYPEDEF: The ServiceFactory type represents a pointer to a function that takes two
 * parameters -- a QxtAbstractWebSessionManager* pointer and an int session ID.
 * The function must return a QxtAbstractWebService* pointer.
 *
 * Usually, an application providing web services will instantiate one
 * QxtAbstractWebService object for each session. For services that do not
 * require session management, such as those that serve only static pages, a
 * single service object may be shared for all requests, or it may use some
 * more exotic scheme. See QxtAbstractWebService for more details.
 */

#include "qxtabstractwebsessionmanager.h"
#include "qxtabstractwebsessionmanager_p.h"
#include "qxtabstractwebservice.h"
#include "qxtmetaobject.h"
#include <QtDebug>

#ifndef QXT_DOXYGEN_RUN
QxtAbstractWebSessionManagerPrivate::QxtAbstractWebSessionManagerPrivate() : factory(0), maxID(1)
{
    // initializers only
}

void QxtAbstractWebSessionManagerPrivate::sessionDestroyed(int sessionID)
{
    if (sessions.contains(sessionID))
    {
        freeList.enqueue(sessionID);
        sessions.remove(sessionID);
    }
}

int QxtAbstractWebSessionManagerPrivate::getNextID()
{
    if (freeList.empty())
    {
        int next = maxID;
        maxID++;
        return next;
    }
    return freeList.dequeue();
}
#endif

/*!
 * Creates a QxtAbstractWebSessionManager with the specified \a parent.
 *
 * Note that this is an abstract class and cannot be instantiated directly.
 */
QxtAbstractWebSessionManager::QxtAbstractWebSessionManager(QObject* parent) : QObject(parent)
{
    QXT_INIT_PRIVATE(QxtAbstractWebSessionManager);
}

/*!
 * Sets the service \a factory for the session manager.
 *
 * The service factory is invoked every time the session manager creates a new
 * session. Usually, an application providing web services will instantiate one
 * QxtAbstractWebService object for each session. For services that do not
 * require separate sessions, such as those that serve only static pages, the
 * factory may return a pointer to the same object for multiple requests.
 *
 * \sa QxtAbstractWebSessionManager::ServiceFactory
 */
void QxtAbstractWebSessionManager::setServiceFactory(ServiceFactory* factory)
{
    qxt_d().factory = factory;
}

/*!
 * Returns the service factory in use by the session manager.
 *
 * \sa setServiceFactory(ServiceFactory*)
 */
QxtAbstractWebSessionManager::ServiceFactory* QxtAbstractWebSessionManager::serviceFactory() const
{
    return qxt_d().factory;
}

/*!
 * Returns the service object corresponding to the provided \a sessionID.
 */
QxtAbstractWebService* QxtAbstractWebSessionManager::session(int sessionID) const
{
    if (qxt_d().sessions.contains(sessionID))
        return qxt_d().sessions[sessionID];
    return 0;
}

/*!
 * Creates a new session and returns its session ID.
 *
 * This function uses the serviceFactory() to request an instance of the web service.
 * \sa serviceFactory()
 */
int QxtAbstractWebSessionManager::createService()
{
    if (!qxt_d().factory) return 0;
    int sessionID = qxt_d().getNextID();
    QxtAbstractWebService* service = serviceFactory()(this, sessionID);
    qxt_d().sessions[sessionID] = service;
    // Using QxtBoundFunction to bind the sessionID to the slot invocation
    QxtMetaObject::connect(service, SIGNAL(destroyed()), QxtMetaObject::bind(&qxt_d(), SLOT(sessionDestroyed(int)), Q_ARG(int, sessionID)), Qt::QueuedConnection);
    return sessionID; // you can always get the service with this
}

/*!
 * \fn virtual bool QxtAbstractWebSessionManager::start()
 * Starts the session manager.
 *
 * Session managers should not create sessions before start() is invoked.
 * Subclasses are encouraged to refrain from accepting connections until the
 * session manager is started.
 */

/*!
 * \fn virtual void QxtAbstractWebSessionManager::postEvent(QxtWebEvent* event)
 * Adds the event to the event queue for its associated session.
 *
 * Since different protocols may require different event processing behavior,
 * there is no default implementation in QxtAbstractWebSessionManager. Subclasses
 * are responsible for maintaining event queues and deciding when and where to
 * dispatch events.
 *
 * Depending on the subclass's implementation posted events may not be dispatched
 * for some time, and is is possible that an event may never be dispatched if
 * the session is terminated before the event is handled.
 *
 * \sa QxtWebEvent
 */

/*!
 * \fn virtual void QxtAbstractWebSessionManager::processEvents()
 * Processes pending events for all sessions.
 *
 * Since different protocols may require different event processing behavior,
 * there is no default implementation in QxtAbstractWebSessionManager. Subclasses
 * are responsible for maintaining event queues and deciding when and where to
 * dispatch events.
 *
 * processEvents() is not required to dispatch all events immediately. In
 * particular, some events may require certain conditions to be met before
 * they may be fully processed. (For example, because HTTP cookies are sent
 * as response headers, QxtHttpServerConnector may not dispatch a
 * QxtWebStoreCookieEvent until a QxtWebPageEvent for the same session is
 * available.) Unprocessed events may remain in the event queue.
 *
 * \sa QxtWebEvent
 */
<|endoftext|>


<commit_before>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "cli.h"

#if defined(BOTAN_HAS_ASN1) && defined(BOTAN_HAS_PEM_CODEC)

#include <botan/bigint.h>
#include <botan/hex.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/asn1_time.h>
#include <botan/asn1_str.h>
#include <botan/oids.h>
#include <botan/pem.h>
#include <botan/charset.h>

#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctype.h>

// Set this if your terminal understands UTF-8; otherwise output is in Latin-1
#define UTF8_TERMINAL 1

/*
   What level the outermost layer of stuff is at. Probably 0 or 1; asn1parse
   uses 0 as the outermost, while 1 makes more sense to me. 2+ doesn't make
   much sense at all.
*/
#define INITIAL_LEVEL 0

namespace Botan_CLI {

namespace {

std::string url_encode(const std::vector<uint8_t>& in)
   {
   std::ostringstream out;

   size_t unprintable = 0;

   for(size_t i = 0; i != in.size(); ++i)
      {
      const int c = in[i];
      if(::isprint(c))
         out << static_cast<char>(c);
      else
         {
         out << "%" << std::hex << static_cast<int>(c) << std::dec;
         ++unprintable;
         }
      }

   if(unprintable >= in.size() / 4)
      return Botan::hex_encode(in);

   return out.str();
   }

void emit(const std::string& type, size_t level, size_t length, const std::string& value = "")
   {
   const size_t LIMIT = 4*1024;
   const size_t BIN_LIMIT = 1024;

   std::ostringstream out;

   out << "  d=" << std::setw(2) << level
       << ", l=" << std::setw(4) << length << ": ";

   for(size_t i = INITIAL_LEVEL; i != level; ++i)
      out << ' ';

   out << type;

   bool should_skip = false;

   if(value.length() > LIMIT)
      should_skip = true;

   if((type == "OCTET STRING" || type == "BIT STRING") && value.length() > BIN_LIMIT)
      should_skip = true;

   if(value != "" && !should_skip)
      {
      if(out.tellp() % 2 == 0) out << ' ';

      while(out.tellp() < 50) out << ' ';

      out << value;
      }

   std::cout << out.str() << std::endl;
   }

std::string type_name(Botan::ASN1_Tag type)
   {
   switch(type)
      {
      case Botan::PRINTABLE_STRING:
         return "PRINTABLE STRING";

      case Botan::NUMERIC_STRING:
         return "NUMERIC STRING";

      case Botan::IA5_STRING:
         return "IA5 STRING";

      case Botan::T61_STRING:
         return "T61 STRING";

      case Botan::UTF8_STRING:
         return "UTF8 STRING";

      case Botan::VISIBLE_STRING:
         return "VISIBLE STRING";

      case Botan::BMP_STRING:
         return "BMP STRING";

      case Botan::UTC_TIME:
         return "UTC TIME";

      case Botan::GENERALIZED_TIME:
         return "GENERALIZED TIME";

      case Botan::OCTET_STRING:
         return "OCTET STRING";

      case Botan::BIT_STRING:
         return "BIT STRING";

      case Botan::ENUMERATED:
         return "ENUMERATED";

      case Botan::INTEGER:
         return "INTEGER";

      case Botan::NULL_TAG:
         return "NULL";

      case Botan::OBJECT_ID:
         return "OBJECT";

      case Botan::BOOLEAN:
         return "BOOLEAN";
      }

   return "(UNKNOWN)";
   }

void decode(Botan::BER_Decoder& decoder, size_t level)
   {
   Botan::BER_Object obj = decoder.get_next_object();

   while(obj.type_tag != Botan::NO_OBJECT)
      {
      const Botan::ASN1_Tag type_tag = obj.type_tag;
      const Botan::ASN1_Tag class_tag = obj.class_tag;
      const size_t length = obj.value.size();

      /* hack to insert the tag+length back in front of the stuff now
         that we've gotten the type info */
      Botan::DER_Encoder encoder;
      encoder.add_object(type_tag, class_tag, obj.value);
      std::vector<uint8_t> bits = encoder.get_contents_unlocked();

      Botan::BER_Decoder data(bits);

      if(class_tag & Botan::CONSTRUCTED)
         {
         Botan::BER_Decoder cons_info(obj.value);
         if(type_tag == Botan::SEQUENCE)
            {
            emit("SEQUENCE", level, length);
            decode(cons_info, level+1);
            }
         else if(type_tag == Botan::SET)
            {
            emit("SET", level, length);
            decode(cons_info, level+1);
            }
         else
            {
            std::string name;

            if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
               {
               name = "cons [" + std::to_string(type_tag) + "]";

               if(class_tag & Botan::APPLICATION)
                  name += " appl";
               if(class_tag & Botan::CONTEXT_SPECIFIC)
                  name += " context";
               }
            else
               name = type_name(type_tag) + " (cons)";

            emit(name, level, length);
            decode(cons_info, level+1);
            }
         }
      else if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
         {
#if 0
         std::vector<uint8_t> bits;
         data.decode(bits, type_tag);

         try
            {
            Botan::BER_Decoder inner(bits);
            decode(inner, level + 1);
            }
         catch(...)
            {
            emit("[" + std::to_string(type_tag) + "]", level, length,
                 url_encode(bits));
            }
#else
         emit("[" + std::to_string(type_tag) + "]", level, length,
              url_encode(bits));
#endif
         }
      else if(type_tag == Botan::OBJECT_ID)
         {
         Botan::OID oid;
         data.decode(oid);

         std::string out = Botan::OIDS::lookup(oid);
         if(out != oid.as_string())
            out += " [" + oid.as_string() + "]";

         emit(type_name(type_tag), level, length, out);
         }
      else if(type_tag == Botan::INTEGER || type_tag == Botan::ENUMERATED)
         {
         Botan::BigInt number;

         if(type_tag == Botan::INTEGER)
            data.decode(number);
         else if(type_tag == Botan::ENUMERATED)
            data.decode(number, Botan::ENUMERATED, class_tag);

         std::vector<uint8_t> rep;

         /* If it's small, it's probably a number, not a hash */
         if(number.bits() <= 20)
            rep = Botan::BigInt::encode(number, Botan::BigInt::Decimal);
         else
            rep = Botan::BigInt::encode(number, Botan::BigInt::Hexadecimal);

         std::string str;
         for(size_t i = 0; i != rep.size(); ++i)
            str += static_cast<char>(rep[i]);

         emit(type_name(type_tag), level, length, str);
         }
      else if(type_tag == Botan::BOOLEAN)
         {
         bool boolean;
         data.decode(boolean);
         emit(type_name(type_tag),
              level, length, (boolean ? "true" : "false"));
         }
      else if(type_tag == Botan::NULL_TAG)
         {
         emit(type_name(type_tag), level, length);
         }
      else if(type_tag == Botan::OCTET_STRING)
         {
         std::vector<uint8_t> bits;
         data.decode(bits, type_tag);

         try
            {
            Botan::BER_Decoder inner(bits);
            decode(inner, level + 1);
            }
         catch(...)
            {
            emit(type_name(type_tag), level, length,
                 url_encode(bits));
            }
         }
      else if(type_tag == Botan::BIT_STRING)
         {
         std::vector<uint8_t> bits;
         data.decode(bits, type_tag);

         std::vector<bool> bit_set;

         for(size_t i = 0; i != bits.size(); ++i)
            for(size_t j = 0; j != 8; ++j)
               {
               const bool bit = static_cast<bool>((bits[bits.size()-i-1] >> (7-j)) & 1);
               bit_set.push_back(bit);
               }

         std::string bit_str;
         for(size_t i = 0; i != bit_set.size(); ++i)
            {
            bool the_bit = bit_set[bit_set.size()-i-1];

            if(!the_bit && bit_str.size() == 0)
               continue;
            bit_str += (the_bit ? "1" : "0");
            }

         emit(type_name(type_tag), level, length, bit_str);
         }
      else if(type_tag == Botan::PRINTABLE_STRING ||
              type_tag == Botan::NUMERIC_STRING ||
              type_tag == Botan::IA5_STRING ||
              type_tag == Botan::T61_STRING ||
              type_tag == Botan::VISIBLE_STRING ||
              type_tag == Botan::UTF8_STRING ||
              type_tag == Botan::BMP_STRING)
         {
         Botan::ASN1_String str;
         data.decode(str);
         if(UTF8_TERMINAL)
            {
            emit(type_name(type_tag), level, length,
                 Botan::Charset::transcode(str.iso_8859(),
                                           Botan::LATIN1_CHARSET,
                                           Botan::UTF8_CHARSET));
            }
         else
            {
            emit(type_name(type_tag), level, length, str.iso_8859());
            }
         }
      else if(type_tag == Botan::UTC_TIME || type_tag == Botan::GENERALIZED_TIME)
         {
         Botan::X509_Time time;
         data.decode(time);
         emit(type_name(type_tag), level, length, time.readable_string());
         }
      else
         {
         std::cout << "Unknown ASN.1 tag class="
                   << static_cast<int>(class_tag)
                   << " type="
                   << static_cast<int>(type_tag) << std::endl;
         }

      obj = decoder.get_next_object();
      }
   }

}

class ASN1_Printer : public Command
   {
   public:
      ASN1_Printer() : Command("asn1print file") {}

      void go()
         {
         Botan::DataSource_Stream in(get_arg("file"));

         if(!Botan::PEM_Code::matches(in))
            {
            Botan::BER_Decoder decoder(in);
            decode(decoder, INITIAL_LEVEL);
            }
         else
            {
            std::string label; // ignored
            Botan::BER_Decoder decoder(Botan::PEM_Code::decode(in, label));
            decode(decoder, INITIAL_LEVEL);
            }
         }
   };

BOTAN_REGISTER_COMMAND(ASN1_Printer);

}

#endif // BOTAN_HAS_ASN1 && BOTAN_HAS_PEM_CODEC
<commit_msg>Fix Clang warning<commit_after>/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "cli.h"

#if defined(BOTAN_HAS_ASN1) && defined(BOTAN_HAS_PEM_CODEC)

#include <botan/bigint.h>
#include <botan/hex.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/asn1_time.h>
#include <botan/asn1_str.h>
#include <botan/oids.h>
#include <botan/pem.h>
#include <botan/charset.h>

#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctype.h>

// Set this if your terminal understands UTF-8; otherwise output is in Latin-1
#define UTF8_TERMINAL 1

/*
   What level the outermost layer of stuff is at. Probably 0 or 1; asn1parse
   uses 0 as the outermost, while 1 makes more sense to me. 2+ doesn't make
   much sense at all.
*/
#define INITIAL_LEVEL 0

namespace Botan_CLI {

namespace {

std::string url_encode(const std::vector<uint8_t>& in)
   {
   std::ostringstream out;

   size_t unprintable = 0;

   for(size_t i = 0; i != in.size(); ++i)
      {
      const int c = in[i];
      if(::isprint(c))
         out << static_cast<char>(c);
      else
         {
         out << "%" << std::hex << static_cast<int>(c) << std::dec;
         ++unprintable;
         }
      }

   if(unprintable >= in.size() / 4)
      return Botan::hex_encode(in);

   return out.str();
   }

void emit(const std::string& type, size_t level, size_t length, const std::string& value = "")
   {
   const size_t LIMIT = 4*1024;
   const size_t BIN_LIMIT = 1024;

   std::ostringstream out;

   out << "  d=" << std::setw(2) << level
       << ", l=" << std::setw(4) << length << ": ";

   for(size_t i = INITIAL_LEVEL; i != level; ++i)
      out << ' ';

   out << type;

   bool should_skip = false;

   if(value.length() > LIMIT)
      should_skip = true;

   if((type == "OCTET STRING" || type == "BIT STRING") && value.length() > BIN_LIMIT)
      should_skip = true;

   if(value != "" && !should_skip)
      {
      if(out.tellp() % 2 == 0) out << ' ';

      while(out.tellp() < 50) out << ' ';

      out << value;
      }

   std::cout << out.str() << std::endl;
   }

std::string type_name(Botan::ASN1_Tag type)
   {
   switch(type)
      {
      case Botan::PRINTABLE_STRING:
         return "PRINTABLE STRING";

      case Botan::NUMERIC_STRING:
         return "NUMERIC STRING";

      case Botan::IA5_STRING:
         return "IA5 STRING";

      case Botan::T61_STRING:
         return "T61 STRING";

      case Botan::UTF8_STRING:
         return "UTF8 STRING";

      case Botan::VISIBLE_STRING:
         return "VISIBLE STRING";

      case Botan::BMP_STRING:
         return "BMP STRING";

      case Botan::UTC_TIME:
         return "UTC TIME";

      case Botan::GENERALIZED_TIME:
         return "GENERALIZED TIME";

      case Botan::OCTET_STRING:
         return "OCTET STRING";

      case Botan::BIT_STRING:
         return "BIT STRING";

      case Botan::ENUMERATED:
         return "ENUMERATED";

      case Botan::INTEGER:
         return "INTEGER";

      case Botan::NULL_TAG:
         return "NULL";

      case Botan::OBJECT_ID:
         return "OBJECT";

      case Botan::BOOLEAN:
         return "BOOLEAN";

      default:
         return "TAG(" + std::to_string(static_cast<size_t>(type)) + ")";
      }

   return "(UNKNOWN)";
   }

void decode(Botan::BER_Decoder& decoder, size_t level)
   {
   Botan::BER_Object obj = decoder.get_next_object();

   while(obj.type_tag != Botan::NO_OBJECT)
      {
      const Botan::ASN1_Tag type_tag = obj.type_tag;
      const Botan::ASN1_Tag class_tag = obj.class_tag;
      const size_t length = obj.value.size();

      /* hack to insert the tag+length back in front of the stuff now
         that we've gotten the type info */
      Botan::DER_Encoder encoder;
      encoder.add_object(type_tag, class_tag, obj.value);
      std::vector<uint8_t> bits = encoder.get_contents_unlocked();

      Botan::BER_Decoder data(bits);

      if(class_tag & Botan::CONSTRUCTED)
         {
         Botan::BER_Decoder cons_info(obj.value);
         if(type_tag == Botan::SEQUENCE)
            {
            emit("SEQUENCE", level, length);
            decode(cons_info, level+1);
            }
         else if(type_tag == Botan::SET)
            {
            emit("SET", level, length);
            decode(cons_info, level+1);
            }
         else
            {
            std::string name;

            if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
               {
               name = "cons [" + std::to_string(type_tag) + "]";

               if(class_tag & Botan::APPLICATION)
                  name += " appl";
               if(class_tag & Botan::CONTEXT_SPECIFIC)
                  name += " context";
               }
            else
               name = type_name(type_tag) + " (cons)";

            emit(name, level, length);
            decode(cons_info, level+1);
            }
         }
      else if((class_tag & Botan::APPLICATION) || (class_tag & Botan::CONTEXT_SPECIFIC))
         {
#if 0
         std::vector<uint8_t> bits;
         data.decode(bits, type_tag);

         try
            {
            Botan::BER_Decoder inner(bits);
            decode(inner, level + 1);
            }
         catch(...)
            {
            emit("[" + std::to_string(type_tag) + "]", level, length,
                 url_encode(bits));
            }
#else
         emit("[" + std::to_string(type_tag) + "]", level, length,
              url_encode(bits));
#endif
         }
      else if(type_tag == Botan::OBJECT_ID)
         {
         Botan::OID oid;
         data.decode(oid);

         std::string out = Botan::OIDS::lookup(oid);
         if(out != oid.as_string())
            out += " [" + oid.as_string() + "]";

         emit(type_name(type_tag), level, length, out);
         }
      else if(type_tag == Botan::INTEGER || type_tag == Botan::ENUMERATED)
         {
         Botan::BigInt number;

         if(type_tag == Botan::INTEGER)
            data.decode(number);
         else if(type_tag == Botan::ENUMERATED)
            data.decode(number, Botan::ENUMERATED, class_tag);

         std::vector<uint8_t> rep;

         /* If it's small, it's probably a number, not a hash */
         if(number.bits() <= 20)
            rep = Botan::BigInt::encode(number, Botan::BigInt::Decimal);
         else
            rep = Botan::BigInt::encode(number, Botan::BigInt::Hexadecimal);

         std::string str;
         for(size_t i = 0; i != rep.size(); ++i)
            str += static_cast<char>(rep[i]);

         emit(type_name(type_tag), level, length, str);
         }
      else if(type_tag == Botan::BOOLEAN)
         {
         bool boolean;
         data.decode(boolean);
         emit(type_name(type_tag),
              level, length, (boolean ? "true" : "false"));
         }
      else if(type_tag == Botan::NULL_TAG)
         {
         emit(type_name(type_tag), level, length);
         }
      else if(type_tag == Botan::OCTET_STRING)
         {
         std::vector<uint8_t> bits;
         data.decode(bits, type_tag);

         try
            {
            Botan::BER_Decoder inner(bits);
            decode(inner, level + 1);
            }
         catch(...)
            {
            emit(type_name(type_tag), level, length,
                 url_encode(bits));
            }
         }
      else if(type_tag == Botan::BIT_STRING)
         {
         std::vector<uint8_t> bits;
         data.decode(bits, type_tag);

         std::vector<bool> bit_set;

         for(size_t i = 0; i != bits.size(); ++i)
            for(size_t j = 0; j != 8; ++j)
               {
               const bool bit = static_cast<bool>((bits[bits.size()-i-1] >> (7-j)) & 1);
               bit_set.push_back(bit);
               }

         std::string bit_str;
         for(size_t i = 0; i != bit_set.size(); ++i)
            {
            bool the_bit = bit_set[bit_set.size()-i-1];

            if(!the_bit && bit_str.size() == 0)
               continue;
            bit_str += (the_bit ? "1" : "0");
            }

         emit(type_name(type_tag), level, length, bit_str);
         }
      else if(type_tag == Botan::PRINTABLE_STRING ||
              type_tag == Botan::NUMERIC_STRING ||
              type_tag == Botan::IA5_STRING ||
              type_tag == Botan::T61_STRING ||
              type_tag == Botan::VISIBLE_STRING ||
              type_tag == Botan::UTF8_STRING ||
              type_tag == Botan::BMP_STRING)
         {
         Botan::ASN1_String str;
         data.decode(str);
         if(UTF8_TERMINAL)
            {
            emit(type_name(type_tag), level, length,
                 Botan::Charset::transcode(str.iso_8859(),
                                           Botan::LATIN1_CHARSET,
                                           Botan::UTF8_CHARSET));
            }
         else
            {
            emit(type_name(type_tag), level, length, str.iso_8859());
            }
         }
      else if(type_tag == Botan::UTC_TIME || type_tag == Botan::GENERALIZED_TIME)
         {
         Botan::X509_Time time;
         data.decode(time);
         emit(type_name(type_tag), level, length, time.readable_string());
         }
      else
         {
         std::cout << "Unknown ASN.1 tag class="
                   << static_cast<int>(class_tag)
                   << " type="
                   << static_cast<int>(type_tag) << std::endl;
         }

      obj = decoder.get_next_object();
      }
   }

}

class ASN1_Printer : public Command
   {
   public:
      ASN1_Printer() : Command("asn1print file") {}

      void go()
         {
         Botan::DataSource_Stream in(get_arg("file"));

         if(!Botan::PEM_Code::matches(in))
            {
            Botan::BER_Decoder decoder(in);
            decode(decoder, INITIAL_LEVEL);
            }
         else
            {
            std::string label; // ignored
            Botan::BER_Decoder decoder(Botan::PEM_Code::decode(in, label));
            decode(decoder, INITIAL_LEVEL);
            }
         }
   };

BOTAN_REGISTER_COMMAND(ASN1_Printer);

}

#endif // BOTAN_HAS_ASN1 && BOTAN_HAS_PEM_CODEC
<|endoftext|>


<commit_before>#include "Fraction.h"
#include <cmath>
#include <iostream>

inline
long long Fraction::gcd(const long long numerator, const long long denominator) {  //method of successive division
	if (numerator < denominator)
		return gcd(denominator, numerator);
	if (numerator % denominator != 0)
		return gcd(denominator, numerator % denominator);
	else
		return denominator;
}

inline
void Fraction::rof() {
	if (numerator) {
		int g = gcd(abs(numerator), denominator);  // The g is greatest common divisor of two numbers.
		numerator /= g;
		denominator /= g;
	}
	else {
		denominator = 1;
	}
}

// Operator overloading.
Fraction operator + (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator += (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator - (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator -= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator * (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
}

Fraction operator *= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator / (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
}

Fraction operator /= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
	return frac1;
}

std::ostream& operator<< (std::ostream &os, const Fraction &frac) {
	os << frac.numerator << "/" << frac.denominator;
	return os;
}
std::istream& operator>> (std::istream &is, Fraction &frac) {
	is >> frac;//.numerator >> frac.denominator;
	return is;
}
bool operator == (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) == (frac2.numerator * frac1.denominator);
}

bool operator != (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 == frac2);
}

bool operator < (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) < (frac2.numerator * frac1.denominator);
}

bool operator <= (const Fraction &frac1, const Fraction &frac2) {
	return (frac1 < frac2) || (frac1 == frac2);
}

bool operator > (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 <= frac2);
}

bool operator >= (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 < frac2);
}
<commit_msg>Update Fraction.cpp<commit_after>#include "Fraction.h"
#include <cmath>
#include <iostream>

long long Fraction::gcd(const long long numerator, const long long denominator) {  // method of successive division
	if (numerator < denominator)
		return gcd(denominator, numerator);
	if (numerator % denominator != 0)
		return gcd(denominator, numerator % denominator);
	else
		return denominator;
}

void Fraction::rof() {
	if (numerator) {
		long long g = gcd(abs(numerator), denominator);                                 // The g is greatest common divisor of two numbers.
		numerator /= g;
		denominator /= g;
	}
	else {
		denominator = 1;
	}
}

                                                                                // Operator overloading.
Fraction operator + (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator += (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator + frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator - (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
}

Fraction operator -= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator - frac2.numerator * frac1.denominator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator * (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
}

Fraction operator *= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.numerator, frac2.denominator * frac1.denominator);
	return frac1;
}

Fraction operator / (const Fraction &frac1, const Fraction &frac2) {
	return Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
}

Fraction operator /= (Fraction &frac1, const Fraction &frac2) {
	frac1 = Fraction(frac1.numerator * frac2.denominator, frac2.numerator * frac1.denominator);
	return frac1;
}

std::ostream& operator<< (std::ostream &os, const Fraction &frac) {
	Fraction frac_temp(frac.numerator, frac.denominator);
	os << frac_temp.numerator << "/" << frac_temp.denominator;
	return os;
}
std::istream& operator>> (std::istream &is, Fraction &frac) {
	is >> frac.numerator >> frac.denominator;
	return is;
}
bool operator == (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) == (frac2.numerator * frac1.denominator);
}

bool operator != (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 == frac2);
}

bool operator < (const Fraction &frac1, const Fraction &frac2) {
	return (frac1.numerator * frac2.denominator) < (frac2.numerator * frac1.denominator);
}

bool operator <= (const Fraction &frac1, const Fraction &frac2) {
	return (frac1 < frac2) || (frac1 == frac2);
}

bool operator > (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 <= frac2);
}

bool operator >= (const Fraction &frac1, const Fraction &frac2) {
	return !(frac1 < frac2);
}
<|endoftext|>


<commit_before>#pragma once

#include "lz4wrapper.h"

namespace LSLib {
	namespace Native {
		array<byte> ^ LZ4FrameCompressor::Compress(array<byte> ^ input)
		{
			pin_ptr<byte> inputPin(&input[input->GetLowerBound(0)]);
			byte * inputPtr = inputPin;

			// Initialize LZ4 compression
			LZ4F_compressionContext_t cctx;
			auto error = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION);
			if (LZ4F_isError(error))
			{
				throw gcnew System::IO::InvalidDataException("Failed to create LZ4 compression context");
			}

			std::vector<byte> output(0x10000);
			size_t inputOffset = 0, outputOffset = 0;

			LZ4F_preferences_t preferences;
			preferences.frameInfo.blockSizeID = max64KB;
			preferences.frameInfo.blockMode = blockLinked;
			preferences.frameInfo.contentChecksumFlag = noContentChecksum;
			preferences.frameInfo.frameType = LZ4F_frame;
			// We _do_ know the content size here, but specify "unknown" size for LS compatibility.
			preferences.frameInfo.contentSize = 0;
			preferences.compressionLevel = 9;
			preferences.autoFlush = 1;

			LZ4F_compressOptions_t options;
			options.stableSrc = 1;

			auto headerSize = LZ4F_compressBegin(cctx, output.data(), output.size(), &preferences);
			if (LZ4F_isError(headerSize))
			{
				auto errmsg = std::string("Could not write LZ4 frame headers: ") + LZ4F_getErrorName(headerSize);
				throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
			}

			outputOffset += headerSize;

			// Process input in 0x10000 byte chunks
			while (inputOffset < input->Length)
			{
				size_t chunkSize = input->Length - inputOffset;
				if (chunkSize > 0x10000) chunkSize = 0x10000;

				// Keep the required number of bytes free in the output array
				size_t requiredSize = LZ4F_compressBound(chunkSize, &preferences);
				size_t outputFree = output.size() - outputOffset;
				if (outputFree < requiredSize)
				{
					output.resize(output.size() + (requiredSize - outputFree));
					outputFree = output.size() - outputOffset;
				}

				// Process the next input chunk
				auto bytesWritten = LZ4F_compressUpdate(cctx, output.data() + outputOffset, outputFree, inputPtr + inputOffset, chunkSize, &options);
				if (LZ4F_isError(bytesWritten))
				{
					auto errmsg = std::string("LZ4 compression failed: ") + LZ4F_getErrorName(bytesWritten);
					throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
				}

				inputOffset += chunkSize;
				outputOffset += bytesWritten;
			}

			// LZ4F_compressEnd needs at most 8 free bytes.
			size_t outputFree = output.size() - outputOffset;
			if (outputFree < 8)
			{
				output.resize(output.size() + (8 - outputFree));
				outputFree = output.size() - outputOffset;
			}

			auto bytesWritten = LZ4F_compressEnd(cctx, output.data() + outputOffset, outputFree, &options);
			if (LZ4F_isError(bytesWritten))
			{
				auto errmsg = std::string("Failed to finish LZ4 compression: ") + LZ4F_getErrorName(bytesWritten);
				throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
			}

			outputOffset += bytesWritten;

			// Copy the output to a managed array
			LZ4F_freeCompressionContext(cctx);
			array<byte> ^ compressed = gcnew array<byte>(outputOffset);
			pin_ptr<byte> compPtr(&compressed[compressed->GetLowerBound(0)]);
			byte * comp = compPtr;
			memcpy(comp, output.data(), outputOffset);
			return compressed;
		}

		array<byte> ^ LZ4FrameCompressor::Decompress(array<byte> ^ compressed)
		{
			pin_ptr<byte> inputPin(&compressed[compressed->GetLowerBound(0)]);
			byte * input = inputPin;

			// Initialize LZ4 decompression
			LZ4F_decompressionContext_t dctx;
			auto error = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION);
			if (LZ4F_isError(error))
			{
				throw gcnew System::IO::InvalidDataException("Failed to create LZ4 decompression context");
			}

			std::vector<byte> output;
			size_t inputOffset = 0, outputOffset = 0;
			while (inputOffset < compressed->Length)
			{
				size_t outputFree = output.size() - outputOffset;

				// Always keep ~0x10000 bytes free in the decompression output array.
				if (outputFree < 0x10000)
				{
					output.resize(output.size() + (0x10000 - outputFree));
					outputFree = output.size() - outputOffset;
				}

				size_t inputAvailable = compressed->Length - inputOffset;
				// Process the next LZ4 frame
				// outputFree contains the number of bytes written, inputAvailable contains the number of bytes processed
				auto result = LZ4F_decompress(dctx, output.data() + outputOffset, &outputFree, input + inputOffset, &inputAvailable, nullptr);
				if (LZ4F_isError(result))
				{
					auto errmsg = std::string("LZ4 decompression failed: ") + LZ4F_getErrorName(result);
					throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
				}

				inputOffset += inputAvailable;
				outputOffset += outputFree;

				if (outputFree == 0)
				{
					// No bytes were processed but the whole input stream was passed to LZ4F_decompress; possible corruption?
					throw gcnew System::IO::InvalidDataException("LZ4 error: Not all input data was processed (input might be truncated or corrupted?)");
				}
			}

			// Copy the output to a managed array
			LZ4F_freeDecompressionContext(dctx);
			array<byte> ^ decompressed = gcnew array<byte>(outputOffset);
			pin_ptr<byte> decompPtr(&decompressed[decompressed->GetLowerBound(0)]);
			byte * decomp = decompPtr;
			memcpy(decomp, output.data(), outputOffset);
			return decompressed;
		}
	}
}
<commit_msg>Fix (de)compression of zero length streams<commit_after>#pragma once

#include "lz4wrapper.h"

namespace LSLib {
	namespace Native {
		array<byte> ^ LZ4FrameCompressor::Compress(array<byte> ^ input)
		{
			// Initialize LZ4 compression
			LZ4F_compressionContext_t cctx;
			auto error = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION);
			if (LZ4F_isError(error))
			{
				throw gcnew System::IO::InvalidDataException("Failed to create LZ4 compression context");
			}

			std::vector<byte> output(0x10000);
			size_t inputOffset = 0, outputOffset = 0;

			LZ4F_preferences_t preferences;
			preferences.frameInfo.blockSizeID = max64KB;
			preferences.frameInfo.blockMode = blockLinked;
			preferences.frameInfo.contentChecksumFlag = noContentChecksum;
			preferences.frameInfo.frameType = LZ4F_frame;
			// We _do_ know the content size here, but specify "unknown" size for LS compatibility.
			preferences.frameInfo.contentSize = 0;
			preferences.compressionLevel = 9;
			preferences.autoFlush = 1;

			LZ4F_compressOptions_t options;
			options.stableSrc = 1;

			auto headerSize = LZ4F_compressBegin(cctx, output.data(), output.size(), &preferences);
			if (LZ4F_isError(headerSize))
			{
				auto errmsg = std::string("Could not write LZ4 frame headers: ") + LZ4F_getErrorName(headerSize);
				throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
			}

			outputOffset += headerSize;

			if (input->Length)
			{
				pin_ptr<byte> inputPin(&input[input->GetLowerBound(0)]);
				byte * inputPtr = inputPin;

				// Process input in 0x10000 byte chunks
				while (inputOffset < input->Length)
				{
					size_t chunkSize = input->Length - inputOffset;
					if (chunkSize > 0x10000) chunkSize = 0x10000;

					// Keep the required number of bytes free in the output array
					size_t requiredSize = LZ4F_compressBound(chunkSize, &preferences);
					size_t outputFree = output.size() - outputOffset;
					if (outputFree < requiredSize)
					{
						output.resize(output.size() + (requiredSize - outputFree));
						outputFree = output.size() - outputOffset;
					}

					// Process the next input chunk
					auto bytesWritten = LZ4F_compressUpdate(cctx, output.data() + outputOffset, outputFree, inputPtr + inputOffset, chunkSize, &options);
					if (LZ4F_isError(bytesWritten))
					{
						auto errmsg = std::string("LZ4 compression failed: ") + LZ4F_getErrorName(bytesWritten);
						throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
					}

					inputOffset += chunkSize;
					outputOffset += bytesWritten;
				}
			}

			// LZ4F_compressEnd needs at most 8 free bytes.
			size_t outputFree = output.size() - outputOffset;
			if (outputFree < 8)
			{
				output.resize(output.size() + (8 - outputFree));
				outputFree = output.size() - outputOffset;
			}

			auto bytesWritten = LZ4F_compressEnd(cctx, output.data() + outputOffset, outputFree, &options);
			if (LZ4F_isError(bytesWritten))
			{
				auto errmsg = std::string("Failed to finish LZ4 compression: ") + LZ4F_getErrorName(bytesWritten);
				throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
			}

			outputOffset += bytesWritten;

			// Copy the output to a managed array
			LZ4F_freeCompressionContext(cctx);
			array<byte> ^ compressed = gcnew array<byte>(outputOffset);
			pin_ptr<byte> compPtr(&compressed[compressed->GetLowerBound(0)]);
			byte * comp = compPtr;
			memcpy(comp, output.data(), outputOffset);
			return compressed;
		}

		array<byte> ^ LZ4FrameCompressor::Decompress(array<byte> ^ compressed)
		{
			pin_ptr<byte> inputPin(&compressed[compressed->GetLowerBound(0)]);
			byte * input = inputPin;

			// Initialize LZ4 decompression
			LZ4F_decompressionContext_t dctx;
			auto error = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION);
			if (LZ4F_isError(error))
			{
				throw gcnew System::IO::InvalidDataException("Failed to create LZ4 decompression context");
			}

			std::vector<byte> output;
			size_t inputOffset = 0, outputOffset = 0;
			while (inputOffset < compressed->Length)
			{
				size_t outputFree = output.size() - outputOffset;

				// Always keep ~0x10000 bytes free in the decompression output array.
				if (outputFree < 0x10000)
				{
					output.resize(output.size() + (0x10000 - outputFree));
					outputFree = output.size() - outputOffset;
				}

				size_t inputAvailable = compressed->Length - inputOffset;
				// Process the next LZ4 frame
				// outputFree contains the number of bytes written, inputAvailable contains the number of bytes processed
				auto result = LZ4F_decompress(dctx, output.data() + outputOffset, &outputFree, input + inputOffset, &inputAvailable, nullptr);
				if (LZ4F_isError(result))
				{
					auto errmsg = std::string("LZ4 decompression failed: ") + LZ4F_getErrorName(result);
					throw gcnew System::IO::InvalidDataException(msclr::interop::marshal_as<System::String ^>(errmsg));
				}

				inputOffset += inputAvailable;
				outputOffset += outputFree;

				if (inputAvailable == 0)
				{
					// No bytes were processed but the whole input stream was passed to LZ4F_decompress; possible corruption?
					throw gcnew System::IO::InvalidDataException("LZ4 error: Not all input data was processed (input might be truncated or corrupted?)");
				}
			}

			// Copy the output to a managed array
			LZ4F_freeDecompressionContext(dctx);
			array<byte> ^ decompressed = gcnew array<byte>(outputOffset);
			if (outputOffset > 0)
			{
				pin_ptr<byte> decompPtr(&decompressed[decompressed->GetLowerBound(0)]);
				byte * decomp = decompPtr;
				memcpy(decomp, output.data(), outputOffset);
			}

			return decompressed;
		}
	}
}
<|endoftext|>