<commit_before>// Copyright (c) 2014 The Bitcoin developers
// Copyright (c) 2017-2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "winshutdownmonitor.h"

#if defined(Q_OS_WIN)
#include "init.h"
#include "util.h"

#include <windows.h>

#include <QDebug>

#include <openssl/rand.h>

// If we don't want a message to be processed by Qt, return true and set result to
// the value that the window procedure should return. Otherwise return false.
bool WinShutdownMonitor::nativeEventFilter(const QByteArray& eventType, void* pMessage, long* pnResult)
{
    Q_UNUSED(eventType);

    MSG* pMsg = static_cast<MSG*>(pMessage);

    // Seed OpenSSL PRNG with Windows event data (e.g.  mouse movements and other user interactions)
    if (RAND_event(pMsg->message, pMsg->wParam, pMsg->lParam) == 0) {
        // Warn only once as this is performance-critical
        static bool warned = false;
        if (!warned) {
            LogPrintf("%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG with enough data.\n", __func__);
            warned = true;
        }
    }

    switch (pMsg->message) {
    case WM_QUERYENDSESSION: {
        // Initiate a client shutdown after receiving a WM_QUERYENDSESSION and block
        // Windows session end until we have finished client shutdown.
        StartShutdown();
        *pnResult = FALSE;
        return true;
    }

    case WM_ENDSESSION: {
        *pnResult = FALSE;
        return true;
    }
    }

    return false;
}

void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId)
{
    typedef BOOL(WINAPI * PSHUTDOWNBRCREATE)(HWND, LPCWSTR);
    PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate");
    if (shutdownBRCreate == NULL) {
        qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed";
        return;
    }

    if (shutdownBRCreate(mainWinId, strReason.toStdWString().c_str()))
        qWarning() << "registerShutdownBlockReason: Successfully registered: " + strReason;
    else
        qWarning() << "registerShutdownBlockReason: Failed to register: " + strReason;
}
#endif
<commit_msg>gui: remove OpenSSL PRNG seeding (Windows, Qt only)<commit_after>// Copyright (c) 2014 The Bitcoin developers
// Copyright (c) 2017-2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "winshutdownmonitor.h"

#if defined(Q_OS_WIN)
#include "init.h"

#include <windows.h>

#include <QDebug>

// If we don't want a message to be processed by Qt, return true and set result to
// the value that the window procedure should return. Otherwise return false.
bool WinShutdownMonitor::nativeEventFilter(const QByteArray& eventType, void* pMessage, long* pnResult)
{
    Q_UNUSED(eventType);

    MSG* pMsg = static_cast<MSG*>(pMessage);

    switch (pMsg->message) {
    case WM_QUERYENDSESSION: {
        // Initiate a client shutdown after receiving a WM_QUERYENDSESSION and block
        // Windows session end until we have finished client shutdown.
        StartShutdown();
        *pnResult = FALSE;
        return true;
    }

    case WM_ENDSESSION: {
        *pnResult = FALSE;
        return true;
    }
    }

    return false;
}

void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId)
{
    typedef BOOL(WINAPI * PSHUTDOWNBRCREATE)(HWND, LPCWSTR);
    PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate");
    if (shutdownBRCreate == NULL) {
        qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed";
        return;
    }

    if (shutdownBRCreate(mainWinId, strReason.toStdWString().c_str()))
        qWarning() << "registerShutdownBlockReason: Successfully registered: " + strReason;
    else
        qWarning() << "registerShutdownBlockReason: Failed to register: " + strReason;
}
#endif
<|endoftext|>


<commit_before>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
 * Qwt Widget Library
 * Copyright (C) 1997   Josef Wilgen
 * Copyright (C) 2002   Uwe Rathmann
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the Qwt License, Version 1.0
 *****************************************************************************/

#include "qwt_plot_spectrocurve.h"
#include "qwt_color_map.h"
#include "qwt_scale_map.h"
#include "qwt_painter.h"
#include <qpainter.h>

class QwtPlotSpectroCurve::PrivateData
{
public:
    PrivateData():
        colorRange( 0.0, 1000.0 ),
        penWidth(0.0),
        paintAttributes( QwtPlotSpectroCurve::ClipPoints )
    {
        colorMap = new QwtLinearColorMap();
    }

    ~PrivateData()
    {
        delete colorMap;
    }

    QwtColorMap *colorMap;
    QwtInterval colorRange;
    QVector<QRgb> colorTable;
    double penWidth;
    QwtPlotSpectroCurve::PaintAttributes paintAttributes;
};

/*!
  Constructor
  \param title Title of the curve
*/
QwtPlotSpectroCurve::QwtPlotSpectroCurve( const QwtText &title ):
    QwtPlotSeriesItem<QwtPoint3D>( title )
{
    init();
}

/*!
  Constructor
  \param title Title of the curve
*/
QwtPlotSpectroCurve::QwtPlotSpectroCurve( const QString &title ):
    QwtPlotSeriesItem<QwtPoint3D>( QwtText( title ) )
{
    init();
}

//! Destructor
QwtPlotSpectroCurve::~QwtPlotSpectroCurve()
{
    delete d_data;
}

/*!
  \brief Initialize data members
*/
void QwtPlotSpectroCurve::init()
{
    setItemAttribute( QwtPlotItem::Legend );
    setItemAttribute( QwtPlotItem::AutoScale );

    d_data = new PrivateData;
    d_series = new QwtPoint3DSeriesData();

    setZ( 20.0 );
}

//! \return QwtPlotItem::Rtti_PlotSpectroCurve
int QwtPlotSpectroCurve::rtti() const
{
    return QwtPlotItem::Rtti_PlotSpectroCurve;
}

/*!
  Specify an attribute how to draw the curve

  \param attribute Paint attribute
  \param on On/Off
  /sa PaintAttribute, testPaintAttribute()
*/
void QwtPlotSpectroCurve::setPaintAttribute( PaintAttribute attribute, bool on )
{
    if ( on )
        d_data->paintAttributes |= attribute;
    else
        d_data->paintAttributes &= ~attribute;
}

/*!
    \brief Return the current paint attributes
    \sa PaintAttribute, setPaintAttribute()
*/
bool QwtPlotSpectroCurve::testPaintAttribute( PaintAttribute attribute ) const
{
    return ( d_data->paintAttributes & attribute );
}

/*!
  Initialize data with an array of samples.
  \param samples Vector of points
*/
void QwtPlotSpectroCurve::setSamples( const QVector<QwtPoint3D> &samples )
{
    delete d_series;
    d_series = new QwtPoint3DSeriesData( samples );
    itemChanged();
}

/*!
  Change the color map

  Often it is useful to display the mapping between intensities and
  colors as an additional plot axis, showing a color bar.

  \param colorMap Color Map

  \sa colorMap(), setColorRange(), QwtColorMap::color(),
      QwtScaleWidget::setColorBarEnabled(), QwtScaleWidget::setColorMap()
*/
void QwtPlotSpectroCurve::setColorMap( QwtColorMap *colorMap )
{
    if ( colorMap != d_data->colorMap )
    {
        delete d_data->colorMap;
        d_data->colorMap = colorMap;
    }

    itemChanged();
}

/*!
   \return Color Map used for mapping the intensity values to colors
   \sa setColorMap(), setColorRange(), QwtColorMap::color()
*/
const QwtColorMap *QwtPlotSpectroCurve::colorMap() const
{
    return d_data->colorMap;
}

/*!
   Set the value interval, that corresponds to the color map

   \param interval interval.minValue() corresponds to 0.0,
                   interval.maxValue() to 1.0 on the color map.

   \sa colorRange(), setColorMap(), QwtColorMap::color()
*/
void QwtPlotSpectroCurve::setColorRange( const QwtInterval &interval )
{
    if ( interval != d_data->colorRange )
    {
        d_data->colorRange = interval;
        itemChanged();
    }
}

/*!
  \return Value interval, that corresponds to the color map
  \sa setColorRange(), setColorMap(), QwtColorMap::color()
*/
QwtInterval &QwtPlotSpectroCurve::colorRange() const
{
    return d_data->colorRange;
}

/*!
  Assign a pen width

  \param penWidth New pen width
  \sa penWidth()
*/
void QwtPlotSpectroCurve::setPenWidth(double penWidth)
{
    if ( penWidth < 0.0 )
        penWidth = 0.0;

    if ( d_data->penWidth != penWidth )
    {
        d_data->penWidth = penWidth;
        itemChanged();
    }
}

/*!
  \return Pen width used to draw a dot
  \sa setPenWidth()
*/
double QwtPlotSpectroCurve::penWidth() const
{
    return d_data->penWidth;
}

/*!
  Draw a subset of the points

  \param painter Painter
  \param xMap Maps x-values into pixel coordinates.
  \param yMap Maps y-values into pixel coordinates.
  \param canvasRect Contents rect of the canvas
  \param from Index of the first sample to be painted
  \param to Index of the last sample to be painted. If to < 0 the
         series will be painted to its last sample.

  \sa drawDots()
*/
void QwtPlotSpectroCurve::drawSeries( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect, int from, int to ) const
{
    if ( !painter || dataSize() <= 0 )
        return;

    if ( to < 0 )
        to = dataSize() - 1;

    if ( from < 0 )
        from = 0;

    if ( from >= to )
        return;

    drawDots( painter, xMap, yMap, canvasRect, from, to );
}

/*!
  Draw a subset of the points

  \param painter Painter
  \param xMap Maps x-values into pixel coordinates.
  \param yMap Maps y-values into pixel coordinates.
  \param canvasRect Contents rect of the canvas
  \param from Index of the first sample to be painted
  \param to Index of the last sample to be painted. If to < 0 the
         series will be painted to its last sample.

  \sa drawSeries()
*/
void QwtPlotSpectroCurve::drawDots( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect, int from, int to ) const
{
    if ( !d_data->colorRange.isValid() )
        return;

    const bool doAlign = QwtPainter::roundingAlignment( painter );

    const QwtColorMap::Format format = d_data->colorMap->format();
    if ( format == QwtColorMap::Indexed )
        d_data->colorTable = d_data->colorMap->colorTable( d_data->colorRange );

    for ( int i = from; i <= to; i++ )
    {
        const QwtPoint3D sample = d_series->sample( i );

        double xi = xMap.transform( sample.x() );
        double yi = yMap.transform( sample.y() );
        if ( doAlign )
        {
            xi = qRound( xi );
            yi = qRound( yi );
        }

        if ( d_data->paintAttributes & QwtPlotSpectroCurve::ClipPoints )
        {
            if ( !canvasRect.contains( xi, yi ) )
                continue;
        }

        if ( format == QwtColorMap::RGB )
        {
            const QRgb rgb = d_data->colorMap->rgb(
                d_data->colorRange, sample.z() );

            painter->setPen( QPen( QColor( rgb ), d_data->penWidth ) );
        }
        else
        {
            const unsigned char index = d_data->colorMap->colorIndex(
                d_data->colorRange, sample.z() );

            painter->setPen( QPen( QColor( d_data->colorTable[index] ),
                d_data->penWidth ) );
        }

        QwtPainter::drawPoint( painter, QPointF( xi, yi ) );
    }

    d_data->colorTable.clear();
}
<commit_msg>fix for curves with only one point<commit_after>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
 * Qwt Widget Library
 * Copyright (C) 1997   Josef Wilgen
 * Copyright (C) 2002   Uwe Rathmann
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the Qwt License, Version 1.0
 *****************************************************************************/

#include "qwt_plot_spectrocurve.h"
#include "qwt_color_map.h"
#include "qwt_scale_map.h"
#include "qwt_painter.h"
#include <qpainter.h>

class QwtPlotSpectroCurve::PrivateData
{
public:
    PrivateData():
        colorRange( 0.0, 1000.0 ),
        penWidth(0.0),
        paintAttributes( QwtPlotSpectroCurve::ClipPoints )
    {
        colorMap = new QwtLinearColorMap();
    }

    ~PrivateData()
    {
        delete colorMap;
    }

    QwtColorMap *colorMap;
    QwtInterval colorRange;
    QVector<QRgb> colorTable;
    double penWidth;
    QwtPlotSpectroCurve::PaintAttributes paintAttributes;
};

/*!
  Constructor
  \param title Title of the curve
*/
QwtPlotSpectroCurve::QwtPlotSpectroCurve( const QwtText &title ):
    QwtPlotSeriesItem<QwtPoint3D>( title )
{
    init();
}

/*!
  Constructor
  \param title Title of the curve
*/
QwtPlotSpectroCurve::QwtPlotSpectroCurve( const QString &title ):
    QwtPlotSeriesItem<QwtPoint3D>( QwtText( title ) )
{
    init();
}

//! Destructor
QwtPlotSpectroCurve::~QwtPlotSpectroCurve()
{
    delete d_data;
}

/*!
  \brief Initialize data members
*/
void QwtPlotSpectroCurve::init()
{
    setItemAttribute( QwtPlotItem::Legend );
    setItemAttribute( QwtPlotItem::AutoScale );

    d_data = new PrivateData;
    d_series = new QwtPoint3DSeriesData();

    setZ( 20.0 );
}

//! \return QwtPlotItem::Rtti_PlotSpectroCurve
int QwtPlotSpectroCurve::rtti() const
{
    return QwtPlotItem::Rtti_PlotSpectroCurve;
}

/*!
  Specify an attribute how to draw the curve

  \param attribute Paint attribute
  \param on On/Off
  /sa PaintAttribute, testPaintAttribute()
*/
void QwtPlotSpectroCurve::setPaintAttribute( PaintAttribute attribute, bool on )
{
    if ( on )
        d_data->paintAttributes |= attribute;
    else
        d_data->paintAttributes &= ~attribute;
}

/*!
    \brief Return the current paint attributes
    \sa PaintAttribute, setPaintAttribute()
*/
bool QwtPlotSpectroCurve::testPaintAttribute( PaintAttribute attribute ) const
{
    return ( d_data->paintAttributes & attribute );
}

/*!
  Initialize data with an array of samples.
  \param samples Vector of points
*/
void QwtPlotSpectroCurve::setSamples( const QVector<QwtPoint3D> &samples )
{
    delete d_series;
    d_series = new QwtPoint3DSeriesData( samples );
    itemChanged();
}

/*!
  Change the color map

  Often it is useful to display the mapping between intensities and
  colors as an additional plot axis, showing a color bar.

  \param colorMap Color Map

  \sa colorMap(), setColorRange(), QwtColorMap::color(),
      QwtScaleWidget::setColorBarEnabled(), QwtScaleWidget::setColorMap()
*/
void QwtPlotSpectroCurve::setColorMap( QwtColorMap *colorMap )
{
    if ( colorMap != d_data->colorMap )
    {
        delete d_data->colorMap;
        d_data->colorMap = colorMap;
    }

    itemChanged();
}

/*!
   \return Color Map used for mapping the intensity values to colors
   \sa setColorMap(), setColorRange(), QwtColorMap::color()
*/
const QwtColorMap *QwtPlotSpectroCurve::colorMap() const
{
    return d_data->colorMap;
}

/*!
   Set the value interval, that corresponds to the color map

   \param interval interval.minValue() corresponds to 0.0,
                   interval.maxValue() to 1.0 on the color map.

   \sa colorRange(), setColorMap(), QwtColorMap::color()
*/
void QwtPlotSpectroCurve::setColorRange( const QwtInterval &interval )
{
    if ( interval != d_data->colorRange )
    {
        d_data->colorRange = interval;
        itemChanged();
    }
}

/*!
  \return Value interval, that corresponds to the color map
  \sa setColorRange(), setColorMap(), QwtColorMap::color()
*/
QwtInterval &QwtPlotSpectroCurve::colorRange() const
{
    return d_data->colorRange;
}

/*!
  Assign a pen width

  \param penWidth New pen width
  \sa penWidth()
*/
void QwtPlotSpectroCurve::setPenWidth(double penWidth)
{
    if ( penWidth < 0.0 )
        penWidth = 0.0;

    if ( d_data->penWidth != penWidth )
    {
        d_data->penWidth = penWidth;
        itemChanged();
    }
}

/*!
  \return Pen width used to draw a dot
  \sa setPenWidth()
*/
double QwtPlotSpectroCurve::penWidth() const
{
    return d_data->penWidth;
}

/*!
  Draw a subset of the points

  \param painter Painter
  \param xMap Maps x-values into pixel coordinates.
  \param yMap Maps y-values into pixel coordinates.
  \param canvasRect Contents rect of the canvas
  \param from Index of the first sample to be painted
  \param to Index of the last sample to be painted. If to < 0 the
         series will be painted to its last sample.

  \sa drawDots()
*/
void QwtPlotSpectroCurve::drawSeries( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect, int from, int to ) const
{
    if ( !painter || dataSize() <= 0 )
        return;

    if ( to < 0 )
        to = dataSize() - 1;

    if ( from < 0 )
        from = 0;

    if ( from > to )
        return;

    drawDots( painter, xMap, yMap, canvasRect, from, to );
}

/*!
  Draw a subset of the points

  \param painter Painter
  \param xMap Maps x-values into pixel coordinates.
  \param yMap Maps y-values into pixel coordinates.
  \param canvasRect Contents rect of the canvas
  \param from Index of the first sample to be painted
  \param to Index of the last sample to be painted. If to < 0 the
         series will be painted to its last sample.

  \sa drawSeries()
*/
void QwtPlotSpectroCurve::drawDots( QPainter *painter,
    const QwtScaleMap &xMap, const QwtScaleMap &yMap,
    const QRectF &canvasRect, int from, int to ) const
{
    if ( !d_data->colorRange.isValid() )
        return;

    const bool doAlign = QwtPainter::roundingAlignment( painter );

    const QwtColorMap::Format format = d_data->colorMap->format();
    if ( format == QwtColorMap::Indexed )
        d_data->colorTable = d_data->colorMap->colorTable( d_data->colorRange );

    for ( int i = from; i <= to; i++ )
    {
        const QwtPoint3D sample = d_series->sample( i );

        double xi = xMap.transform( sample.x() );
        double yi = yMap.transform( sample.y() );
        if ( doAlign )
        {
            xi = qRound( xi );
            yi = qRound( yi );
        }

        if ( d_data->paintAttributes & QwtPlotSpectroCurve::ClipPoints )
        {
            if ( !canvasRect.contains( xi, yi ) )
                continue;
        }

        if ( format == QwtColorMap::RGB )
        {
            const QRgb rgb = d_data->colorMap->rgb(
                d_data->colorRange, sample.z() );

            painter->setPen( QPen( QColor( rgb ), d_data->penWidth ) );
        }
        else
        {
            const unsigned char index = d_data->colorMap->colorIndex(
                d_data->colorRange, sample.z() );

            painter->setPen( QPen( QColor( d_data->colorTable[index] ),
                d_data->penWidth ) );
        }

        QwtPainter::drawPoint( painter, QPointF( xi, yi ) );
    }

    d_data->colorTable.clear();
}
<|endoftext|>


<commit_before>#ifndef __CLITL_HPP__
#define __CLITL_HPP__

#include <cstdio>
#include <iosfwd>
#include <locale>
#include <string>
#include <tuple>
#include <utility>

#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif

namespace clitl {
    /* Color class */
    enum class color {
#ifdef UNIX
        VOIDSPACE = -1,
        DEFAULT = 0,
        BLACK = 30,
        RED = 31,
        GREEN = 32,
        BROWN = 33,
        BLUE = 34,
        MAGENTA = 35,
        CYAN = 36,
#elif WIN32
        VOIDSPACE = -1,
        DEFAULT = 7,
        BLACK = 0,
        RED = 4,
        GREEN = 2,
        BROWN = 7, // Worthless
        BLUE = 1,
        MAGENTA = 7, // Worthless
        CYAN = 9,
#endif
    };

    /* Basic definitions and containers */
    typedef int coord_t;
    typedef int colornum_t;

    template <typename T>
    class rect {
        std::pair<T, T> origin;
        std::pair<T, T> endpoint;
        color foreground;
    public:
        explicit rect(const std::pair<T, T>& origin,
            const std::pair<T, T>& endpoint,
            const color& foreground)
            : origin(origin), endpoint(endpoint), foreground(foreground) {}
        explicit rect(const std::pair<T, T>& origin,
            const std::pair<T, T>& endpoint)
            : rect(origin, endpoint, color::DEFAULT) {}
        explicit rect() : rect(std::pair<T, T>(0, 0),
            std::pair<T, T>(0, 0), color::DEFAULT) {}

        const rect<T>& set_origin(const std::pair<T, T>& coord)
        {
            origin = coord;
            return *this;
        }

        const rect<T>& set_endpoint(const std::pair<T, T>& coord)
        {
            endpoint = coord;
            return *this;
        }

        const rect<T>& set_foreground(const color& foreg)
        {
            foreground = foreg;
            return *this;
        }

        const std::pair<T, T>& get_origin() const
        {
            return origin;
        }

        const std::pair<T, T>& get_endpoint() const
        {
            return endpoint;
        }

        const color& get_foreground() const
        {
            return foreground;
        }
    };

    template <typename charT,
        class traits = char_traits<charT>,
        class Alloc = allocator<charT> >
    struct colorstring {
        std::basic_string<charT, traits, Alloc> str;
        color foreground;
    };

    /* Output buffer */
    template <typename charT, typename traits = std::char_traits<charT> >
    class basic_outbuf : public std::basic_streambuf<charT, traits> {
    protected:
        virtual typename traits::int_type
            overflow(typename traits::int_type c)
        {
            if (std::putchar(c) == EOF) {
                return traits::eof();
            }
            return traits::not_eof(c);
        }
    };

    typedef basic_outbuf<char> outbuf;
    typedef basic_outbuf<wchar_t> woutbuf;

    /* Output stream */
    template <typename charT, typename traits = std::char_traits<charT> >
    class basic_ostream : public std::basic_ostream<charT, traits> {
    public:
#ifdef UNIX
        struct winsize wsize;
#endif
#ifdef WIN32
        HANDLE termout_handle;
        CONSOLE_CURSOR_INFO termout_curinfo;
        CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
        explicit basic_ostream(basic_outbuf<charT, traits>* sb)
            : std::basic_ostream<charT, traits>(sb)
        {
#ifdef UNIX
            wsize = { 0 };
#elif WIN32
            termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
        }

        basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
        {
#ifdef TARGET_IS_POSIX
            cout << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
            COORD pos = { static_cast<SHORT>(coord.first), static_cast<SHORT>(coord.second) };
            SetConsoleCursorPosition(termout_handle, pos);
#endif
            return *this;
        }

        std::pair<coord_t, coord_t> screensize()
        {
            static coord_t column;
            static coord_t row;

#ifdef UNIX
            column = wsize.ws_col;
            row = wsize.ws_row;
#elif WIN32
            GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
            column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
            row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif

            return std::pair<coord_t, coord_t>(column, row);
        }

        basic_ostream<charT, traits>& operator<<
            (basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
        {
            return (*op)(*this);
        }
    };

    typedef basic_ostream<char> ostream;
    typedef basic_ostream<wchar_t> wostream;

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
    {
        os << alternative_system_screenbuffer;
        os << hide_cursor;
        os << clear;
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
    {
        os << normal_system_screenbuffer;
        os << show_cursor;
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
    {
#if UNIX
        cout << "\033[?1049h"; // Use alternate screen buffer
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
    {
#ifdef UNIX
        cout << "\033[2J";
#elif WIN32
        COORD startpoint = { 0, 0 };
        DWORD dw;

        GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
        FillConsoleOutputCharacterA(os.termout_handle, ' ',
            os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
            startpoint, &dw);
        FillConsoleOutputAttribute(os.termout_handle,
            FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
            os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
            startpoint, &dw);
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
    {
#ifdef UNIX
        cout << "\033[?25l"; // Hide cursor
#elif WIN32
    GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
    os.termout_curinfo.bVisible = 0;
    SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
    {
#if UNIX
        cout << "\033[?1049l"; // Use normal screen buffer
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
    {
        fflush(stdout);
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
    {
#if UNIX
        cout << "\033[?25h"; // Show cursor
#elif WIN32
    CONSOLE_CURSOR_INFO termout_curinfo;
    GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
    termout_curinfo.bVisible = 1;
    SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
        return os;
    }

    template <typename charT, typename traits, typename Alloc>
    basic_ostream<charT, traits>& operator<<
        (basic_ostream<charT, traits>& os,
            const std::tuple<std::basic_string<charT, traits, Alloc>, color>& tu)
    {
#ifdef UNIX
        os << "\033[" << static_cast<coord_t>(std::get<1>(tu))
            << "m" << std::get<0>(tu).c_str() << "\033[0m";
#elif WIN32
        WORD termout_attribute;

        GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
        termout_attribute = os.termout_sbufinfo.wAttributes;

        SetConsoleTextAttribute(os.termout_handle, static_cast<coord_t>(std::get<1>(tu)));
        os << std::get<0>(tu);
        SetConsoleTextAttribute(os.termout_handle, termout_attribute);
#endif
        return os;
    }

    template <typename charT, typename traits, typename coordT>
    basic_ostream<charT, traits>& operator<<
        (basic_ostream<charT, traits>& os, const rect<coordT>& re)
    {
        for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) {
            for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) {
                os.moveto(std::pair<coord_t, coord_t>(i, j));
                os << std::tuple<std::basic_string<charT>, color>
                    ("@", re.get_foreground());
            }
        }
        return os;
    }

    /* Input buffer */

    /* Input stream */
    template <typename charT, typename traits = std::char_traits<charT> >
    class basic_istream : public std::basic_istream<charT, traits> {

    };

    typedef basic_istream<char> istream;
    typedef basic_istream<wchar_t> wistream;
}

#endif
<commit_msg>Modify entire structure to fit with g++<commit_after>#ifndef __CLITL_HPP__
#define __CLITL_HPP__

#include <cstdio>
#include <locale>
#include <ostream>
#include <string>
#include <tuple>
#include <utility>

#ifdef UNIX
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#elif WIN32
#include <conio.h>
#include <Windows.h>
#endif

namespace clitl {
    /* Color class */
    enum class color {
#ifdef UNIX
        VOIDSPACE = -1,
        DEFAULT = 0,
        BLACK = 30,
        RED = 31,
        GREEN = 32,
        BROWN = 33,
        BLUE = 34,
        MAGENTA = 35,
        CYAN = 36,
#elif WIN32
        VOIDSPACE = -1,
        DEFAULT = 7,
        BLACK = 0,
        RED = 4,
        GREEN = 2,
        BROWN = 7, // Worthless
        BLUE = 1,
        MAGENTA = 7, // Worthless
        CYAN = 9,
#endif
    };

    /* Basic definitions and containers */
    typedef int coord_t;
    typedef int colornum_t;

    template <typename T>
    class rect {
        std::pair<T, T> origin;
        std::pair<T, T> endpoint;
        color foreground;
    public:
        explicit rect(const std::pair<T, T>& origin,
            const std::pair<T, T>& endpoint,
            const color& foreground)
            : origin(origin), endpoint(endpoint), foreground(foreground) {}
        explicit rect(const std::pair<T, T>& origin,
            const std::pair<T, T>& endpoint)
            : rect(origin, endpoint, color::DEFAULT) {}
        explicit rect() : rect(std::pair<T, T>(0, 0),
            std::pair<T, T>(0, 0), color::DEFAULT) {}

        const rect<T>& set_origin(const std::pair<T, T>& coord)
        {
            origin = coord;
            return *this;
        }

        const rect<T>& set_endpoint(const std::pair<T, T>& coord)
        {
            endpoint = coord;
            return *this;
        }

        const rect<T>& set_foreground(const color& foreg)
        {
            foreground = foreg;
            return *this;
        }

        const std::pair<T, T>& get_origin() const
        {
            return origin;
        }

        const std::pair<T, T>& get_endpoint() const
        {
            return endpoint;
        }

        const color& get_foreground() const
        {
            return foreground;
        }
    };

    template <typename charT,
        typename traits = std::char_traits<charT>,
        typename Alloc = std::allocator<charT> >
    struct colorstring {
        std::basic_string<charT, traits, Alloc> str;
        color foreground;
    };

    /* Output buffer */
    template <typename charT, typename traits = std::char_traits<charT> >
    class basic_outbuf : public std::basic_streambuf<charT, traits> {
    protected:
        virtual typename traits::int_type
            overflow(typename traits::int_type c)
        {
            if (std::putchar(c) == EOF) {
                return traits::eof();
            }
            return traits::not_eof(c);
        }
    };

    typedef basic_outbuf<char> outbuf;
    typedef basic_outbuf<wchar_t> woutbuf;

    /* Output stream */
    template <typename charT, typename traits = std::char_traits<charT> >
    class basic_ostream : public std::basic_ostream<charT, traits> {
    public:
#ifdef UNIX
        struct winsize wsize;
#endif
#ifdef WIN32
        HANDLE termout_handle;
        CONSOLE_CURSOR_INFO termout_curinfo;
        CONSOLE_SCREEN_BUFFER_INFO termout_sbufinfo;
#endif
        explicit basic_ostream(basic_outbuf<charT, traits>* sb)
            : std::basic_ostream<charT, traits>(sb)
        {
#ifdef UNIX
            wsize = { 0 };
#elif WIN32
            termout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
        }

        basic_ostream<charT, traits>& moveto(const std::pair<coord_t, coord_t>& coord)
        {
#ifdef UNIX
            *this << "\033[" << coord.second << ";" << coord.first << "f";
#elif WIN32
            COORD pos = { static_cast<SHORT>(coord.first), static_cast<SHORT>(coord.second) };
            SetConsoleCursorPosition(termout_handle, pos);
#endif
            return *this;
        }

        std::pair<coord_t, coord_t> screensize()
        {
            static coord_t column;
            static coord_t row;

#ifdef UNIX
            column = wsize.ws_col;
            row = wsize.ws_row;
#elif WIN32
            GetConsoleScreenBufferInfo(termout_handle, &termout_sbufinfo);
            column = static_cast<coord_t>(termout_sbufinfo.dwSize.X);
            row = static_cast<coord_t>(termout_sbufinfo.dwSize.Y);
#endif

            return std::pair<coord_t, coord_t>(column, row);
        }

        basic_ostream<charT, traits>& operator<<
            (basic_ostream<charT, traits>& (*op)(basic_ostream<charT, traits>&))
        {
            return (*op)(*this);
        }
    };

    typedef basic_ostream<char> ostream;
    typedef basic_ostream<wchar_t> wostream;

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& alternative_system_screenbuffer(basic_ostream<charT, traits>& os)
    {
#if UNIX
        os << "\033[?1049h"; // Use alternate screen buffer
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& clear(basic_ostream<charT, traits>& os)
    {
#ifdef UNIX
        os << "\033[2J";
#elif WIN32
        COORD startpoint = { 0, 0 };
        DWORD dw;

        GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
        FillConsoleOutputCharacterA(os.termout_handle, ' ',
            os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
            startpoint, &dw);
        FillConsoleOutputAttribute(os.termout_handle,
            FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
            os.termout_sbufinfo.dwSize.X * os.termout_sbufinfo.dwSize.Y,
            startpoint, &dw);
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& hide_cursor(basic_ostream<charT, traits>& os)
    {
#ifdef UNIX
        os << "\033[?25l"; // Hide cursor
#elif WIN32
    GetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
    os.termout_curinfo.bVisible = 0;
    SetConsoleCursorInfo(os.termout_handle, &os.termout_curinfo);
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& normal_system_screenbuffer(basic_ostream<charT, traits>& os)
    {
#if UNIX
        os << "\033[?1049l"; // Use normal screen buffer
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& refresh(basic_ostream<charT, traits>& os)
    {
        fflush(stdout);
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& show_cursor(basic_ostream<charT, traits>& os)
    {
#if UNIX
        os << "\033[?25h"; // Show cursor
#elif WIN32
    CONSOLE_CURSOR_INFO termout_curinfo;
    GetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
    termout_curinfo.bVisible = 1;
    SetConsoleCursorInfo(os.termout_handle, &termout_curinfo);
#endif
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& pre_process(basic_ostream<charT, traits>& os)
    {
        os << alternative_system_screenbuffer;
        os << hide_cursor;
        os << clear;
        return os;
    }

    template <typename charT, typename traits>
    basic_ostream<charT, traits>& post_process(basic_ostream<charT, traits>& os)
    {
        os << normal_system_screenbuffer;
        os << show_cursor;
        return os;
    }

    template <typename charT, typename traits, typename Alloc>
    basic_ostream<charT, traits>& operator<<
        (basic_ostream<charT, traits>& os,
            const std::tuple<std::basic_string<charT, traits, Alloc>, color>& tu)
    {
#ifdef UNIX
        os << "\033[" << static_cast<coord_t>(std::get<1>(tu))
            << "m" << std::get<0>(tu).c_str() << "\033[0m";
#elif WIN32
        WORD termout_attribute;

        GetConsoleScreenBufferInfo(os.termout_handle, &os.termout_sbufinfo);
        termout_attribute = os.termout_sbufinfo.wAttributes;

        SetConsoleTextAttribute(os.termout_handle, static_cast<coord_t>(std::get<1>(tu)));
        os << std::get<0>(tu);
        SetConsoleTextAttribute(os.termout_handle, termout_attribute);
#endif
        return os;
    }

    template <typename charT, typename traits, typename coordT>
    basic_ostream<charT, traits>& operator<<
        (basic_ostream<charT, traits>& os, const rect<coordT>& re)
    {
        for (int i = re.get_origin().first; i <= re.get_endpoint().first; ++i) {
            for (int j = re.get_origin().second; j <= re.get_endpoint().second; ++j) {
                os.moveto(std::pair<coord_t, coord_t>(i, j));
                os << std::tuple<std::basic_string<charT>, color>
                    ("@", re.get_foreground());
            }
        }
        return os;
    }

    /* Input buffer */

    /* Input stream */
    template <typename charT, typename traits = std::char_traits<charT> >
    class basic_istream : public std::basic_istream<charT, traits> {

    };

    typedef basic_istream<char> istream;
    typedef basic_istream<wchar_t> wistream;
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2015] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_COLUMN_DATETIME_HPP
#define REALM_COLUMN_DATETIME_HPP

#include <realm/column.hpp>

namespace realm {

struct NewDate {
    NewDate(int64_t seconds, int32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) { }
    NewDate(const null&) : m_is_null(true) { }
    NewDate() : NewDate(null()) { }

    bool is_null() const { return m_is_null; }
    bool operator == (const NewDate& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
    bool operator != (const NewDate& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
    bool operator > (const NewDate& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
    bool operator < (const NewDate& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
    NewDate& operator = (const NewDate& rhs) = default;

    int64_t m_seconds;
    int32_t m_nanoseconds;
    bool m_is_null;
};

class DateTimeColumn : public ColumnBase, public ColumnTemplate<NewDate> {
public:
    DateTimeColumn() : m_seconds(Allocator::get_default(), IntNullColumn::create(Allocator::get_default())),
                       m_nanoseconds(Allocator::get_default(), IntegerColumn::create(Allocator::get_default()))
    {
    }

    /// Get the number of entries in this column. This operation is relatively
    /// slow.
    size_t size() const noexcept override {
        // FIXME: Consider debug asserts on the columns having the same size
        return m_seconds.size();
    }

    /// Whether or not this column is nullable.
    bool is_nullable() const noexcept override {
        return m_seconds.is_nullable();
    }

    /// Whether or not the value at \a row_ndx is NULL. If the column is not
    /// nullable, always returns false.
    bool is_null(size_t row_ndx) const noexcept override {
        return m_seconds.is_null(row_ndx);
    }

    /// Sets the value at \a row_ndx to be NULL.
    /// \throw LogicError Thrown if this column is not nullable.
    void set_null(size_t row_ndx) override {
        m_seconds.set_null(row_ndx);
    }

    void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override {
        m_seconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
        m_nanoseconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
    }

    void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
                    bool broken_reciprocal_backlinks) override {
        m_seconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
        m_nanoseconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
    }

    void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
                            bool broken_reciprocal_backlinks) override {
        m_seconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
        m_nanoseconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
    }

    void clear(size_t num_rows, bool broken_reciprocal_backlinks) override {
        m_seconds.clear(num_rows, broken_reciprocal_backlinks);
        m_nanoseconds.clear(num_rows, broken_reciprocal_backlinks);
    }

    void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override {
        m_seconds.swap_rows(row_ndx_1, row_ndx_2);
        m_nanoseconds.swap_rows(row_ndx_1, row_ndx_2);
    }

    void destroy() noexcept override {
        m_seconds.destroy();
        m_nanoseconds.destroy();
    }

    StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override {
        // FIXME: Dummy implementation
        return null();
    }

    Allocator& get_alloc() const noexcept override {
        // FIXME: Dummy implementation
        return Allocator::get_default();
    }

    /// Returns the 'ref' of the root array.
    ref_type get_ref() const noexcept override {
        // FIXME: Dummy implementation
        return 0;
    }
    MemRef get_mem() const noexcept override {
        // FIXME: Dummy implementation
        return MemRef();
    }

    void replace_root_array(std::unique_ptr<Array> leaf) override {
        // FIXME: Dummy implementation

    }

    MemRef clone_deep(Allocator& alloc) const override {
        // FIXME: Dummy implementation
        return MemRef();

    }

    void detach() override {
        m_seconds.detach();
        m_nanoseconds.detach();
    }

    bool is_attached() const noexcept override {
        // FIXME: Assert on both columns having same attached state?
        return m_seconds.is_attached();
    }

    ref_type write(size_t slice_offset, size_t slice_size,
                   size_t table_size, _impl::OutputStream&) const override {
        // FIXME: Dummy implementation
        return 0;
    }

    void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept override {
        // FIXME: Dummy implementation

    }

    size_t get_ndx_in_parent() const noexcept override {
        // FIXME: Dummy implementation
        return 0;
    }

    void set_ndx_in_parent(size_t ndx_in_parent) noexcept override {
        // FIXME: Dummy implementation
    }

    void update_from_parent(size_t old_baseline) noexcept override {
        // FIXME: Dummy implementation
    }

    void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override {
        // FIXME: Dummy implementation
    }

    void verify() const override {
        // FIXME: Dummy implementation
    }

    void to_dot(std::ostream&, StringData title = StringData()) const override {
        // FIXME: Dummy implementation
    }

    void do_dump_node_structure(std::ostream&, int level) const override {
        // FIXME: Dummy implementation
    }

    void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent,
                     std::ostream&) const override {
        // FIXME: Dummy implementation
    }

    void add(const NewDate& ndt = NewDate{}) {
        util::Optional<int64_t> seconds = ndt.is_null() ? util::none : util::make_optional(ndt.m_seconds);
        int32_t nanoseconds = ndt.is_null() ? 0 : ndt.m_nanoseconds;
        m_seconds.add(seconds);
        m_nanoseconds.add(nanoseconds);
    }

    NewDate get(size_t row_ndx) const noexcept {
        util::Optional<int64_t> seconds = m_seconds.get(row_ndx);
        return seconds ? NewDate(*seconds, m_nanoseconds.get(row_ndx)) : NewDate();
    }

    NewDate get_val(size_t row_ndx) const override {
        return get(row_ndx);
    }

    void set(size_t index, const NewDate& ndt) {
        util::Optional<int64_t> seconds = ndt.is_null() ? util::none : util::make_optional(ndt.m_seconds);
        int32_t nanoseconds = ndt.is_null() ? 0 : ndt.m_nanoseconds;
        m_seconds.set(index, seconds);
        m_nanoseconds.set(index, nanoseconds);
    }

private:
    IntNullColumn m_seconds;
    IntegerColumn m_nanoseconds;
};

} // namespace realm

#endif // REALM_COLUMN_DATETIME_HPP
<commit_msg>Renamed index->row_ndx<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2015] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_COLUMN_DATETIME_HPP
#define REALM_COLUMN_DATETIME_HPP

#include <realm/column.hpp>

namespace realm {

struct NewDate {
    NewDate(int64_t seconds, int32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false) { }
    NewDate(const null&) : m_is_null(true) { }
    NewDate() : NewDate(null()) { }

    bool is_null() const { return m_is_null; }
    bool operator == (const NewDate& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
    bool operator != (const NewDate& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
    bool operator > (const NewDate& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
    bool operator < (const NewDate& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
    NewDate& operator = (const NewDate& rhs) = default;

    int64_t m_seconds;
    int32_t m_nanoseconds;
    bool m_is_null;
};

class DateTimeColumn : public ColumnBase, public ColumnTemplate<NewDate> {
public:
    DateTimeColumn() : m_seconds(Allocator::get_default(), IntNullColumn::create(Allocator::get_default())),
                       m_nanoseconds(Allocator::get_default(), IntegerColumn::create(Allocator::get_default()))
    {
    }

    /// Get the number of entries in this column. This operation is relatively
    /// slow.
    size_t size() const noexcept override {
        // FIXME: Consider debug asserts on the columns having the same size
        return m_seconds.size();
    }

    /// Whether or not this column is nullable.
    bool is_nullable() const noexcept override {
        return m_seconds.is_nullable();
    }

    /// Whether or not the value at \a row_ndx is NULL. If the column is not
    /// nullable, always returns false.
    bool is_null(size_t row_ndx) const noexcept override {
        return m_seconds.is_null(row_ndx);
    }

    /// Sets the value at \a row_ndx to be NULL.
    /// \throw LogicError Thrown if this column is not nullable.
    void set_null(size_t row_ndx) override {
        m_seconds.set_null(row_ndx);
    }

    void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override {
        m_seconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
        m_nanoseconds.insert_rows(row_ndx, num_rows_to_insert, prior_num_rows, nullable);
    }

    void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
                    bool broken_reciprocal_backlinks) override {
        m_seconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
        m_nanoseconds.erase_rows(row_ndx, num_rows_to_erase, prior_num_rows, broken_reciprocal_backlinks);
    }

    void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
                            bool broken_reciprocal_backlinks) override {
        m_seconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
        m_nanoseconds.move_last_row_over(row_ndx, prior_num_rows, broken_reciprocal_backlinks);
    }

    void clear(size_t num_rows, bool broken_reciprocal_backlinks) override {
        m_seconds.clear(num_rows, broken_reciprocal_backlinks);
        m_nanoseconds.clear(num_rows, broken_reciprocal_backlinks);
    }

    void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override {
        m_seconds.swap_rows(row_ndx_1, row_ndx_2);
        m_nanoseconds.swap_rows(row_ndx_1, row_ndx_2);
    }

    void destroy() noexcept override {
        m_seconds.destroy();
        m_nanoseconds.destroy();
    }

    StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override {
        // FIXME: Dummy implementation
        return null();
    }

    Allocator& get_alloc() const noexcept override {
        // FIXME: Dummy implementation
        return Allocator::get_default();
    }

    /// Returns the 'ref' of the root array.
    ref_type get_ref() const noexcept override {
        // FIXME: Dummy implementation
        return 0;
    }
    MemRef get_mem() const noexcept override {
        // FIXME: Dummy implementation
        return MemRef();
    }

    void replace_root_array(std::unique_ptr<Array> leaf) override {
        // FIXME: Dummy implementation

    }

    MemRef clone_deep(Allocator& alloc) const override {
        // FIXME: Dummy implementation
        return MemRef();

    }

    void detach() override {
        m_seconds.detach();
        m_nanoseconds.detach();
    }

    bool is_attached() const noexcept override {
        // FIXME: Assert on both columns having same attached state?
        return m_seconds.is_attached();
    }

    ref_type write(size_t slice_offset, size_t slice_size,
                   size_t table_size, _impl::OutputStream&) const override {
        // FIXME: Dummy implementation
        return 0;
    }

    void set_parent(ArrayParent*, size_t ndx_in_parent) noexcept override {
        // FIXME: Dummy implementation

    }

    size_t get_ndx_in_parent() const noexcept override {
        // FIXME: Dummy implementation
        return 0;
    }

    void set_ndx_in_parent(size_t ndx_in_parent) noexcept override {
        // FIXME: Dummy implementation
    }

    void update_from_parent(size_t old_baseline) noexcept override {
        // FIXME: Dummy implementation
    }

    void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override {
        // FIXME: Dummy implementation
    }

    void verify() const override {
        // FIXME: Dummy implementation
    }

    void to_dot(std::ostream&, StringData title = StringData()) const override {
        // FIXME: Dummy implementation
    }

    void do_dump_node_structure(std::ostream&, int level) const override {
        // FIXME: Dummy implementation
    }

    void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent,
                     std::ostream&) const override {
        // FIXME: Dummy implementation
    }

    void add(const NewDate& ndt = NewDate{}) {
        util::Optional<int64_t> seconds = ndt.is_null() ? util::none : util::make_optional(ndt.m_seconds);
        int32_t nanoseconds = ndt.is_null() ? 0 : ndt.m_nanoseconds;
        m_seconds.add(seconds);
        m_nanoseconds.add(nanoseconds);
    }

    NewDate get(size_t row_ndx) const noexcept {
        util::Optional<int64_t> seconds = m_seconds.get(row_ndx);
        return seconds ? NewDate(*seconds, m_nanoseconds.get(row_ndx)) : NewDate();
    }

    NewDate get_val(size_t row_ndx) const override {
        return get(row_ndx);
    }

    void set(size_t row_ndx, const NewDate& ndt) {
        util::Optional<int64_t> seconds = ndt.is_null() ? util::none : util::make_optional(ndt.m_seconds);
        int32_t nanoseconds = ndt.is_null() ? 0 : ndt.m_nanoseconds;
        m_seconds.set(row_ndx, seconds);
        m_nanoseconds.set(row_ndx, nanoseconds);
    }

private:
    IntNullColumn m_seconds;
    IntegerColumn m_nanoseconds;
};

} // namespace realm

#endif // REALM_COLUMN_DATETIME_HPP
<|endoftext|>


<commit_before>#pragma once

#include <cstdlib>
#include <type_traits>
#include <cmath>
#include <array>
#include <unordered_map>
#include <random>

#include <tools.hpp>
#include <itertools.hpp>

namespace euler::primes {

/**
 * Return a N+1 size array of booleans such that
 * mask[a] is true iff a is a composite number.
 */
template<int N>
std::array<bool, N + 1> composite_mask() {

    static_assert(N >= 0, "N must be non-negative.");

    std::array<bool, N + 1> mask = { {true, true} };

    for (int i = 2; i*i <= N; ++i)
        if (!mask[i])
            for (int j = i * i; j <= N; j += i)
                mask[j] = true;
    return mask;
}
template<> std::array<bool, 1> composite_mask<0>() { return { {true} }; }
template<> std::array<bool, 2> composite_mask<1>() { return { {true, true} }; }

template<int N>
std::vector<int> primes_up_to() {
    const auto composite = composite_mask<N>();
    std::vector<int> primes = {2};
    for (std::size_t i = 3; i < composite.size(); i += 2)
        if (not composite[i])
            primes.push_back(i);
    return primes;
};
template<> std::vector<int> primes_up_to<0>() { return {}; }
template<> std::vector<int> primes_up_to<1>() { return {}; }
template<> std::vector<int> primes_up_to<2>() { return {2}; }

/**
 * Fill a supplied map with (p : a) pairs where a is
 * the largest power of p which divides n.
 */
template<typename Integer = int,
        typename Power = int,
        typename Maptype = std::unordered_map<Integer, Power>>
void prime_map(Integer n, Maptype &map) {

    static_assert(std::is_integral<Integer>::value, "Integral required.");
    static_assert(std::is_integral<Power>::value, "Integral required.");

    Integer d = 2;

    while (d * d <= n) {
        while (n % d == 0) {
            if (map.count(d)) {
                map[d] += 1;
            } else {
                map.emplace(d, 1);
            }
            n /= d;
        }
        ++d;
    }

    if (n > 1)
        map.emplace(n, 1);
};

/**
 * Return an unordered_map with (p : a) pairs where a is
 * the largest power of p which divides n.
 */
template<typename Integer = int,
        typename Power = int>
std::unordered_map<Integer, Power> prime_map(Integer n) {
    std::unordered_map<Integer, Power> primes;
    prime_map(n, primes);
    return primes;
}

/**
 * Return a vector with all factors of n, including duplicates.
 */
template<typename Integer = int>
std::vector<Integer> prime_list(Integer n) {
    std::vector<Integer> primes;
    for (const auto& [prime, power] : prime_map(n)) {
        for (int i = 0; i < power; ++i)
            primes.push_back(prime);
    }
    return primes;
}

/**
 * Return all divisors of n.
 */
template<typename Integer = int>
std::set<Integer> divisors(Integer n) {
    auto factors = prime_list(n);
    auto divisors = itertools::powerset(factors.begin(), factors.end());
    std::set<Integer> divs;
    for (const auto& factors : divisors) {
        divs.insert(std::accumulate(factors.begin(), factors.end(), 1, std::multiplies<Integer>()));
    }
    return divs;
}

/**
 * Return the number of divisors for n^(power).
 */
template<typename Integer = int, typename Power = int>
Integer number_of_divisors(Integer n, Power power = 1) {

    static_assert(std::is_integral<Integer>::value, "Integral required.");
    static_assert(std::is_integral<Power>::value, "Integral required.");

    auto primes = prime_map(n);
    Integer count = 1;
    for (auto it = primes.begin(); it != primes.end(); ++it) {
        count *= power * it->second + 1;
    }
    return count;
}

/**
 * Miller-Rabin test for primality.
 * If the return is false, then n is definitively composite.
 * If the return is true, n is probably prime, with accuracy depending
 * on the value of k. k = 40 -> prob of false positive ~2^-80.
 *
 * See https://en.wikipedia.org/wiki/Miller-Rabin_primality_test
 */
template<typename Integer>
bool is_prime(Integer n, int k = 20) {
    if ( n == 2 or n == 3 ) return true;
    if ( n <= 1 or even(n) ) return false;

    static std::default_random_engine generator;
    std::uniform_int_distribution<Integer> distribution(2, n - 2);

    Integer r = 0, d = n - 1;
    for (; even(d); ++r, d >>= 1);

    for (int check = 0; check < k; ++check) {
        Integer a = distribution(generator);

        Integer x = pow_mod(a, d, n);
        if (x == 1 or x == n - 1)
            continue;

        for (Integer inner_check = 0; inner_check < r - 1; ++inner_check) {
            x = mul_mod(x, x, n);
            if (x == 1)
                return false;
            if (x == n - 1)
                goto continue_checks;
        }
        return false;

        continue_checks:
        continue;
    }
    return true;
}

}
<commit_msg>Fix precision bug in divisors.<commit_after>#pragma once

#include <cstdlib>
#include <type_traits>
#include <cmath>
#include <array>
#include <unordered_map>
#include <set>
#include <random>

#include <tools.hpp>
#include <itertools.hpp>

namespace euler::primes {

/**
 * Return a N+1 size array of booleans such that
 * mask[a] is true iff a is a composite number.
 */
template<int N>
std::array<bool, N + 1> composite_mask() {

    static_assert(N >= 0, "N must be non-negative.");

    std::array<bool, N + 1> mask = { {true, true} };

    for (int i = 2; i*i <= N; ++i)
        if (!mask[i])
            for (int j = i * i; j <= N; j += i)
                mask[j] = true;
    return mask;
}
template<> std::array<bool, 1> composite_mask<0>() { return { {true} }; }
template<> std::array<bool, 2> composite_mask<1>() { return { {true, true} }; }

template<int N>
std::vector<int> primes_up_to() {
    const auto composite = composite_mask<N>();
    std::vector<int> primes = {2};
    for (std::size_t i = 3; i < composite.size(); i += 2)
        if (not composite[i])
            primes.push_back(i);
    return primes;
};
template<> std::vector<int> primes_up_to<0>() { return {}; }
template<> std::vector<int> primes_up_to<1>() { return {}; }
template<> std::vector<int> primes_up_to<2>() { return {2}; }

/**
 * Fill a supplied map with (p : a) pairs where a is
 * the largest power of p which divides n.
 */
template<typename Integer = int,
        typename Power = int,
        typename Maptype = std::unordered_map<Integer, Power>>
void prime_map(Integer n, Maptype &map) {

    static_assert(std::is_integral<Integer>::value, "Integral required.");
    static_assert(std::is_integral<Power>::value, "Integral required.");

    Integer d = 2;

    while (d * d <= n) {
        while (n % d == 0) {
            if (map.count(d)) {
                map[d] += 1;
            } else {
                map.emplace(d, 1);
            }
            n /= d;
        }
        ++d;
    }

    if (n > 1)
        map.emplace(n, 1);
};

/**
 * Return an unordered_map with (p : a) pairs where a is
 * the largest power of p which divides n.
 */
template<typename Integer = int,
        typename Power = int>
std::unordered_map<Integer, Power> prime_map(Integer n) {
    std::unordered_map<Integer, Power> primes;
    prime_map(n, primes);
    return primes;
}

/**
 * Return a vector with all factors of n, including duplicates.
 */
template<typename Integer = int>
std::vector<Integer> prime_list(Integer n) {
    std::vector<Integer> primes;
    for (const auto& [prime, power] : prime_map(n)) {
        for (int i = 0; i < power; ++i)
            primes.push_back(prime);
    }
    return primes;
}

/**
 * Return all divisors of n.
 */
template<typename Integer = int>
std::set<Integer> divisors(Integer n) {
    auto factors = prime_list(n);
    auto divisors = itertools::powerset(factors.begin(), factors.end());
    std::set<Integer> divs;
    for (const auto& factors : divisors) {
        divs.insert(std::accumulate(factors.begin(), factors.end(), (Integer) 1, std::multiplies<Integer>()));
    }
    return divs;
}

/**
 * Return the number of divisors for n^(power).
 */
template<typename Integer = int, typename Power = int>
Integer number_of_divisors(Integer n, Power power = 1) {

    static_assert(std::is_integral<Integer>::value, "Integral required.");
    static_assert(std::is_integral<Power>::value, "Integral required.");

    auto primes = prime_map(n);
    Integer count = 1;
    for (auto it = primes.begin(); it != primes.end(); ++it) {
        count *= power * it->second + 1;
    }
    return count;
}

/**
 * Miller-Rabin test for primality.
 * If the return is false, then n is definitively composite.
 * If the return is true, n is probably prime, with accuracy depending
 * on the value of k. k = 40 -> prob of false positive ~2^-80.
 *
 * See https://en.wikipedia.org/wiki/Miller-Rabin_primality_test
 */
template<typename Integer>
bool is_prime(Integer n, int k = 20) {
    if ( n == 2 or n == 3 ) return true;
    if ( n <= 1 or even(n) ) return false;

    static std::default_random_engine generator;
    std::uniform_int_distribution<Integer> distribution(2, n - 2);

    Integer r = 0, d = n - 1;
    for (; even(d); ++r, d >>= 1);

    for (int check = 0; check < k; ++check) {
        Integer a = distribution(generator);

        Integer x = pow_mod(a, d, n);
        if (x == 1 or x == n - 1)
            continue;

        for (Integer inner_check = 0; inner_check < r - 1; ++inner_check) {
            x = mul_mod(x, x, n);
            if (x == 1)
                return false;
            if (x == n - 1)
                goto continue_checks;
        }
        return false;

        continue_checks:
        continue;
    }
    return true;
}

}
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "SIPAddressCtrl.h"

#define SEP_EDIT    2

namespace SOUI
{
    class SEditIP: public SEdit
    {
        SOUI_CLASS_NAME(SIPAddressCtrl,L"ipedit")
    public:
        SEditIP();
        ~SEditIP();
        inline const BYTE GetFiled(){return m_nField;}
        inline void SetField(BYTE nField){
            m_nField = nField;
            SStringW str;
            str.Format(L"%u",nField);
            SetWindowText(str);
            }
        inline void ClearEdit(){SetField(0);}
    protected:
        //OnFinalRelease֤newdeleteͬһģ顣ͲҪϵͳĴ೧עSEditIPˡ
        virtual void OnFinalRelease()
        {
            delete this;
        }
        void OnChar(UINT nChar,UINT nRepCnt,UINT nFlags);
        void OnKillFocus();
        SOUI_MSG_MAP_BEGIN()
            MSG_WM_CHAR(OnChar)
            MSG_WM_KILLFOCUS_EX(OnKillFocus)
        SOUI_MSG_MAP_END()
    private:
        BYTE m_nField;
    };

	SEditIP::SEditIP()
	{
		m_nField = 0;
	}

	SEditIP::~SEditIP()
	{

	}

	void SEditIP::OnChar(UINT nChar,UINT nRepCnt,UINT nFlags)
	{
		if(nChar == '.')
		{
			SWindow *pSwnd = GetWindow(GSW_NEXTSIBLING);
			if (NULL != pSwnd && pSwnd->IsClass(SEditIP::GetClassName()))
			{
				pSwnd->SetFocus();
			}
		}
		else if (isdigit(nChar))
		{
			__super::OnChar(nChar,nRepCnt,nFlags);
		}
	}

    void SEditIP::OnKillFocus()
    {
        __super::OnKillFocus();
        SStringW strValue = GetWindowText();
        UINT uiValue = _wtoi(strValue);
        m_nField = (BYTE)uiValue;
        if (uiValue > 255)
        {
            SetField(255);
        }
    }

    //////////////////////////////////////////////////////////////////////////
    //
	SIPAddressCtrl::SIPAddressCtrl(void)
	{
	    memset(m_editFields,0,sizeof(m_editFields));
	}

	SIPAddressCtrl::~SIPAddressCtrl(void)
	{
	}

	void SIPAddressCtrl::OnSize( UINT nType, CSize size )
	{
		__super::OnSize(nType,size);

		if(!m_editFields[0]) return;

		CRect rcClient;
		GetClientRect(&rcClient);

		int nEditWid = (rcClient.Width() - SEP_EDIT*3)/4;
		CRect rcEdit = rcClient;
		rcEdit.right =rcEdit.left + nEditWid;
		for(int i=0;i<4;i++)
		{
		    m_editFields[i]->Move(&rcEdit);
		    rcEdit.OffsetRect(nEditWid+SEP_EDIT,0);
		}
	}

    LRESULT SIPAddressCtrl::OnCreate( LPVOID )
    {
        wchar_t szEditAttr[] = L"<ipedit margin=\"0\" number=\"1\" transparent=\"1\" align=\"center\" maxBuf=\"3\" mouseRelay=\"1\"/>";
        pugi::xml_document xmlDoc;
        xmlDoc.load_buffer(szEditAttr,sizeof(szEditAttr));
        for(int i=0;i<4;i++)
        {
            m_editFields[i] = new SEditIP;//ֱnew
            InsertChild(m_editFields[i]);
            m_editFields[i]->InitFromXml(xmlDoc.first_child());
        }
        return 0;
    }

    void SIPAddressCtrl::OnPaint( IRenderTarget *pRT )
    {
        CRect rcClient;
        GetClientRect(&rcClient);
        int nEditWid = (rcClient.Width()-SEP_EDIT*3)/4;
        CRect rcSep =rcClient;
        rcSep.left += nEditWid;
        rcSep.right =rcSep.left + SEP_EDIT;
        for(int i=0;i<3;i++)
        {
            CRect rcDot = rcSep;
            rcDot.top += (rcSep.Height()-SEP_EDIT)/2;
            rcDot.bottom = rcDot.top+SEP_EDIT+1;
            rcDot.right += 1;
			pRT->FillSolidRect(rcDot,RGBA(153,153,153,255));
            rcSep.OffsetRect(nEditWid+SEP_EDIT,0);
        }
    }

	BOOL SIPAddressCtrl::IsBlank() const
	{
		if (m_editFields[0]->GetWindowText().GetLength() == 0 && m_editFields[1]->GetWindowText().GetLength() == 0 &&
			m_editFields[2]->GetWindowText().GetLength() == 0 && m_editFields[3]->GetWindowText().GetLength() == 0)
		{
			return TRUE;
		}
		return FALSE;
	}

	int SIPAddressCtrl::GetAddress(_Out_ BYTE& nField0,_Out_ BYTE& nField1,_Out_ BYTE& nField2,_Out_ BYTE& nField3) const
	{
		nField0 = m_editFields[0]->GetFiled();
		nField1 = m_editFields[1]->GetFiled();
		nField2 = m_editFields[2]->GetFiled();
		nField3 = m_editFields[3]->GetFiled();
		return 0;
	}

	int SIPAddressCtrl::GetAddress(_Out_ DWORD& dwAddress) const
	{
	    SASSERT(m_editFields[0]);
	    dwAddress = MAKELONG(MAKEWORD(m_editFields[0]->GetFiled(),m_editFields[1]->GetFiled()),
	                         MAKEWORD(m_editFields[2]->GetFiled(),m_editFields[3]->GetFiled()));
		return 0;
	}

	void SIPAddressCtrl::SetAddress(_In_ DWORD dwAddress)
	{
		in_addr inaddr;
		inaddr.s_addr = dwAddress;
		SetAddress(inaddr.S_un.S_un_b.s_b1,inaddr.S_un.S_un_b.s_b2,
					inaddr.S_un.S_un_b.s_b3,inaddr.S_un.S_un_b.s_b4);
	}

	void SIPAddressCtrl::SetAddress(_In_ BYTE nField0,_In_ BYTE nField1,_In_ BYTE nField2,_In_ BYTE nField3)
	{
		SStringT data;
		m_editFields[0]->SetField(nField0);
		data.Format(_T("%d"),nField0);
		m_editFields[0]->SetWindowText(data);

		m_editFields[1]->SetField(nField1);
		data.Format(_T("%d"),nField1);
		m_editFields[1]->SetWindowText(data);

		m_editFields[2]->SetField(nField2);
		data.Format(_T("%d"),nField2);
		m_editFields[2]->SetWindowText(data);

		m_editFields[3]->SetField(nField3);
		data.Format(_T("%d"),nField3);
		m_editFields[3]->SetWindowText(data);
	}

	void SIPAddressCtrl::ClearAddress()
	{
		m_editFields[0]->ClearEdit();
		m_editFields[0]->SetWindowText(_T(""));
		m_editFields[1]->ClearEdit();
		m_editFields[1]->SetWindowText(_T(""));
		m_editFields[2]->ClearEdit();
		m_editFields[2]->SetWindowText(_T(""));
		m_editFields[3]->ClearEdit();
		m_editFields[3]->SetWindowText(_T(""));
	}
}

<commit_msg><commit_after>#include "StdAfx.h"
#include "SIPAddressCtrl.h"

#define SEP_EDIT    2

namespace SOUI
{
    class SEditIP: public SEdit
    {
        SOUI_CLASS_NAME(SIPAddressCtrl,L"ipedit")
    public:
        SEditIP();
        ~SEditIP();
        inline const BYTE GetFiled(){return m_nField;}
        inline void SetField(BYTE nField){
            m_nField = nField;
            SStringW str;
            str.Format(L"%u",nField);
            SetWindowText(str);
            }
        inline void ClearEdit(){SetField(0);}
    protected:
        //OnFinalRelease֤newdeleteͬһģ顣ͲҪϵͳĴ೧עSEditIPˡ
        virtual void OnFinalRelease()
        {
            delete this;
        }
        void OnChar(UINT nChar,UINT nRepCnt,UINT nFlags);
        void OnKillFocus();
        SOUI_MSG_MAP_BEGIN()
            MSG_WM_CHAR(OnChar)
            MSG_WM_KILLFOCUS_EX(OnKillFocus)
        SOUI_MSG_MAP_END()
    private:
        BYTE m_nField;
    };

	SEditIP::SEditIP()
	{
		m_nField = 0;
	}

	SEditIP::~SEditIP()
	{

	}

	void SEditIP::OnChar(UINT nChar,UINT nRepCnt,UINT nFlags)
	{
		if(nChar == '.')
		{
			SWindow *pSwnd = GetWindow(GSW_NEXTSIBLING);
			if (NULL != pSwnd && pSwnd->IsClass(SEditIP::GetClassName()))
			{
				pSwnd->SetFocus();
			}
		}
		else if (isdigit(nChar))
		{
			__super::OnChar(nChar,nRepCnt,nFlags);
		}
	}

    void SEditIP::OnKillFocus()
    {
        __super::OnKillFocus();
        SStringW strValue = GetWindowText();
        UINT uiValue = _wtoi(strValue);
        m_nField = (BYTE)uiValue;
        if (uiValue > 255)
        {
            SetField(255);
        }
    }

    //////////////////////////////////////////////////////////////////////////
    //
	SIPAddressCtrl::SIPAddressCtrl(void)
	{
	    memset(m_editFields,0,sizeof(m_editFields));
	}

	SIPAddressCtrl::~SIPAddressCtrl(void)
	{
	}

	void SIPAddressCtrl::OnSize( UINT nType, CSize size )
	{
		__super::OnSize(nType,size);

		if(!m_editFields[0]) return;

		CRect rcClient;
		GetClientRect(&rcClient);

		int nEditWid = (rcClient.Width() - SEP_EDIT*3)/4;
		CRect rcEdit = rcClient;
		rcEdit.right =rcEdit.left + nEditWid;
		for(int i=0;i<4;i++)
		{
		    m_editFields[i]->Move(&rcEdit);
		    rcEdit.OffsetRect(nEditWid+SEP_EDIT,0);
		}
	}

    LRESULT SIPAddressCtrl::OnCreate( LPVOID )
    {
        wchar_t szEditAttr[] = L"<ipedit margin=\"0\" number=\"1\" transparent=\"1\" align=\"center\" maxBuf=\"3\" mouseRelay=\"1\"/>";
        pugi::xml_document xmlDoc;
        xmlDoc.load_buffer(szEditAttr,sizeof(szEditAttr));
        for(int i=0;i<4;i++)
        {
            m_editFields[i] = new SEditIP;//ֱnew
            InsertChild(m_editFields[i]);
            m_editFields[i]->InitFromXml(xmlDoc.first_child());
        }
        return 0;
    }

    void SIPAddressCtrl::OnPaint( IRenderTarget *pRT )
    {
        CRect rcClient;
        GetClientRect(&rcClient);
        int nEditWid = (rcClient.Width()-SEP_EDIT*3)/4;
        CRect rcSep =rcClient;
        rcSep.left += nEditWid;
        rcSep.right =rcSep.left + SEP_EDIT;
        for(int i=0;i<3;i++)
        {
            CRect rcDot = rcSep;
            rcDot.top += (rcSep.Height()-SEP_EDIT)/2;
            rcDot.bottom = rcDot.top+SEP_EDIT+1;
            rcDot.right += 1;
			pRT->FillSolidRect(rcDot,RGBA(153,153,153,255));
            rcSep.OffsetRect(nEditWid+SEP_EDIT,0);
        }
    }

	BOOL SIPAddressCtrl::IsBlank() const
	{
		if (m_editFields[0]->GetWindowText().GetLength() == 0 && m_editFields[1]->GetWindowText().GetLength() == 0 &&
			m_editFields[2]->GetWindowText().GetLength() == 0 && m_editFields[3]->GetWindowText().GetLength() == 0)
		{
			return TRUE;
		}
		return FALSE;
	}

	int SIPAddressCtrl::GetAddress(_Out_ BYTE& nField0,_Out_ BYTE& nField1,_Out_ BYTE& nField2,_Out_ BYTE& nField3) const
	{
		nField0 = m_editFields[0]->GetFiled();
		nField1 = m_editFields[1]->GetFiled();
		nField2 = m_editFields[2]->GetFiled();
		nField3 = m_editFields[3]->GetFiled();
		return 0;
	}

	int SIPAddressCtrl::GetAddress(_Out_ DWORD& dwAddress) const
	{
	    SASSERT(m_editFields[0]);
	    dwAddress = MAKELONG(MAKEWORD(m_editFields[0]->GetFiled(),m_editFields[1]->GetFiled()),
	                         MAKEWORD(m_editFields[2]->GetFiled(),m_editFields[3]->GetFiled()));
		return 0;
	}

	void SIPAddressCtrl::SetAddress(_In_ DWORD dwAddress)
	{
		in_addr inaddr;
		inaddr.s_addr = dwAddress;
		SetAddress(inaddr.S_un.S_un_b.s_b1,inaddr.S_un.S_un_b.s_b2,
					inaddr.S_un.S_un_b.s_b3,inaddr.S_un.S_un_b.s_b4);
	}

	void SIPAddressCtrl::SetAddress(_In_ BYTE nField0,_In_ BYTE nField1,_In_ BYTE nField2,_In_ BYTE nField3)
	{
		m_editFields[0]->SetField(nField0);
		m_editFields[1]->SetField(nField1);
		m_editFields[2]->SetField(nField2);
		m_editFields[3]->SetField(nField3);
	}

	void SIPAddressCtrl::ClearAddress()
	{
		m_editFields[0]->ClearEdit();
		m_editFields[1]->ClearEdit();
		m_editFields[2]->ClearEdit();
		m_editFields[3]->ClearEdit();
	}
}

<|endoftext|>


<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/banners/app_banner_data_fetcher.h"

#include "base/command_line.h"
#include "base/location.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/browser/banners/app_banner_data_fetcher_desktop.h"
#include "chrome/browser/banners/app_banner_settings_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/test/embedded_test_server/embedded_test_server.h"

namespace banners {

class TestObserver : public AppBannerDataFetcher::Observer {
 public:
  TestObserver(AppBannerDataFetcher* fetcher, base::Closure quit_closure)
      : fetcher_(fetcher),
        quit_closure_(quit_closure) {
    fetcher_->AddObserverForTesting(this);
  }

  virtual ~TestObserver() {
    if (fetcher_)
      fetcher_->RemoveObserverForTesting(this);
  }

  void OnDecidedWhetherToShow(AppBannerDataFetcher* fetcher,
                              bool will_show) override {
    base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
    ASSERT_FALSE(will_show_.get());
    will_show_.reset(new bool(will_show));
  }

  void OnFetcherDestroyed(AppBannerDataFetcher* fetcher) override {
    base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
    fetcher_ = nullptr;
  }

  bool will_show() { return will_show_.get() && *will_show_; }

 private:
  AppBannerDataFetcher* fetcher_;
  base::Closure quit_closure_;
  scoped_ptr<bool> will_show_;
};

class AppBannerDataFetcherBrowserTest : public InProcessBrowserTest,
                                        public AppBannerDataFetcher::Delegate {
 public:
  AppBannerDataFetcherBrowserTest() : weak_factory_(this) {
  }

  void SetUpOnMainThread() override {
    ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
    InProcessBrowserTest::SetUpOnMainThread();
  }

  bool HandleNonWebApp(const std::string& platform,
                       const GURL& url,
                       const std::string& id) override {
    base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
    non_web_platform_ = platform;
    return false;
  }

  void SetUp() override {
    AppBannerSettingsHelper::SetEngagementWeights(1, 1);
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(
        switches::kEnableExperimentalWebPlatformFeatures);
    // Make sure app banners are disabled in the browser, otherwise they will
    // interfere with the test.
    command_line->AppendSwitch(switches::kDisableAddToShelf);
  }

 protected:
  void RunFetcher(const GURL& url,
                  const std::string& expected_non_web_platform,
                  ui::PageTransition transition,
                  bool expected_to_show) {
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    scoped_refptr<AppBannerDataFetcherDesktop> fetcher(
        new AppBannerDataFetcherDesktop(web_contents,
                                        weak_factory_.GetWeakPtr(), 128));

    base::RunLoop run_loop;
    quit_closure_ = run_loop.QuitClosure();
    scoped_ptr<TestObserver> observer(new TestObserver(fetcher.get(),
                                                       run_loop.QuitClosure()));
    fetcher->Start(url, transition);
    run_loop.Run();

    EXPECT_EQ(expected_non_web_platform, non_web_platform_);
    EXPECT_EQ(expected_to_show, observer->will_show());
    ASSERT_FALSE(fetcher->is_active());
  }

  void LoadURLAndWaitForServiceWorker(const GURL& url) {
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    content::TestNavigationObserver observer(web_contents, 2);
    ui_test_utils::NavigateToURL(browser(), url);
    observer.Wait();
    EXPECT_EQ("sw_activated", observer.last_navigation_url().ref());
  }

  void RunBannerTest(const std::string& manifest_page,
                     ui::PageTransition transition,
                     unsigned int unshown_repetitions,
                     bool expectation) {
    std::string valid_page(manifest_page);
    GURL test_url = embedded_test_server()->GetURL(valid_page);
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();

    for (unsigned int i = 0; i < unshown_repetitions; ++i) {
      LoadURLAndWaitForServiceWorker(test_url);
      RunFetcher(web_contents->GetURL(), std::string(), transition, false);
      AppBannerDataFetcher::SetTimeDeltaForTesting(i+1);
    }

    // On the final loop, check whether the banner triggered or not as expected.
    LoadURLAndWaitForServiceWorker(test_url);
    RunFetcher(web_contents->GetURL(), std::string(), transition, expectation);
  }

 private:
  std::string non_web_platform_;
  base::Closure quit_closure_;
  base::WeakPtrFactory<AppBannerDataFetcherBrowserTest> weak_factory_;
};

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedDirect) {
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_TYPED,
                1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedDirectSingle) {
  AppBannerSettingsHelper::SetEngagementWeights(2, 1);
  RunBannerTest("/banners/manifest_test_page.html",
                ui::PAGE_TRANSITION_GENERATED, 0, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedDirectMultiple) {
  AppBannerSettingsHelper::SetEngagementWeights(0.5, 1);
  RunBannerTest("/banners/manifest_test_page.html",
                ui::PAGE_TRANSITION_GENERATED, 3, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedIndirect) {
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_LINK,
                1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedIndirectSingle) {
  AppBannerSettingsHelper::SetEngagementWeights(1, 3);
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_RELOAD,
                0, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedIndirectMultiple) {
  AppBannerSettingsHelper::SetEngagementWeights(1, 0.5);
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_LINK,
                3, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedVarious) {
  AppBannerSettingsHelper::SetEngagementWeights(0.5, 0.25);

  std::string valid_page("/banners/manifest_test_page.html");
  GURL test_url = embedded_test_server()->GetURL(valid_page);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Add a direct nav on day 1.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(), ui::PAGE_TRANSITION_TYPED,
             false);

  // Add an indirect nav on day 1 which is ignored.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(), ui::PAGE_TRANSITION_LINK,
             false);
  AppBannerDataFetcher::SetTimeDeltaForTesting(1);

  // Add an indirect nav on day 2.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_MANUAL_SUBFRAME, false);

  // Add a direct nav on day 2 which overrides.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_GENERATED, false);
  AppBannerDataFetcher::SetTimeDeltaForTesting(2);

  // Add a direct nav on day 3.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_GENERATED, false);
  AppBannerDataFetcher::SetTimeDeltaForTesting(3);

  // Add an indirect nav on day 4.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_FORM_SUBMIT, false);

  // Add a direct nav on day 4 which should trigger the banner.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_TYPED, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerNoTypeInManifest) {
  RunBannerTest("/banners/manifest_no_type_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerNoTypeInManifestCapsExtension) {
  RunBannerTest("/banners/manifest_no_type_caps_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, PlayAppManifest) {
  std::string valid_page("/banners/play_app_test_page.html");
  GURL test_url = embedded_test_server()->GetURL(valid_page);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Native banners do not require the SW, so we can just load the URL.
  ui_test_utils::NavigateToURL(browser(), test_url);
  std::string play_platform("play");
  RunFetcher(web_contents->GetURL(), play_platform, ui::PAGE_TRANSITION_TYPED,
             false);

  // The logic to get the details for a play app banner are only on android
  // builds, so this test does not check that the banner is shown.
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, NoManifest) {
  RunBannerTest("/banners/no_manifest_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, false);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, CancelBannerDirect) {
  RunBannerTest("/banners/cancel_test_page.html", ui::PAGE_TRANSITION_TYPED, 1,
                false);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, CancelBannerIndirect) {
  AppBannerSettingsHelper::SetEngagementWeights(1, 0.5);
  RunBannerTest("/banners/cancel_test_page.html", ui::PAGE_TRANSITION_TYPED, 3,
                false);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, PromptBanner) {
  RunBannerTest("/banners/prompt_test_page.html", ui::PAGE_TRANSITION_TYPED, 1,
                true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, PromptBannerInHandler) {
  RunBannerTest("/banners/prompt_in_handler_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, WebAppBannerInIFrame) {
  RunBannerTest("/banners/iframe_test_page.html", ui::PAGE_TRANSITION_TYPED, 1,
                false);
}

}  // namespace banners
<commit_msg>Remove override of SetUp and move its contents to SetUpOnMainThread.<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/banners/app_banner_data_fetcher.h"

#include "base/command_line.h"
#include "base/location.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/browser/banners/app_banner_data_fetcher_desktop.h"
#include "chrome/browser/banners/app_banner_settings_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/test_navigation_observer.h"
#include "net/test/embedded_test_server/embedded_test_server.h"

namespace banners {

class TestObserver : public AppBannerDataFetcher::Observer {
 public:
  TestObserver(AppBannerDataFetcher* fetcher, base::Closure quit_closure)
      : fetcher_(fetcher),
        quit_closure_(quit_closure) {
    fetcher_->AddObserverForTesting(this);
  }

  virtual ~TestObserver() {
    if (fetcher_)
      fetcher_->RemoveObserverForTesting(this);
  }

  void OnDecidedWhetherToShow(AppBannerDataFetcher* fetcher,
                              bool will_show) override {
    base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
    ASSERT_FALSE(will_show_.get());
    will_show_.reset(new bool(will_show));
  }

  void OnFetcherDestroyed(AppBannerDataFetcher* fetcher) override {
    base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
    fetcher_ = nullptr;
  }

  bool will_show() { return will_show_.get() && *will_show_; }

 private:
  AppBannerDataFetcher* fetcher_;
  base::Closure quit_closure_;
  scoped_ptr<bool> will_show_;
};

class AppBannerDataFetcherBrowserTest : public InProcessBrowserTest,
                                        public AppBannerDataFetcher::Delegate {
 public:
  AppBannerDataFetcherBrowserTest() : weak_factory_(this) {
  }

  void SetUpOnMainThread() override {
    AppBannerSettingsHelper::SetEngagementWeights(1, 1);
    ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
    InProcessBrowserTest::SetUpOnMainThread();
  }

  bool HandleNonWebApp(const std::string& platform,
                       const GURL& url,
                       const std::string& id) override {
    base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_);
    non_web_platform_ = platform;
    return false;
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(
        switches::kEnableExperimentalWebPlatformFeatures);
    // Make sure app banners are disabled in the browser, otherwise they will
    // interfere with the test.
    command_line->AppendSwitch(switches::kDisableAddToShelf);
  }

 protected:
  void RunFetcher(const GURL& url,
                  const std::string& expected_non_web_platform,
                  ui::PageTransition transition,
                  bool expected_to_show) {
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    scoped_refptr<AppBannerDataFetcherDesktop> fetcher(
        new AppBannerDataFetcherDesktop(web_contents,
                                        weak_factory_.GetWeakPtr(), 128));

    base::RunLoop run_loop;
    quit_closure_ = run_loop.QuitClosure();
    scoped_ptr<TestObserver> observer(new TestObserver(fetcher.get(),
                                                       run_loop.QuitClosure()));
    fetcher->Start(url, transition);
    run_loop.Run();

    EXPECT_EQ(expected_non_web_platform, non_web_platform_);
    EXPECT_EQ(expected_to_show, observer->will_show());
    ASSERT_FALSE(fetcher->is_active());
  }

  void LoadURLAndWaitForServiceWorker(const GURL& url) {
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();
    content::TestNavigationObserver observer(web_contents, 2);
    ui_test_utils::NavigateToURL(browser(), url);
    observer.Wait();
    EXPECT_EQ("sw_activated", observer.last_navigation_url().ref());
  }

  void RunBannerTest(const std::string& manifest_page,
                     ui::PageTransition transition,
                     unsigned int unshown_repetitions,
                     bool expectation) {
    std::string valid_page(manifest_page);
    GURL test_url = embedded_test_server()->GetURL(valid_page);
    content::WebContents* web_contents =
        browser()->tab_strip_model()->GetActiveWebContents();

    for (unsigned int i = 0; i < unshown_repetitions; ++i) {
      LoadURLAndWaitForServiceWorker(test_url);
      RunFetcher(web_contents->GetURL(), std::string(), transition, false);
      AppBannerDataFetcher::SetTimeDeltaForTesting(i+1);
    }

    // On the final loop, check whether the banner triggered or not as expected.
    LoadURLAndWaitForServiceWorker(test_url);
    RunFetcher(web_contents->GetURL(), std::string(), transition, expectation);
  }

 private:
  std::string non_web_platform_;
  base::Closure quit_closure_;
  base::WeakPtrFactory<AppBannerDataFetcherBrowserTest> weak_factory_;
};

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedDirect) {
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_TYPED,
                1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedDirectSingle) {
  AppBannerSettingsHelper::SetEngagementWeights(2, 1);
  RunBannerTest("/banners/manifest_test_page.html",
                ui::PAGE_TRANSITION_GENERATED, 0, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedDirectMultiple) {
  AppBannerSettingsHelper::SetEngagementWeights(0.5, 1);
  RunBannerTest("/banners/manifest_test_page.html",
                ui::PAGE_TRANSITION_GENERATED, 3, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedIndirect) {
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_LINK,
                1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedIndirectSingle) {
  AppBannerSettingsHelper::SetEngagementWeights(1, 3);
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_RELOAD,
                0, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedIndirectMultiple) {
  AppBannerSettingsHelper::SetEngagementWeights(1, 0.5);
  RunBannerTest("/banners/manifest_test_page.html", ui::PAGE_TRANSITION_LINK,
                3, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerCreatedVarious) {
  AppBannerSettingsHelper::SetEngagementWeights(0.5, 0.25);

  std::string valid_page("/banners/manifest_test_page.html");
  GURL test_url = embedded_test_server()->GetURL(valid_page);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Add a direct nav on day 1.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(), ui::PAGE_TRANSITION_TYPED,
             false);

  // Add an indirect nav on day 1 which is ignored.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(), ui::PAGE_TRANSITION_LINK,
             false);
  AppBannerDataFetcher::SetTimeDeltaForTesting(1);

  // Add an indirect nav on day 2.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_MANUAL_SUBFRAME, false);

  // Add a direct nav on day 2 which overrides.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_GENERATED, false);
  AppBannerDataFetcher::SetTimeDeltaForTesting(2);

  // Add a direct nav on day 3.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_GENERATED, false);
  AppBannerDataFetcher::SetTimeDeltaForTesting(3);

  // Add an indirect nav on day 4.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_FORM_SUBMIT, false);

  // Add a direct nav on day 4 which should trigger the banner.
  LoadURLAndWaitForServiceWorker(test_url);
  RunFetcher(web_contents->GetURL(), std::string(),
             ui::PAGE_TRANSITION_TYPED, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerNoTypeInManifest) {
  RunBannerTest("/banners/manifest_no_type_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest,
                       WebAppBannerNoTypeInManifestCapsExtension) {
  RunBannerTest("/banners/manifest_no_type_caps_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, PlayAppManifest) {
  std::string valid_page("/banners/play_app_test_page.html");
  GURL test_url = embedded_test_server()->GetURL(valid_page);
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();

  // Native banners do not require the SW, so we can just load the URL.
  ui_test_utils::NavigateToURL(browser(), test_url);
  std::string play_platform("play");
  RunFetcher(web_contents->GetURL(), play_platform, ui::PAGE_TRANSITION_TYPED,
             false);

  // The logic to get the details for a play app banner are only on android
  // builds, so this test does not check that the banner is shown.
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, NoManifest) {
  RunBannerTest("/banners/no_manifest_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, false);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, CancelBannerDirect) {
  RunBannerTest("/banners/cancel_test_page.html", ui::PAGE_TRANSITION_TYPED, 1,
                false);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, CancelBannerIndirect) {
  AppBannerSettingsHelper::SetEngagementWeights(1, 0.5);
  RunBannerTest("/banners/cancel_test_page.html", ui::PAGE_TRANSITION_TYPED, 3,
                false);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, PromptBanner) {
  RunBannerTest("/banners/prompt_test_page.html", ui::PAGE_TRANSITION_TYPED, 1,
                true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, PromptBannerInHandler) {
  RunBannerTest("/banners/prompt_in_handler_test_page.html",
                ui::PAGE_TRANSITION_TYPED, 1, true);
}

IN_PROC_BROWSER_TEST_F(AppBannerDataFetcherBrowserTest, WebAppBannerInIFrame) {
  RunBannerTest("/banners/iframe_test_page.html", ui::PAGE_TRANSITION_TYPED, 1,
                false);
}

}  // namespace banners
<|endoftext|>