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

#ifndef SD_WINDOW_HXX
#define SD_WINDOW_HXX

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif

namespace sd {

class ViewShell;

// Since we removed all old SV-stuff, there is no brush any more
// and so there is no BRUSH_SIZE defined in VCL.
// So I define it here
// #i2237#
// removed old stuff here which still forced zoom to be
// %BRUSH_SIZE which is outdated now
//#define BRUSH_SIZE        8

/** An SdWindow contains the actual working area of ViewShell.

The zoom factor used by this class controls how much the page and the
    shapes on it are scaled down (<100%) or up (>100%) when displayed on the
    output device represented by the <type>OutputDevice</type>base class.  A
    zoom factor of 100% would result (with a correctly set DPI value for an
    output device) in a one to one mapping of the internal coordinates that
    are stored in 100th of mm.  The zoom factor is stored in the map mode
    member of the <type>OutputDevice</type> base class.  It is calculated to
    be an integer percent value.
*/
class Window
    : public ::Window,
      public ::DropTargetHelper
{
public:
    Window (::Window* pParent);
    virtual ~Window (void);

    void    SetViewShell (ViewShell* pViewSh);

    void    ShareViewArea(::sd::Window* pOtherWin);

    /** Set the zoom factor to the specified value and center the display
        area arround the zoom center.
        @param nZoom
            The zoom factor is given as integral percent value.
    */
    void    SetZoom(long nZoom);

    /** This internally used method performs the actual adaption of the
        window's map mode to the specified zoom factor.
        @param nZoom
            The zoom factor is given as integral percent value.
        @return
            When the given zoom factor lies outside the valid range enclosed
            by the minimal zoom factor previously calculated by
            <member>CalcMinZoom</member> and a constant upper value it is
            forced into that interval.  Therefore the returned value is a
            valid zoom factor.
    */
    long    SetZoomFactor(long nZoom);

    /** This method is called when the whole page shall be displayed in the
        window.  Position and zoom factor are set so that the given
        rectangle is displayed as large as possible in the window while at
        the same time maintaining the rectangle's aspect ratio and adding a
        small space at all its four sides (about 3% of width and height).
        The map mode is adapted accordingly.
        @param rZoomRect
            The rectangle is expected to be given relative to the upper left
            corner of the window in logical coordinates (100th of mm).
        @return
            The new zoom factor is returned as integral percent value.
    */
    long SetZoomRect (const Rectangle& rZoomRect);

    void SetMinZoomAutoCalc (bool bAuto);
    void SetCalcMinZoomByMinSide (bool bMin);

    /** Calculate the minimal zoom factor as the value at which the
        application area would completely fill the window.  All values set
        manually or programatically are set to this value if they are
        smaller.  If the currently used zoom factor is smaller than the minimal zoom
        factor than set the minimal zoom factor as the new current zoom
        factor.

This calculation is performed only when the
        <member>bMinZoomAutoCalc</member> is set (to <TRUE/>).

    */
    void CalcMinZoom (void);
    void SetMinZoom (long int nMin);
    long GetMinZoom (void) const;
    void SetMaxZoom (long int nMax);
    long GetMaxZoom (void) const;

    long GetZoom (void) const;

    Point GetWinViewPos (void) const;
    Point GetViewOrigin (void) const;
    Size GetViewSize (void) const;
    void SetWinViewPos(const Point& rPnt);
    void SetViewOrigin(const Point& rPnt);
    void SetViewSize(const Size& rSize);
    void SetCenterAllowed (bool bIsAllowed);

    /** Calculate origin of the map mode accoring to the size of the view
        and window (its size in model coordinates; that takes the zoom
        factor into account), and the bCenterAllowed flag.  When it is not
        set then nothing is changed.  When in any direction the window is
        larger than the view or the value of aWinPos in this direction is -1
        then the window is centered in this direction.
        */
    void UpdateMapOrigin (BOOL bInvalidate = TRUE);

    void UpdateMapMode (void);

    double  GetVisibleX();          // Interface fuer ScrollBars
    double  GetVisibleY();
    void    SetVisibleXY(double fX, double fY);
    double  GetVisibleWidth();
    double  GetVisibleHeight();
    double  GetScrlLineWidth();
    double  GetScrlLineHeight();
    double  GetScrlPageWidth();
    double  GetScrlPageHeight();
    virtual void GrabFocus();
    virtual void DataChanged( const DataChangedEvent& rDCEvt );

    // DropTargetHelper
    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );

    /** The DropScroll() method is used by AcceptDrop() to scroll the
        content of the window while dragging and dropping.  With this method
        you can control whether DropScroll() shall be used.
    */
    void SetUseDropScroll (bool bUseDropScroll);
    void DropScroll (const Point& rMousePos);

protected:
    ::sd::Window* mpShareWin;
    Point maWinPos;
    Point maViewOrigin;
    Size maViewSize;
    USHORT mnMinZoom;
    USHORT mnMaxZoom;
    /** This flag tells whether to re-calculate the minimal zoom factor
        depening on the current zoom factor.  According to task #105436# its
        default value is now FALSE.
    */
    bool mbMinZoomAutoCalc;
    bool mbCalcMinZoomByMinSide;
    bool mbCenterAllowed;
    long mnTicks;
    bool mbDraggedFrom;

    ViewShell* mpViewShell;
    bool mbUseDropScroll;

    virtual void Resize();
    virtual void Paint(const Rectangle& rRect);
    virtual void KeyInput(const KeyEvent& rKEvt);
    virtual void MouseMove(const MouseEvent& rMEvt);
    virtual void MouseButtonUp(const MouseEvent& rMEvt);
    virtual void MouseButtonDown(const MouseEvent& rMEvt);
    virtual void Command(const CommandEvent& rCEvt);
    virtual void RequestHelp( const HelpEvent& rEvt );
    virtual void LoseFocus();
    virtual long Notify( NotifyEvent& rNEvt );

    /** Create an accessibility object that makes this window accessible.

        @return
            The returned reference is empty if an accessible object could
            not be created.
    */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>
        CreateAccessible (void);
};

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.316); FILE MERGED 2006/12/01 14:15:14 cl 1.5.316.3: made sd warning free 2006/11/29 15:16:09 cl 1.5.316.2: #i69285# warning free code changes for sd project 2006/11/22 12:42:03 cl 1.5.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Window.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:40:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_WINDOW_HXX
#define SD_WINDOW_HXX

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif

namespace sd {

class ViewShell;

// Since we removed all old SV-stuff, there is no brush any more
// and so there is no BRUSH_SIZE defined in VCL.
// So I define it here
// #i2237#
// removed old stuff here which still forced zoom to be
// %BRUSH_SIZE which is outdated now
//#define BRUSH_SIZE        8

/** An SdWindow contains the actual working area of ViewShell.

The zoom factor used by this class controls how much the page and the
    shapes on it are scaled down (<100%) or up (>100%) when displayed on the
    output device represented by the <type>OutputDevice</type>base class.  A
    zoom factor of 100% would result (with a correctly set DPI value for an
    output device) in a one to one mapping of the internal coordinates that
    are stored in 100th of mm.  The zoom factor is stored in the map mode
    member of the <type>OutputDevice</type> base class.  It is calculated to
    be an integer percent value.
*/
class Window
    : public ::Window,
      public ::DropTargetHelper
{
public:
    Window (::Window* pParent);
    virtual ~Window (void);

    void    SetViewShell (ViewShell* pViewSh);

    void    ShareViewArea(::sd::Window* pOtherWin);

    /** Set the zoom factor to the specified value and center the display
        area arround the zoom center.
        @param nZoom
            The zoom factor is given as integral percent value.
    */
    void    SetZoomIntegral(long nZoom);

    /** This internally used method performs the actual adaption of the
        window's map mode to the specified zoom factor.
        @param nZoom
            The zoom factor is given as integral percent value.
        @return
            When the given zoom factor lies outside the valid range enclosed
            by the minimal zoom factor previously calculated by
            <member>CalcMinZoom</member> and a constant upper value it is
            forced into that interval.  Therefore the returned value is a
            valid zoom factor.
    */
    long    SetZoomFactor(long nZoom);

    /** This method is called when the whole page shall be displayed in the
        window.  Position and zoom factor are set so that the given
        rectangle is displayed as large as possible in the window while at
        the same time maintaining the rectangle's aspect ratio and adding a
        small space at all its four sides (about 3% of width and height).
        The map mode is adapted accordingly.
        @param rZoomRect
            The rectangle is expected to be given relative to the upper left
            corner of the window in logical coordinates (100th of mm).
        @return
            The new zoom factor is returned as integral percent value.
    */
    long SetZoomRect (const Rectangle& rZoomRect);

    void SetMinZoomAutoCalc (bool bAuto);
    void SetCalcMinZoomByMinSide (bool bMin);

    /** Calculate the minimal zoom factor as the value at which the
        application area would completely fill the window.  All values set
        manually or programatically are set to this value if they are
        smaller.  If the currently used zoom factor is smaller than the minimal zoom
        factor than set the minimal zoom factor as the new current zoom
        factor.

This calculation is performed only when the
        <member>bMinZoomAutoCalc</member> is set (to <TRUE/>).

    */
    void CalcMinZoom (void);
    void SetMinZoom (long int nMin);
    long GetMinZoom (void) const;
    void SetMaxZoom (long int nMax);
    long GetMaxZoom (void) const;

    long GetZoom (void) const;

    Point GetWinViewPos (void) const;
    Point GetViewOrigin (void) const;
    Size GetViewSize (void) const;
    void SetWinViewPos(const Point& rPnt);
    void SetViewOrigin(const Point& rPnt);
    void SetViewSize(const Size& rSize);
    void SetCenterAllowed (bool bIsAllowed);

    /** Calculate origin of the map mode accoring to the size of the view
        and window (its size in model coordinates; that takes the zoom
        factor into account), and the bCenterAllowed flag.  When it is not
        set then nothing is changed.  When in any direction the window is
        larger than the view or the value of aWinPos in this direction is -1
        then the window is centered in this direction.
        */
    void UpdateMapOrigin (BOOL bInvalidate = TRUE);

    void UpdateMapMode (void);

    double  GetVisibleX();          // Interface fuer ScrollBars
    double  GetVisibleY();
    void    SetVisibleXY(double fX, double fY);
    double  GetVisibleWidth();
    double  GetVisibleHeight();
    double  GetScrlLineWidth();
    double  GetScrlLineHeight();
    double  GetScrlPageWidth();
    double  GetScrlPageHeight();
    virtual void GrabFocus();
    virtual void DataChanged( const DataChangedEvent& rDCEvt );

    // DropTargetHelper
    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );

    /** The DropScroll() method is used by AcceptDrop() to scroll the
        content of the window while dragging and dropping.  With this method
        you can control whether DropScroll() shall be used.
    */
    void SetUseDropScroll (bool bUseDropScroll);
    void DropScroll (const Point& rMousePos);
protected:
    ::sd::Window* mpShareWin;
    Point maWinPos;
    Point maViewOrigin;
    Size maViewSize;
    USHORT mnMinZoom;
    USHORT mnMaxZoom;
    /** This flag tells whether to re-calculate the minimal zoom factor
        depening on the current zoom factor.  According to task #105436# its
        default value is now FALSE.
    */
    bool mbMinZoomAutoCalc;
    bool mbCalcMinZoomByMinSide;
    bool mbCenterAllowed;
    long mnTicks;
    bool mbDraggedFrom;

    ViewShell* mpViewShell;
    bool mbUseDropScroll;

    virtual void Resize();
    virtual void Paint(const Rectangle& rRect);
    virtual void KeyInput(const KeyEvent& rKEvt);
    virtual void MouseMove(const MouseEvent& rMEvt);
    virtual void MouseButtonUp(const MouseEvent& rMEvt);
    virtual void MouseButtonDown(const MouseEvent& rMEvt);
    virtual void Command(const CommandEvent& rCEvt);
    virtual void RequestHelp( const HelpEvent& rEvt );
    virtual void LoseFocus();
    virtual long Notify( NotifyEvent& rNEvt );

    /** Create an accessibility object that makes this window accessible.

        @return
            The returned reference is empty if an accessible object could
            not be created.
    */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>
        CreateAccessible (void);
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>#include "mathutils.h"
#include <limits>

namespace BuiltInFunctions {

QList<Number> MathUtils::multiplyVectorByNumber(QList<Number> vector, Number number)
{
	QList<Number> result;

	foreach (Number element, vector) {
		result << element * number;
	}

	return result;
}

QList<Number> MathUtils::subtractVectorFromVector(QList<Number> source, QList<Number> subtrahend)
{
	QList<Number> result;

	for (int i = 0; i < source.size(); i++) {
		result << source.at(i) - subtrahend.at(i);
	}

	return result;
}

QList<Number> MathUtils::addVectorToVector(QList<Number> source, QList<Number> summand)
{
	QList<Number> result;

	for (int i = 0; i < source.size(); i++) {
		result << source.at(i) + summand.at(i);
	}

	return result;
}

Number MathUtils::multiplyVectorByVectorScalar(QList<Number> source, QList<Number> factor)
{
	Number result = 0;

	for (int i = 0; i < source.size(); i++) {
		result += source.at(i) * factor.at(i);
	}

	return result;
}

Number MathUtils::vectorNorm(QList<Number> vector)
{
	Number result = 0;

	foreach (Number element, vector) {
		result += qPow(element, 2);
	}

	return qSqrt(result);
}

QList<Number> MathUtils::divideVectorByNumber(QList<Number> vector, Number divisor)
{
	QList<Number> result;

	foreach (Number element, vector) {
		result << element / divisor;
	}

	return result;
}

Number MathUtils::countDeterminant(QList<QList<Number> > matrix)
{
	ensureSquareMatrix(matrix);

	int numberOfSwaps = 0;

	// Direct pass

	for (int i = 0; i < matrix.count(); ++i) {

		int mainElementIndex = i;
		Number mainElement = matrix[i][i];

		// find main element of the current row
		for (int j = i + 1; j < matrix.count() - 1; ++j) {
			if (qAbs(mainElement) < qAbs(matrix[i][j])) {
				mainElementIndex = j;
				mainElement = matrix[i][j];
			}
		}

		if (MathUtils::isNull(mainElement)) {
			return 0.0;
		}

		// swap columns
		if (mainElementIndex != i) {
			swapColumns(matrix, i, mainElementIndex);
			++numberOfSwaps;
		}

		// subtract current row (multiplied before) from rows below.
		for (int j = i + 1; j < matrix.count(); ++j) {
			Number multiplyer = matrix[j][i] / matrix[i][i];
			QList<Number> multipliedRow = MathUtils::multiplyVectorByNumber(matrix[i], multiplyer);
			matrix[j] = MathUtils::subtractVectorFromVector(matrix[j], multipliedRow);
		}
	}

	// Now we've got triangular matrix, multiply all elements of its main diagonal

	Number result = 1.0;
	for (int i = 0; i < matrix.count(); ++i) {
		result *= matrix[i][i];
	}
	if (numberOfSwaps % 2 == 1) {
		result *= -1.0;
	}

	return result;
}

bool MathUtils::isBetween(Number value, Number left, Number right, bool canBeEqual)
{
	if (canBeEqual) {
		return (value >= left) && (value <= right);
	}
	else {
		return (value > left) && (value < right);
	}
}

bool MathUtils::equal(Number number1, Number number2)
{
	return qFuzzyCompare(number1, number2);
}

bool MathUtils::isNull(Number number)
{
	return qFuzzyCompare(number + 1.0, 1.0); // see qFuzzyCompare(double, double) documentation
}

Number MathUtils::getNaN()
{
	return std::numeric_limits<Number>::quiet_NaN();
}

bool MathUtils::isNaN(const Number number)
{
	volatile Number value = number;
	return value != value;
}

QList<Number> MathUtils::generateRandomNumbers(int count, Number lowerLimit, Number higherLimit)
{
	QList<Number> result;

	for (int i = 0; i < count; i++) {
		result << getRandomNumber(qAbs(lowerLimit - higherLimit)) + lowerLimit;
	}

	return result;
}

// Return a random number between 0 and higher limit
// For currect using initialize random first with srand function
Number MathUtils::getRandomNumber(Number higherLimit)
{
	Number result;

	do {
		result = rand() / (RAND_MAX / (higherLimit + 1));
	} while (result > higherLimit);

	return result;
}

void MathUtils::ensureSquareMatrix(const QList<QList<Number> > &matrix)
{
	int matrixSize = matrix.size();
	foreach (const QList<Number> &row, matrix) {
		if (row.size() != matrixSize) {
			THROW(ENotSquareMatrix());
		}
	}
}

void MathUtils::ensureMatrix(const QList<QList<Number> > &matrix)
{
	int matrixSize = matrix.first().size();
	foreach (const QList<Number> &row, matrix) {
		if (row.size() != matrixSize) {
			THROW(ENotMatrix());
		}
	}
}

void MathUtils::swapColumns(QList<QList<Number> > &matrix, int index1, int index2)
{
	// Matrix 'matrix' must be really a matrix :), not just a list of list of numbers.

	if ((index1 >= matrix.first().count()) || (index2 >= matrix.first().count())) {
		THROW(EInternal());
	}

	QMutableListIterator<QList<Number> > i(matrix);
	while (i.hasNext()) {
		i.next().swap(index1, index2);
	}
}

} // namespace
<commit_msg>Fix for determinant counting.<commit_after>#include "mathutils.h"
#include <limits>

namespace BuiltInFunctions {

QList<Number> MathUtils::multiplyVectorByNumber(QList<Number> vector, Number number)
{
	QList<Number> result;

	foreach (Number element, vector) {
		result << element * number;
	}

	return result;
}

QList<Number> MathUtils::subtractVectorFromVector(QList<Number> source, QList<Number> subtrahend)
{
	QList<Number> result;

	for (int i = 0; i < source.size(); i++) {
		result << source.at(i) - subtrahend.at(i);
	}

	return result;
}

QList<Number> MathUtils::addVectorToVector(QList<Number> source, QList<Number> summand)
{
	QList<Number> result;

	for (int i = 0; i < source.size(); i++) {
		result << source.at(i) + summand.at(i);
	}

	return result;
}

Number MathUtils::multiplyVectorByVectorScalar(QList<Number> source, QList<Number> factor)
{
	Number result = 0;

	for (int i = 0; i < source.size(); i++) {
		result += source.at(i) * factor.at(i);
	}

	return result;
}

Number MathUtils::vectorNorm(QList<Number> vector)
{
	Number result = 0;

	foreach (Number element, vector) {
		result += qPow(element, 2);
	}

	return qSqrt(result);
}

QList<Number> MathUtils::divideVectorByNumber(QList<Number> vector, Number divisor)
{
	QList<Number> result;

	foreach (Number element, vector) {
		result << element / divisor;
	}

	return result;
}

Number MathUtils::countDeterminant(QList<QList<Number> > matrix)
{
	ensureSquareMatrix(matrix);

	int numberOfSwaps = 0;

	// Direct pass

	for (int i = 0; i < matrix.count(); ++i) {

		int mainElementIndex = i;
		Number mainElement = matrix[i][i];

		// find main element of the current row
		for (int j = i + 1; j < matrix.count(); ++j) {
			if (qAbs(mainElement) < qAbs(matrix[i][j])) {
				mainElementIndex = j;
				mainElement = matrix[i][j];
			}
		}

		if (MathUtils::isNull(mainElement)) {
			return 0.0;
		}

		// swap columns
		if (mainElementIndex != i) {
			swapColumns(matrix, i, mainElementIndex);
			++numberOfSwaps;
		}

		// subtract current row (multiplied before) from rows below.
		for (int j = i + 1; j < matrix.count(); ++j) {
			Number multiplyer = matrix[j][i] / matrix[i][i];
			QList<Number> multipliedRow = MathUtils::multiplyVectorByNumber(matrix[i], multiplyer);
			matrix[j] = MathUtils::subtractVectorFromVector(matrix[j], multipliedRow);
		}
	}

	// Now we've got triangular matrix, multiply all elements of its main diagonal

	Number result = 1.0;
	for (int i = 0; i < matrix.count(); ++i) {
		result *= matrix[i][i];
	}
	if (numberOfSwaps % 2 == 1) {
		result *= -1.0;
	}

	return result;
}

bool MathUtils::isBetween(Number value, Number left, Number right, bool canBeEqual)
{
	if (canBeEqual) {
		return (value >= left) && (value <= right);
	}
	else {
		return (value > left) && (value < right);
	}
}

bool MathUtils::equal(Number number1, Number number2)
{
	return qFuzzyCompare(number1, number2);
}

bool MathUtils::isNull(Number number)
{
	return qFuzzyCompare(number + 1.0, 1.0); // see qFuzzyCompare(double, double) documentation
}

Number MathUtils::getNaN()
{
	return std::numeric_limits<Number>::quiet_NaN();
}

bool MathUtils::isNaN(const Number number)
{
	volatile Number value = number;
	return value != value;
}

QList<Number> MathUtils::generateRandomNumbers(int count, Number lowerLimit, Number higherLimit)
{
	QList<Number> result;

	for (int i = 0; i < count; i++) {
		result << getRandomNumber(qAbs(lowerLimit - higherLimit)) + lowerLimit;
	}

	return result;
}

// Return a random number between 0 and higher limit
// For currect using initialize random first with srand function
Number MathUtils::getRandomNumber(Number higherLimit)
{
	Number result;

	do {
		result = rand() / (RAND_MAX / (higherLimit + 1));
	} while (result > higherLimit);

	return result;
}

void MathUtils::ensureSquareMatrix(const QList<QList<Number> > &matrix)
{
	int matrixSize = matrix.size();
	foreach (const QList<Number> &row, matrix) {
		if (row.size() != matrixSize) {
			THROW(ENotSquareMatrix());
		}
	}
}

void MathUtils::ensureMatrix(const QList<QList<Number> > &matrix)
{
	int matrixSize = matrix.first().size();
	foreach (const QList<Number> &row, matrix) {
		if (row.size() != matrixSize) {
			THROW(ENotMatrix());
		}
	}
}

void MathUtils::swapColumns(QList<QList<Number> > &matrix, int index1, int index2)
{
	// Matrix 'matrix' must be really a matrix :), not just a list of list of numbers.

	if ((index1 >= matrix.first().count()) || (index2 >= matrix.first().count())) {
		THROW(EInternal());
	}

	QMutableListIterator<QList<Number> > i(matrix);
	while (i.hasNext()) {
		i.next().swap(index1, index2);
	}
}

} // namespace
<|endoftext|>


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

#ifndef _SD_FUSLID_HXX
#define _SD_FUSLID_HXX

#ifndef _SD_FUPOOR_HXX
#include "fupoor.hxx"
#endif

class SdSlideViewShell;
class SdSlideView;
class SdWindow;
class SdDrawDocument;

/*************************************************************************
|*
|* Basisklasse der Funktionen des Diamodus
|*
\************************************************************************/

class FuSlide : public FuPoor
{
 protected:
    SdSlideViewShell* pSlViewShell;
    SdSlideView*      pSlView;

 public:
    TYPEINFO();

    FuSlide(SdSlideViewShell* pViewSh, SdWindow* pWin,
            SdSlideView* pView, SdDrawDocument* pDoc, SfxRequest& rReq);

    virtual ~FuSlide();

    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt) { return FALSE; }
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt) { return FALSE; }
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt) { return FALSE; }

    virtual void Activate();
    virtual void Deactivate();

    virtual void ScrollStart();
    virtual void ScrollEnd();
};

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

#ifndef SD_FU_SLIDE_HXX
#define SD_FU_SLIDE_HXX

#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif

class SdDrawDocument;

namespace sd {

class SlideView;
class SlideViewShell;
class Window;

/*************************************************************************
|*
|* Basisklasse der Funktionen des Diamodus
|*
\************************************************************************/

class FuSlide
    : public FuPoor
{
public:
    TYPEINFO();

    FuSlide (
        SlideViewShell* pViewSh,
        ::sd::Window* pWin,
        SlideView* pView,
        SdDrawDocument* pDoc,
        SfxRequest& rReq);
    virtual ~FuSlide (void);

    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt) { return FALSE; }
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt) { return FALSE; }
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt) { return FALSE; }

    virtual void Activate();
    virtual void Deactivate();

    virtual void ScrollStart();
    virtual void ScrollEnd();

protected:
    SlideViewShell* pSlViewShell;
    SlideView*    pSlView;
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "router/manager/router_proxy.h"

#include "base/logging.h"
#include "base/task_runner.h"
#include "router/manager/router.h"

namespace router {

class RouterProxy::Impl : public std::enable_shared_from_this<Impl>
{
public:
    Impl(std::shared_ptr<base::TaskRunner> io_task_runner, std::unique_ptr<Router> router);
    ~Impl();

    void connectToRouter(const std::u16string& address, uint16_t port);
    void disconnectFromRouter();
    void refreshHostList();
    void disconnectHost(base::HostId host_id);
    void refreshRelayList();
    void refreshUserList();
    void addUser(const proto::User& user);
    void modifyUser(const proto::User& user);
    void deleteUser(int64_t entry_id);

private:
    std::shared_ptr<base::TaskRunner> io_task_runner_;
    std::unique_ptr<Router> router_;

    DISALLOW_COPY_AND_ASSIGN(Impl);
};

RouterProxy::Impl::Impl(std::shared_ptr<base::TaskRunner> io_task_runner,
                        std::unique_ptr<Router> router)
    : io_task_runner_(std::move(io_task_runner)),
      router_(std::move(router))
{
    DCHECK(io_task_runner_ && router_);
}

RouterProxy::Impl::~Impl()
{
    DCHECK(!router_);
}

void RouterProxy::Impl::connectToRouter(const std::u16string& address, uint16_t port)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(
            std::bind(&Impl::connectToRouter, shared_from_this(), address, port));
        return;
    }

    if (router_)
        router_->connectToRouter(address, port);
}

void RouterProxy::Impl::disconnectFromRouter()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(
            std::bind(&Impl::disconnectFromRouter, shared_from_this()));
        return;
    }

    router_.reset();
}

void RouterProxy::Impl::refreshHostList()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::refreshHostList, shared_from_this()));
        return;
    }

    if (router_)
        router_->refreshHostList();
}

void RouterProxy::Impl::disconnectHost(base::HostId host_id)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::disconnectHost, shared_from_this(), host_id));
        return;
    }

    if (router_)
        router_->disconnectHost(host_id);
}

void RouterProxy::Impl::refreshRelayList()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::refreshRelayList, shared_from_this()));
        return;
    }

    if (router_)
        router_->refreshRelayList();
}

void RouterProxy::Impl::refreshUserList()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::refreshUserList, shared_from_this()));
        return;
    }

    if (router_)
        router_->refreshUserList();
}

void RouterProxy::Impl::addUser(const proto::User& user)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::addUser, shared_from_this(), user));
        return;
    }

    if (router_)
        router_->addUser(user);
}

void RouterProxy::Impl::modifyUser(const proto::User& user)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::modifyUser, shared_from_this(), user));
        return;
    }

    if (router_)
        router_->modifyUser(user);
}

void RouterProxy::Impl::deleteUser(int64_t entry_id)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::deleteUser, shared_from_this(), entry_id));
        return;
    }

    if (router_)
        router_->deleteUser(entry_id);
}

RouterProxy::RouterProxy(std::shared_ptr<base::TaskRunner> io_task_runner,
                         std::unique_ptr<Router> router)
    : impl_(std::make_shared<Impl>(std::move(io_task_runner), std::move(router)))
{
    // Nothing
}

RouterProxy::~RouterProxy()
{
    impl_->disconnectFromRouter();
}

void RouterProxy::connectToRouter(const std::u16string& address, uint16_t port)
{
    impl_->connectToRouter(address, port);
}

void RouterProxy::disconnectFromRouter()
{
    impl_->disconnectFromRouter();
}

void RouterProxy::refreshHostList()
{
    impl_->refreshHostList();
}

void RouterProxy::disconnectHost(uint64_t host_id)
{
    impl_->disconnectHost(host_id);
}

void RouterProxy::refreshRelayList()
{
    impl_->refreshRelayList();
}

void RouterProxy::refreshUserList()
{
    impl_->refreshUserList();
}

void RouterProxy::addUser(const proto::User& user)
{
    impl_->addUser(user);
}

void RouterProxy::modifyUser(const proto::User& user)
{
    impl_->modifyUser(user);
}

void RouterProxy::deleteUser(int64_t entry_id)
{
    impl_->deleteUser(entry_id);
}

} // namespace router
<commit_msg>Fix Linux build.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//

#include "router/manager/router_proxy.h"

#include "base/logging.h"
#include "base/task_runner.h"
#include "router/manager/router.h"

namespace router {

class RouterProxy::Impl : public std::enable_shared_from_this<Impl>
{
public:
    Impl(std::shared_ptr<base::TaskRunner> io_task_runner, std::unique_ptr<Router> router);
    ~Impl();

    void connectToRouter(const std::u16string& address, uint16_t port);
    void disconnectFromRouter();
    void refreshHostList();
    void disconnectHost(base::HostId host_id);
    void refreshRelayList();
    void refreshUserList();
    void addUser(const proto::User& user);
    void modifyUser(const proto::User& user);
    void deleteUser(int64_t entry_id);

private:
    std::shared_ptr<base::TaskRunner> io_task_runner_;
    std::unique_ptr<Router> router_;

    DISALLOW_COPY_AND_ASSIGN(Impl);
};

RouterProxy::Impl::Impl(std::shared_ptr<base::TaskRunner> io_task_runner,
                        std::unique_ptr<Router> router)
    : io_task_runner_(std::move(io_task_runner)),
      router_(std::move(router))
{
    DCHECK(io_task_runner_ && router_);
}

RouterProxy::Impl::~Impl()
{
    DCHECK(!router_);
}

void RouterProxy::Impl::connectToRouter(const std::u16string& address, uint16_t port)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(
            std::bind(&Impl::connectToRouter, shared_from_this(), address, port));
        return;
    }

    if (router_)
        router_->connectToRouter(address, port);
}

void RouterProxy::Impl::disconnectFromRouter()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(
            std::bind(&Impl::disconnectFromRouter, shared_from_this()));
        return;
    }

    router_.reset();
}

void RouterProxy::Impl::refreshHostList()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::refreshHostList, shared_from_this()));
        return;
    }

    if (router_)
        router_->refreshHostList();
}

void RouterProxy::Impl::disconnectHost(base::HostId host_id)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::disconnectHost, shared_from_this(), host_id));
        return;
    }

    if (router_)
        router_->disconnectHost(host_id);
}

void RouterProxy::Impl::refreshRelayList()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::refreshRelayList, shared_from_this()));
        return;
    }

    if (router_)
        router_->refreshRelayList();
}

void RouterProxy::Impl::refreshUserList()
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::refreshUserList, shared_from_this()));
        return;
    }

    if (router_)
        router_->refreshUserList();
}

void RouterProxy::Impl::addUser(const proto::User& user)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::addUser, shared_from_this(), user));
        return;
    }

    if (router_)
        router_->addUser(user);
}

void RouterProxy::Impl::modifyUser(const proto::User& user)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::modifyUser, shared_from_this(), user));
        return;
    }

    if (router_)
        router_->modifyUser(user);
}

void RouterProxy::Impl::deleteUser(int64_t entry_id)
{
    if (!io_task_runner_->belongsToCurrentThread())
    {
        io_task_runner_->postTask(std::bind(&Impl::deleteUser, shared_from_this(), entry_id));
        return;
    }

    if (router_)
        router_->deleteUser(entry_id);
}

RouterProxy::RouterProxy(std::shared_ptr<base::TaskRunner> io_task_runner,
                         std::unique_ptr<Router> router)
    : impl_(std::make_shared<Impl>(std::move(io_task_runner), std::move(router)))
{
    // Nothing
}

RouterProxy::~RouterProxy()
{
    impl_->disconnectFromRouter();
}

void RouterProxy::connectToRouter(const std::u16string& address, uint16_t port)
{
    impl_->connectToRouter(address, port);
}

void RouterProxy::disconnectFromRouter()
{
    impl_->disconnectFromRouter();
}

void RouterProxy::refreshHostList()
{
    impl_->refreshHostList();
}

void RouterProxy::disconnectHost(base::HostId host_id)
{
    impl_->disconnectHost(host_id);
}

void RouterProxy::refreshRelayList()
{
    impl_->refreshRelayList();
}

void RouterProxy::refreshUserList()
{
    impl_->refreshUserList();
}

void RouterProxy::addUser(const proto::User& user)
{
    impl_->addUser(user);
}

void RouterProxy::modifyUser(const proto::User& user)
{
    impl_->modifyUser(user);
}

void RouterProxy::deleteUser(int64_t entry_id)
{
    impl_->deleteUser(entry_id);
}

} // namespace router
<|endoftext|>


<commit_before>#include "platform.hpp"

#include "../coding/file_reader.hpp"
#include "../coding/zip_reader.hpp"

#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>

Platform::Platform()
{}

Platform::~Platform()
{}

/// @warning doesn't work for files inside .apk (zip)!!!
bool Platform::IsFileExists(string const & file) const
{
  struct stat s;
  return stat(file.c_str(), &s) == 0;
}

ModelReader * Platform::GetReader(string const & file) const
{
  if (IsFileExists(m_writableDir + file))
    return new FileReader(ReadPathForFile(file), 10, 12);
  else
  { // paths from GetFilesInDir will already contain "assets/"
    if (file.find("assets/") != string::npos)
      return new ZipFileReader(m_resourcesDir, file);
    else
      return new ZipFileReader(m_resourcesDir, "assets/" + file);
  }
}

void Platform::GetFilesInDir(string const & directory, string const & mask, FilesList & res) const
{
  if (ZipFileReader::IsZip(directory))
  { // Get files list inside zip file
    res = ZipFileReader::FilesList(directory);
    // filter out according to the mask
    // @TODO we don't support wildcards at the moment
    string fixedMask = mask;
    if (fixedMask.size() && fixedMask[0] == '*')
      fixedMask.erase(0, 1);
    for (FilesList::iterator it = res.begin(); it != res.end();)
    {
      if (it->find(fixedMask) == string::npos)
        it = res.erase(it);
      else
        ++it;
    }
  }
  else
  {
    DIR * dir;
    struct dirent * entry;
    if ((dir = opendir(directory.c_str())) == NULL)
      return;
    // TODO: take wildcards into account...
    string mask_fixed = mask;
    if (mask_fixed.size() && mask_fixed[0] == '*')
      mask_fixed.erase(0, 1);
    do
    {
      if ((entry = readdir(dir)) != NULL)
      {
        string fname(entry->d_name);
        size_t index = fname.rfind(mask_fixed);
        if (index != string::npos && index == fname.size() - mask_fixed.size())
        {
            res.push_back(fname);
        }
      }
    } while (entry != NULL);

    closedir(dir);
  }
}

int Platform::CpuCores() const
{
  long const numCPU = sysconf(_SC_NPROCESSORS_ONLN);
  if (numCPU >= 1)
    return static_cast<int>(numCPU);
  return 1;

}

string Platform::DeviceName() const
{
  return "Android";
}

double Platform::VisualScale() const
{
  return 1.5;
}

string Platform::SkinName() const
{
  return "basic_hdpi.skn";
}

void Platform::GetFontNames(FilesList & res) const
{
  GetFilesInDir(ResourcesDir(), "*.ttf", res);
  sort(res.begin(), res.end());
}

int Platform::ScaleEtalonSize() const
{
  return 512 + 256;
}

int Platform::TileSize() const
{
  return 256;
}

int Platform::MaxTilesCount() const
{
  return 120;
}

int Platform::VideoMemoryLimit() const
{
  return 10 * 1024 * 1024;
}

bool Platform::GetFileSize(string const & file, uint64_t & size) const
{
  try
  {
    size = ReaderPtr<Reader>(GetReader(file)).Size();
    return true;
  }
  catch (RootException const &)
  {
    return false;
  }
}

string Platform::UniqueClientId() const
{
  return "@TODO";
}
<commit_msg>[ANDROID] changed default skin to basic_mdpi.<commit_after>#include "platform.hpp"

#include "../coding/file_reader.hpp"
#include "../coding/zip_reader.hpp"

#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>

Platform::Platform()
{}

Platform::~Platform()
{}

/// @warning doesn't work for files inside .apk (zip)!!!
bool Platform::IsFileExists(string const & file) const
{
  struct stat s;
  return stat(file.c_str(), &s) == 0;
}

ModelReader * Platform::GetReader(string const & file) const
{
  if (IsFileExists(m_writableDir + file))
    return new FileReader(ReadPathForFile(file), 10, 12);
  else
  { // paths from GetFilesInDir will already contain "assets/"
    if (file.find("assets/") != string::npos)
      return new ZipFileReader(m_resourcesDir, file);
    else
      return new ZipFileReader(m_resourcesDir, "assets/" + file);
  }
}

void Platform::GetFilesInDir(string const & directory, string const & mask, FilesList & res) const
{
  if (ZipFileReader::IsZip(directory))
  { // Get files list inside zip file
    res = ZipFileReader::FilesList(directory);
    // filter out according to the mask
    // @TODO we don't support wildcards at the moment
    string fixedMask = mask;
    if (fixedMask.size() && fixedMask[0] == '*')
      fixedMask.erase(0, 1);
    for (FilesList::iterator it = res.begin(); it != res.end();)
    {
      if (it->find(fixedMask) == string::npos)
        it = res.erase(it);
      else
        ++it;
    }
  }
  else
  {
    DIR * dir;
    struct dirent * entry;
    if ((dir = opendir(directory.c_str())) == NULL)
      return;
    // TODO: take wildcards into account...
    string mask_fixed = mask;
    if (mask_fixed.size() && mask_fixed[0] == '*')
      mask_fixed.erase(0, 1);
    do
    {
      if ((entry = readdir(dir)) != NULL)
      {
        string fname(entry->d_name);
        size_t index = fname.rfind(mask_fixed);
        if (index != string::npos && index == fname.size() - mask_fixed.size())
        {
            res.push_back(fname);
        }
      }
    } while (entry != NULL);

    closedir(dir);
  }
}

int Platform::CpuCores() const
{
  long const numCPU = sysconf(_SC_NPROCESSORS_ONLN);
  if (numCPU >= 1)
    return static_cast<int>(numCPU);
  return 1;

}

string Platform::DeviceName() const
{
  return "Android";
}

double Platform::VisualScale() const
{
  return 1.5;
}

string Platform::SkinName() const
{
  return "basic_mdpi.skn";
}

void Platform::GetFontNames(FilesList & res) const
{
  GetFilesInDir(ResourcesDir(), "*.ttf", res);
  sort(res.begin(), res.end());
}

int Platform::ScaleEtalonSize() const
{
  return 512 + 256;
}

int Platform::TileSize() const
{
  return 256;
}

int Platform::MaxTilesCount() const
{
  return 120;
}

int Platform::VideoMemoryLimit() const
{
  return 10 * 1024 * 1024;
}

bool Platform::GetFileSize(string const & file, uint64_t & size) const
{
  try
  {
    size = ReaderPtr<Reader>(GetReader(file)).Size();
    return true;
  }
  catch (RootException const &)
  {
    return false;
  }
}

string Platform::UniqueClientId() const
{
  return "@TODO";
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/os.h"

#include <errno.h>
#include <limits.h>
#include <malloc.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include "platform/utils.h"
#include "vm/code_observers.h"
#include "vm/dart.h"
#include "vm/debuginfo.h"
#include "vm/isolate.h"
#include "vm/zone.h"

namespace dart {

// Linux CodeObservers.

DEFINE_FLAG(bool, generate_gdb_symbols, false,
    "Generate symbols of generated dart functions for debugging with GDB");
DEFINE_FLAG(bool, generate_perf_events_symbols, false,
    "Generate events symbols for profiling with perf");
DEFINE_FLAG(charp, generate_pprof_symbols, NULL,
    "Generate events symbols for profiling with pprof");

class PerfCodeObserver : public CodeObserver {
 public:
  PerfCodeObserver() {
    Dart_FileOpenCallback file_open = Isolate::file_open_callback();
    if (file_open == NULL) {
      return;
    }
    const char* format = "/tmp/perf-%ld.map";
    intptr_t pid = getpid();
    intptr_t len = OS::SNPrint(NULL, 0, format, pid);
    char* filename = new char[len + 1];
    OS::SNPrint(filename, len + 1, format, pid);
    out_file_ = (*file_open)(filename);
  }

  ~PerfCodeObserver() {
    Dart_FileCloseCallback file_close = Isolate::file_close_callback();
    if (file_close == NULL) {
      return;
    }
    ASSERT(out_file_ != NULL);
    (*file_close)(out_file_);
  }

  virtual bool IsActive() const {
    return FLAG_generate_perf_events_symbols;
  }

  virtual void Notify(const char* name,
                      uword base,
                      uword prologue_offset,
                      uword size,
                      bool optimized) {
    Dart_FileWriteCallback file_write = Isolate::file_write_callback();
    ASSERT(file_write != NULL);
    const char* format = "%"Px" %"Px" %s%s\n";
    const char* marker = optimized ? "*" : "";
    intptr_t len = OS::SNPrint(NULL, 0, format, base, size, marker, name);
    char* buffer = Isolate::Current()->current_zone()->Alloc<char>(len + 1);
    OS::SNPrint(buffer, len + 1, format, base, size, marker, name);
    ASSERT(out_file_ != NULL);
    (*file_write)(buffer, len, out_file_);
  }

 private:
  void* out_file_;

  DISALLOW_COPY_AND_ASSIGN(PerfCodeObserver);
};

class PprofCodeObserver : public CodeObserver {
 public:
  PprofCodeObserver() {
    pprof_symbol_generator_ = DebugInfo::NewGenerator();
  }

  ~PprofCodeObserver() {
    Dart_FileOpenCallback file_open = Isolate::file_open_callback();
    if (file_open == NULL) {
      return;
    }
    Dart_FileCloseCallback file_close = Isolate::file_close_callback();
    if (file_close == NULL) {
      return;
    }
    Dart_FileWriteCallback file_write = Isolate::file_write_callback();
    if (file_write == NULL) {
      return;
    }
    if (FLAG_generate_pprof_symbols == NULL) {
      return;
    }
    const char* filename = FLAG_generate_pprof_symbols;
    void* out_file = (*file_open)(filename);
    ASSERT(out_file != NULL);
    DebugInfo::ByteBuffer* debug_region = new DebugInfo::ByteBuffer();
    ASSERT(debug_region != NULL);
    pprof_symbol_generator_->WriteToMemory(debug_region);
    int buffer_size = debug_region->size();
    void* buffer = debug_region->data();
    delete debug_region;
    if (buffer_size > 0) {
      ASSERT(buffer != NULL);
      (*file_write)(buffer, buffer_size, out_file);
    }
    (*file_close)(out_file);
    DebugInfo::UnregisterAllSections();
  }

  virtual bool IsActive() const {
    return FLAG_generate_pprof_symbols != NULL;
  }

  virtual void Notify(const char* name,
                      uword base,
                      uword prologue_offset,
                      uword size,
                      bool optimized) {
    ASSERT(pprof_symbol_generator_ != NULL);
    pprof_symbol_generator_->AddCode(base, size);
    pprof_symbol_generator_->AddCodeRegion(name, base, size);
  }

 private:
  DebugInfo* pprof_symbol_generator_;

  DISALLOW_COPY_AND_ASSIGN(PprofCodeObserver);
};

class GdbCodeObserver : public CodeObserver {
 public:
  GdbCodeObserver() { }

  virtual bool IsActive() const {
    return FLAG_generate_gdb_symbols;
  }

  virtual void Notify(const char* name,
                      uword base,
                      uword prologue_offset,
                      uword size,
                      bool optimized) {
    if (prologue_offset > 0) {
      // In order to ensure that gdb sees the first instruction of a function
      // as the prologue sequence we register two symbols for the cases when
      // the prologue sequence is not the first instruction:
      // <name>_entry is used for code preceding the prologue sequence.
      // <name> for rest of the code (first instruction is prologue sequence).
      const char* kFormat = "%s_%s";
      intptr_t len = OS::SNPrint(NULL, 0, kFormat, name, "entry");
      char* pname = Isolate::Current()->current_zone()->Alloc<char>(len + 1);
      OS::SNPrint(pname, (len + 1), kFormat, name, "entry");
      DebugInfo::RegisterSection(pname, base, size);
      DebugInfo::RegisterSection(name,
                                 (base + prologue_offset),
                                 (size - prologue_offset));
    } else {
      DebugInfo::RegisterSection(name, base, size);
    }
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(GdbCodeObserver);
};

static bool LocalTime(int64_t seconds_since_epoch, tm* tm_result) {
  time_t seconds = static_cast<time_t>(seconds_since_epoch);
  if (seconds != seconds_since_epoch) return false;
  struct tm* error_code = localtime_r(&seconds, tm_result);
  return error_code != NULL;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // If unsuccessful, return an empty string like V8 does.
  return (succeeded && (decomposed.tm_zone != NULL)) ? decomposed.tm_zone : "";
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // If unsuccessful, return zero like V8 does.
  return succeeded ? static_cast<int>(decomposed.tm_gmtoff) : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  // TODO(floitsch): avoid excessive calls to tzset?
  tzset();
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // Note that Unix and Dart disagree on the sign.
  return static_cast<int>(-timezone);
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  // gettimeofday has microsecond resolution.
  struct timeval tv;
  if (gettimeofday(&tv, NULL) < 0) {
    UNREACHABLE();
    return 0;
  }
  return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
}

void* OS::AlignedAllocate(intptr_t size, intptr_t alignment) {
  const int kMinimumAlignment = 16;
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  void* p = memalign(alignment, size);
  if (p == NULL) {
    UNREACHABLE();
  }
  return p;
}

void OS::AlignedFree(void* ptr) {
  free(ptr);
}

// TODO(5411554):  May need to hoist these architecture dependent code
// into a architecture specific file e.g: os_ia32_linux.cc
word OS::ActivationFrameAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 8;
#else
#error Unsupported architecture.
#endif
  word alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default stack alignment for
  // testing purposes.
  // Flags::DebugIsInt("stackalign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  return alignment;
}

word OS::PreferredCodeAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 16;
#else
#error Unsupported architecture.
#endif
  word alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default code alignment for
  // testing purposes.
  // Flags::DebugIsInt("codealign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  ASSERT(alignment <= OS::kMaxPreferredCodeAlignment);
  return alignment;
}

uword OS::GetStackSizeLimit() {
  struct rlimit stack_limit;
  int retval = getrlimit(RLIMIT_STACK, &stack_limit);
  ASSERT(retval == 0);
  if (stack_limit.rlim_cur > INT_MAX) {
    retval = INT_MAX;
  } else {
    retval = stack_limit.rlim_cur;
  }
  return retval;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_ONLN);
}

void OS::Sleep(int64_t millis) {
  // TODO(5411554):  For now just use usleep we may have to revisit this.
  usleep(millis * 1000);
}

void OS::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

int OS::SNPrint(char* str, size_t size, const char* format, ...) {
  va_list args;
  va_start(args, format);
  int retval = VSNPrint(str, size, format, args);
  va_end(args);
  return retval;
}

int OS::VSNPrint(char* str, size_t size, const char* format, va_list args) {
  int retval = vsnprintf(str, size, format, args);
  if (retval < 0) {
    FATAL1("Fatal error in OS::VSNPrint with format '%s'", format);
  }
  return retval;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  }
  if ((str[i] == '0') &&
      (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  *value = strtoll(str, &endptr, base);
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
  if (FLAG_generate_perf_events_symbols) {
    CodeObservers::Register(new PerfCodeObserver);
  }
  if (FLAG_generate_gdb_symbols) {
    CodeObservers::Register(new GdbCodeObserver);
  }
  if (FLAG_generate_pprof_symbols != NULL) {
    CodeObservers::Register(new PprofCodeObserver);
  }
#if defined(DART_VTUNE_SUPPORT)
  Register(new VTuneCodeObserver);
#endif
}

void OS::PrintErr(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
}

void OS::InitOnce() {
  // TODO(5411554): For now we check that initonce is called only once,
  // Once there is more formal mechanism to call InitOnce we can move
  // this check there.
  static bool init_once_called = false;
  ASSERT(init_once_called == false);
  init_once_called = true;
}

void OS::Shutdown() {
}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  exit(code);
}

}  // namespace dart
<commit_msg>Fix pprof VM flag description<commit_after>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "vm/os.h"

#include <errno.h>
#include <limits.h>
#include <malloc.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include "platform/utils.h"
#include "vm/code_observers.h"
#include "vm/dart.h"
#include "vm/debuginfo.h"
#include "vm/isolate.h"
#include "vm/zone.h"

namespace dart {

// Linux CodeObservers.

DEFINE_FLAG(bool, generate_gdb_symbols, false,
    "Generate symbols of generated dart functions for debugging with GDB");
DEFINE_FLAG(bool, generate_perf_events_symbols, false,
    "Generate events symbols for profiling with perf");
DEFINE_FLAG(charp, generate_pprof_symbols, NULL,
    "Writes pprof events symbols to the provided file");

class PerfCodeObserver : public CodeObserver {
 public:
  PerfCodeObserver() {
    Dart_FileOpenCallback file_open = Isolate::file_open_callback();
    if (file_open == NULL) {
      return;
    }
    const char* format = "/tmp/perf-%ld.map";
    intptr_t pid = getpid();
    intptr_t len = OS::SNPrint(NULL, 0, format, pid);
    char* filename = new char[len + 1];
    OS::SNPrint(filename, len + 1, format, pid);
    out_file_ = (*file_open)(filename);
  }

  ~PerfCodeObserver() {
    Dart_FileCloseCallback file_close = Isolate::file_close_callback();
    if (file_close == NULL) {
      return;
    }
    ASSERT(out_file_ != NULL);
    (*file_close)(out_file_);
  }

  virtual bool IsActive() const {
    return FLAG_generate_perf_events_symbols;
  }

  virtual void Notify(const char* name,
                      uword base,
                      uword prologue_offset,
                      uword size,
                      bool optimized) {
    Dart_FileWriteCallback file_write = Isolate::file_write_callback();
    ASSERT(file_write != NULL);
    const char* format = "%"Px" %"Px" %s%s\n";
    const char* marker = optimized ? "*" : "";
    intptr_t len = OS::SNPrint(NULL, 0, format, base, size, marker, name);
    char* buffer = Isolate::Current()->current_zone()->Alloc<char>(len + 1);
    OS::SNPrint(buffer, len + 1, format, base, size, marker, name);
    ASSERT(out_file_ != NULL);
    (*file_write)(buffer, len, out_file_);
  }

 private:
  void* out_file_;

  DISALLOW_COPY_AND_ASSIGN(PerfCodeObserver);
};

class PprofCodeObserver : public CodeObserver {
 public:
  PprofCodeObserver() {
    pprof_symbol_generator_ = DebugInfo::NewGenerator();
  }

  ~PprofCodeObserver() {
    Dart_FileOpenCallback file_open = Isolate::file_open_callback();
    if (file_open == NULL) {
      return;
    }
    Dart_FileCloseCallback file_close = Isolate::file_close_callback();
    if (file_close == NULL) {
      return;
    }
    Dart_FileWriteCallback file_write = Isolate::file_write_callback();
    if (file_write == NULL) {
      return;
    }
    if (FLAG_generate_pprof_symbols == NULL) {
      return;
    }
    const char* filename = FLAG_generate_pprof_symbols;
    void* out_file = (*file_open)(filename);
    ASSERT(out_file != NULL);
    DebugInfo::ByteBuffer* debug_region = new DebugInfo::ByteBuffer();
    ASSERT(debug_region != NULL);
    pprof_symbol_generator_->WriteToMemory(debug_region);
    int buffer_size = debug_region->size();
    void* buffer = debug_region->data();
    delete debug_region;
    if (buffer_size > 0) {
      ASSERT(buffer != NULL);
      (*file_write)(buffer, buffer_size, out_file);
    }
    (*file_close)(out_file);
    DebugInfo::UnregisterAllSections();
  }

  virtual bool IsActive() const {
    return FLAG_generate_pprof_symbols != NULL;
  }

  virtual void Notify(const char* name,
                      uword base,
                      uword prologue_offset,
                      uword size,
                      bool optimized) {
    ASSERT(pprof_symbol_generator_ != NULL);
    pprof_symbol_generator_->AddCode(base, size);
    pprof_symbol_generator_->AddCodeRegion(name, base, size);
  }

 private:
  DebugInfo* pprof_symbol_generator_;

  DISALLOW_COPY_AND_ASSIGN(PprofCodeObserver);
};

class GdbCodeObserver : public CodeObserver {
 public:
  GdbCodeObserver() { }

  virtual bool IsActive() const {
    return FLAG_generate_gdb_symbols;
  }

  virtual void Notify(const char* name,
                      uword base,
                      uword prologue_offset,
                      uword size,
                      bool optimized) {
    if (prologue_offset > 0) {
      // In order to ensure that gdb sees the first instruction of a function
      // as the prologue sequence we register two symbols for the cases when
      // the prologue sequence is not the first instruction:
      // <name>_entry is used for code preceding the prologue sequence.
      // <name> for rest of the code (first instruction is prologue sequence).
      const char* kFormat = "%s_%s";
      intptr_t len = OS::SNPrint(NULL, 0, kFormat, name, "entry");
      char* pname = Isolate::Current()->current_zone()->Alloc<char>(len + 1);
      OS::SNPrint(pname, (len + 1), kFormat, name, "entry");
      DebugInfo::RegisterSection(pname, base, size);
      DebugInfo::RegisterSection(name,
                                 (base + prologue_offset),
                                 (size - prologue_offset));
    } else {
      DebugInfo::RegisterSection(name, base, size);
    }
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(GdbCodeObserver);
};

static bool LocalTime(int64_t seconds_since_epoch, tm* tm_result) {
  time_t seconds = static_cast<time_t>(seconds_since_epoch);
  if (seconds != seconds_since_epoch) return false;
  struct tm* error_code = localtime_r(&seconds, tm_result);
  return error_code != NULL;
}

const char* OS::GetTimeZoneName(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // If unsuccessful, return an empty string like V8 does.
  return (succeeded && (decomposed.tm_zone != NULL)) ? decomposed.tm_zone : "";
}

int OS::GetTimeZoneOffsetInSeconds(int64_t seconds_since_epoch) {
  tm decomposed;
  bool succeeded = LocalTime(seconds_since_epoch, &decomposed);
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // If unsuccessful, return zero like V8 does.
  return succeeded ? static_cast<int>(decomposed.tm_gmtoff) : 0;
}

int OS::GetLocalTimeZoneAdjustmentInSeconds() {
  // TODO(floitsch): avoid excessive calls to tzset?
  tzset();
  // Even if the offset was 24 hours it would still easily fit into 32 bits.
  // Note that Unix and Dart disagree on the sign.
  return static_cast<int>(-timezone);
}

int64_t OS::GetCurrentTimeMillis() {
  return GetCurrentTimeMicros() / 1000;
}

int64_t OS::GetCurrentTimeMicros() {
  // gettimeofday has microsecond resolution.
  struct timeval tv;
  if (gettimeofday(&tv, NULL) < 0) {
    UNREACHABLE();
    return 0;
  }
  return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec;
}

void* OS::AlignedAllocate(intptr_t size, intptr_t alignment) {
  const int kMinimumAlignment = 16;
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  void* p = memalign(alignment, size);
  if (p == NULL) {
    UNREACHABLE();
  }
  return p;
}

void OS::AlignedFree(void* ptr) {
  free(ptr);
}

// TODO(5411554):  May need to hoist these architecture dependent code
// into a architecture specific file e.g: os_ia32_linux.cc
word OS::ActivationFrameAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 8;
#else
#error Unsupported architecture.
#endif
  word alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default stack alignment for
  // testing purposes.
  // Flags::DebugIsInt("stackalign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  return alignment;
}

word OS::PreferredCodeAlignment() {
#if defined(TARGET_ARCH_IA32) || defined(TARGET_ARCH_X64)
  const int kMinimumAlignment = 16;
#elif defined(TARGET_ARCH_ARM)
  const int kMinimumAlignment = 16;
#else
#error Unsupported architecture.
#endif
  word alignment = kMinimumAlignment;
  // TODO(5411554): Allow overriding default code alignment for
  // testing purposes.
  // Flags::DebugIsInt("codealign", &alignment);
  ASSERT(Utils::IsPowerOfTwo(alignment));
  ASSERT(alignment >= kMinimumAlignment);
  ASSERT(alignment <= OS::kMaxPreferredCodeAlignment);
  return alignment;
}

uword OS::GetStackSizeLimit() {
  struct rlimit stack_limit;
  int retval = getrlimit(RLIMIT_STACK, &stack_limit);
  ASSERT(retval == 0);
  if (stack_limit.rlim_cur > INT_MAX) {
    retval = INT_MAX;
  } else {
    retval = stack_limit.rlim_cur;
  }
  return retval;
}

int OS::NumberOfAvailableProcessors() {
  return sysconf(_SC_NPROCESSORS_ONLN);
}

void OS::Sleep(int64_t millis) {
  // TODO(5411554):  For now just use usleep we may have to revisit this.
  usleep(millis * 1000);
}

void OS::Print(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stdout, format, args);
  va_end(args);
}

void OS::VFPrint(FILE* stream, const char* format, va_list args) {
  vfprintf(stream, format, args);
  fflush(stream);
}

int OS::SNPrint(char* str, size_t size, const char* format, ...) {
  va_list args;
  va_start(args, format);
  int retval = VSNPrint(str, size, format, args);
  va_end(args);
  return retval;
}

int OS::VSNPrint(char* str, size_t size, const char* format, va_list args) {
  int retval = vsnprintf(str, size, format, args);
  if (retval < 0) {
    FATAL1("Fatal error in OS::VSNPrint with format '%s'", format);
  }
  return retval;
}

bool OS::StringToInt64(const char* str, int64_t* value) {
  ASSERT(str != NULL && strlen(str) > 0 && value != NULL);
  int32_t base = 10;
  char* endptr;
  int i = 0;
  if (str[0] == '-') {
    i = 1;
  }
  if ((str[i] == '0') &&
      (str[i + 1] == 'x' || str[i + 1] == 'X') &&
      (str[i + 2] != '\0')) {
    base = 16;
  }
  errno = 0;
  *value = strtoll(str, &endptr, base);
  return ((errno == 0) && (endptr != str) && (*endptr == 0));
}

void OS::RegisterCodeObservers() {
  if (FLAG_generate_perf_events_symbols) {
    CodeObservers::Register(new PerfCodeObserver);
  }
  if (FLAG_generate_gdb_symbols) {
    CodeObservers::Register(new GdbCodeObserver);
  }
  if (FLAG_generate_pprof_symbols != NULL) {
    CodeObservers::Register(new PprofCodeObserver);
  }
#if defined(DART_VTUNE_SUPPORT)
  Register(new VTuneCodeObserver);
#endif
}

void OS::PrintErr(const char* format, ...) {
  va_list args;
  va_start(args, format);
  VFPrint(stderr, format, args);
  va_end(args);
}

void OS::InitOnce() {
  // TODO(5411554): For now we check that initonce is called only once,
  // Once there is more formal mechanism to call InitOnce we can move
  // this check there.
  static bool init_once_called = false;
  ASSERT(init_once_called == false);
  init_once_called = true;
}

void OS::Shutdown() {
}

void OS::Abort() {
  abort();
}

void OS::Exit(int code) {
  exit(code);
}

}  // namespace dart
<|endoftext|>


<commit_before>#include "plotmagnifier.h"
#include <qwt_plot.h>
#include <QDebug>
#include <limits>
#include <QWheelEvent>
#include <QApplication>

PlotMagnifier::PlotMagnifier( QWidget *canvas) : QwtPlotMagnifier(canvas)
{
    _x_pressed = false;
    _y_pressed = false;
    for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
    {
        _lower_bounds[axisId] = -std::numeric_limits<double>::max();
        _upper_bounds[axisId] =  std::numeric_limits<double>::max();
    }
}

PlotMagnifier::~PlotMagnifier() {}

void PlotMagnifier::setAxisLimits(int axis, double lower, double upper)
{
    if ( axis >= 0 && axis < QwtPlot::axisCnt )
    {
        _lower_bounds[axis] = lower;
        _upper_bounds[axis] = upper;
    }
}

void PlotMagnifier::rescale( double factor )
{
    factor = qAbs( factor );

    QwtPlot* plt = plot();
    if ( plt == NULL || factor == 1.0 ){
        return;
    }

    bool doReplot = false;

    const bool autoReplot = plt->autoReplot();
    plt->setAutoReplot( false );

    const int axis_list[2] = {QwtPlot::xBottom, QwtPlot::yLeft};
    QRectF new_rect;

    for ( int i = 0; i <2; i++ )
    {
        double temp_factor = factor;
        if( i==1 && _x_pressed)
        {
            temp_factor = 1.0;
        }
        if( i==0 && _y_pressed)
        {
            temp_factor = 1.0;
        }

        int axisId = axis_list[i];

        if ( isAxisEnabled( axisId ) )
        {
            const QwtScaleMap scaleMap = plt->canvasMap( axisId );

            double v1 = scaleMap.s1();
            double v2 = scaleMap.s2();
            double center = _mouse_position.x();

            if( axisId == QwtPlot::yLeft){
                center = _mouse_position.y();
            }

            if ( scaleMap.transformation() )
            {
                // the coordinate system of the paint device is always linear
                v1 = scaleMap.transform( v1 ); // scaleMap.p1()
                v2 = scaleMap.transform( v2 ); // scaleMap.p2()
            }

            const double width = ( v2 - v1 );
            const double ratio = (v2-center)/ (width);

            v1 = center - width*temp_factor*(1-ratio);
            v2 = center + width*temp_factor*(ratio);

            if( v1 > v2 ) std::swap( v1, v2 );

            if ( scaleMap.transformation() )
            {
                v1 = scaleMap.invTransform( v1 );
                v2 = scaleMap.invTransform( v2 );
            }

            if( v1 < _lower_bounds[axisId]) v1 = _lower_bounds[axisId];
            if( v2 > _upper_bounds[axisId]) v2 = _upper_bounds[axisId];

            plt->setAxisScale( axisId, v1, v2 );

            if( axisId == QwtPlot::xBottom)
            {
                new_rect.setLeft(  v1 );
                new_rect.setRight( v2 );
            }
            else{
                new_rect.setBottom( v1 );
                new_rect.setTop( v2 );
            }

            doReplot = true;
        }
    }

    plt->setAutoReplot( autoReplot );

    if ( doReplot ){
        emit rescaled( new_rect );
    }
}

QPointF PlotMagnifier::invTransform(QPoint pos)
{
    QwtScaleMap xMap = plot()->canvasMap( QwtPlot::xBottom );
    QwtScaleMap yMap = plot()->canvasMap( QwtPlot::yLeft );
    return QPointF ( xMap.invTransform( pos.x() ), yMap.invTransform( pos.y() ) );
}

void PlotMagnifier::widgetWheelEvent(QWheelEvent *event)
{
    _mouse_position = invTransform(event->pos());
    QwtPlotMagnifier::widgetWheelEvent(event);
}

void PlotMagnifier::widgetMousePressEvent(QMouseEvent *event)
{
    _mouse_position = invTransform(event->pos());
    QwtPlotMagnifier::widgetMousePressEvent(event);
}

bool PlotMagnifier::eventFilter(QObject *obj, QEvent *event)
{
    if( event->type() == QEvent::Enter || event->type() == QEvent::Leave)
    {
        _x_pressed = false;
        _y_pressed = false;
    }
    else if( event->type() == QEvent::KeyPress)
    {
        auto key_event = static_cast<QKeyEvent*>(event);
        if( key_event->key() == Qt::Key_X )
        {
            _x_pressed = true;
        }
        else if( key_event->key() == Qt::Key_Y )
        {
            _y_pressed = true;
        }
        //qDebug() << "p "<< _x_pressed << " " << _y_pressed;
    }
    else if( event->type() == QEvent::KeyRelease)
    {
        auto key_event = static_cast<QKeyEvent*>(event);
        if( key_event->key() == Qt::Key_X )
        {
            _x_pressed = false;
        }
        else if( key_event->key() == Qt::Key_Y )
        {
            _y_pressed = false;
        }
      //  qDebug() << "R "<< _x_pressed << " " << _y_pressed;
    }

    return QwtPlotMagnifier::eventFilter(obj, event);
}
<commit_msg>Inverted mouse wheel zoom #153<commit_after>#include "plotmagnifier.h"
#include <qwt_plot.h>
#include <QDebug>
#include <limits>
#include <QWheelEvent>
#include <QApplication>

PlotMagnifier::PlotMagnifier( QWidget *canvas) : QwtPlotMagnifier(canvas)
{
    _x_pressed = false;
    _y_pressed = false;
    for ( int axisId = 0; axisId < QwtPlot::axisCnt; axisId++ )
    {
        _lower_bounds[axisId] = -std::numeric_limits<double>::max();
        _upper_bounds[axisId] =  std::numeric_limits<double>::max();
    }
}

PlotMagnifier::~PlotMagnifier() {}

void PlotMagnifier::setAxisLimits(int axis, double lower, double upper)
{
    if ( axis >= 0 && axis < QwtPlot::axisCnt )
    {
        _lower_bounds[axis] = lower;
        _upper_bounds[axis] = upper;
    }
}

void PlotMagnifier::rescale( double factor )
{
    factor = qAbs( 1.0/factor );

    QwtPlot* plt = plot();
    if ( plt == nullptr || factor == 1.0 ){
        return;
    }

    bool doReplot = false;

    const bool autoReplot = plt->autoReplot();
    plt->setAutoReplot( false );

    const int axis_list[2] = {QwtPlot::xBottom, QwtPlot::yLeft};
    QRectF new_rect;

    for ( int i = 0; i <2; i++ )
    {
        double temp_factor = factor;
        if( i==1 && _x_pressed)
        {
            temp_factor = 1.0;
        }
        if( i==0 && _y_pressed)
        {
            temp_factor = 1.0;
        }

        int axisId = axis_list[i];

        if ( isAxisEnabled( axisId ) )
        {
            const QwtScaleMap scaleMap = plt->canvasMap( axisId );

            double v1 = scaleMap.s1();
            double v2 = scaleMap.s2();
            double center = _mouse_position.x();

            if( axisId == QwtPlot::yLeft){
                center = _mouse_position.y();
            }

            if ( scaleMap.transformation() )
            {
                // the coordinate system of the paint device is always linear
                v1 = scaleMap.transform( v1 ); // scaleMap.p1()
                v2 = scaleMap.transform( v2 ); // scaleMap.p2()
            }

            const double width = ( v2 - v1 );
            const double ratio = (v2-center)/ (width);

            v1 = center - width*temp_factor*(1-ratio);
            v2 = center + width*temp_factor*(ratio);

            if( v1 > v2 ) std::swap( v1, v2 );

            if ( scaleMap.transformation() )
            {
                v1 = scaleMap.invTransform( v1 );
                v2 = scaleMap.invTransform( v2 );
            }

            if( v1 < _lower_bounds[axisId]) v1 = _lower_bounds[axisId];
            if( v2 > _upper_bounds[axisId]) v2 = _upper_bounds[axisId];

            plt->setAxisScale( axisId, v1, v2 );

            if( axisId == QwtPlot::xBottom)
            {
                new_rect.setLeft(  v1 );
                new_rect.setRight( v2 );
            }
            else{
                new_rect.setBottom( v1 );
                new_rect.setTop( v2 );
            }

            doReplot = true;
        }
    }

    plt->setAutoReplot( autoReplot );

    if ( doReplot ){
        emit rescaled( new_rect );
    }
}

QPointF PlotMagnifier::invTransform(QPoint pos)
{
    QwtScaleMap xMap = plot()->canvasMap( QwtPlot::xBottom );
    QwtScaleMap yMap = plot()->canvasMap( QwtPlot::yLeft );
    return QPointF ( xMap.invTransform( pos.x() ), yMap.invTransform( pos.y() ) );
}

void PlotMagnifier::widgetWheelEvent(QWheelEvent *event)
{
    _mouse_position = invTransform(event->pos());
    QwtPlotMagnifier::widgetWheelEvent(event);
}

void PlotMagnifier::widgetMousePressEvent(QMouseEvent *event)
{
    _mouse_position = invTransform(event->pos());
    QwtPlotMagnifier::widgetMousePressEvent(event);
}

bool PlotMagnifier::eventFilter(QObject *obj, QEvent *event)
{
    if( event->type() == QEvent::Enter || event->type() == QEvent::Leave)
    {
        _x_pressed = false;
        _y_pressed = false;
    }
    else if( event->type() == QEvent::KeyPress)
    {
        auto key_event = static_cast<QKeyEvent*>(event);
        if( key_event->key() == Qt::Key_X )
        {
            _x_pressed = true;
        }
        else if( key_event->key() == Qt::Key_Y )
        {
            _y_pressed = true;
        }
        //qDebug() << "p "<< _x_pressed << " " << _y_pressed;
    }
    else if( event->type() == QEvent::KeyRelease)
    {
        auto key_event = static_cast<QKeyEvent*>(event);
        if( key_event->key() == Qt::Key_X )
        {
            _x_pressed = false;
        }
        else if( key_event->key() == Qt::Key_Y )
        {
            _y_pressed = false;
        }
      //  qDebug() << "R "<< _x_pressed << " " << _y_pressed;
    }

    return QwtPlotMagnifier::eventFilter(obj, event);
}
<|endoftext|>


<commit_before>/** @file

  A brief file description

  @section license License

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

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

#include "balancer.h"
#include <ts/remap.h>
#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <stdlib.h>
#include <iterator>

// Using ink_inet API is cheating, but I was too lazy to write new IPv6 address parsing routines ;)
#include "ts/ink_inet.h"

// The policy type is the first comma-separated token.
static BalancerInstance *
MakeBalancerInstance(const char *opt)
{
  const char *end = strchr(opt, ',');
  size_t len      = end ? std::distance(opt, end) : strlen(opt);

  if (len == lengthof("hash") && strncmp(opt, "hash", len) == 0) {
    return MakeHashBalancer(end ? end + 1 : NULL);
  } else if (len == lengthof("roundrobin") && strncmp(opt, "roundrobin", len) == 0) {
    return MakeRoundRobinBalancer(end ? end + 1 : NULL);
  } else {
    TSError("[balancer] Invalid balancing policy '%.*s'", (int)len, opt);
    return NULL;
  }
}

static BalancerTarget
MakeBalancerTarget(const char *strval)
{
  BalancerTarget target = BalancerTarget();

  union {
    struct sockaddr_storage storage;
    struct sockaddr sa;
  } address;

  memset(&address, 0, sizeof(address));

  // First, check whether we have an address literal.
  if (ats_ip_pton(strval, &address.sa) == 0) {
    char namebuf[INET6_ADDRSTRLEN];

    target.port = ats_ip_port_host_order(&address.sa);
    target.name = ats_ip_ntop(&address.sa, namebuf, sizeof(namebuf));
  } else {
    const char *colon = strrchr(strval, ':');

    if (colon) {
      size_t len = std::distance(strval, colon);

      target.port = strtol(colon + 1, NULL, 10);
      target.name = std::string(strval, len);
    } else {
      target.port = 0;
      target.name = strval;
    }
  }

  if (target.port > UINT16_MAX) {
    TSError("[balancer] Ignoring invalid port number for target '%s'", strval);
    target.port = 0;
  }

  return target;
}

TSReturnCode
TSRemapInit(TSRemapInterface * /* api */, char * /* errbuf */, int /* bufsz */)
{
  return TS_SUCCESS;
}

///////////////////////////////////////////////////////////////////////////////
// One instance per remap.config invocation.
//
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **instance, char *errbuf, int errbuf_size)
{
  static const struct option longopt[] = {
    {const_cast<char *>("policy"), required_argument, 0, 'p'}, {0, 0, 0, 0},
  };

  BalancerInstance *balancer = NULL;

  // The first two arguments are the "from" and "to" URL string. We need to
  // skip them, but we also require that there be an option to masquerade as
  // argv[0], so we increment the argument indexes by 1 rather than by 2.
  argc--;
  argv++;

  for (;;) {
    int opt;

    opt = getopt_long(argc, (char *const *)argv, "", longopt, NULL);
    switch (opt) {
    case 'p':
      balancer = MakeBalancerInstance(optarg);
      break;
    case -1:
      break;
    default:
      snprintf(errbuf, errbuf_size, "invalid balancer option '%d'", opt);
      delete balancer;
      return TS_ERROR;
    }

    if (opt == -1) {
      break;
    }
  }

  if (!balancer) {
    strncpy(errbuf, "missing balancer policy", errbuf_size);
    return TS_ERROR;
  }

  // Pick up the remaining options as balance targets.
  for (int i = optind; i < argc; ++i) {
    BalancerTarget target = MakeBalancerTarget(argv[i]);

    balancer->push_target(target);
    if (target.port) {
      TSDebug("balancer", "added target -> %s:%u", target.name.c_str(), target.port);
    } else {
      TSDebug("balancer", "added target -> %s", target.name.c_str());
    }
  }

  *instance = balancer;
  return TS_SUCCESS;
}

void
TSRemapDeleteInstance(void *instance)
{
  delete (BalancerInstance *)instance;
}

TSRemapStatus
TSRemapDoRemap(void *instance, TSHttpTxn txn, TSRemapRequestInfo *rri)
{
  BalancerInstance *balancer   = (BalancerInstance *)instance;
  const BalancerTarget &target = balancer->balance(txn, rri);

  if (TSIsDebugTagSet("balancer")) {
    char *url;
    int len;

    url = TSHttpTxnEffectiveUrlStringGet(txn, &len);
    if (target.port) {
      TSDebug("balancer", "%s:%u <- %.*s", target.name.c_str(), target.port, len, url);
    } else {
      TSDebug("balancer", "%s <- %.*s", target.name.c_str(), len, url);
    }

    TSfree(url);
  }

  TSUrlHostSet(rri->requestBufp, rri->requestUrl, target.name.data(), target.name.size());

  if (target.port) {
    TSUrlPortSet(rri->requestBufp, rri->requestUrl, target.port);
  }

  return TSREMAP_DID_REMAP;
}
<commit_msg>TS-4582: Do not allow multiple --policy arguments<commit_after>/** @file

  A brief file description

  @section license License

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

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

#include "balancer.h"
#include <ts/remap.h>
#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <stdlib.h>
#include <iterator>

// Using ink_inet API is cheating, but I was too lazy to write new IPv6 address parsing routines ;)
#include "ts/ink_inet.h"

// The policy type is the first comma-separated token.
static BalancerInstance *
MakeBalancerInstance(const char *opt)
{
  const char *end = strchr(opt, ',');
  size_t len      = end ? std::distance(opt, end) : strlen(opt);

  if (len == lengthof("hash") && strncmp(opt, "hash", len) == 0) {
    return MakeHashBalancer(end ? end + 1 : NULL);
  } else if (len == lengthof("roundrobin") && strncmp(opt, "roundrobin", len) == 0) {
    return MakeRoundRobinBalancer(end ? end + 1 : NULL);
  } else {
    TSError("[balancer] Invalid balancing policy '%.*s'", (int)len, opt);
    return NULL;
  }
}

static BalancerTarget
MakeBalancerTarget(const char *strval)
{
  BalancerTarget target = BalancerTarget();

  union {
    struct sockaddr_storage storage;
    struct sockaddr sa;
  } address;

  memset(&address, 0, sizeof(address));

  // First, check whether we have an address literal.
  if (ats_ip_pton(strval, &address.sa) == 0) {
    char namebuf[INET6_ADDRSTRLEN];

    target.port = ats_ip_port_host_order(&address.sa);
    target.name = ats_ip_ntop(&address.sa, namebuf, sizeof(namebuf));
  } else {
    const char *colon = strrchr(strval, ':');

    if (colon) {
      size_t len = std::distance(strval, colon);

      target.port = strtol(colon + 1, NULL, 10);
      target.name = std::string(strval, len);
    } else {
      target.port = 0;
      target.name = strval;
    }
  }

  if (target.port > UINT16_MAX) {
    TSError("[balancer] Ignoring invalid port number for target '%s'", strval);
    target.port = 0;
  }

  return target;
}

TSReturnCode
TSRemapInit(TSRemapInterface * /* api */, char * /* errbuf */, int /* bufsz */)
{
  return TS_SUCCESS;
}

///////////////////////////////////////////////////////////////////////////////
// One instance per remap.config invocation.
//
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **instance, char *errbuf, int errbuf_size)
{
  static const struct option longopt[] = {
    {const_cast<char *>("policy"), required_argument, 0, 'p'}, {0, 0, 0, 0},
  };

  BalancerInstance *balancer = NULL;

  // The first two arguments are the "from" and "to" URL string. We need to
  // skip them, but we also require that there be an option to masquerade as
  // argv[0], so we increment the argument indexes by 1 rather than by 2.
  argc--;
  argv++;

  for (;;) {
    int opt;

    opt = getopt_long(argc, (char *const *)argv, "", longopt, NULL);
    switch (opt) {
    case 'p':
      if (!balancer) {
        balancer = MakeBalancerInstance(optarg);
      } else {
        TSError("[balancer] Duplicate --policy options, ignored %s", optarg);
      }
      break;
    case -1:
      break;
    default:
      snprintf(errbuf, errbuf_size, "invalid balancer option '%d'", opt);
      delete balancer;
      return TS_ERROR;
    }

    if (opt == -1) {
      break;
    }
  }

  if (!balancer) {
    strncpy(errbuf, "missing balancer policy", errbuf_size);
    return TS_ERROR;
  }

  // Pick up the remaining options as balance targets.
  for (int i = optind; i < argc; ++i) {
    BalancerTarget target = MakeBalancerTarget(argv[i]);

    balancer->push_target(target);
    if (target.port) {
      TSDebug("balancer", "added target -> %s:%u", target.name.c_str(), target.port);
    } else {
      TSDebug("balancer", "added target -> %s", target.name.c_str());
    }
  }

  *instance = balancer;
  return TS_SUCCESS;
}

void
TSRemapDeleteInstance(void *instance)
{
  delete (BalancerInstance *)instance;
}

TSRemapStatus
TSRemapDoRemap(void *instance, TSHttpTxn txn, TSRemapRequestInfo *rri)
{
  BalancerInstance *balancer   = (BalancerInstance *)instance;
  const BalancerTarget &target = balancer->balance(txn, rri);

  if (TSIsDebugTagSet("balancer")) {
    char *url;
    int len;

    url = TSHttpTxnEffectiveUrlStringGet(txn, &len);
    if (target.port) {
      TSDebug("balancer", "%s:%u <- %.*s", target.name.c_str(), target.port, len, url);
    } else {
      TSDebug("balancer", "%s <- %.*s", target.name.c_str(), len, url);
    }

    TSfree(url);
  }

  TSUrlHostSet(rri->requestBufp, rri->requestUrl, target.name.data(), target.name.size());

  if (target.port) {
    TSUrlPortSet(rri->requestBufp, rri->requestUrl, target.port);
  }

  return TSREMAP_DID_REMAP;
}
<|endoftext|>