<commit_before>/*************************************************************************
 *
 *  $RCSfile: wmfwr.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2003-06-06 10:47:51 $
 *
 *  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 _WMFWR_HXX
#define _WMFWR_HXX

#include <tools/bigint.hxx>
#include <tools/debug.hxx>
#include <vcl/metaact.hxx>
#include <vcl/graph.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/virdev.hxx>
#include "fltcall.hxx"

// -----------------------------------------------------------------------------

#define MAXOBJECTHANDLES 16

// -----------------------------------------------------------------------------

struct WMFWriterAttrStackMember
{
    struct WMFWriterAttrStackMember * pSucc;
    Color aLineColor;
    Color aFillColor;
    Color aTextColor;
    LineInfo aLineInfo;
    TextAlign eTextAlign;
    RasterOp eRasterOp;
    Font aFont;
    MapMode aMapMode;
    Region aClipRegion;
    sal_uInt16 nFlags;
};

// -------------
// - WMFWriter -
// -------------

class StarSymbolToMSMultiFont;
class WMFWriter
{
private:

    BOOL            bStatus;

    PFilterCallback pCallback;
    void*           pCallerData;
    ULONG           nLastPercent; // Mit welcher Zahl pCallback zuletzt aufgerufen wurde.

    SvStream*       pWMF;
    VirtualDevice*  pVirDev;
    StarSymbolToMSMultiFont *pConvert;
    MapMode         aTargetMapMode;
    Size            aTargetSize;
    USHORT          nTargetDivisor;

    ULONG nMetafileHeaderPos;
    ULONG nMaxRecordSize; // in Worten
    ULONG nActRecordPos;

    // Aktuelle Attribute im Quell-Metafile:
    Color     aSrcLineColor;
    Color     aSrcFillColor;
    Color     aSrcTextColor;
    LineInfo  aSrcLineInfo;
    RasterOp  eSrcRasterOp;
    FontAlign eSrcTextAlign;
    Font      aSrcFont;
    MapMode   aSrcMapMode;
    BOOL      bSrcIsClipping;
    Region    aSrcClipRegion;
    WMFWriterAttrStackMember * pAttrStack;

    // Aktuelle Attribute im Ziel-Metafile:
    Color     aDstLineColor;
    Color     aDstFillColor;
    Color     aDstTextColor;
    LineInfo  aDstLineInfo;
    RasterOp  eDstROP2;
    FontAlign eDstTextAlign;
    Font      aDstFont;

    BOOL      bDstIsClipping; // ???: derzeit unberuecksichtigt
    Region    aDstClipRegion; // ???: derzeit unberuecksichtigt
    BOOL bHandleAllocated[MAXOBJECTHANDLES];             // Welche Handles vergeben sind
    USHORT nDstPenHandle,nDstFontHandle,nDstBrushHandle; // Welche Handles die jeweiligen
                                                         // Selected-Objects besitzen
                                                         // 0xffff = keines:

    // Damit nicht bei jeder Operation alle Attribute verglichen werden muessen:

    ULONG nNumberOfActions; // Anzahl der Actions im GDIMetafile
    ULONG nNumberOfBitmaps; // Anzahl der Bitmaps
    ULONG nWrittenActions;  // Anzahl der bereits verarbeiteten Actions beim Schreiben der Orders
    ULONG nWrittenBitmaps;  // Anzahl der bereits geschriebenen Bitmaps
    ULONG nActBitmapPercent; // Wieviel Prozent die naechste Bitmap schon geschrieben ist.

    void MayCallback();
        // Berechnet anhand der obigen 5 Parameter eine Prozentzahl
        // und macht dann ggf. einen Callback. Setzt bStatus auf FALSE wenn User abbrechen
        // moechte.

    void CountActionsAndBitmaps(const GDIMetaFile & rMTF);
        // Zaehlt die Bitmaps und Actions (nNumberOfActions und nNumberOfBitmaps muessen
        // zu Anfang auf 0 gesetzt werden, weil diese Methode rekursiv ist)

    void WritePointXY(const Point & rPoint);
    void WritePointYX(const Point & rPoint);
    sal_Int32 ScaleWidth( sal_Int32 nDX );
    void WriteSize(const Size & rSize);
    void WriteHeightWidth(const Size & rSize);
    void WriteRectangle(const Rectangle & rRect);
    void WriteColor(const Color & rColor);

    void WriteRecordHeader(ULONG nSizeWords, USHORT nType);
        // nSizeWords ist die Groesse des gesammten Records in Anzahl Worte.
        // Wenn nSizeWords unbekannt ist, dann 0 einsetzen (siehe UpdateRecordHeader()).

    void UpdateRecordHeader();
        // berichtig die Groesse des Records nach dem Schreiben der Parameter, wenn
        // nSizeWords bei Aufruf von WriteRecordHeader(..) unbekannt war.
        // fuegt ggf. noch ein BYTE 0 ein damit Anzahl Bytes immer gerade.

    void WMFRecord_Arc(const Rectangle & rRect, const Point & rStartPt, const Point & rEndPt);
    void WMFRecord_Chord(const Rectangle & rRect, const Point & rStartPt, const Point & rEndPt);
    void WMFRecord_CreateBrushIndirect(const Color& rColor);
    void WMFRecord_CreateFontIndirect(const Font & rFont);
    void WMFRecord_CreatePenIndirect(const Color& rColor, const LineInfo& rLineInfo );
    void WMFRecord_DeleteObject(USHORT nObjectHandle);
    void WMFRecord_Ellipse(const Rectangle & rRect);
    void WMFRecord_Escape( sal_uInt32 nEsc, sal_uInt32 nLen, const sal_Int8* pData );
    sal_Bool WMFRecord_Escape_Unicode( const Point& rPoint, const String& rStr, const long * pDXAry );
    void WMFRecord_ExtTextOut(const Point & rPoint, const String & rString, const long * pDXAry);

    void TrueExtTextOut(const Point & rPoint, const String & rString,
        const ByteString & rByteString, const long * pDXAry);
    void TrueTextOut(const Point & rPoint, const ByteString& rString);
    void WMFRecord_LineTo(const Point & rPoint);
    void WMFRecord_MoveTo(const Point & rPoint);
    void WMFRecord_Pie(const Rectangle & rRect, const Point & rStartPt, const Point & rEndPt);
    void WMFRecord_Polygon(const Polygon & rPoly);
    void WMFRecord_PolyLine(const Polygon & rPoly);
    void WMFRecord_PolyPolygon(const PolyPolygon & rPolyPoly);
    void WMFRecord_Rectangle(const Rectangle & rRect);
    void WMFRecord_RestoreDC();
    void WMFRecord_RoundRect(const Rectangle & rRect, long nHorzRound, long nVertRound);
    void WMFRecord_SaveDC();
    void WMFRecord_SelectObject(USHORT nObjectHandle);
    void WMFRecord_SetBkColor(const Color & rColor);
    void WMFRecord_SetBkMode(BOOL bTransparent);
    void WMFRecord_SetStretchBltMode();
    void WMFRecord_SetPixel(const Point & rPoint, const Color & rColor);
    void WMFRecord_SetROP2(RasterOp eROP);
    void WMFRecord_SetTextAlign(FontAlign eFontAlign);
    void WMFRecord_SetTextColor(const Color & rColor);
    void WMFRecord_SetWindowExt(const Size & rSize);
    void WMFRecord_SetWindowOrg(const Point & rPoint);
    void WMFRecord_StretchDIB(const Point & rPoint, const Size & rSize, const Bitmap & rBitmap, ULONG nROP = 0UL );
    void WMFRecord_TextOut(const Point & rPoint, const String & rString);
    void WMFRecord_EndOfFile();
    void WMFRecord_IntersectClipRect( const Rectangle& rRect);

    USHORT AllocHandle();
    void FreeHandle(USHORT nObjectHandle);
    void CreateSelectDeletePen( const Color& rColor, const LineInfo& rLineInfo );
    void CreateSelectDeleteFont(const Font & rFont);
    void CreateSelectDeleteBrush(const Color& rColor);

    void SetLineAndFillAttr();
    void SetAllAttr();

    void WriteRecords(const GDIMetaFile & rMTF);

    void WriteHeader(const GDIMetaFile & rMTF, BOOL bPlaceable);
    void UpdateHeader();

    USHORT CalcSaveTargetMapMode(MapMode& rMapMode, const Size& rPrefSize);

public:

    WMFWriter() {}

    BOOL WriteWMF(const GDIMetaFile & rMTF, SvStream & rTargetStream,
                  PFilterCallback pcallback, void * pcallerdata,
                  BOOL bPlaceable=TRUE);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.840); FILE MERGED 2005/09/05 14:53:10 rt 1.7.840.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: wmfwr.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:47:44 $
 *
 *  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 _WMFWR_HXX
#define _WMFWR_HXX

#include <tools/bigint.hxx>
#include <tools/debug.hxx>
#include <vcl/metaact.hxx>
#include <vcl/graph.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/virdev.hxx>
#include "fltcall.hxx"

// -----------------------------------------------------------------------------

#define MAXOBJECTHANDLES 16

// -----------------------------------------------------------------------------

struct WMFWriterAttrStackMember
{
    struct WMFWriterAttrStackMember * pSucc;
    Color aLineColor;
    Color aFillColor;
    Color aTextColor;
    LineInfo aLineInfo;
    TextAlign eTextAlign;
    RasterOp eRasterOp;
    Font aFont;
    MapMode aMapMode;
    Region aClipRegion;
    sal_uInt16 nFlags;
};

// -------------
// - WMFWriter -
// -------------

class StarSymbolToMSMultiFont;
class WMFWriter
{
private:

    BOOL            bStatus;

    PFilterCallback pCallback;
    void*           pCallerData;
    ULONG           nLastPercent; // Mit welcher Zahl pCallback zuletzt aufgerufen wurde.

    SvStream*       pWMF;
    VirtualDevice*  pVirDev;
    StarSymbolToMSMultiFont *pConvert;
    MapMode         aTargetMapMode;
    Size            aTargetSize;
    USHORT          nTargetDivisor;

    ULONG nMetafileHeaderPos;
    ULONG nMaxRecordSize; // in Worten
    ULONG nActRecordPos;

    // Aktuelle Attribute im Quell-Metafile:
    Color     aSrcLineColor;
    Color     aSrcFillColor;
    Color     aSrcTextColor;
    LineInfo  aSrcLineInfo;
    RasterOp  eSrcRasterOp;
    FontAlign eSrcTextAlign;
    Font      aSrcFont;
    MapMode   aSrcMapMode;
    BOOL      bSrcIsClipping;
    Region    aSrcClipRegion;
    WMFWriterAttrStackMember * pAttrStack;

    // Aktuelle Attribute im Ziel-Metafile:
    Color     aDstLineColor;
    Color     aDstFillColor;
    Color     aDstTextColor;
    LineInfo  aDstLineInfo;
    RasterOp  eDstROP2;
    FontAlign eDstTextAlign;
    Font      aDstFont;

    BOOL      bDstIsClipping; // ???: derzeit unberuecksichtigt
    Region    aDstClipRegion; // ???: derzeit unberuecksichtigt
    BOOL bHandleAllocated[MAXOBJECTHANDLES];             // Welche Handles vergeben sind
    USHORT nDstPenHandle,nDstFontHandle,nDstBrushHandle; // Welche Handles die jeweiligen
                                                         // Selected-Objects besitzen
                                                         // 0xffff = keines:

    // Damit nicht bei jeder Operation alle Attribute verglichen werden muessen:

    ULONG nNumberOfActions; // Anzahl der Actions im GDIMetafile
    ULONG nNumberOfBitmaps; // Anzahl der Bitmaps
    ULONG nWrittenActions;  // Anzahl der bereits verarbeiteten Actions beim Schreiben der Orders
    ULONG nWrittenBitmaps;  // Anzahl der bereits geschriebenen Bitmaps
    ULONG nActBitmapPercent; // Wieviel Prozent die naechste Bitmap schon geschrieben ist.

    void MayCallback();
        // Berechnet anhand der obigen 5 Parameter eine Prozentzahl
        // und macht dann ggf. einen Callback. Setzt bStatus auf FALSE wenn User abbrechen
        // moechte.

    void CountActionsAndBitmaps(const GDIMetaFile & rMTF);
        // Zaehlt die Bitmaps und Actions (nNumberOfActions und nNumberOfBitmaps muessen
        // zu Anfang auf 0 gesetzt werden, weil diese Methode rekursiv ist)

    void WritePointXY(const Point & rPoint);
    void WritePointYX(const Point & rPoint);
    sal_Int32 ScaleWidth( sal_Int32 nDX );
    void WriteSize(const Size & rSize);
    void WriteHeightWidth(const Size & rSize);
    void WriteRectangle(const Rectangle & rRect);
    void WriteColor(const Color & rColor);

    void WriteRecordHeader(ULONG nSizeWords, USHORT nType);
        // nSizeWords ist die Groesse des gesammten Records in Anzahl Worte.
        // Wenn nSizeWords unbekannt ist, dann 0 einsetzen (siehe UpdateRecordHeader()).

    void UpdateRecordHeader();
        // berichtig die Groesse des Records nach dem Schreiben der Parameter, wenn
        // nSizeWords bei Aufruf von WriteRecordHeader(..) unbekannt war.
        // fuegt ggf. noch ein BYTE 0 ein damit Anzahl Bytes immer gerade.

    void WMFRecord_Arc(const Rectangle & rRect, const Point & rStartPt, const Point & rEndPt);
    void WMFRecord_Chord(const Rectangle & rRect, const Point & rStartPt, const Point & rEndPt);
    void WMFRecord_CreateBrushIndirect(const Color& rColor);
    void WMFRecord_CreateFontIndirect(const Font & rFont);
    void WMFRecord_CreatePenIndirect(const Color& rColor, const LineInfo& rLineInfo );
    void WMFRecord_DeleteObject(USHORT nObjectHandle);
    void WMFRecord_Ellipse(const Rectangle & rRect);
    void WMFRecord_Escape( sal_uInt32 nEsc, sal_uInt32 nLen, const sal_Int8* pData );
    sal_Bool WMFRecord_Escape_Unicode( const Point& rPoint, const String& rStr, const long * pDXAry );
    void WMFRecord_ExtTextOut(const Point & rPoint, const String & rString, const long * pDXAry);

    void TrueExtTextOut(const Point & rPoint, const String & rString,
        const ByteString & rByteString, const long * pDXAry);
    void TrueTextOut(const Point & rPoint, const ByteString& rString);
    void WMFRecord_LineTo(const Point & rPoint);
    void WMFRecord_MoveTo(const Point & rPoint);
    void WMFRecord_Pie(const Rectangle & rRect, const Point & rStartPt, const Point & rEndPt);
    void WMFRecord_Polygon(const Polygon & rPoly);
    void WMFRecord_PolyLine(const Polygon & rPoly);
    void WMFRecord_PolyPolygon(const PolyPolygon & rPolyPoly);
    void WMFRecord_Rectangle(const Rectangle & rRect);
    void WMFRecord_RestoreDC();
    void WMFRecord_RoundRect(const Rectangle & rRect, long nHorzRound, long nVertRound);
    void WMFRecord_SaveDC();
    void WMFRecord_SelectObject(USHORT nObjectHandle);
    void WMFRecord_SetBkColor(const Color & rColor);
    void WMFRecord_SetBkMode(BOOL bTransparent);
    void WMFRecord_SetStretchBltMode();
    void WMFRecord_SetPixel(const Point & rPoint, const Color & rColor);
    void WMFRecord_SetROP2(RasterOp eROP);
    void WMFRecord_SetTextAlign(FontAlign eFontAlign);
    void WMFRecord_SetTextColor(const Color & rColor);
    void WMFRecord_SetWindowExt(const Size & rSize);
    void WMFRecord_SetWindowOrg(const Point & rPoint);
    void WMFRecord_StretchDIB(const Point & rPoint, const Size & rSize, const Bitmap & rBitmap, ULONG nROP = 0UL );
    void WMFRecord_TextOut(const Point & rPoint, const String & rString);
    void WMFRecord_EndOfFile();
    void WMFRecord_IntersectClipRect( const Rectangle& rRect);

    USHORT AllocHandle();
    void FreeHandle(USHORT nObjectHandle);
    void CreateSelectDeletePen( const Color& rColor, const LineInfo& rLineInfo );
    void CreateSelectDeleteFont(const Font & rFont);
    void CreateSelectDeleteBrush(const Color& rColor);

    void SetLineAndFillAttr();
    void SetAllAttr();

    void WriteRecords(const GDIMetaFile & rMTF);

    void WriteHeader(const GDIMetaFile & rMTF, BOOL bPlaceable);
    void UpdateHeader();

    USHORT CalcSaveTargetMapMode(MapMode& rMapMode, const Size& rPrefSize);

public:

    WMFWriter() {}

    BOOL WriteWMF(const GDIMetaFile & rMTF, SvStream & rTargetStream,
                  PFilterCallback pcallback, void * pcallerdata,
                  BOOL bPlaceable=TRUE);
};

#endif
<|endoftext|>


<commit_before><commit_msg>updated lumi ref table with pp once XeXe is over, from 280244<commit_after><|endoftext|>


<commit_before>/*
**
* BEGIN_COPYRIGHT
*
* TODO: add license
*
* END_COPYRIGHT
*/

#include "query/Operator.h"

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory>
#include <cstddef>
#include <deque>

namespace scidb
{

using namespace std;

namespace windowed_activity
{

struct WindowEntry
{
	int64_t time;
	double activityDelta;
	WindowEntry(int64_t t, double d):
		time(t),
		activityDelta(d)
	{}
};

class Window
{
private:
	int64_t const _precedingLimit;
	int64_t const _followingLimit;
	double _runningActivitySum;
	size_t _centerIdx;
	size_t _frontIdx;
	uint8_t _lastX;
	uint8_t _lastY;
	uint8_t _lastZ;
	std::deque<WindowEntry> _window;

public:
	Window(int64_t const numPreceding, int64_t const numFollowing):
		_precedingLimit(numPreceding),
		_followingLimit(numFollowing),
		_runningActivitySum(0),
		_centerIdx(0),
		_frontIdx(0),
		_lastX(0),
		_lastY(0),
		_lastZ(0)
	{}

	bool iterate(int64_t const& inputTime, uint8_t const& x, uint8_t const& y, uint8_t const& z,
			     int64_t& outputTime, double& outputScore)
	{
		double activityDelta = _window.size() == 0 ? 0 :
				sqrt(((double)x-_lastX)*((double)x-_lastX) + ((double)y-_lastY)*((double)y-_lastY) + ((double)z-_lastZ)*((double)z-_lastZ));
		_lastX = x;
		_lastY = y;
		_lastZ = z;
		_window.emplace_back(inputTime, activityDelta);
		if(_window.size() == 1) //first element evah!
		{
			return false;
		}
		else
		{
			WindowEntry center = _window[_centerIdx];
			if(inputTime - center.time <= _followingLimit)
			{
				_runningActivitySum += activityDelta;
				_frontIdx ++;
				return false;
			}
			else
			{
				outputTime = center.time;
				double timeDelta = _window[_frontIdx].time - _window[0].time;
				outputScore = timeDelta > 0 ? _runningActivitySum / (timeDelta) : 0;
				if(outputScore<0)
				{
					outputScore = 0;
				}
				_centerIdx++;
				center = _window[_centerIdx];
				while(_frontIdx+1 < _window.size() && _window[_frontIdx+1].time - center.time <= _followingLimit)
				{
					_frontIdx++;
					_runningActivitySum += _window[_frontIdx].activityDelta;
				}
				while(center.time - _window[0].time > _precedingLimit)
				{
					_runningActivitySum -= _window[0].activityDelta;
					_window.pop_front();
					_centerIdx--;
					_frontIdx--;
				}
				return true;
			}
		}
	}

	bool finalize(int64_t& outputTime, double& outputScore)
	{
		if(_window.size()==0 || _centerIdx >= _window.size())
		{
			return false;
		}
		else
		{
			WindowEntry center = _window[_centerIdx];
			outputTime = center.time;
			double timeDelta = _window[_frontIdx].time - _window[0].time;
			outputScore = timeDelta > 0 ? _runningActivitySum / (timeDelta) : 0;
			if(outputScore<0)
			{
				outputScore = 0;
			}
			_centerIdx++;
			if(_centerIdx < _window.size())
			{
				center = _window[_centerIdx];
				while(_frontIdx+1 < _window.size() && _window[_frontIdx+1].time - center.time <= _followingLimit)
				{
					_frontIdx++;
					_runningActivitySum += _window[_frontIdx].activityDelta;
				}
				while(center.time - _window[0].time > _precedingLimit)
				{
					_runningActivitySum -= _window[0].activityDelta;
					_window.pop_front();
					_centerIdx--;
					_frontIdx--;
				}
			}
			return true;
		}
	}
};

}

class PhysicalComputeActivity : public PhysicalOperator
{
public:
	PhysicalComputeActivity(string const& logicalName,
                            string const& physicalName,
                            Parameters const& parameters,
                            ArrayDesc const& schema):
        PhysicalOperator(logicalName, physicalName, parameters, schema)
    {}

    shared_ptr< Array> execute(vector< shared_ptr< Array> >& inputArrays, shared_ptr<Query> query)
    {
        Value const& precVal = ((std::shared_ptr<OperatorParamPhysicalExpression>&)_parameters[0])->getExpression()->evaluate();
        if (precVal.isNull() || precVal.getInt64() < 0)
        {
        	throw SYSTEM_EXCEPTION(SCIDB_SE_INTERNAL, SCIDB_LE_ILLEGAL_OPERATION) << "Invalid number of preceding cells";
        }
        Value const& folVal = ((std::shared_ptr<OperatorParamPhysicalExpression>&)_parameters[1])->getExpression()->evaluate();
        if (folVal.isNull() || folVal.getInt64() < 0)
        {
        	throw SYSTEM_EXCEPTION(SCIDB_SE_INTERNAL, SCIDB_LE_ILLEGAL_OPERATION) << "Invalid number of following cells";
        }
    	shared_ptr<Array> input = inputArrays[0];
    	shared_ptr<ConstArrayIterator> iaiterX = input->getConstIterator(0);
    	shared_ptr<ConstArrayIterator> iaiterY = input->getConstIterator(1);
    	shared_ptr<ConstArrayIterator> iaiterZ = input->getConstIterator(2);
    	shared_ptr<ConstChunkIterator> iciterX;
    	shared_ptr<ConstChunkIterator> iciterY;
    	shared_ptr<ConstChunkIterator> iciterZ;
    	shared_ptr<Array> output(new MemArray(_schema, query));
    	shared_ptr<ArrayIterator> oaiter = output->getIterator(0);
    	shared_ptr<ChunkIterator> ociter;
    	while(!iaiterX->end())
    	{
    		Coordinates pos = iaiterX->getPosition();
    		iciterX = iaiterX->getChunk().getConstIterator();
    		iciterY = iaiterY->getChunk().getConstIterator();
    		iciterZ = iaiterZ->getChunk().getConstIterator();
    		ociter = oaiter->newChunk(pos).getIterator(query, ChunkIterator::SEQUENTIAL_WRITE);
    		windowed_activity::Window window(precVal.getInt64(), folVal.getInt64());
    		double score;
    		Value res;
    		while(!iciterX->end())
    		{
    			int64_t time = iciterX->getPosition()[2];
    			uint8_t x = iciterX->getItem().getUint8();
    			uint8_t y = iciterY->getItem().getUint8();
    			uint8_t z = iciterZ->getItem().getUint8();
    			if(window.iterate(time, x,y,z, pos[2],score))
    			{
    				res.setDouble(score);
        			ociter->setPosition(pos);
        			ociter->writeItem(res);
    			}
    			++(*iciterX);
    			++(*iciterY);
    			++(*iciterZ);
    		}
    		while(window.finalize(pos[2],score))
    		{
    			res.setDouble(score);
				ociter->setPosition(pos);
				ociter->writeItem(res);
    		}
    		ociter->flush();
    		ociter.reset();
    		++(*iaiterX);
    		++(*iaiterY);
    		++(*iaiterZ);
    	}
    	return output;
    }
};

REGISTER_PHYSICAL_OPERATOR_FACTORY(PhysicalComputeActivity, "compute_windowed_activity", "physical_compute_activity");
} //namespace scidb
<commit_msg>Update PhysicalActivity.cpp<commit_after>/*
**
* BEGIN_COPYRIGHT
*
* compute_windowed_activity is a plugin for SciDB.  Copyright (C) 2008-2015 SciDB, Inc.
*
* compute_windowed_activity is free software: you can redistribute it and/or modify
* it under the terms of the AFFERO GNU General Public License as published by
* the Free Software Foundation.
*
* compute_windowed_activity is distributed "AS-IS" AND WITHOUT ANY WARRANTY OF ANY KIND,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* NON-INFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. See
* the AFFERO GNU General Public License for the complete license terms.
*
* You should have received a copy of the AFFERO GNU General Public License
* along with compute_windowed_activity.  If not, see <http://www.gnu.org/licenses/agpl-3.0.html>
*
* END_COPYRIGHT
*/

#include "query/Operator.h"

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory>
#include <cstddef>
#include <deque>

namespace scidb
{

using namespace std;

namespace windowed_activity
{

struct WindowEntry
{
	int64_t time;
	double activityDelta;
	WindowEntry(int64_t t, double d):
		time(t),
		activityDelta(d)
	{}
};

class Window
{
private:
	int64_t const _precedingLimit;
	int64_t const _followingLimit;
	double _runningActivitySum;
	size_t _centerIdx;
	size_t _frontIdx;
	uint8_t _lastX;
	uint8_t _lastY;
	uint8_t _lastZ;
	std::deque<WindowEntry> _window;

public:
	Window(int64_t const numPreceding, int64_t const numFollowing):
		_precedingLimit(numPreceding),
		_followingLimit(numFollowing),
		_runningActivitySum(0),
		_centerIdx(0),
		_frontIdx(0),
		_lastX(0),
		_lastY(0),
		_lastZ(0)
	{}

	bool iterate(int64_t const& inputTime, uint8_t const& x, uint8_t const& y, uint8_t const& z,
			     int64_t& outputTime, double& outputScore)
	{
		double activityDelta = _window.size() == 0 ? 0 :
				sqrt(((double)x-_lastX)*((double)x-_lastX) + ((double)y-_lastY)*((double)y-_lastY) + ((double)z-_lastZ)*((double)z-_lastZ));
		_lastX = x;
		_lastY = y;
		_lastZ = z;
		_window.emplace_back(inputTime, activityDelta);
		if(_window.size() == 1) //first element evah!
		{
			return false;
		}
		else
		{
			WindowEntry center = _window[_centerIdx];
			if(inputTime - center.time <= _followingLimit)
			{
				_runningActivitySum += activityDelta;
				_frontIdx ++;
				return false;
			}
			else
			{
				outputTime = center.time;
				double timeDelta = _window[_frontIdx].time - _window[0].time;
				outputScore = timeDelta > 0 ? _runningActivitySum / (timeDelta) : 0;
				if(outputScore<0)
				{
					outputScore = 0;
				}
				_centerIdx++;
				center = _window[_centerIdx];
				while(_frontIdx+1 < _window.size() && _window[_frontIdx+1].time - center.time <= _followingLimit)
				{
					_frontIdx++;
					_runningActivitySum += _window[_frontIdx].activityDelta;
				}
				while(center.time - _window[0].time > _precedingLimit)
				{
					_runningActivitySum -= _window[0].activityDelta;
					_window.pop_front();
					_centerIdx--;
					_frontIdx--;
				}
				return true;
			}
		}
	}

	bool finalize(int64_t& outputTime, double& outputScore)
	{
		if(_window.size()==0 || _centerIdx >= _window.size())
		{
			return false;
		}
		else
		{
			WindowEntry center = _window[_centerIdx];
			outputTime = center.time;
			double timeDelta = _window[_frontIdx].time - _window[0].time;
			outputScore = timeDelta > 0 ? _runningActivitySum / (timeDelta) : 0;
			if(outputScore<0)
			{
				outputScore = 0;
			}
			_centerIdx++;
			if(_centerIdx < _window.size())
			{
				center = _window[_centerIdx];
				while(_frontIdx+1 < _window.size() && _window[_frontIdx+1].time - center.time <= _followingLimit)
				{
					_frontIdx++;
					_runningActivitySum += _window[_frontIdx].activityDelta;
				}
				while(center.time - _window[0].time > _precedingLimit)
				{
					_runningActivitySum -= _window[0].activityDelta;
					_window.pop_front();
					_centerIdx--;
					_frontIdx--;
				}
			}
			return true;
		}
	}
};

}

class PhysicalComputeActivity : public PhysicalOperator
{
public:
	PhysicalComputeActivity(string const& logicalName,
                            string const& physicalName,
                            Parameters const& parameters,
                            ArrayDesc const& schema):
        PhysicalOperator(logicalName, physicalName, parameters, schema)
    {}

    shared_ptr< Array> execute(vector< shared_ptr< Array> >& inputArrays, shared_ptr<Query> query)
    {
        Value const& precVal = ((std::shared_ptr<OperatorParamPhysicalExpression>&)_parameters[0])->getExpression()->evaluate();
        if (precVal.isNull() || precVal.getInt64() < 0)
        {
        	throw SYSTEM_EXCEPTION(SCIDB_SE_INTERNAL, SCIDB_LE_ILLEGAL_OPERATION) << "Invalid number of preceding cells";
        }
        Value const& folVal = ((std::shared_ptr<OperatorParamPhysicalExpression>&)_parameters[1])->getExpression()->evaluate();
        if (folVal.isNull() || folVal.getInt64() < 0)
        {
        	throw SYSTEM_EXCEPTION(SCIDB_SE_INTERNAL, SCIDB_LE_ILLEGAL_OPERATION) << "Invalid number of following cells";
        }
    	shared_ptr<Array> input = inputArrays[0];
    	shared_ptr<ConstArrayIterator> iaiterX = input->getConstIterator(0);
    	shared_ptr<ConstArrayIterator> iaiterY = input->getConstIterator(1);
    	shared_ptr<ConstArrayIterator> iaiterZ = input->getConstIterator(2);
    	shared_ptr<ConstChunkIterator> iciterX;
    	shared_ptr<ConstChunkIterator> iciterY;
    	shared_ptr<ConstChunkIterator> iciterZ;
    	shared_ptr<Array> output(new MemArray(_schema, query));
    	shared_ptr<ArrayIterator> oaiter = output->getIterator(0);
    	shared_ptr<ChunkIterator> ociter;
    	while(!iaiterX->end())
    	{
    		Coordinates pos = iaiterX->getPosition();
    		iciterX = iaiterX->getChunk().getConstIterator();
    		iciterY = iaiterY->getChunk().getConstIterator();
    		iciterZ = iaiterZ->getChunk().getConstIterator();
    		ociter = oaiter->newChunk(pos).getIterator(query, ChunkIterator::SEQUENTIAL_WRITE);
    		windowed_activity::Window window(precVal.getInt64(), folVal.getInt64());
    		double score;
    		Value res;
    		while(!iciterX->end())
    		{
    			int64_t time = iciterX->getPosition()[2];
    			uint8_t x = iciterX->getItem().getUint8();
    			uint8_t y = iciterY->getItem().getUint8();
    			uint8_t z = iciterZ->getItem().getUint8();
    			if(window.iterate(time, x,y,z, pos[2],score))
    			{
    				res.setDouble(score);
        			ociter->setPosition(pos);
        			ociter->writeItem(res);
    			}
    			++(*iciterX);
    			++(*iciterY);
    			++(*iciterZ);
    		}
    		while(window.finalize(pos[2],score))
    		{
    			res.setDouble(score);
				ociter->setPosition(pos);
				ociter->writeItem(res);
    		}
    		ociter->flush();
    		ociter.reset();
    		++(*iaiterX);
    		++(*iaiterY);
    		++(*iaiterZ);
    	}
    	return output;
    }
};

REGISTER_PHYSICAL_OPERATOR_FACTORY(PhysicalComputeActivity, "compute_windowed_activity", "physical_compute_activity");
} //namespace scidb
<|endoftext|>


<commit_before>#include "init-shared.h"

WARNINGS_DISABLE
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QList>
#include <QMetaType>
#include <QUrl>
#include <QVector>
WARNINGS_ENABLE

#include "backuptask.h"
#include "debug.h"
#include "notification_info.h"
#include "persistentmodel/archive.h"
#include "persistentmodel/job.h"
#include "persistentmodel/journal.h"
#include "persistentmodel/persistentstore.h"
#include "scheduling.h"
#include "tarsnaperror.h"
#include "taskstatus.h"
#include "utils.h"

#include <ConsoleLog.h>
#include <TSettings.h>

#define DEFAULT_LOG_FILE "tarsnap.log"

/*
 * It's unnecessary from a programming standpoint to put these in a separate
 * function, but it helps me keep track of how the various Qt layers work.
 */
static void init_no_app()
{
    qRegisterMetaType<TaskStatus>("TaskStatus");
    qRegisterMetaType<QList<QUrl>>("QList<QUrl>");
    qRegisterMetaType<BackupTaskPtr>("BackupTaskPtr");
    qRegisterMetaType<QList<ArchivePtr>>("QList<ArchivePtr >");
    qRegisterMetaType<ArchivePtr>("ArchivePtr");
    qRegisterMetaType<ArchiveRestoreOptions>("ArchiveRestoreOptions");
    qRegisterMetaType<QSqlQuery>("QSqlQuery");
    qRegisterMetaType<JobPtr>("JobPtr");
    qRegisterMetaType<QMap<QString, JobPtr>>("QMap<QString, JobPtr>");
    qRegisterMetaType<TarsnapError>("TarsnapError");
    qRegisterMetaType<LogEntry>("LogEntry");
    qRegisterMetaType<QVector<LogEntry>>("QVector<LogEntry>");
    qRegisterMetaType<QVector<File>>("QVector<File>");
    qRegisterMetaType<enum message_type>("enum message_type");
}

static void init_no_explicit_app()
{
#ifndef QT_TESTLIB_LIB
    // Don't do this for the tests, since we want them to have unique names.
    QCoreApplication::setOrganizationName(QLatin1String("Tarsnap Backup Inc."));
    QCoreApplication::setOrganizationDomain(QLatin1String("tarsnap.com"));
    QCoreApplication::setApplicationName(QLatin1String("Tarsnap"));
    QCoreApplication::setApplicationVersion(APP_VERSION);
#endif

#if defined(QT_DEBUG)
    qSetMessagePattern("%{if-debug}%{file}(%{line}): %{endif}%{message}");
#endif

    // In order to avoid a memory leak (?), must be done after setting up
    // the application and/or organization name.
    ConsoleLog::initializeConsoleLog();
}

/**
 * Constructor initialization shared between GUI and non-GUI.  Cannot fail.
 */
static void init_shared_nofail()
{
    init_no_app();
    init_no_explicit_app();

    QCoreApplication::setQuitLockEnabled(false);
    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
}

static QString migrateSettings(QSettings *settingsOld, QSettings *settingsNew)
{
    // Copy old settings to new, by group.  (On OSX, QSettings contains a whole
    // bunch of system-wide settings which we don't want to copy.)
    QStringList groups = {"app", "tarsnap"};
    for(const QString &groupname : groups)
    {
        settingsOld->beginGroup(groupname);
        settingsNew->beginGroup(groupname);
        QStringList keys = settingsOld->childKeys();
        for(const QString &key : keys)
        {
            settingsNew->setValue(key, settingsOld->value(key));
        }
        settingsOld->endGroup();
        settingsNew->endGroup();
    }
    settingsNew->sync();

    // Rename old settings to prevent migrating it again.
    QFile   fileOld(settingsOld->fileName());
    QString renamed = settingsOld->fileName()
                      + QDate::currentDate().toString(".yyyy-MMM-dd.bak");

    // Close the Settings to prevent it from re-writing the file.
    delete settingsOld;
    fileOld.rename(renamed);
    return renamed;
}

static QString check_migrateSettings()
{
    // Get default settings file.
    QSettings::setDefaultFormat(QSettings::NativeFormat);
    QSettings *settingsOld = new QSettings();

    // Shouldn't be necessary, but just in case.
    TSettings::destroy();

    // Get new settings file.  Must be done after getting the default one!
    TSettings  tsettings;
    QSettings *settingsNew = tsettings.getQSettings();

    // Bail if we don't need to migrate anything.
    if(QFileInfo::exists(settingsNew->fileName())
       || !QFileInfo::exists(settingsOld->fileName()))
    {
        delete settingsOld;
        return "";
    }

    return migrateSettings(settingsOld, settingsNew);
}

/**
 * Configures the app-wide Settings.  Cannot fail, but can report a message.
 */
static struct init_info init_shared_settings(QString configDir)
{
    struct init_info info = {INIT_OK, "", ""};

    // Handle soon-to-be-deprecated --appdata argument.  Must be done before
    // instantiating any settings object.
    if(!configDir.isEmpty())
    {
        QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
                           configDir);
        QSettings::setDefaultFormat(QSettings::IniFormat);
        // Make sure that TSettings uses the right filename in this case.
        QSettings defaultSettings;
        TSettings::setFilename(defaultSettings.fileName());
    }

    // Migrate settings from old settings file to new (if applicable).
    QString renamedOldSettings;
    if(configDir.isEmpty())
    {
        renamedOldSettings = check_migrateSettings();
    }

    TSettings settings;

    if(!renamedOldSettings.isEmpty())
    {
        info.status = INIT_SETTINGS_RENAMED;
        info.message =
            QString("Updated config file, new location:\n\n%1\n\nThe old file "
                    "was renamed to:\n\n%2")
                .arg(settings.getQSettings()->fileName(), renamedOldSettings);
    }

    return info;
}

static QString getDefaultLogFilename()
{
    TSettings settings;
    QString   appdata = settings.value("app/app_data", "").toString();
    if(appdata.isEmpty())
    {
        DEBUG << "Error saving Console Log message: app/app_data dir not set.";
        return "";
    }

    return appdata + QDir::separator() + DEFAULT_LOG_FILE;
}

/* Do we need to run the setup wizard? */
static struct init_info need_setup_wizard()
{
    struct init_info info = {INIT_OK, "", ""};
    TSettings        settings;

    bool wizardDone = settings.value("app/wizard_done", false).toBool();
    if(!wizardDone)
        info.status = INIT_NEEDS_SETUP;
    return (info);
}

/**
 * Initialization shared between GUI and non-GUI.  Can fail and report messages.
 */
static struct init_info init_shared_core()
{
    struct init_info info = {INIT_OK, "", ""};
    TSettings        settings;

    // Check if we should run the setup wizard.
    info = need_setup_wizard();
    if(info.status == INIT_NEEDS_SETUP)
        return (info);

    // Ensure that we have a location to store app data.  Must be
    // after the setup wizard!
    if(settings.value("app/app_data", "").toString().isEmpty())
    {
        QString appDataDir = QStandardPaths::writableLocation(APPDATA);
        LOG << "Setting default \"app/app_data\" to" << appDataDir;
        settings.setValue("app/app_data", appDataDir);
    }

    // Set up the log file.  Must be done after setup wizard!
    LOG.setFilename(getDefaultLogFilename());

    // Initialize the persistentstore.  Must be after setup wizard!
    PersistentStore::initializePersistentStore();
    PersistentStore &store = PersistentStore::instance();
    if(!store.init())
    {
        info.status = INIT_DB_FAILED;
        return (info);
    }

    // Warn about --dry-run before trying to run --jobs.
    if(settings.value("tarsnap/dry_run", false).toBool())
    {
        info.status  = INIT_DRY_RUN;
        info.message = QObject::tr("Simulation mode is enabled.  Archives will"
                                   " not be uploaded to the Tarsnap server."
                                   "  Disable in Settings -> Backup.");
        return (info);
    }

    // Make sure we have the path to the current Tarsnap-GUI binary
    struct scheduleinfo correctedPath = correctedSchedulingPath();

    if(correctedPath.status == SCHEDULE_OK)
    {
        info.status  = INIT_SCHEDULE_OK;
        info.message = correctedPath.message;
    }
    if(correctedPath.status == SCHEDULE_ERROR)
    {
        info.status  = INIT_SCHEDULE_ERROR;
        info.message = correctedPath.message;
        info.extra   = correctedPath.extra;
    }

    return info;
}

/**
 * Initialization shared between GUI and non-GUI.
 * \return list a QList<struct init_info> with one element per
 * step of the initialization.
 */
QList<struct init_info> init_shared(const QString configDir)
{
    QList<struct init_info> steps;
    struct init_info        info;

    // Step 1: can't fail
    init_shared_nofail();

    // Step 2: check if we need to migrate settings, and generally
    // make sure that TSettings is ready.
    info = init_shared_settings(configDir);
    steps.append(info);
    // Bail if an error occurred.
    if(!((info.status == INIT_OK) || (info.status == INIT_SETTINGS_RENAMED)))
        return (steps);

    // Step 3: everything else.
    info = init_shared_core();
    steps.append(info);

    /* Success! */
    return (steps);
}

void init_shared_free(void)
{
    // Destroy objects in reverse order from their creation.
    PersistentStore::destroy();
    TSettings::destroy();
    ConsoleLog::destroy();
}
<commit_msg>init-shared: explicit check of needs_setup_wizard()<commit_after>#include "init-shared.h"

WARNINGS_DISABLE
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QList>
#include <QMetaType>
#include <QUrl>
#include <QVector>
WARNINGS_ENABLE

#include "backuptask.h"
#include "debug.h"
#include "notification_info.h"
#include "persistentmodel/archive.h"
#include "persistentmodel/job.h"
#include "persistentmodel/journal.h"
#include "persistentmodel/persistentstore.h"
#include "scheduling.h"
#include "tarsnaperror.h"
#include "taskstatus.h"
#include "utils.h"

#include <ConsoleLog.h>
#include <TSettings.h>

#define DEFAULT_LOG_FILE "tarsnap.log"

/*
 * It's unnecessary from a programming standpoint to put these in a separate
 * function, but it helps me keep track of how the various Qt layers work.
 */
static void init_no_app()
{
    qRegisterMetaType<TaskStatus>("TaskStatus");
    qRegisterMetaType<QList<QUrl>>("QList<QUrl>");
    qRegisterMetaType<BackupTaskPtr>("BackupTaskPtr");
    qRegisterMetaType<QList<ArchivePtr>>("QList<ArchivePtr >");
    qRegisterMetaType<ArchivePtr>("ArchivePtr");
    qRegisterMetaType<ArchiveRestoreOptions>("ArchiveRestoreOptions");
    qRegisterMetaType<QSqlQuery>("QSqlQuery");
    qRegisterMetaType<JobPtr>("JobPtr");
    qRegisterMetaType<QMap<QString, JobPtr>>("QMap<QString, JobPtr>");
    qRegisterMetaType<TarsnapError>("TarsnapError");
    qRegisterMetaType<LogEntry>("LogEntry");
    qRegisterMetaType<QVector<LogEntry>>("QVector<LogEntry>");
    qRegisterMetaType<QVector<File>>("QVector<File>");
    qRegisterMetaType<enum message_type>("enum message_type");
}

static void init_no_explicit_app()
{
#ifndef QT_TESTLIB_LIB
    // Don't do this for the tests, since we want them to have unique names.
    QCoreApplication::setOrganizationName(QLatin1String("Tarsnap Backup Inc."));
    QCoreApplication::setOrganizationDomain(QLatin1String("tarsnap.com"));
    QCoreApplication::setApplicationName(QLatin1String("Tarsnap"));
    QCoreApplication::setApplicationVersion(APP_VERSION);
#endif

#if defined(QT_DEBUG)
    qSetMessagePattern("%{if-debug}%{file}(%{line}): %{endif}%{message}");
#endif

    // In order to avoid a memory leak (?), must be done after setting up
    // the application and/or organization name.
    ConsoleLog::initializeConsoleLog();
}

/**
 * Constructor initialization shared between GUI and non-GUI.  Cannot fail.
 */
static void init_shared_nofail()
{
    init_no_app();
    init_no_explicit_app();

    QCoreApplication::setQuitLockEnabled(false);
    QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
}

static QString migrateSettings(QSettings *settingsOld, QSettings *settingsNew)
{
    // Copy old settings to new, by group.  (On OSX, QSettings contains a whole
    // bunch of system-wide settings which we don't want to copy.)
    QStringList groups = {"app", "tarsnap"};
    for(const QString &groupname : groups)
    {
        settingsOld->beginGroup(groupname);
        settingsNew->beginGroup(groupname);
        QStringList keys = settingsOld->childKeys();
        for(const QString &key : keys)
        {
            settingsNew->setValue(key, settingsOld->value(key));
        }
        settingsOld->endGroup();
        settingsNew->endGroup();
    }
    settingsNew->sync();

    // Rename old settings to prevent migrating it again.
    QFile   fileOld(settingsOld->fileName());
    QString renamed = settingsOld->fileName()
                      + QDate::currentDate().toString(".yyyy-MMM-dd.bak");

    // Close the Settings to prevent it from re-writing the file.
    delete settingsOld;
    fileOld.rename(renamed);
    return renamed;
}

static QString check_migrateSettings()
{
    // Get default settings file.
    QSettings::setDefaultFormat(QSettings::NativeFormat);
    QSettings *settingsOld = new QSettings();

    // Shouldn't be necessary, but just in case.
    TSettings::destroy();

    // Get new settings file.  Must be done after getting the default one!
    TSettings  tsettings;
    QSettings *settingsNew = tsettings.getQSettings();

    // Bail if we don't need to migrate anything.
    if(QFileInfo::exists(settingsNew->fileName())
       || !QFileInfo::exists(settingsOld->fileName()))
    {
        delete settingsOld;
        return "";
    }

    return migrateSettings(settingsOld, settingsNew);
}

/**
 * Configures the app-wide Settings.  Cannot fail, but can report a message.
 */
static struct init_info init_shared_settings(QString configDir)
{
    struct init_info info = {INIT_OK, "", ""};

    // Handle soon-to-be-deprecated --appdata argument.  Must be done before
    // instantiating any settings object.
    if(!configDir.isEmpty())
    {
        QSettings::setPath(QSettings::IniFormat, QSettings::UserScope,
                           configDir);
        QSettings::setDefaultFormat(QSettings::IniFormat);
        // Make sure that TSettings uses the right filename in this case.
        QSettings defaultSettings;
        TSettings::setFilename(defaultSettings.fileName());
    }

    // Migrate settings from old settings file to new (if applicable).
    QString renamedOldSettings;
    if(configDir.isEmpty())
    {
        renamedOldSettings = check_migrateSettings();
    }

    TSettings settings;

    if(!renamedOldSettings.isEmpty())
    {
        info.status = INIT_SETTINGS_RENAMED;
        info.message =
            QString("Updated config file, new location:\n\n%1\n\nThe old file "
                    "was renamed to:\n\n%2")
                .arg(settings.getQSettings()->fileName(), renamedOldSettings);
    }

    return info;
}

static QString getDefaultLogFilename()
{
    TSettings settings;
    QString   appdata = settings.value("app/app_data", "").toString();
    if(appdata.isEmpty())
    {
        DEBUG << "Error saving Console Log message: app/app_data dir not set.";
        return "";
    }

    return appdata + QDir::separator() + DEFAULT_LOG_FILE;
}

/* Do we need to run the setup wizard? */
static struct init_info need_setup_wizard()
{
    struct init_info info = {INIT_OK, "", ""};
    TSettings        settings;

    bool wizardDone = settings.value("app/wizard_done", false).toBool();
    if(!wizardDone)
        info.status = INIT_NEEDS_SETUP;
    return (info);
}

/**
 * Initialization shared between GUI and non-GUI.  Can fail and report messages.
 */
static struct init_info init_shared_core()
{
    struct init_info info = {INIT_OK, "", ""};
    TSettings        settings;

    // Ensure that we have a location to store app data.  Must be
    // after the setup wizard!
    if(settings.value("app/app_data", "").toString().isEmpty())
    {
        QString appDataDir = QStandardPaths::writableLocation(APPDATA);
        LOG << "Setting default \"app/app_data\" to" << appDataDir;
        settings.setValue("app/app_data", appDataDir);
    }

    // Set up the log file.  Must be done after setup wizard!
    LOG.setFilename(getDefaultLogFilename());

    // Initialize the persistentstore.  Must be after setup wizard!
    PersistentStore::initializePersistentStore();
    PersistentStore &store = PersistentStore::instance();
    if(!store.init())
    {
        info.status = INIT_DB_FAILED;
        return (info);
    }

    // Warn about --dry-run before trying to run --jobs.
    if(settings.value("tarsnap/dry_run", false).toBool())
    {
        info.status  = INIT_DRY_RUN;
        info.message = QObject::tr("Simulation mode is enabled.  Archives will"
                                   " not be uploaded to the Tarsnap server."
                                   "  Disable in Settings -> Backup.");
        return (info);
    }

    // Make sure we have the path to the current Tarsnap-GUI binary
    struct scheduleinfo correctedPath = correctedSchedulingPath();

    if(correctedPath.status == SCHEDULE_OK)
    {
        info.status  = INIT_SCHEDULE_OK;
        info.message = correctedPath.message;
    }
    if(correctedPath.status == SCHEDULE_ERROR)
    {
        info.status  = INIT_SCHEDULE_ERROR;
        info.message = correctedPath.message;
        info.extra   = correctedPath.extra;
    }

    return info;
}

/**
 * Initialization shared between GUI and non-GUI.
 * \return list a QList<struct init_info> with one element per
 * step of the initialization.
 */
QList<struct init_info> init_shared(const QString configDir)
{
    QList<struct init_info> steps;
    struct init_info        info;

    // Step 1: can't fail
    init_shared_nofail();

    // Step 2: check if we need to migrate settings, and generally
    // make sure that TSettings is ready.
    info = init_shared_settings(configDir);
    steps.append(info);
    // Bail if an error occurred.
    if(!((info.status == INIT_OK) || (info.status == INIT_SETTINGS_RENAMED)))
        return (steps);

    // Step 3: check if we need to run the setup wizard.
    info = need_setup_wizard();
    steps.append(info);
    if(info.status == INIT_NEEDS_SETUP)
        return (steps);

    // Step 4: everything else.
    info = init_shared_core();
    steps.append(info);

    /* Success! */
    return (steps);
}

void init_shared_free(void)
{
    // Destroy objects in reverse order from their creation.
    PersistentStore::destroy();
    TSettings::destroy();
    ConsoleLog::destroy();
}
<|endoftext|>


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

#ifndef SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX
#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX

#include "View.hxx"

#include <sfx2/viewfrm.hxx>

#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#include <memory>

class Point;

namespace sdr { namespace contact {
class ObjectContact;
} }

namespace sd { namespace slidesorter {
class SlideSorterViewShell;
} }

namespace sd { namespace slidesorter { namespace controller {
class SlideSorterController;
} } }

namespace sd { namespace slidesorter { namespace cache {
class PageCache;
} } }

namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
class PageDescriptor;
} } }

namespace sd { namespace slidesorter { namespace view {

class Layouter;
class ViewOverlay;

class SlideSorterView
    : public View
{
public:
    /** Create a new view for the slide sorter.
        @param rViewShell
            This reference is simply passed to the base class and not used
            by this class.

    */
    SlideSorterView (
        SlideSorterViewShell& rViewShell,
        model::SlideSorterModel& rModel);

    virtual ~SlideSorterView (void);

    void RequestRepaint (void);
    void RequestRepaint (model::PageDescriptor& rDescriptor);

    Rectangle GetModelArea (void);

    enum CoordinateSystem { CS_SCREEN, CS_MODEL };
    enum BoundingBoxType { BBT_SHAPE, BBT_INFO };

    /** Return the rectangle that bounds the page object represented by the
        given page descriptor.
        @param rDescriptor
            The descriptor of the page for which to return the bounding box.
        @param eCoordinateSystem
            Specifies whether to return the screen or model coordinates.
        @param eBoundingBoxType
            Specifies whether to return the bounding box of only the page
            object or the one that additionally includes other displayed
            information like page name and fader symbol.
    */
    Rectangle GetPageBoundingBox (
        model::PageDescriptor& rDescriptor,
        CoordinateSystem eCoordinateSystem,
        BoundingBoxType eBoundingBoxType) const;

    /** Return the rectangle that bounds the page object represented by the
        given page index .
        @param nIndex
            The index of the page for which to return the bounding box.
        @param eCoordinateSystem
            Specifies whether to return the screen or model coordinates.
        @param eBoundingBoxType
            Specifies whether to return the bounding box of only the page
            object or the one that additionally includes other displayed
            information like page name and fader symbol.
    */
    Rectangle GetPageBoundingBox (
        sal_Int32 nIndex,
        CoordinateSystem eCoordinateSystem,
        BoundingBoxType eBoundingBoxType) const;

    /** Return the index of the page that is rendered at the given position.
        @param rPosition
            The position is expected to be in pixel coordinates.
        @return
            The returned index is -1 when there is no page object at the
            given position.
    */
    sal_Int32 GetPageIndexAtPoint (const Point& rPosition) const;
    sal_Int32 GetFadePageIndexAtPoint (const Point& rPosition) const;

    view::Layouter& GetLayouter (void);

    virtual void ModelHasChanged (void);

    /** This method is typically called before a model change takes place.
        All references to model data are released.  PostModelChange() has to
        be called to complete the handling of the model change.  When the
        calls to Pre- and PostModelChange() are very close to each other you
        may call HandleModelChange() instead.
    */
    void PreModelChange (void);

    /** This method is typically called after a model change took place.
        References to model data are re-allocated.  Call this method only
        after PreModelChange() has been called.
    */
    void PostModelChange (void);

    /** This method is a convenience function that simply calls
        PreModelChange() and then PostModelChange().
    */
    void HandleModelChange (void);

    virtual void Resize (void);
    virtual void CompleteRedraw (
        OutputDevice* pDevice,
        const Region& rPaintArea,
        ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);
    virtual void InvalidateOneWin (
        ::Window& rWindow);
    virtual void InvalidateOneWin (
        ::Window& rWindow,
        const Rectangle& rPaintArea );

    void Layout (void);
    /** This tells the view that it has to re-determine the visibility of
        the page objects before painting them the next time.
    */
    void InvalidatePageObjectVisibilities (void);

    /** Return the window to which this view renders its output.
    */
    ::sd::Window* GetWindow (void) const;

    cache::PageCache& GetPreviewCache (void);

    view::ViewOverlay& GetOverlay (void);

    /** Set the bounding box of the insertion marker in model coordinates.

        It will be painted as a dark rectangle that fills the given box.
    */
    void SetInsertionMarker (const Rectangle& rBBox);

    /** Specify whether the insertion marker will be painted or not.
    */
    void SetInsertionMarkerVisibility (bool bVisible);

    /** Set the size and position of the selection rectangle.

        It will be painted as a dashed rectangle.
    */
    void SetSelectionRectangle (const Rectangle& rBox);

    /** Specify whether the selection rectangle will be painted or not.
    */
    void SetSelectionRectangleVisibility (bool bVisible);

    ::sdr::contact::ObjectContact& GetObjectContact (void) const;

    typedef ::std::pair<sal_Int32,sal_Int32> PageRange;
    /** Return the range of currently visible page objects including the
        first and last one in that range.
        @return
            The returned pair of page object indices is empty when the
            second index is lower than the first.
    */
    PageRange GetVisiblePageRange (void);

private:
    model::SlideSorterModel& mrModel;
    /// This model is used for the maPage object.
    SdrModel maPageModel;
    /** This page acts as container for the page objects that represent the
        pages of the document that is represented by the SlideSorterModel.
    */
    SdrPage* mpPage;
    std::auto_ptr<Layouter> mpLayouter;
    bool mbPageObjectVisibilitiesValid;
    std::auto_ptr<cache::PageCache> mpPreviewCache;
    std::auto_ptr<ViewOverlay> mpViewOverlay;

    int mnFirstVisiblePageIndex;
    int mnLastVisiblePageIndex;

    SvBorder maPagePixelBorder;

    /** Adapt the coordinates of the given bounding box according to the
        other parameters.
        @param rModelPageObjectBoundingBox
            Bounding box given in model coordinates that bounds only the
            page object.
        @param eCoordinateSystem
            When CS_SCREEN is given then the bounding box is converted into
            screen coordinates.
        @param eBoundingBoxType
            When BBT_INFO is given then the bounding box is made larger so
            that it encloses all relevant displayed information.
        */
    void AdaptBoundingBox (
        Rectangle& rModelPageObjectBoundingBox,
        CoordinateSystem eCoordinateSystem,
        BoundingBoxType eBoundingBoxType) const;

    /** Determine the visibility of all page objects.
    */
    void DeterminePageObjectVisibilities (void);

    controller::SlideSorterController& GetController (void);

    /** Update the page borders used by the layouter by using those returned
        by the first page.  Call this function when the model changes,
        especially when the number of pages changes, or when the window is
        resized as the borders may be device dependent.
    */
    void UpdatePageBorders (void);
};

} } } // end of namespace ::sd::slidesorter::view

#endif
<commit_msg>INTEGRATION: CWS impress69 (1.5.72); FILE MERGED 2005/10/14 11:12:10 af 1.5.72.4: RESYNC: (1.5-1.6); FILE MERGED 2005/09/22 15:33:43 af 1.5.72.3: #i54916# Fixed Solaris compiler problem. 2005/09/14 11:32:14 af 1.5.72.2: #i54589# Added support for persistent caches. 2005/09/01 15:36:05 af 1.5.72.1: #i54118# Added mbModelChangeWhileModifyEnabled flag and SFX_NOTIFY() method.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlideSorterView.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-10-24 07:43:50 $
 *
 *  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_SLIDESORTER_SLIDE_SORTER_VIEW_HXX
#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX

#include "View.hxx"

#include <sfx2/viewfrm.hxx>

#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#include <memory>
#include <boost/shared_ptr.hpp>

class Point;

namespace sdr { namespace contact {
class ObjectContact;
} }

namespace sd { namespace slidesorter {
class SlideSorterViewShell;
} }

namespace sd { namespace slidesorter { namespace controller {
class SlideSorterController;
} } }

namespace sd { namespace slidesorter { namespace cache {
class PageCache;
} } }

namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
class PageDescriptor;
} } }

namespace sd { namespace slidesorter { namespace view {

class Layouter;
class ViewOverlay;

class SlideSorterView
    : public View
{
public:
    /** Create a new view for the slide sorter.
        @param rViewShell
            This reference is simply passed to the base class and not used
            by this class.

    */
    SlideSorterView (
        SlideSorterViewShell& rViewShell,
        model::SlideSorterModel& rModel);

    virtual ~SlideSorterView (void);

    void RequestRepaint (void);
    void RequestRepaint (model::PageDescriptor& rDescriptor);

    Rectangle GetModelArea (void);

    enum CoordinateSystem { CS_SCREEN, CS_MODEL };
    enum BoundingBoxType { BBT_SHAPE, BBT_INFO };

    /** Return the rectangle that bounds the page object represented by the
        given page descriptor.
        @param rDescriptor
            The descriptor of the page for which to return the bounding box.
        @param eCoordinateSystem
            Specifies whether to return the screen or model coordinates.
        @param eBoundingBoxType
            Specifies whether to return the bounding box of only the page
            object or the one that additionally includes other displayed
            information like page name and fader symbol.
    */
    Rectangle GetPageBoundingBox (
        model::PageDescriptor& rDescriptor,
        CoordinateSystem eCoordinateSystem,
        BoundingBoxType eBoundingBoxType) const;

    /** Return the rectangle that bounds the page object represented by the
        given page index .
        @param nIndex
            The index of the page for which to return the bounding box.
        @param eCoordinateSystem
            Specifies whether to return the screen or model coordinates.
        @param eBoundingBoxType
            Specifies whether to return the bounding box of only the page
            object or the one that additionally includes other displayed
            information like page name and fader symbol.
    */
    Rectangle GetPageBoundingBox (
        sal_Int32 nIndex,
        CoordinateSystem eCoordinateSystem,
        BoundingBoxType eBoundingBoxType) const;

    /** Return the index of the page that is rendered at the given position.
        @param rPosition
            The position is expected to be in pixel coordinates.
        @return
            The returned index is -1 when there is no page object at the
            given position.
    */
    sal_Int32 GetPageIndexAtPoint (const Point& rPosition) const;
    sal_Int32 GetFadePageIndexAtPoint (const Point& rPosition) const;

    view::Layouter& GetLayouter (void);

    virtual void ModelHasChanged (void);

    /** This method is typically called before a model change takes place.
        All references to model data are released.  PostModelChange() has to
        be called to complete the handling of the model change.  When the
        calls to Pre- and PostModelChange() are very close to each other you
        may call HandleModelChange() instead.
    */
    void PreModelChange (void);

    /** This method is typically called after a model change took place.
        References to model data are re-allocated.  Call this method only
        after PreModelChange() has been called.
    */
    void PostModelChange (void);

    /** This method is a convenience function that simply calls
        PreModelChange() and then PostModelChange().
    */
    void HandleModelChange (void);

    virtual void Resize (void);
    virtual void CompleteRedraw (
        OutputDevice* pDevice,
        const Region& rPaintArea,
        ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);
    virtual void InvalidateOneWin (
        ::Window& rWindow);
    virtual void InvalidateOneWin (
        ::Window& rWindow,
        const Rectangle& rPaintArea );

    void Layout (void);
    /** This tells the view that it has to re-determine the visibility of
        the page objects before painting them the next time.
    */
    void InvalidatePageObjectVisibilities (void);

    /** Return the window to which this view renders its output.
    */
    ::sd::Window* GetWindow (void) const;

    ::boost::shared_ptr<cache::PageCache> GetPreviewCache (void);

    view::ViewOverlay& GetOverlay (void);

    /** Set the bounding box of the insertion marker in model coordinates.

        It will be painted as a dark rectangle that fills the given box.
    */
    void SetInsertionMarker (const Rectangle& rBBox);

    /** Specify whether the insertion marker will be painted or not.
    */
    void SetInsertionMarkerVisibility (bool bVisible);

    /** Set the size and position of the selection rectangle.

        It will be painted as a dashed rectangle.
    */
    void SetSelectionRectangle (const Rectangle& rBox);

    /** Specify whether the selection rectangle will be painted or not.
    */
    void SetSelectionRectangleVisibility (bool bVisible);

    ::sdr::contact::ObjectContact& GetObjectContact (void) const;

    typedef ::std::pair<sal_Int32,sal_Int32> PageRange;
    /** Return the range of currently visible page objects including the
        first and last one in that range.
        @return
            The returned pair of page object indices is empty when the
            second index is lower than the first.
    */
    PageRange GetVisiblePageRange (void);

protected:
    virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint);

private:
    model::SlideSorterModel& mrModel;
    /// This model is used for the maPage object.
    SdrModel maPageModel;
    /** This page acts as container for the page objects that represent the
        pages of the document that is represented by the SlideSorterModel.
    */
    SdrPage* mpPage;
    ::std::auto_ptr<Layouter> mpLayouter;
    bool mbPageObjectVisibilitiesValid;
    ::boost::shared_ptr<cache::PageCache> mpPreviewCache;
    ::std::auto_ptr<ViewOverlay> mpViewOverlay;

    int mnFirstVisiblePageIndex;
    int mnLastVisiblePageIndex;

    SvBorder maPagePixelBorder;

    bool mbModelChangedWhileModifyEnabled;

    Size maPreviewSize;

    bool mbPreciousFlagUpdatePending;

    /** Adapt the coordinates of the given bounding box according to the
        other parameters.
        @param rModelPageObjectBoundingBox
            Bounding box given in model coordinates that bounds only the
            page object.
        @param eCoordinateSystem
            When CS_SCREEN is given then the bounding box is converted into
            screen coordinates.
        @param eBoundingBoxType
            When BBT_INFO is given then the bounding box is made larger so
            that it encloses all relevant displayed information.
        */
    void AdaptBoundingBox (
        Rectangle& rModelPageObjectBoundingBox,
        CoordinateSystem eCoordinateSystem,
        BoundingBoxType eBoundingBoxType) const;

    /** Determine the visibility of all page objects.
    */
    void DeterminePageObjectVisibilities (void);

    controller::SlideSorterController& GetController (void);

    /** Update the page borders used by the layouter by using those returned
        by the first page.  Call this function when the model changes,
        especially when the number of pages changes, or when the window is
        resized as the borders may be device dependent.
    */
    void UpdatePageBorders (void);

    void UpdatePreciousFlags (void);
};

} } } // end of namespace ::sd::slidesorter::view

#endif
<|endoftext|>


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

using namespace ::connectivity;
using namespace ::connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;

DBG_NAME( file_OSQLAnalyzer )
//------------------------------------------------------------------
OSQLAnalyzer::OSQLAnalyzer()
               : m_bSelectionFirstTime(sal_True)
               , m_bHasSelectionCode(sal_False)
{
    DBG_CTOR( file_OSQLAnalyzer, NULL );
    m_aCompiler = new OPredicateCompiler(this);
    m_aInterpreter = new OPredicateInterpreter(m_aCompiler);
}

// -----------------------------------------------------------------------------
OSQLAnalyzer::~OSQLAnalyzer()
{
    DBG_DTOR( file_OSQLAnalyzer, NULL );
}

// -----------------------------------------------------------------------------
void OSQLAnalyzer::setIndexes(const Reference< XNameAccess>& _xIndexes)
{
    m_aCompiler->m_xIndexes = _xIndexes;
}
//------------------------------------------------------------------
void OSQLAnalyzer::start(OSQLParseNode* pSQLParseNode)
{
    if (SQL_ISRULE(pSQLParseNode,select_statement))
    {
        DBG_ASSERT(pSQLParseNode->count() >= 4,"OFILECursor: Fehler im Parse Tree");

        // check that we don't use anything other than count(*) as function
        OSQLParseNode* pSelection = pSQLParseNode->getChild(2);
        if ( SQL_ISRULE(pSelection,scalar_exp_commalist) )
        {
            for (sal_uInt32 i = 0; i < pSelection->count(); i++)
            {
                OSQLParseNode *pColumnRef = pSelection->getChild(i)->getChild(0);
                if (    ( SQL_ISRULE(pColumnRef,set_fct_spec) && pColumnRef->count() == 4 )
                    ||  SQL_ISRULE(pColumnRef,char_value_fct)
                    ||  SQL_ISRULE(pColumnRef,char_substring_fct)
                    ||  SQL_ISRULE(pColumnRef,position_exp)
                    ||  SQL_ISRULE(pColumnRef,fold)
                    ||  SQL_ISRULE(pColumnRef,length_exp)
                    ||  SQL_ISRULE(pColumnRef,set_fct_spec) )
                {
                    ::vos::ORef<OPredicateCompiler>     pCompiler = new OPredicateCompiler(this);
                    pCompiler->setOrigColumns(m_aCompiler->getOrigColumns());
                    ::vos::ORef<OPredicateInterpreter>  pInterpreter = new OPredicateInterpreter(pCompiler);
                    pCompiler->execute( pColumnRef );
                    m_aSelectionEvaluations.push_back( TPredicates(pCompiler,pInterpreter) );
                }
                else if ( ( SQL_ISRULE(pColumnRef,general_set_fct) && pColumnRef->count() != 4 ) )
                {
                    ::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Statement to complex. Only \"COUNT(*)\" is supported.")),NULL);
                }
                else
                    m_aSelectionEvaluations.push_back( TPredicates() );
            }
        }
    }

    m_aCompiler->start(pSQLParseNode);
}

//------------------------------------------------------------------
void OSQLAnalyzer::bindRow(OCodeList& rCodeList,const OValueRefRow& _pRow,OEvaluateSetList& _rEvaluateSetList)
{
    // Zaehlen, wieviele Kriterien
    // wenn nur ein Kriterium, und das entsprechende Feld ist indiziert
    // dann wird der Index verwendet

    OEvaluateSet*       pEvaluateSet = NULL;

    for (OCodeList::iterator aIter = rCodeList.begin(); aIter != rCodeList.end(); ++aIter)
    {
        OOperandAttr* pAttr = PTR_CAST(OOperandAttr,(*aIter));
        if (pAttr)
        {
            if (pAttr->isIndexed() && !m_aCompiler->hasORCondition())
            {
                OCode* pCode1 = *(aIter + 1);
                OCode* pCode2 = *(aIter + 2);

                if (PTR_CAST(OOperand,pCode1))
                    pEvaluateSet = pAttr->preProcess(PTR_CAST(OBoolOperator,pCode2), PTR_CAST(OOperand,pCode1));
                else
                    pEvaluateSet = pAttr->preProcess(PTR_CAST(OBoolOperator,pCode1));
            }

            if (pEvaluateSet)
            {
                _rEvaluateSetList.push_back(pEvaluateSet);
                pEvaluateSet = NULL;
            }
            pAttr->bindValue(_pRow);
        }
    }
}
//------------------------------------------------------------------
void OSQLAnalyzer::bindSelectRow(const OValueRefRow& _pRow)
{
    // first the select part
    OEvaluateSetList    aEvaluateSetList;
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter)
    {
        if ( aIter->first.isValid() )
            bindRow( aIter->first->m_aCodeList,_pRow,aEvaluateSetList);
    }
}
//------------------------------------------------------------------
::std::vector<sal_Int32>* OSQLAnalyzer::bindEvaluationRow(OValueRefRow& _pRow)
{
    OEvaluateSetList    aEvaluateSetList;
    bindRow( m_aCompiler->m_aCodeList,_pRow,aEvaluateSetList);

    ::std::vector<sal_Int32>*   pKeySet      = NULL;
    OEvaluateSet*               pEvaluateSet = NULL;

    // Keyset erzeugen mit kleinster Liste
    if(!aEvaluateSetList.empty())
    {
        // welche Liste hat den kleinsten count ?
        OEvaluateSetList::iterator i = aEvaluateSetList.begin();
        pEvaluateSet = *(i);
        for(++i; i != aEvaluateSetList.end();++i)
        {
            OEvaluateSet*   pEvaluateSetComp = (*i);
            for(OEvaluateSet::reverse_iterator j = pEvaluateSet->rbegin(); j != pEvaluateSet->rend(); ++j)
            {
                if (pEvaluateSetComp->find(j->second) != pEvaluateSetComp->end())
                    pEvaluateSet->erase(j->second);
            }
        }
        pKeySet = new ::std::vector<sal_Int32>(pEvaluateSet->size());
        sal_Int32 k=0;
        for(OEvaluateSet::iterator j = pEvaluateSet->begin(); j != pEvaluateSet->end(); ++j,++k)
        {
            (*pKeySet)[k] = j->second;
        }

        // alle loeschen
        for(i = aEvaluateSetList.begin(); i != aEvaluateSetList.end();++i)
            delete (*i);
    }

    return pKeySet;
}

//------------------------------------------------------------------
void OSQLAnalyzer::describeParam(::vos::ORef<OSQLColumns> rParameterColumns)
{
    OCodeList& rCodeList    = m_aCompiler->m_aCodeList;
    OCodeStack aCodeStack;

    if (!rCodeList.size())
        return;     // kein Praedikat
    if (!rParameterColumns->size())
        return; // keine Parameter

    // Anlegen von Columns, die eine genauere Beschreibung fuer die enthalten
    ::vos::ORef<OSQLColumns> aNewParamColumns = new OSQLColumns(*rParameterColumns);

    // Anlegen einer Testzeile, wird benoetigt um die Parameter zu beschreiben
    OValueRefRow aParameterRow  = new OValueRefVector(rParameterColumns->size());
    bindParameterRow(aParameterRow);

    OValueRefRow aTestRow = new OValueRefVector(Reference< XIndexAccess>(m_aCompiler->getOrigColumns(),UNO_QUERY)->getCount());
    delete bindEvaluationRow(aTestRow);                 // Binden der Attribute an die Values

    for(OCodeList::iterator aIter = rCodeList.begin(); aIter != rCodeList.end(); ++aIter)
    {
        OOperand* pOperand = PTR_CAST(OOperand,(*aIter));
        OOperator* pOperator = PTR_CAST(OOperator,(*aIter));
        if (pOperand)
            aCodeStack.push(pOperand);
        else
        {
            if (pOperator->getRequestedOperands() == 2)     // bei zwei Operatoren ist es moeglich
            {                                               // einen Parameter weiter zu spezifizieren
                OOperandParam *pParam  = PTR_CAST(OOperandParam,aCodeStack.top());
                if (pParam)  // Anpassen des ParameterTyps, wenn der linke Operand ein Attribut ist
                {
                    OOperandAttr *pLeft  = PTR_CAST(OOperandAttr,*(rCodeList.end() - 2));
                    if (pLeft)
                    {
                        Reference< XPropertySet> xCol;
                        Reference< XIndexAccess>(m_aCompiler->getOrigColumns(),UNO_QUERY)->getByIndex(pLeft->getRowPos()) >>= xCol;
                        OSL_ENSURE(xCol.is(), "Ungueltige Struktur");
                        pParam->describe(xCol, aNewParamColumns);
                    }
                }
            }
            pOperator->Exec(aCodeStack);
        }
    }
    OOperand* pOperand = aCodeStack.top();
    aCodeStack.pop();

    OSL_ENSURE(aCodeStack.size() == 0, "StackFehler");
    OSL_ENSURE(pOperand, "StackFehler");
    if (IS_TYPE(OOperandResult,pOperand))
        delete pOperand;
    else
        OSL_ENSURE(0,"Illegal here!");

    rParameterColumns = aNewParamColumns;
    //  m_aCompiler->setParameterColumns(rParameterColumns);
}

// -----------------------------------------------------------------------------
OOperandAttr* OSQLAnalyzer::createOperandAttr(sal_Int32 _nPos,
                                              const Reference< XPropertySet>& _xCol,
                                              const Reference< XNameAccess>& _xIndexes)
{
    return new OOperandAttr(static_cast<sal_uInt16>(_nPos),_xCol);
}
// -----------------------------------------------------------------------------
BOOL OSQLAnalyzer::hasRestriction() const
{
    return m_aCompiler->hasCode();
}
// -----------------------------------------------------------------------------
BOOL OSQLAnalyzer::hasFunctions() const
{
    if ( m_bSelectionFirstTime )
    {
        m_bSelectionFirstTime = sal_False;
        for ( ::std::vector< TPredicates >::const_iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end() && !m_bHasSelectionCode ;++aIter)
        {
            if ( aIter->first.isValid() )
                m_bHasSelectionCode = aIter->first->hasCode();
        }
    }
    return m_bHasSelectionCode;;
}
// -----------------------------------------------------------------------------
void OSQLAnalyzer::setSelectionEvaluationResult(OValueRefRow& _pRow,const ::std::vector<sal_Int32>& _rColumnMapping)
{
    sal_Int32 nPos = 1;
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter,++nPos)
    {
        if ( aIter->second.isValid() )
        {
            sal_Int32   map = nPos;
            // the first column (index 0) is for convenience only. The first real select column is no 1.
            if ( (nPos > 0) && (nPos < static_cast<sal_Int32>(_rColumnMapping.size())) )
                map = _rColumnMapping[nPos];
            aIter->second->startSelection((*_pRow)[map]);
        }
    }
}
// -----------------------------------------------------------------------------
void OSQLAnalyzer::dispose()
{
    m_aCompiler->dispose();
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter)
    {
        if ( aIter->first.isValid() )
            aIter->first->dispose();
    }
}
// -----------------------------------------------------------------------------
void OSQLAnalyzer::setOrigColumns(const OFileColumns& rCols)
{
    m_aCompiler->setOrigColumns(rCols);
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter)
    {
        if ( aIter->first.isValid() )
            aIter->first->setOrigColumns(rCols);
    }
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.21.78); FILE MERGED 2005/09/05 17:23:50 rt 1.21.78.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fanalyzer.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 05:58:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_FILE_FANALYZER_HXX_
#include "file/fanalyzer.hxx"
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include "connectivity/sqlparse.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include "connectivity/sqlnode.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif

using namespace ::connectivity;
using namespace ::connectivity::file;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;

DBG_NAME( file_OSQLAnalyzer )
//------------------------------------------------------------------
OSQLAnalyzer::OSQLAnalyzer()
               : m_bSelectionFirstTime(sal_True)
               , m_bHasSelectionCode(sal_False)
{
    DBG_CTOR( file_OSQLAnalyzer, NULL );
    m_aCompiler = new OPredicateCompiler(this);
    m_aInterpreter = new OPredicateInterpreter(m_aCompiler);
}

// -----------------------------------------------------------------------------
OSQLAnalyzer::~OSQLAnalyzer()
{
    DBG_DTOR( file_OSQLAnalyzer, NULL );
}

// -----------------------------------------------------------------------------
void OSQLAnalyzer::setIndexes(const Reference< XNameAccess>& _xIndexes)
{
    m_aCompiler->m_xIndexes = _xIndexes;
}
//------------------------------------------------------------------
void OSQLAnalyzer::start(OSQLParseNode* pSQLParseNode)
{
    if (SQL_ISRULE(pSQLParseNode,select_statement))
    {
        DBG_ASSERT(pSQLParseNode->count() >= 4,"OFILECursor: Fehler im Parse Tree");

        // check that we don't use anything other than count(*) as function
        OSQLParseNode* pSelection = pSQLParseNode->getChild(2);
        if ( SQL_ISRULE(pSelection,scalar_exp_commalist) )
        {
            for (sal_uInt32 i = 0; i < pSelection->count(); i++)
            {
                OSQLParseNode *pColumnRef = pSelection->getChild(i)->getChild(0);
                if (    ( SQL_ISRULE(pColumnRef,set_fct_spec) && pColumnRef->count() == 4 )
                    ||  SQL_ISRULE(pColumnRef,char_value_fct)
                    ||  SQL_ISRULE(pColumnRef,char_substring_fct)
                    ||  SQL_ISRULE(pColumnRef,position_exp)
                    ||  SQL_ISRULE(pColumnRef,fold)
                    ||  SQL_ISRULE(pColumnRef,length_exp)
                    ||  SQL_ISRULE(pColumnRef,set_fct_spec) )
                {
                    ::vos::ORef<OPredicateCompiler>     pCompiler = new OPredicateCompiler(this);
                    pCompiler->setOrigColumns(m_aCompiler->getOrigColumns());
                    ::vos::ORef<OPredicateInterpreter>  pInterpreter = new OPredicateInterpreter(pCompiler);
                    pCompiler->execute( pColumnRef );
                    m_aSelectionEvaluations.push_back( TPredicates(pCompiler,pInterpreter) );
                }
                else if ( ( SQL_ISRULE(pColumnRef,general_set_fct) && pColumnRef->count() != 4 ) )
                {
                    ::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Statement to complex. Only \"COUNT(*)\" is supported.")),NULL);
                }
                else
                    m_aSelectionEvaluations.push_back( TPredicates() );
            }
        }
    }

    m_aCompiler->start(pSQLParseNode);
}

//------------------------------------------------------------------
void OSQLAnalyzer::bindRow(OCodeList& rCodeList,const OValueRefRow& _pRow,OEvaluateSetList& _rEvaluateSetList)
{
    // Zaehlen, wieviele Kriterien
    // wenn nur ein Kriterium, und das entsprechende Feld ist indiziert
    // dann wird der Index verwendet

    OEvaluateSet*       pEvaluateSet = NULL;

    for (OCodeList::iterator aIter = rCodeList.begin(); aIter != rCodeList.end(); ++aIter)
    {
        OOperandAttr* pAttr = PTR_CAST(OOperandAttr,(*aIter));
        if (pAttr)
        {
            if (pAttr->isIndexed() && !m_aCompiler->hasORCondition())
            {
                OCode* pCode1 = *(aIter + 1);
                OCode* pCode2 = *(aIter + 2);

                if (PTR_CAST(OOperand,pCode1))
                    pEvaluateSet = pAttr->preProcess(PTR_CAST(OBoolOperator,pCode2), PTR_CAST(OOperand,pCode1));
                else
                    pEvaluateSet = pAttr->preProcess(PTR_CAST(OBoolOperator,pCode1));
            }

            if (pEvaluateSet)
            {
                _rEvaluateSetList.push_back(pEvaluateSet);
                pEvaluateSet = NULL;
            }
            pAttr->bindValue(_pRow);
        }
    }
}
//------------------------------------------------------------------
void OSQLAnalyzer::bindSelectRow(const OValueRefRow& _pRow)
{
    // first the select part
    OEvaluateSetList    aEvaluateSetList;
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter)
    {
        if ( aIter->first.isValid() )
            bindRow( aIter->first->m_aCodeList,_pRow,aEvaluateSetList);
    }
}
//------------------------------------------------------------------
::std::vector<sal_Int32>* OSQLAnalyzer::bindEvaluationRow(OValueRefRow& _pRow)
{
    OEvaluateSetList    aEvaluateSetList;
    bindRow( m_aCompiler->m_aCodeList,_pRow,aEvaluateSetList);

    ::std::vector<sal_Int32>*   pKeySet      = NULL;
    OEvaluateSet*               pEvaluateSet = NULL;

    // Keyset erzeugen mit kleinster Liste
    if(!aEvaluateSetList.empty())
    {
        // welche Liste hat den kleinsten count ?
        OEvaluateSetList::iterator i = aEvaluateSetList.begin();
        pEvaluateSet = *(i);
        for(++i; i != aEvaluateSetList.end();++i)
        {
            OEvaluateSet*   pEvaluateSetComp = (*i);
            for(OEvaluateSet::reverse_iterator j = pEvaluateSet->rbegin(); j != pEvaluateSet->rend(); ++j)
            {
                if (pEvaluateSetComp->find(j->second) != pEvaluateSetComp->end())
                    pEvaluateSet->erase(j->second);
            }
        }
        pKeySet = new ::std::vector<sal_Int32>(pEvaluateSet->size());
        sal_Int32 k=0;
        for(OEvaluateSet::iterator j = pEvaluateSet->begin(); j != pEvaluateSet->end(); ++j,++k)
        {
            (*pKeySet)[k] = j->second;
        }

        // alle loeschen
        for(i = aEvaluateSetList.begin(); i != aEvaluateSetList.end();++i)
            delete (*i);
    }

    return pKeySet;
}

//------------------------------------------------------------------
void OSQLAnalyzer::describeParam(::vos::ORef<OSQLColumns> rParameterColumns)
{
    OCodeList& rCodeList    = m_aCompiler->m_aCodeList;
    OCodeStack aCodeStack;

    if (!rCodeList.size())
        return;     // kein Praedikat
    if (!rParameterColumns->size())
        return; // keine Parameter

    // Anlegen von Columns, die eine genauere Beschreibung fuer die enthalten
    ::vos::ORef<OSQLColumns> aNewParamColumns = new OSQLColumns(*rParameterColumns);

    // Anlegen einer Testzeile, wird benoetigt um die Parameter zu beschreiben
    OValueRefRow aParameterRow  = new OValueRefVector(rParameterColumns->size());
    bindParameterRow(aParameterRow);

    OValueRefRow aTestRow = new OValueRefVector(Reference< XIndexAccess>(m_aCompiler->getOrigColumns(),UNO_QUERY)->getCount());
    delete bindEvaluationRow(aTestRow);                 // Binden der Attribute an die Values

    for(OCodeList::iterator aIter = rCodeList.begin(); aIter != rCodeList.end(); ++aIter)
    {
        OOperand* pOperand = PTR_CAST(OOperand,(*aIter));
        OOperator* pOperator = PTR_CAST(OOperator,(*aIter));
        if (pOperand)
            aCodeStack.push(pOperand);
        else
        {
            if (pOperator->getRequestedOperands() == 2)     // bei zwei Operatoren ist es moeglich
            {                                               // einen Parameter weiter zu spezifizieren
                OOperandParam *pParam  = PTR_CAST(OOperandParam,aCodeStack.top());
                if (pParam)  // Anpassen des ParameterTyps, wenn der linke Operand ein Attribut ist
                {
                    OOperandAttr *pLeft  = PTR_CAST(OOperandAttr,*(rCodeList.end() - 2));
                    if (pLeft)
                    {
                        Reference< XPropertySet> xCol;
                        Reference< XIndexAccess>(m_aCompiler->getOrigColumns(),UNO_QUERY)->getByIndex(pLeft->getRowPos()) >>= xCol;
                        OSL_ENSURE(xCol.is(), "Ungueltige Struktur");
                        pParam->describe(xCol, aNewParamColumns);
                    }
                }
            }
            pOperator->Exec(aCodeStack);
        }
    }
    OOperand* pOperand = aCodeStack.top();
    aCodeStack.pop();

    OSL_ENSURE(aCodeStack.size() == 0, "StackFehler");
    OSL_ENSURE(pOperand, "StackFehler");
    if (IS_TYPE(OOperandResult,pOperand))
        delete pOperand;
    else
        OSL_ENSURE(0,"Illegal here!");

    rParameterColumns = aNewParamColumns;
    //  m_aCompiler->setParameterColumns(rParameterColumns);
}

// -----------------------------------------------------------------------------
OOperandAttr* OSQLAnalyzer::createOperandAttr(sal_Int32 _nPos,
                                              const Reference< XPropertySet>& _xCol,
                                              const Reference< XNameAccess>& _xIndexes)
{
    return new OOperandAttr(static_cast<sal_uInt16>(_nPos),_xCol);
}
// -----------------------------------------------------------------------------
BOOL OSQLAnalyzer::hasRestriction() const
{
    return m_aCompiler->hasCode();
}
// -----------------------------------------------------------------------------
BOOL OSQLAnalyzer::hasFunctions() const
{
    if ( m_bSelectionFirstTime )
    {
        m_bSelectionFirstTime = sal_False;
        for ( ::std::vector< TPredicates >::const_iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end() && !m_bHasSelectionCode ;++aIter)
        {
            if ( aIter->first.isValid() )
                m_bHasSelectionCode = aIter->first->hasCode();
        }
    }
    return m_bHasSelectionCode;;
}
// -----------------------------------------------------------------------------
void OSQLAnalyzer::setSelectionEvaluationResult(OValueRefRow& _pRow,const ::std::vector<sal_Int32>& _rColumnMapping)
{
    sal_Int32 nPos = 1;
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter,++nPos)
    {
        if ( aIter->second.isValid() )
        {
            sal_Int32   map = nPos;
            // the first column (index 0) is for convenience only. The first real select column is no 1.
            if ( (nPos > 0) && (nPos < static_cast<sal_Int32>(_rColumnMapping.size())) )
                map = _rColumnMapping[nPos];
            aIter->second->startSelection((*_pRow)[map]);
        }
    }
}
// -----------------------------------------------------------------------------
void OSQLAnalyzer::dispose()
{
    m_aCompiler->dispose();
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter)
    {
        if ( aIter->first.isValid() )
            aIter->first->dispose();
    }
}
// -----------------------------------------------------------------------------
void OSQLAnalyzer::setOrigColumns(const OFileColumns& rCols)
{
    m_aCompiler->setOrigColumns(rCols);
    for ( ::std::vector< TPredicates >::iterator aIter = m_aSelectionEvaluations.begin(); aIter != m_aSelectionEvaluations.end();++aIter)
    {
        if ( aIter->first.isValid() )
            aIter->first->setOrigColumns(rCols);
    }
}
// -----------------------------------------------------------------------------
<|endoftext|>