<commit_before>/*************************************************************************
 *
 *  $RCSfile: printfun.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2003-11-24 17:27:13 $
 *
 *  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 SC_PRINTFUN_HXX
#define SC_PRINTFUN_HXX

#ifndef SC_PAGEPAR_HXX
#include "pagepar.hxx"
#endif

#ifndef SC_EDITUTIL_HXX
#include "editutil.hxx"
#endif

#ifndef _PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif

class SfxPrinter;
class SfxProgress;
class ScDocShell;
class ScDocument;
class ScViewData;
class SfxItemSet;
class ScPageHFItem;
class EditTextObject;
class MultiSelection;
class ScHeaderEditEngine;
class ScPageBreakData;
class ScPreviewLocationData;
class ScPrintOptions;
class SvxBoxItem;
class SvxBrushItem;
class SvxShadowItem;
class FmFormView;

#define RANGENO_NORANGE             USHRT_MAX

#define PRINT_HEADER_WIDTH          (1.0 * TWIPS_PER_CM)
#define PRINT_HEADER_HEIGHT         (12.8 * TWIPS_PER_POINT)
#define PRINT_HEADER_FONTHEIGHT     200

                                            //  Einstellungen fuer Kopf-/Fusszeilen
struct ScPrintHFParam
{
    BOOL                bEnable;
    BOOL                bDynamic;
    BOOL                bShared;
    long                nHeight;            //  insgesamt (Hoehe+Abstand+Rahmen)
    long                nManHeight;         //  eingestellte Groesse (Min. bei dynamisch)
    USHORT              nDistance;
    USHORT              nLeft;              //  Raender
    USHORT              nRight;
    const ScPageHFItem* pLeft;
    const ScPageHFItem* pRight;
    const SvxBoxItem*   pBorder;
    const SvxBrushItem* pBack;
    const SvxShadowItem* pShadow;
};

// "Ersatz" fuer SV-JobSetup:

class ScJobSetup
{
public:
    ScJobSetup( SfxPrinter* pPrinter );

    Size        aUserSize;
    MapMode     aUserMapMode;
    Paper       ePaper;
    Orientation eOrientation;
    USHORT      nPaperBin;
};

struct ScPrintState                         //  Variablen aus ScPrintFunc retten
{
    USHORT  nPrintTab;
    USHORT  nStartCol;
    USHORT  nStartRow;
    USHORT  nEndCol;
    USHORT  nEndRow;
    USHORT  nZoom;
    USHORT  nPagesX;
    USHORT  nPagesY;
    long    nTabPages;
    long    nTotalPages;
    long    nPageStart;
    long    nDocPages;
};

class ScPageRowEntry
{
private:
    USHORT  nStartRow;
    USHORT  nEndRow;
    USHORT  nPagesX;
    BOOL*   pHidden;
    //!     Anzahl wirklich sichtbarer cachen???

public:
            ScPageRowEntry()    { nStartRow = nEndRow = nPagesX = 0; pHidden = NULL; }
            ~ScPageRowEntry()   { delete[] pHidden; }

            ScPageRowEntry(const ScPageRowEntry& r);
    const ScPageRowEntry& operator=(const ScPageRowEntry& r);

    USHORT  GetStartRow() const     { return nStartRow; }
    USHORT  GetEndRow() const       { return nEndRow; }
    USHORT  GetPagesX() const       { return nPagesX; }
    void    SetStartRow(USHORT n)   { nStartRow = n; }
    void    SetEndRow(USHORT n)     { nEndRow = n; }

    void    SetPagesX(USHORT nNew);
    void    SetHidden(USHORT nX);
    BOOL    IsHidden(USHORT nX) const;

    USHORT  CountVisible() const;
};

class ScPrintFunc
{
private:
    ScDocShell*         pDocShell;
    ScDocument*         pDoc;
    SfxPrinter*         pPrinter;
    OutputDevice*       pDev;
    FmFormView*         pDrawView;

    MapMode             aOldPrinterMode;    //  MapMode vor dem Aufruf

    Point               aSrcOffset;         //  Papier-1/100 mm
    Point               aOffset;            //  mit Faktor aus Seitenformat skaliert
    USHORT              nManualZoom;        //  Zoom in Preview (Prozent)
    BOOL                bClearWin;          //  Ausgabe vorher loeschen
    BOOL                bUseStyleColor;
    BOOL                bIsRender;

    USHORT              nPrintTab;
    long                nPageStart;         //  Offset fuer erste Seite
    long                nDocPages;          //  Seiten im Dokument

    const ScRange*      pUserArea;          //  Selektion, wenn im Dialog eingestellt

    const SfxItemSet*   pParamSet;          //  eingestellte Vorlage
    BOOL                bState;             //  aus State-struct erzeugt

                                            //  Parameter aus Vorlage:
    USHORT              nLeftMargin;
    USHORT              nTopMargin;
    USHORT              nRightMargin;
    USHORT              nBottomMargin;
    BOOL                bCenterHor;
    BOOL                bCenterVer;
    BOOL                bLandscape;
    BOOL                bSourceRangeValid;

    USHORT              nPageUsage;
    Size                aPageSize;          //  Drucker-Twips
    const SvxBoxItem*   pBorderItem;
    const SvxBrushItem* pBackgroundItem;
    const SvxShadowItem* pShadowItem;

    ScRange             aLastSourceRange;
    ScPrintHFParam      aHdr;
    ScPrintHFParam      aFtr;
    ScPageTableParam    aTableParam;
    ScPageAreaParam     aAreaParam;

                                            //  berechnete Werte:
    USHORT              nZoom;
    BOOL                bPrintCurrentTable;
    BOOL                bMultiArea;
    long                nTabPages;
    long                nTotalPages;

    // #109985#
    // see new defines in svx containing SDRPAINTMODE_SC_
    sal_uInt16          mnPaintMode;
    //USHORT                nObjectFlags;

    Rectangle           aPageRect;          //  Dokument-Twips

    MapMode             aLogicMode;         //  in DoPrint gesetzt
    MapMode             aOffsetMode;
    MapMode             aTwipMode;
    double              nScaleX;
    double              nScaleY;

    USHORT              nRepeatStartCol;
    USHORT              nRepeatEndCol;
    USHORT              nRepeatStartRow;
    USHORT              nRepeatEndRow;

    USHORT              nStartCol;
    USHORT              nStartRow;
    USHORT              nEndCol;
    USHORT              nEndRow;

    USHORT*             pPageEndX;          // Seitenaufteilung
    USHORT*             pPageEndY;
    ScPageRowEntry*     pPageRows;
    USHORT              nPagesX;
    USHORT              nPagesY;
    USHORT              nTotalY;

    ScHeaderEditEngine* pEditEngine;
    SfxItemSet*         pEditDefaults;

    ScHeaderFieldData   aFieldData;

    List                aNotePosList;       //  Reihenfolge der Notizen

    ScPageBreakData*    pPageData;          // zum Eintragen der Umbrueche etc.

public:
                    ScPrintFunc( ScDocShell* pShell, SfxPrinter* pNewPrinter, USHORT nTab,
                                 long nPage = 0, long nDocP = 0,
                                 const ScRange* pArea = NULL,
                                 const ScPrintOptions* pOptions = NULL,
                                 ScPageBreakData* pData = NULL );

                    // ctors for device other than printer - for preview and pdf:

                    ScPrintFunc( OutputDevice* pOutDev, ScDocShell* pShell, USHORT nTab,
                                 long nPage = 0, long nDocP = 0,
                                 const ScRange* pArea = NULL,
                                 const ScPrintOptions* pOptions = NULL );

                    ScPrintFunc( OutputDevice* pOutDev, ScDocShell* pShell,
                                 const ScPrintState& rState,
                                 const ScPrintOptions* pOptions );

                    ~ScPrintFunc();

    static void     DrawToDev( ScDocument* pDoc, OutputDevice* pDev, double nPrintFactor,
                                const Rectangle& rBound, ScViewData* pViewData, BOOL bMetaFile );

    void            SetDrawView( FmFormView* pNew );

    void            SetOffset( const Point& rOfs );
    void            SetManualZoom( USHORT nNewZoom );
    void            SetDateTime( const Date& rDate, const Time& rTime );

    void            SetClearFlag( BOOL bFlag );
    void            SetUseStyleColor( BOOL bFlag );
    void            SetRenderFlag( BOOL bFlag );

    BOOL            UpdatePages();

    void            ApplyPrintSettings();       // aus DoPrint() schon gerufen
    long            DoPrint( const MultiSelection& rPageRanges,
                                long nStartPage, long nDisplayStart, BOOL bDoPrint,
                                SfxProgress* pProgress, ScPreviewLocationData* pLocationData );

                    //  Werte abfragen - sofort

    Size            GetPageSize() const { return aPageSize; }
    Size            GetDataSize() const;
    void            GetScaleData( Size& rPhysSize, long& rDocHdr, long& rDocFtr );
    long            GetFirstPageNo() const  { return aTableParam.nFirstPageNo; }

                    //  letzte Werte abfragen - nach DoPrint !!!

    double          GetScaleX() const { return nScaleX; }
    double          GetScaleY() const { return nScaleY; }
    long            GetTotalPages() const { return nTotalPages; }
    USHORT          GetZoom() const { return nZoom; }

    void            ResetBreaks( USHORT nTab );

    void            GetPrintState( ScPrintState& rState );
    BOOL            GetLastSourceRange( ScRange& rRange ) const;

#ifdef _PRINTFUN_CXX
private:
    void            Construct( const ScPrintOptions* pOptions );
    void            InitParam( const ScPrintOptions* pOptions );
    void            CalcZoom( USHORT nRangeNo );
    void            CalcPages();
    long            CountPages();
    long            CountNotePages();

    BOOL            AdjustPrintArea( BOOL bNew );

    Size            GetDocPageSize();

    long            TextHeight( const EditTextObject* pObject );
    void            MakeEditEngine();
    void            UpdateHFHeight( ScPrintHFParam& rParam );

    void            InitModes();

    BOOL            IsLeft( long nPageNo );
    BOOL            IsMirror( long nPageNo );
    void            ReplaceFields( long nPageNo );      // aendert Text in pEditEngine
    void            MakeTableString();                  // setzt aTableStr

    void            PrintPage( long nPageNo,
                                    USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2,
                                    BOOL bDoPrint, ScPreviewLocationData* pLocationData );
    void            PrintArea( USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2,
                                    long nScrX, long nScrY,
                                    BOOL bShLeft, BOOL bShTop, BOOL bShRight, BOOL bShBottom );
    void            LocateArea( USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2,
                                    long nScrX, long nScrY, BOOL bRepCol, BOOL bRepRow,
                                    ScPreviewLocationData& rLocationData );
    void            PrintColHdr( USHORT nX1, USHORT nX2, long nScrX, long nScrY );
    void            PrintRowHdr( USHORT nY1, USHORT nY2, long nScrX, long nScrY );
    void            LocateColHdr( USHORT nX1, USHORT nX2, long nScrX, long nScrY,
                                BOOL bRepCol, ScPreviewLocationData& rLocationData );
    void            LocateRowHdr( USHORT nY1, USHORT nY2, long nScrX, long nScrY,
                                BOOL bRepRow, ScPreviewLocationData& rLocationData );
    void            PrintHF( long nPageNo, BOOL bHeader, long nStartY,
                                    BOOL bDoPrint, ScPreviewLocationData* pLocationData );

    long            PrintNotes( long nPageNo, long nNoteStart, BOOL bDoPrint, ScPreviewLocationData* pLocationData );
    long            DoNotes( long nNoteStart, BOOL bDoPrint, ScPreviewLocationData* pLocationData );

    void            DrawBorder( long nScrX, long nScrY, long nScrW, long nScrH,
                                    const SvxBoxItem* pBorderData,
                                    const SvxBrushItem* pBackground,
                                    const SvxShadowItem* pShadow );

    void            FillPageData();
#endif
};

#endif

<commit_msg>INTEGRATION: CWS sab008 (1.8.104); FILE MERGED 2004/01/26 10:30:03 sab 1.8.104.2: RESYNC: (1.8-1.9); FILE MERGED 2003/08/29 12:03:40 dr 1.8.104.1: #i8868# 1st prototype: scale printout to width/height<commit_after>/*************************************************************************
 *
 *  $RCSfile: printfun.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-19 16:13:24 $
 *
 *  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 SC_PRINTFUN_HXX
#define SC_PRINTFUN_HXX

#ifndef SC_PAGEPAR_HXX
#include "pagepar.hxx"
#endif

#ifndef SC_EDITUTIL_HXX
#include "editutil.hxx"
#endif

#ifndef _PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif

class SfxPrinter;
class SfxProgress;
class ScDocShell;
class ScDocument;
class ScViewData;
class SfxItemSet;
class ScPageHFItem;
class EditTextObject;
class MultiSelection;
class ScHeaderEditEngine;
class ScPageBreakData;
class ScPreviewLocationData;
class ScPrintOptions;
class SvxBoxItem;
class SvxBrushItem;
class SvxShadowItem;
class FmFormView;

#define RANGENO_NORANGE             USHRT_MAX

#define PRINT_HEADER_WIDTH          (1.0 * TWIPS_PER_CM)
#define PRINT_HEADER_HEIGHT         (12.8 * TWIPS_PER_POINT)
#define PRINT_HEADER_FONTHEIGHT     200

                                            //  Einstellungen fuer Kopf-/Fusszeilen
struct ScPrintHFParam
{
    BOOL                bEnable;
    BOOL                bDynamic;
    BOOL                bShared;
    long                nHeight;            //  insgesamt (Hoehe+Abstand+Rahmen)
    long                nManHeight;         //  eingestellte Groesse (Min. bei dynamisch)
    USHORT              nDistance;
    USHORT              nLeft;              //  Raender
    USHORT              nRight;
    const ScPageHFItem* pLeft;
    const ScPageHFItem* pRight;
    const SvxBoxItem*   pBorder;
    const SvxBrushItem* pBack;
    const SvxShadowItem* pShadow;
};

// "Ersatz" fuer SV-JobSetup:

class ScJobSetup
{
public:
    ScJobSetup( SfxPrinter* pPrinter );

    Size        aUserSize;
    MapMode     aUserMapMode;
    Paper       ePaper;
    Orientation eOrientation;
    USHORT      nPaperBin;
};

struct ScPrintState                         //  Variablen aus ScPrintFunc retten
{
    USHORT  nPrintTab;
    USHORT  nStartCol;
    USHORT  nStartRow;
    USHORT  nEndCol;
    USHORT  nEndRow;
    USHORT  nZoom;
    USHORT  nPagesX;
    USHORT  nPagesY;
    long    nTabPages;
    long    nTotalPages;
    long    nPageStart;
    long    nDocPages;
};

class ScPageRowEntry
{
private:
    USHORT  nStartRow;
    USHORT  nEndRow;
    USHORT  nPagesX;
    BOOL*   pHidden;
    //!     Anzahl wirklich sichtbarer cachen???

public:
            ScPageRowEntry()    { nStartRow = nEndRow = nPagesX = 0; pHidden = NULL; }
            ~ScPageRowEntry()   { delete[] pHidden; }

            ScPageRowEntry(const ScPageRowEntry& r);
    const ScPageRowEntry& operator=(const ScPageRowEntry& r);

    USHORT  GetStartRow() const     { return nStartRow; }
    USHORT  GetEndRow() const       { return nEndRow; }
    USHORT  GetPagesX() const       { return nPagesX; }
    void    SetStartRow(USHORT n)   { nStartRow = n; }
    void    SetEndRow(USHORT n)     { nEndRow = n; }

    void    SetPagesX(USHORT nNew);
    void    SetHidden(USHORT nX);
    BOOL    IsHidden(USHORT nX) const;

    USHORT  CountVisible() const;
};

class ScPrintFunc
{
private:
    ScDocShell*         pDocShell;
    ScDocument*         pDoc;
    SfxPrinter*         pPrinter;
    OutputDevice*       pDev;
    FmFormView*         pDrawView;

    MapMode             aOldPrinterMode;    //  MapMode vor dem Aufruf

    Point               aSrcOffset;         //  Papier-1/100 mm
    Point               aOffset;            //  mit Faktor aus Seitenformat skaliert
    USHORT              nManualZoom;        //  Zoom in Preview (Prozent)
    BOOL                bClearWin;          //  Ausgabe vorher loeschen
    BOOL                bUseStyleColor;
    BOOL                bIsRender;

    USHORT              nPrintTab;
    long                nPageStart;         //  Offset fuer erste Seite
    long                nDocPages;          //  Seiten im Dokument

    const ScRange*      pUserArea;          //  Selektion, wenn im Dialog eingestellt

    const SfxItemSet*   pParamSet;          //  eingestellte Vorlage
    BOOL                bState;             //  aus State-struct erzeugt

                                            //  Parameter aus Vorlage:
    USHORT              nLeftMargin;
    USHORT              nTopMargin;
    USHORT              nRightMargin;
    USHORT              nBottomMargin;
    BOOL                bCenterHor;
    BOOL                bCenterVer;
    BOOL                bLandscape;
    BOOL                bSourceRangeValid;

    USHORT              nPageUsage;
    Size                aPageSize;          //  Drucker-Twips
    const SvxBoxItem*   pBorderItem;
    const SvxBrushItem* pBackgroundItem;
    const SvxShadowItem* pShadowItem;

    ScRange             aLastSourceRange;
    ScPrintHFParam      aHdr;
    ScPrintHFParam      aFtr;
    ScPageTableParam    aTableParam;
    ScPageAreaParam     aAreaParam;

                                            //  berechnete Werte:
    USHORT              nZoom;
    BOOL                bPrintCurrentTable;
    BOOL                bMultiArea;
    long                nTabPages;
    long                nTotalPages;

    // #109985#
    // see new defines in svx containing SDRPAINTMODE_SC_
    sal_uInt16          mnPaintMode;
    //USHORT                nObjectFlags;

    Rectangle           aPageRect;          //  Dokument-Twips

    MapMode             aLogicMode;         //  in DoPrint gesetzt
    MapMode             aOffsetMode;
    MapMode             aTwipMode;
    double              nScaleX;
    double              nScaleY;

    USHORT              nRepeatStartCol;
    USHORT              nRepeatEndCol;
    USHORT              nRepeatStartRow;
    USHORT              nRepeatEndRow;

    USHORT              nStartCol;
    USHORT              nStartRow;
    USHORT              nEndCol;
    USHORT              nEndRow;

    USHORT*             pPageEndX;          // Seitenaufteilung
    USHORT*             pPageEndY;
    ScPageRowEntry*     pPageRows;
    USHORT              nPagesX;
    USHORT              nPagesY;
    USHORT              nTotalY;

    ScHeaderEditEngine* pEditEngine;
    SfxItemSet*         pEditDefaults;

    ScHeaderFieldData   aFieldData;

    List                aNotePosList;       //  Reihenfolge der Notizen

    ScPageBreakData*    pPageData;          // zum Eintragen der Umbrueche etc.

public:
                    ScPrintFunc( ScDocShell* pShell, SfxPrinter* pNewPrinter, USHORT nTab,
                                 long nPage = 0, long nDocP = 0,
                                 const ScRange* pArea = NULL,
                                 const ScPrintOptions* pOptions = NULL,
                                 ScPageBreakData* pData = NULL );

                    // ctors for device other than printer - for preview and pdf:

                    ScPrintFunc( OutputDevice* pOutDev, ScDocShell* pShell, USHORT nTab,
                                 long nPage = 0, long nDocP = 0,
                                 const ScRange* pArea = NULL,
                                 const ScPrintOptions* pOptions = NULL );

                    ScPrintFunc( OutputDevice* pOutDev, ScDocShell* pShell,
                                 const ScPrintState& rState,
                                 const ScPrintOptions* pOptions );

                    ~ScPrintFunc();

    static void     DrawToDev( ScDocument* pDoc, OutputDevice* pDev, double nPrintFactor,
                                const Rectangle& rBound, ScViewData* pViewData, BOOL bMetaFile );

    void            SetDrawView( FmFormView* pNew );

    void            SetOffset( const Point& rOfs );
    void            SetManualZoom( USHORT nNewZoom );
    void            SetDateTime( const Date& rDate, const Time& rTime );

    void            SetClearFlag( BOOL bFlag );
    void            SetUseStyleColor( BOOL bFlag );
    void            SetRenderFlag( BOOL bFlag );

    BOOL            UpdatePages();

    void            ApplyPrintSettings();       // aus DoPrint() schon gerufen
    long            DoPrint( const MultiSelection& rPageRanges,
                                long nStartPage, long nDisplayStart, BOOL bDoPrint,
                                SfxProgress* pProgress, ScPreviewLocationData* pLocationData );

                    //  Werte abfragen - sofort

    Size            GetPageSize() const { return aPageSize; }
    Size            GetDataSize() const;
    void            GetScaleData( Size& rPhysSize, long& rDocHdr, long& rDocFtr );
    long            GetFirstPageNo() const  { return aTableParam.nFirstPageNo; }

                    //  letzte Werte abfragen - nach DoPrint !!!

    double          GetScaleX() const { return nScaleX; }
    double          GetScaleY() const { return nScaleY; }
    long            GetTotalPages() const { return nTotalPages; }
    USHORT          GetZoom() const { return nZoom; }

    void            ResetBreaks( USHORT nTab );

    void            GetPrintState( ScPrintState& rState );
    BOOL            GetLastSourceRange( ScRange& rRange ) const;

private:
    void            Construct( const ScPrintOptions* pOptions );
    void            InitParam( const ScPrintOptions* pOptions );
    void            CalcZoom( USHORT nRangeNo );
    void            CalcPages();
    long            CountPages();
    long            CountNotePages();

    BOOL            AdjustPrintArea( BOOL bNew );

    Size            GetDocPageSize();

    long            TextHeight( const EditTextObject* pObject );
    void            MakeEditEngine();
    void            UpdateHFHeight( ScPrintHFParam& rParam );

    void            InitModes();

    BOOL            IsLeft( long nPageNo );
    BOOL            IsMirror( long nPageNo );
    void            ReplaceFields( long nPageNo );      // aendert Text in pEditEngine
    void            MakeTableString();                  // setzt aTableStr

    void            PrintPage( long nPageNo,
                                    USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2,
                                    BOOL bDoPrint, ScPreviewLocationData* pLocationData );
    void            PrintArea( USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2,
                                    long nScrX, long nScrY,
                                    BOOL bShLeft, BOOL bShTop, BOOL bShRight, BOOL bShBottom );
    void            LocateArea( USHORT nX1, USHORT nY1, USHORT nX2, USHORT nY2,
                                    long nScrX, long nScrY, BOOL bRepCol, BOOL bRepRow,
                                    ScPreviewLocationData& rLocationData );
    void            PrintColHdr( USHORT nX1, USHORT nX2, long nScrX, long nScrY );
    void            PrintRowHdr( USHORT nY1, USHORT nY2, long nScrX, long nScrY );
    void            LocateColHdr( USHORT nX1, USHORT nX2, long nScrX, long nScrY,
                                BOOL bRepCol, ScPreviewLocationData& rLocationData );
    void            LocateRowHdr( USHORT nY1, USHORT nY2, long nScrX, long nScrY,
                                BOOL bRepRow, ScPreviewLocationData& rLocationData );
    void            PrintHF( long nPageNo, BOOL bHeader, long nStartY,
                                    BOOL bDoPrint, ScPreviewLocationData* pLocationData );

    long            PrintNotes( long nPageNo, long nNoteStart, BOOL bDoPrint, ScPreviewLocationData* pLocationData );
    long            DoNotes( long nNoteStart, BOOL bDoPrint, ScPreviewLocationData* pLocationData );

    void            DrawBorder( long nScrX, long nScrY, long nScrW, long nScrH,
                                    const SvxBoxItem* pBorderData,
                                    const SvxBrushItem* pBackground,
                                    const SvxShadowItem* pShadow );

    void            FillPageData();
};

#endif

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
//  TEST    Foundation::DataExchangeFormat::ObjectVariantMapper
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Configuration/Locale.h"
#include    "Stroika/Foundation/DataExchangeFormat/BadFormatException.h"
#include    "Stroika/Foundation/DataExchangeFormat/ObjectVariantMapper.h"
#include    "Stroika/Foundation/DataExchangeFormat/JSON/Reader.h"
#include    "Stroika/Foundation/DataExchangeFormat/JSON/Writer.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include    "Stroika/Foundation/IO/FileSystem/BinaryFileOutputStream.h"
#include    "Stroika/Foundation/Memory/VariantValue.h"
#include    "Stroika/Foundation/Streams/BasicBinaryInputOutputStream.h"
#include    "Stroika/Foundation/Math/Common.h"
#include    "Stroika/Foundation/Time/DateTime.h"

#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::DataExchangeFormat;

using   Memory::Byte;
using   Memory::VariantValue;
using   Time::DateTime;

namespace   {
    void    DoRegressionTests_SimpleRegisterEtc_1_ ()
    {
    }
}

namespace   {
    void    DoRegressionTests_SimpleMapToFromJSON_2_ ()
    {
        const bool kWrite2FileAsWell_ = false;      // just for debugging

        struct SharedContactsConfig_ {
            bool                        fEnabled;
            DateTime                    fLastSynchronizedAt;
            Mapping<String, String>     fThisPHRsIDToSharedContactID;

            SharedContactsConfig_ ()
                : fEnabled (false)
                , fLastSynchronizedAt ()
                , fThisPHRsIDToSharedContactID () {
            }

            bool operator== (const SharedContactsConfig_& rhs) const {
                return fEnabled == rhs.fEnabled and
                       fLastSynchronizedAt == rhs.fLastSynchronizedAt and
                       fThisPHRsIDToSharedContactID == rhs.fThisPHRsIDToSharedContactID
                       ;
            }
        };

        ObjectVariantMapper mapper;

        // register each of your mappable (even private) types
#if     qCompilerAndStdLib_Supports_initializer_lists
        mapper.RegisterClass<SharedContactsConfig_> (Sequence<ObjectVariantMapper::StructureFieldInfo> ( {
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
        }));
#else
        ObjectVariantMapper::StructureFieldInfo kInfo[] = {
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
        };
        mapper.RegisterClass<SharedContactsConfig_> (Sequence<ObjectVariantMapper::StructureFieldInfo> (std::begin (kInfo), std::end (kInfo)));
#endif

        bool newEnabled = true;
        SharedContactsConfig_   tmp;
        tmp.fEnabled = newEnabled;
        tmp.fThisPHRsIDToSharedContactID.Add (L"A", L"B");
        tmp.fLastSynchronizedAt = DateTime (Time::Date (Time::Year (1998), Time::MonthOfYear::eApril, Time::DayOfMonth::e11), Time::TimeOfDay::Parse (L"3pm", locale::classic ()));

        VariantValue v = mapper.FromObject  (tmp);

        // at this point - we should have VariantValue object with "Enabled" field.
        // This can then be serialized using

        Streams::BasicBinaryInputOutputStream   tmpStream;
        JSON::Writer ().Write (v, tmpStream);

        if (kWrite2FileAsWell_) {
            IO::FileSystem::BinaryFileOutputStream tmp (L"t.txt");
            JSON::Writer ().Write (v, tmp);
        }

        if (kWrite2FileAsWell_) {
            IO::FileSystem::BinaryFileInputStream tmp (L"t.txt");
            SharedContactsConfig_    tmp2 = mapper.ToObject<SharedContactsConfig_> (JSON::Reader ().Read (tmp));
        }

        // THEN deserialized, and mapped back to C++ object form
        SharedContactsConfig_    tmp2 = mapper.ToObject<SharedContactsConfig_> (JSON::Reader ().Read (tmpStream));
        VerifyTestResult (tmp2 == tmp);
    }
}

namespace   {
    void    DoRegressionTests_ ()
    {
        DoRegressionTests_SimpleRegisterEtc_1_ ();
        DoRegressionTests_SimpleMapToFromJSON_2_ ();
    }
}

int     main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<commit_msg>upped game on Tests/23/Test.cpp - writing to IO::FileSystem::BinaryFileInputStream<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
//  TEST    Foundation::DataExchangeFormat::ObjectVariantMapper
#include    "Stroika/Foundation/StroikaPreComp.h"

#include    "Stroika/Foundation/Configuration/Locale.h"
#include    "Stroika/Foundation/DataExchangeFormat/BadFormatException.h"
#include    "Stroika/Foundation/DataExchangeFormat/ObjectVariantMapper.h"
#include    "Stroika/Foundation/DataExchangeFormat/JSON/Reader.h"
#include    "Stroika/Foundation/DataExchangeFormat/JSON/Writer.h"
#include    "Stroika/Foundation/Debug/Assertions.h"
#include    "Stroika/Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include    "Stroika/Foundation/IO/FileSystem/BinaryFileOutputStream.h"
#include    "Stroika/Foundation/IO/FileSystem/WellKnownLocations.h"
#include    "Stroika/Foundation/Memory/VariantValue.h"
#include    "Stroika/Foundation/Streams/BasicBinaryInputOutputStream.h"
#include    "Stroika/Foundation/Math/Common.h"
#include    "Stroika/Foundation/Time/DateTime.h"

#include    "../TestHarness/TestHarness.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::DataExchangeFormat;

using   Memory::Byte;
using   Memory::VariantValue;
using   Time::DateTime;

namespace   {
    void    DoRegressionTests_SimpleRegisterEtc_1_ ()
    {
    }
}

namespace   {
    void    DoRegressionTests_SimpleMapToFromJSON_2_ ()
    {
        const bool kWrite2FileAsWell_ = true;      // just for debugging

        struct SharedContactsConfig_ {
            bool                        fEnabled;
            DateTime                    fLastSynchronizedAt;
            Mapping<String, String>     fThisPHRsIDToSharedContactID;

            SharedContactsConfig_ ()
                : fEnabled (false)
                , fLastSynchronizedAt ()
                , fThisPHRsIDToSharedContactID () {
            }

            bool operator== (const SharedContactsConfig_& rhs) const {
                return fEnabled == rhs.fEnabled and
                       fLastSynchronizedAt == rhs.fLastSynchronizedAt and
                       fThisPHRsIDToSharedContactID == rhs.fThisPHRsIDToSharedContactID
                       ;
            }
        };

        ObjectVariantMapper mapper;

        // register each of your mappable (even private) types
#if     qCompilerAndStdLib_Supports_initializer_lists
        mapper.RegisterClass<SharedContactsConfig_> (Sequence<ObjectVariantMapper::StructureFieldInfo> ( {
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
        }));
#else
        ObjectVariantMapper::StructureFieldInfo kInfo[] = {
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fEnabled, L"Enabled"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fLastSynchronizedAt, L"Last-Synchronized-At"),
            ObjectVariantMapper_StructureFieldInfo_Construction_Helper (SharedContactsConfig_, fThisPHRsIDToSharedContactID, L"This-HR-ContactID-To-SharedContactID-Map"),
        };
        mapper.RegisterClass<SharedContactsConfig_> (Sequence<ObjectVariantMapper::StructureFieldInfo> (std::begin (kInfo), std::end (kInfo)));
#endif

        bool newEnabled = true;
        SharedContactsConfig_   tmp;
        tmp.fEnabled = newEnabled;
        tmp.fThisPHRsIDToSharedContactID.Add (L"A", L"B");
        tmp.fLastSynchronizedAt = DateTime (Time::Date (Time::Year (1998), Time::MonthOfYear::eApril, Time::DayOfMonth::e11), Time::TimeOfDay::Parse (L"3pm", locale::classic ()));

        VariantValue v = mapper.FromObject  (tmp);

        // at this point - we should have VariantValue object with "Enabled" field.
        // This can then be serialized using

        Streams::BasicBinaryInputOutputStream   tmpStream;
        JSON::Writer ().Write (v, tmpStream);

        if (kWrite2FileAsWell_) {
            IO::FileSystem::BinaryFileOutputStream tmp (IO::FileSystem::WellKnownLocations::GetTemporary () + L"t.txt");
            JSON::Writer ().Write (v, tmp);
        }

        if (kWrite2FileAsWell_) {
            IO::FileSystem::BinaryFileInputStream tmp (IO::FileSystem::WellKnownLocations::GetTemporary () + L"t.txt");
            SharedContactsConfig_    tmp2 = mapper.ToObject<SharedContactsConfig_> (JSON::Reader ().Read (tmp));
        }

        // THEN deserialized, and mapped back to C++ object form
        SharedContactsConfig_    tmp2 = mapper.ToObject<SharedContactsConfig_> (JSON::Reader ().Read (tmpStream));
        VerifyTestResult (tmp2 == tmp);
    }
}

namespace   {
    void    DoRegressionTests_ ()
    {
        DoRegressionTests_SimpleRegisterEtc_1_ ();
        DoRegressionTests_SimpleMapToFromJSON_2_ ();
    }
}

int     main (int argc, const char* argv[])
{
    Stroika::TestHarness::Setup ();
    Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);
    return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>//
// Created by padeler on 3/8/2017.
//
/**
 * Code adapted for PyOpenPose from opencv cv2.cpp for use with boost::python
 */

#include "opencv_expose.h"

#include <Python.h>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>

#include <opencv2/opencv.hpp>

namespace bpy = boost::python;
using namespace cv;

static PyObject* opencv_error = 0;

int initialize_array()
{
    // XXX This is needed to initialize numpy. Otherwise: Silent segfault
    static bool init = false;
    if(!init)
    {
        init = true;
        import_array1(0);
        bpy::numeric::array::set_module_and_type("numpy", "ndarray");
        return 0;
    }
    return 1;
}

static int failmsg(const char *fmt, ...)
{
    char str[1000];

    va_list ap;
    va_start(ap, fmt);
    vsnprintf(str, sizeof(str), fmt, ap);
    va_end(ap);

    PyErr_SetString(PyExc_TypeError, str);
    return 0;
}

class PyAllowThreads
{
public:
    PyAllowThreads() : _state(PyEval_SaveThread()) {}
    ~PyAllowThreads()
    {
        PyEval_RestoreThread(_state);
    }
private:
    PyThreadState* _state;
};

class PyEnsureGIL
{
public:
    PyEnsureGIL() : _state(PyGILState_Ensure()) {}
    ~PyEnsureGIL()
    {
        PyGILState_Release(_state);
    }
private:
    PyGILState_STATE _state;
};

#define ERRWRAP2(expr) \
try \
{ \
    PyAllowThreads allowThreads; \
    expr; \
} \
catch (const cv::Exception &e) \
{ \
    PyErr_SetString(opencv_error, e.what()); \
    return 0; \
}

class NumpyAllocator : public MatAllocator
{
public:
    NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
    ~NumpyAllocator() {}

    UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
    {
        UMatData* u = new UMatData(this);
        u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*)o);
        npy_intp* _strides = PyArray_STRIDES((PyArrayObject*)o);
        for (int i = 0; i < dims - 1; i++)
            step[i] = (size_t)_strides[i];
        step[dims - 1] = CV_ELEM_SIZE(type);
        u->size = sizes[0] * step[0];
        u->userdata = o;
        return u;
    }

    UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
    {
        if (data != 0)
        {
            CV_Error(Error::StsAssert, "The data should normally be nullptr!");
            // probably this is safe to do in such extreme case
            return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
        }
        PyEnsureGIL gil;

        int depth = CV_MAT_DEPTH(type);
        int cn = CV_MAT_CN(type);
        const int f = (int)(sizeof(size_t) / 8);
        int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
                                                   depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
                                                                                depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
                                                                                depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f ^ 1)*NPY_UINT;
        int i, dims = dims0;
        cv::AutoBuffer<npy_intp> _sizes(dims + 1);
        for (i = 0; i < dims; i++)
            _sizes[i] = sizes[i];
        if (cn > 1)
            _sizes[dims++] = cn;
        PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
        if (!o)
            CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
        return allocate(o, dims0, sizes, type, step);
    }

    bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const
    {
        return stdAllocator->allocate(u, accessFlags, usageFlags);
    }

    void deallocate(UMatData* u) const
    {
        if (!u)
            return;
        PyEnsureGIL gil;
        CV_Assert(u->urefcount >= 0);
        CV_Assert(u->refcount >= 0);
        if (u->refcount == 0)
        {
            PyObject* o = (PyObject*)u->userdata;
            Py_XDECREF(o);
            delete u;
        }
    }

    const MatAllocator* stdAllocator;
};

NumpyAllocator g_numpyAllocator;

static PyObject* pyopencv_from(const cv::Mat& m)
{
    if (!m.data)
        Py_RETURN_NONE;
    Mat temp, *p = (Mat*)&m;
    if (!p->u || p->allocator != &g_numpyAllocator)
    {
        temp.allocator = &g_numpyAllocator;
        ERRWRAP2(m.copyTo(temp));
        p = &temp;
    }
    PyObject* o = (PyObject*)p->u->userdata;
    Py_INCREF(o);
    return o;
}

static bool pyopencv_to(PyObject* o, Mat& m, const char* name = "<unknown>")
{
    bool allowND = true;
    if (!o || o == Py_None)
    {
        if (!m.data)
            m.allocator = &g_numpyAllocator;
        return true;
    }

    if (PyInt_Check(o))
    {
        double v[] = { static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0. };
        m = Mat(4, 1, CV_64F, v).clone();
        return true;
    }
    if (PyFloat_Check(o))
    {
        double v[] = { PyFloat_AsDouble((PyObject*)o), 0., 0., 0. };
        m = Mat(4, 1, CV_64F, v).clone();
        return true;
    }
    if (PyTuple_Check(o))
    {
        int i, sz = (int)PyTuple_Size((PyObject*)o);
        m = Mat(sz, 1, CV_64F);
        for (i = 0; i < sz; i++)
        {
            PyObject* oi = PyTuple_GET_ITEM(o, i);
            if (PyInt_Check(oi))
                m.at<double>(i) = (double)PyInt_AsLong(oi);
            else if (PyFloat_Check(oi))
                m.at<double>(i) = (double)PyFloat_AsDouble(oi);
            else
            {
                failmsg("%s is not a numerical tuple", name);
                m.release();
                return false;
            }
        }
        return true;
    }

    if (!PyArray_Check(o))
    {
        failmsg("%s is not a numpy array, neither a scalar", name);
        return false;
    }

    PyArrayObject* oarr = (PyArrayObject*)o;

    bool needcopy = false, needcast = false;
    int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
    int type = typenum == NPY_UBYTE ? CV_8U :
               typenum == NPY_BYTE ? CV_8S :
               typenum == NPY_USHORT ? CV_16U :
               typenum == NPY_SHORT ? CV_16S :
               typenum == NPY_INT ? CV_32S :
               typenum == NPY_INT32 ? CV_32S :
               typenum == NPY_FLOAT ? CV_32F :
               typenum == NPY_DOUBLE ? CV_64F : -1;

    if (type < 0)
    {
        if (typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG)
        {
            needcopy = needcast = true;
            new_typenum = NPY_INT;
            type = CV_32S;
        }
        else
        {
            failmsg("%s data type = %d is not supported", name, typenum);
            return false;
        }
    }

#ifndef CV_MAX_DIM
    const int CV_MAX_DIM = 32;
#endif

    int ndims = PyArray_NDIM(oarr);
    if (ndims >= CV_MAX_DIM)
    {
        failmsg("%s dimensionality (=%d) is too high", name, ndims);
        return false;
    }

    int size[CV_MAX_DIM + 1];
    size_t step[CV_MAX_DIM + 1];
    size_t elemsize = CV_ELEM_SIZE1(type);
    const npy_intp* _sizes = PyArray_DIMS(oarr);
    const npy_intp* _strides = PyArray_STRIDES(oarr);
    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;

    for (int i = ndims - 1; i >= 0 && !needcopy; i--)
    {
        // these checks handle cases of
        //  a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
        //  b) transposed arrays, where _strides[] elements go in non-descending order
        //  c) flipped arrays, where some of _strides[] elements are negative
        // the _sizes[i] > 1 is needed to avoid spurious copies when NPY_RELAXED_STRIDES is set
        if ((i == ndims - 1 && _sizes[i] > 1 && (size_t)_strides[i] != elemsize) ||
            (i < ndims - 1 && _sizes[i] > 1 && _strides[i] < _strides[i + 1]))
            needcopy = true;
    }

    if (ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2])
        needcopy = true;

    if (needcopy)
    {
        if (needcast) {
            o = PyArray_Cast(oarr, new_typenum);
            oarr = (PyArrayObject*)o;
        }
        else {
            oarr = PyArray_GETCONTIGUOUS(oarr);
            o = (PyObject*)oarr;
        }

        _strides = PyArray_STRIDES(oarr);
    }

    // Normalize strides in case NPY_RELAXED_STRIDES is set
    size_t default_step = elemsize;
    for (int i = ndims - 1; i >= 0; --i)
    {
        size[i] = (int)_sizes[i];
        if (size[i] > 1)
        {
            step[i] = (size_t)_strides[i];
            default_step = step[i] * size[i];
        }
        else
        {
            step[i] = default_step;
            default_step *= size[i];
        }
    }

    // handle degenerate case
    if (ndims == 0) {
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }

    if (ismultichannel)
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }

    if (ndims > 2 && !allowND)
    {
        failmsg("%s has more than 2 dimensions", name);
        return false;
    }

    m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
    m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
    m.addref();

    if (!needcopy)
    {
        Py_INCREF(o);
    }
    m.allocator = &g_numpyAllocator;

    return true;
}

struct PythonConverterForSize
{
    PythonConverterForSize()
    {
        bpy::converter::registry::push_back(
                &convertible,
                &construct,
                bpy::type_id<cv::Size>());
        bpy::to_python_converter<cv::Size, PythonConverterForSize, false>();
    }

    static PyObject* convert(const cv::Size &t)
    {
        return Py_BuildValue("(ii)", t.width, t.height);
    }

    static bool pyopencv_to(PyObject* obj, cv::Size& sz)
    {
        if (!obj || obj == Py_None)
            return true;
        return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
    }

    static void* convertible(PyObject *obj)
    {
        cv::Size tmp;
        return pyopencv_to(obj, tmp) ? obj : nullptr;
    }

    static void construct(PyObject * obj, bpy::converter::rvalue_from_python_stage1_data* data)
    {
        cv::Size *t = new cv::Size;
        pyopencv_to(obj, *t);
        data->convertible = t;
    }
};

struct PythonConverterForMat
{
    PythonConverterForMat()
    {
        bpy::converter::registry::push_back(
                &convertible,
                &construct,
                bpy::type_id<cv::Mat>());
        bpy::to_python_converter<cv::Mat, PythonConverterForMat, false>();
    }

    static PyObject* convert(const cv::Mat& m)
    {
        initialize_array();
        return pyopencv_from(m);
    }

    static bool is_convertible(const bpy::object &o)
    {
        return PyArray_Check(o.ptr());
    }

    // Convert obj_ptr into a QString
    static void construct_from(const bpy::object &o, cv::Mat *storage)
    {
        cv::Mat value;
        pyopencv_to(o.ptr(), value);
        new (storage) cv::Mat(value);
    }

    static void * convertible(PyObject *obj)
    {
        return is_convertible(bpy::object(bpy::handle<>(bpy::borrowed(obj)))) ? obj : 0;
    }

    static void construct(PyObject *obj, bpy::converter::rvalue_from_python_stage1_data *data)
    {
        void *storage = ((bpy::converter::rvalue_from_python_storage<cv::Mat>*)data)->storage.bytes;
        construct_from(bpy::object(bpy::handle<>(bpy::borrowed(obj))), (cv::Mat*)storage);
        data->convertible = storage;
    }
};

struct MatVectorToPython
{
    static PyObject* pyopencv_from_vec(const std::vector<cv::Mat>& value)
    {
        int i, n = (int)value.size();
        PyObject* seq = PyList_New(n);
        for (i = 0; i < n; i++)
        {
            PyObject* item = pyopencv_from(value[i]);
            if (!item)
                break;
            PyList_SET_ITEM(seq, i, item);
        }
        if (i < n)
        {
            Py_DECREF(seq);
            return 0;
        }
        return seq;
    }

    static PyObject* convert(const std::vector<cv::Mat> &m)
    {
        return pyopencv_from_vec(m);
    }
};

void expose_opencv()
{

    initialize_array();

    PythonConverterForMat();
    PythonConverterForSize();

    bpy::to_python_converter<std::vector< cv::Mat >, MatVectorToPython, false>();
}<commit_msg>fix issue https://github.com/FORTH-ModelBasedTracker/PyOpenPose/issues/23<commit_after>//
// Created by padeler on 3/8/2017.
//
/**
 * Code adapted for PyOpenPose from opencv cv2.cpp for use with boost::python
 */

#include "opencv_expose.h"

#include <Python.h>

#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>

#include <opencv2/opencv.hpp>

namespace bpy = boost::python;
using namespace cv;

static PyObject* opencv_error = 0;

int initialize_array()
{
    // XXX This is needed to initialize numpy. Otherwise: Silent segfault
    static bool init = false;
    if(!init)
    {
        init = true;
        import_array1(0);
        return 0;
    }
    return 1;
}

static int failmsg(const char *fmt, ...)
{
    char str[1000];

    va_list ap;
    va_start(ap, fmt);
    vsnprintf(str, sizeof(str), fmt, ap);
    va_end(ap);

    PyErr_SetString(PyExc_TypeError, str);
    return 0;
}

class PyAllowThreads
{
public:
    PyAllowThreads() : _state(PyEval_SaveThread()) {}
    ~PyAllowThreads()
    {
        PyEval_RestoreThread(_state);
    }
private:
    PyThreadState* _state;
};

class PyEnsureGIL
{
public:
    PyEnsureGIL() : _state(PyGILState_Ensure()) {}
    ~PyEnsureGIL()
    {
        PyGILState_Release(_state);
    }
private:
    PyGILState_STATE _state;
};

#define ERRWRAP2(expr) \
try \
{ \
    PyAllowThreads allowThreads; \
    expr; \
} \
catch (const cv::Exception &e) \
{ \
    PyErr_SetString(opencv_error, e.what()); \
    return 0; \
}

class NumpyAllocator : public MatAllocator
{
public:
    NumpyAllocator() { stdAllocator = Mat::getStdAllocator(); }
    ~NumpyAllocator() {}

    UMatData* allocate(PyObject* o, int dims, const int* sizes, int type, size_t* step) const
    {
        UMatData* u = new UMatData(this);
        u->data = u->origdata = (uchar*)PyArray_DATA((PyArrayObject*)o);
        npy_intp* _strides = PyArray_STRIDES((PyArrayObject*)o);
        for (int i = 0; i < dims - 1; i++)
            step[i] = (size_t)_strides[i];
        step[dims - 1] = CV_ELEM_SIZE(type);
        u->size = sizes[0] * step[0];
        u->userdata = o;
        return u;
    }

    UMatData* allocate(int dims0, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
    {
        if (data != 0)
        {
            CV_Error(Error::StsAssert, "The data should normally be nullptr!");
            // probably this is safe to do in such extreme case
            return stdAllocator->allocate(dims0, sizes, type, data, step, flags, usageFlags);
        }
        PyEnsureGIL gil;

        int depth = CV_MAT_DEPTH(type);
        int cn = CV_MAT_CN(type);
        const int f = (int)(sizeof(size_t) / 8);
        int typenum = depth == CV_8U ? NPY_UBYTE : depth == CV_8S ? NPY_BYTE :
                                                   depth == CV_16U ? NPY_USHORT : depth == CV_16S ? NPY_SHORT :
                                                                                depth == CV_32S ? NPY_INT : depth == CV_32F ? NPY_FLOAT :
                                                                                depth == CV_64F ? NPY_DOUBLE : f*NPY_ULONGLONG + (f ^ 1)*NPY_UINT;
        int i, dims = dims0;
        cv::AutoBuffer<npy_intp> _sizes(dims + 1);
        for (i = 0; i < dims; i++)
            _sizes[i] = sizes[i];
        if (cn > 1)
            _sizes[dims++] = cn;
        PyObject* o = PyArray_SimpleNew(dims, _sizes, typenum);
        if (!o)
            CV_Error_(Error::StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims));
        return allocate(o, dims0, sizes, type, step);
    }

    bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const
    {
        return stdAllocator->allocate(u, accessFlags, usageFlags);
    }

    void deallocate(UMatData* u) const
    {
        if (!u)
            return;
        PyEnsureGIL gil;
        CV_Assert(u->urefcount >= 0);
        CV_Assert(u->refcount >= 0);
        if (u->refcount == 0)
        {
            PyObject* o = (PyObject*)u->userdata;
            Py_XDECREF(o);
            delete u;
        }
    }

    const MatAllocator* stdAllocator;
};

NumpyAllocator g_numpyAllocator;

static PyObject* pyopencv_from(const cv::Mat& m)
{
    if (!m.data)
        Py_RETURN_NONE;
    Mat temp, *p = (Mat*)&m;
    if (!p->u || p->allocator != &g_numpyAllocator)
    {
        temp.allocator = &g_numpyAllocator;
        ERRWRAP2(m.copyTo(temp));
        p = &temp;
    }
    PyObject* o = (PyObject*)p->u->userdata;
    Py_INCREF(o);
    return o;
}

static bool pyopencv_to(PyObject* o, Mat& m, const char* name = "<unknown>")
{
    bool allowND = true;
    if (!o || o == Py_None)
    {
        if (!m.data)
            m.allocator = &g_numpyAllocator;
        return true;
    }

    if (PyInt_Check(o))
    {
        double v[] = { static_cast<double>(PyInt_AsLong((PyObject*)o)), 0., 0., 0. };
        m = Mat(4, 1, CV_64F, v).clone();
        return true;
    }
    if (PyFloat_Check(o))
    {
        double v[] = { PyFloat_AsDouble((PyObject*)o), 0., 0., 0. };
        m = Mat(4, 1, CV_64F, v).clone();
        return true;
    }
    if (PyTuple_Check(o))
    {
        int i, sz = (int)PyTuple_Size((PyObject*)o);
        m = Mat(sz, 1, CV_64F);
        for (i = 0; i < sz; i++)
        {
            PyObject* oi = PyTuple_GET_ITEM(o, i);
            if (PyInt_Check(oi))
                m.at<double>(i) = (double)PyInt_AsLong(oi);
            else if (PyFloat_Check(oi))
                m.at<double>(i) = (double)PyFloat_AsDouble(oi);
            else
            {
                failmsg("%s is not a numerical tuple", name);
                m.release();
                return false;
            }
        }
        return true;
    }

    if (!PyArray_Check(o))
    {
        failmsg("%s is not a numpy array, neither a scalar", name);
        return false;
    }

    PyArrayObject* oarr = (PyArrayObject*)o;

    bool needcopy = false, needcast = false;
    int typenum = PyArray_TYPE(oarr), new_typenum = typenum;
    int type = typenum == NPY_UBYTE ? CV_8U :
               typenum == NPY_BYTE ? CV_8S :
               typenum == NPY_USHORT ? CV_16U :
               typenum == NPY_SHORT ? CV_16S :
               typenum == NPY_INT ? CV_32S :
               typenum == NPY_INT32 ? CV_32S :
               typenum == NPY_FLOAT ? CV_32F :
               typenum == NPY_DOUBLE ? CV_64F : -1;

    if (type < 0)
    {
        if (typenum == NPY_INT64 || typenum == NPY_UINT64 || typenum == NPY_LONG)
        {
            needcopy = needcast = true;
            new_typenum = NPY_INT;
            type = CV_32S;
        }
        else
        {
            failmsg("%s data type = %d is not supported", name, typenum);
            return false;
        }
    }

#ifndef CV_MAX_DIM
    const int CV_MAX_DIM = 32;
#endif

    int ndims = PyArray_NDIM(oarr);
    if (ndims >= CV_MAX_DIM)
    {
        failmsg("%s dimensionality (=%d) is too high", name, ndims);
        return false;
    }

    int size[CV_MAX_DIM + 1];
    size_t step[CV_MAX_DIM + 1];
    size_t elemsize = CV_ELEM_SIZE1(type);
    const npy_intp* _sizes = PyArray_DIMS(oarr);
    const npy_intp* _strides = PyArray_STRIDES(oarr);
    bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX;

    for (int i = ndims - 1; i >= 0 && !needcopy; i--)
    {
        // these checks handle cases of
        //  a) multi-dimensional (ndims > 2) arrays, as well as simpler 1- and 2-dimensional cases
        //  b) transposed arrays, where _strides[] elements go in non-descending order
        //  c) flipped arrays, where some of _strides[] elements are negative
        // the _sizes[i] > 1 is needed to avoid spurious copies when NPY_RELAXED_STRIDES is set
        if ((i == ndims - 1 && _sizes[i] > 1 && (size_t)_strides[i] != elemsize) ||
            (i < ndims - 1 && _sizes[i] > 1 && _strides[i] < _strides[i + 1]))
            needcopy = true;
    }

    if (ismultichannel && _strides[1] != (npy_intp)elemsize*_sizes[2])
        needcopy = true;

    if (needcopy)
    {
        if (needcast) {
            o = PyArray_Cast(oarr, new_typenum);
            oarr = (PyArrayObject*)o;
        }
        else {
            oarr = PyArray_GETCONTIGUOUS(oarr);
            o = (PyObject*)oarr;
        }

        _strides = PyArray_STRIDES(oarr);
    }

    // Normalize strides in case NPY_RELAXED_STRIDES is set
    size_t default_step = elemsize;
    for (int i = ndims - 1; i >= 0; --i)
    {
        size[i] = (int)_sizes[i];
        if (size[i] > 1)
        {
            step[i] = (size_t)_strides[i];
            default_step = step[i] * size[i];
        }
        else
        {
            step[i] = default_step;
            default_step *= size[i];
        }
    }

    // handle degenerate case
    if (ndims == 0) {
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }

    if (ismultichannel)
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }

    if (ndims > 2 && !allowND)
    {
        failmsg("%s has more than 2 dimensions", name);
        return false;
    }

    m = Mat(ndims, size, type, PyArray_DATA(oarr), step);
    m.u = g_numpyAllocator.allocate(o, ndims, size, type, step);
    m.addref();

    if (!needcopy)
    {
        Py_INCREF(o);
    }
    m.allocator = &g_numpyAllocator;

    return true;
}

struct PythonConverterForSize
{
    PythonConverterForSize()
    {
        bpy::converter::registry::push_back(
                &convertible,
                &construct,
                bpy::type_id<cv::Size>());
        bpy::to_python_converter<cv::Size, PythonConverterForSize, false>();
    }

    static PyObject* convert(const cv::Size &t)
    {
        return Py_BuildValue("(ii)", t.width, t.height);
    }

    static bool pyopencv_to(PyObject* obj, cv::Size& sz)
    {
        if (!obj || obj == Py_None)
            return true;
        return PyArg_ParseTuple(obj, "ii", &sz.width, &sz.height) > 0;
    }

    static void* convertible(PyObject *obj)
    {
        cv::Size tmp;
        return pyopencv_to(obj, tmp) ? obj : nullptr;
    }

    static void construct(PyObject * obj, bpy::converter::rvalue_from_python_stage1_data* data)
    {
        cv::Size *t = new cv::Size;
        pyopencv_to(obj, *t);
        data->convertible = t;
    }
};

struct PythonConverterForMat
{
    PythonConverterForMat()
    {
        bpy::converter::registry::push_back(
                &convertible,
                &construct,
                bpy::type_id<cv::Mat>());
        bpy::to_python_converter<cv::Mat, PythonConverterForMat, false>();
    }

    static PyObject* convert(const cv::Mat& m)
    {
        initialize_array();
        return pyopencv_from(m);
    }

    static bool is_convertible(const bpy::object &o)
    {
        return PyArray_Check(o.ptr());
    }

    // Convert obj_ptr into a QString
    static void construct_from(const bpy::object &o, cv::Mat *storage)
    {
        cv::Mat value;
        pyopencv_to(o.ptr(), value);
        new (storage) cv::Mat(value);
    }

    static void * convertible(PyObject *obj)
    {
        return is_convertible(bpy::object(bpy::handle<>(bpy::borrowed(obj)))) ? obj : 0;
    }

    static void construct(PyObject *obj, bpy::converter::rvalue_from_python_stage1_data *data)
    {
        void *storage = ((bpy::converter::rvalue_from_python_storage<cv::Mat>*)data)->storage.bytes;
        construct_from(bpy::object(bpy::handle<>(bpy::borrowed(obj))), (cv::Mat*)storage);
        data->convertible = storage;
    }
};

struct MatVectorToPython
{
    static PyObject* pyopencv_from_vec(const std::vector<cv::Mat>& value)
    {
        int i, n = (int)value.size();
        PyObject* seq = PyList_New(n);
        for (i = 0; i < n; i++)
        {
            PyObject* item = pyopencv_from(value[i]);
            if (!item)
                break;
            PyList_SET_ITEM(seq, i, item);
        }
        if (i < n)
        {
            Py_DECREF(seq);
            return 0;
        }
        return seq;
    }

    static PyObject* convert(const std::vector<cv::Mat> &m)
    {
        return pyopencv_from_vec(m);
    }
};

void expose_opencv()
{

    initialize_array();

    PythonConverterForMat();
    PythonConverterForSize();

    bpy::to_python_converter<std::vector< cv::Mat >, MatVectorToPython, false>();
}<|endoftext|>


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

#include "chrome/browser/extensions/event_router_forwarder.h"

#include "base/bind.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/event_router.h"
#include "url/gurl.h"

using content::BrowserThread;

namespace extensions {

EventRouterForwarder::EventRouterForwarder() {
}

EventRouterForwarder::~EventRouterForwarder() {
}

void EventRouterForwarder::BroadcastEventToRenderers(
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    const GURL& event_url) {
  HandleEvent(std::string(), event_name, event_args.Pass(), 0, true, event_url);
}

void EventRouterForwarder::DispatchEventToRenderers(
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    void* profile,
    bool use_profile_to_restrict_events,
    const GURL& event_url) {
  if (!profile)
    return;
  HandleEvent(std::string(),
              event_name,
              event_args.Pass(),
              profile,
              use_profile_to_restrict_events,
              event_url);
}

void EventRouterForwarder::BroadcastEventToExtension(
    const std::string& extension_id,
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    const GURL& event_url) {
  HandleEvent(extension_id, event_name, event_args.Pass(), 0, true, event_url);
}

void EventRouterForwarder::DispatchEventToExtension(
    const std::string& extension_id,
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    void* profile,
    bool use_profile_to_restrict_events,
    const GURL& event_url) {
  if (!profile)
    return;
  HandleEvent(extension_id, event_name, event_args.Pass(), profile,
              use_profile_to_restrict_events, event_url);
}

void EventRouterForwarder::HandleEvent(const std::string& extension_id,
                                       const std::string& event_name,
                                       scoped_ptr<base::ListValue> event_args,
                                       void* profile_ptr,
                                       bool use_profile_to_restrict_events,
                                       const GURL& event_url) {
  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        base::Bind(&EventRouterForwarder::HandleEvent, this,
                   extension_id, event_name, base::Passed(&event_args),
                   profile_ptr, use_profile_to_restrict_events, event_url));
    return;
  }

  if (!g_browser_process || !g_browser_process->profile_manager())
    return;

  ProfileManager* profile_manager = g_browser_process->profile_manager();
  Profile* profile = NULL;
  if (profile_ptr) {
    profile = reinterpret_cast<Profile*>(profile_ptr);
    if (!profile_manager->IsValidProfile(profile))
      return;
  }
  if (profile) {
    CallEventRouter(profile, extension_id, event_name, event_args.Pass(),
                    use_profile_to_restrict_events ? profile : NULL, event_url);
  } else {
    std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
    for (size_t i = 0; i < profiles.size(); ++i) {
      scoped_ptr<base::ListValue> per_profile_event_args(
          event_args->DeepCopy());
      CallEventRouter(
          profiles[i], extension_id, event_name, per_profile_event_args.Pass(),
          use_profile_to_restrict_events ? profiles[i] : NULL, event_url);
    }
  }
}

void EventRouterForwarder::CallEventRouter(
    Profile* profile,
    const std::string& extension_id,
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    Profile* restrict_to_profile,
    const GURL& event_url) {
  // We may not have an extension in cases like chromeos login
  // (crosbug.com/12856), chrome_frame_net_tests.exe which reuses the chrome
  // browser single process framework.
  if (!extensions::ExtensionSystem::Get(profile)->event_router())
    return;

  scoped_ptr<Event> event(new Event(event_name, event_args.Pass()));
  event->restrict_to_browser_context = restrict_to_profile;
  event->event_url = event_url;
  if (extension_id.empty()) {
    ExtensionSystem::Get(profile)->event_router()->BroadcastEvent(event.Pass());
  } else {
    ExtensionSystem::Get(profile)->event_router()->
        DispatchEventToExtension(extension_id, event.Pass());
  }
}

}  // namespace extensions
<commit_msg>Revert hack introduced in r84247 to support Chrome Frame net tests.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/event_router_forwarder.h"

#include "base/bind.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/event_router.h"
#include "url/gurl.h"

using content::BrowserThread;

namespace extensions {

EventRouterForwarder::EventRouterForwarder() {
}

EventRouterForwarder::~EventRouterForwarder() {
}

void EventRouterForwarder::BroadcastEventToRenderers(
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    const GURL& event_url) {
  HandleEvent(std::string(), event_name, event_args.Pass(), 0, true, event_url);
}

void EventRouterForwarder::DispatchEventToRenderers(
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    void* profile,
    bool use_profile_to_restrict_events,
    const GURL& event_url) {
  if (!profile)
    return;
  HandleEvent(std::string(),
              event_name,
              event_args.Pass(),
              profile,
              use_profile_to_restrict_events,
              event_url);
}

void EventRouterForwarder::BroadcastEventToExtension(
    const std::string& extension_id,
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    const GURL& event_url) {
  HandleEvent(extension_id, event_name, event_args.Pass(), 0, true, event_url);
}

void EventRouterForwarder::DispatchEventToExtension(
    const std::string& extension_id,
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    void* profile,
    bool use_profile_to_restrict_events,
    const GURL& event_url) {
  if (!profile)
    return;
  HandleEvent(extension_id, event_name, event_args.Pass(), profile,
              use_profile_to_restrict_events, event_url);
}

void EventRouterForwarder::HandleEvent(const std::string& extension_id,
                                       const std::string& event_name,
                                       scoped_ptr<base::ListValue> event_args,
                                       void* profile_ptr,
                                       bool use_profile_to_restrict_events,
                                       const GURL& event_url) {
  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        base::Bind(&EventRouterForwarder::HandleEvent, this,
                   extension_id, event_name, base::Passed(&event_args),
                   profile_ptr, use_profile_to_restrict_events, event_url));
    return;
  }

  if (!g_browser_process || !g_browser_process->profile_manager())
    return;

  ProfileManager* profile_manager = g_browser_process->profile_manager();
  Profile* profile = NULL;
  if (profile_ptr) {
    profile = reinterpret_cast<Profile*>(profile_ptr);
    if (!profile_manager->IsValidProfile(profile))
      return;
  }
  if (profile) {
    CallEventRouter(profile, extension_id, event_name, event_args.Pass(),
                    use_profile_to_restrict_events ? profile : NULL, event_url);
  } else {
    std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
    for (size_t i = 0; i < profiles.size(); ++i) {
      scoped_ptr<base::ListValue> per_profile_event_args(
          event_args->DeepCopy());
      CallEventRouter(
          profiles[i], extension_id, event_name, per_profile_event_args.Pass(),
          use_profile_to_restrict_events ? profiles[i] : NULL, event_url);
    }
  }
}

void EventRouterForwarder::CallEventRouter(
    Profile* profile,
    const std::string& extension_id,
    const std::string& event_name,
    scoped_ptr<base::ListValue> event_args,
    Profile* restrict_to_profile,
    const GURL& event_url) {
#if defined(OS_CHROMEOS)
  // Extension does not exist for chromeos login.  This needs to be
  // removed once we have an extension service for login screen.
  // crosbug.com/12856.
  if (!extensions::ExtensionSystem::Get(profile)->event_router())
    return;
#endif

  scoped_ptr<Event> event(new Event(event_name, event_args.Pass()));
  event->restrict_to_browser_context = restrict_to_profile;
  event->event_url = event_url;
  if (extension_id.empty()) {
    ExtensionSystem::Get(profile)->event_router()->BroadcastEvent(event.Pass());
  } else {
    ExtensionSystem::Get(profile)->event_router()->
        DispatchEventToExtension(extension_id, event.Pass());
  }
}

}  // namespace extensions
<|endoftext|>


<commit_before>#ifndef SOLARIZED_HPP
#define SOLARIZED_HPP
#include <wx/colour.h>

#include "ColorScheme/ColorSchemeBase.hpp"

namespace Slic3r { namespace GUI {

/// S O L A R I Z E
/// http://ethanschoonover.com/solarized
///
/// Implements a colorscheme lookup of wxColors
class Solarized : public ColorScheme {
public:
    const wxColour SELECTED_COLOR() const { return COLOR_MAGENTA; }
    const wxColour HOVER_COLOR() const { return COLOR_VIOLET; }
    const wxColour SUPPORT_COLOR() const { return COLOR_VIOLET; }

    const wxColour BACKGROUND_COLOR() const { return COLOR_BASE3; }

private:
    const wxColour COLOR_BASE0()    const {wxColour(255*0.51373,255*0.58039,255*0.58824)};
    const wxColour COLOR_BASE00()   const {wxColour(255*0.39608,255*0.48235,255*0.51373)};
    const wxColour COLOR_BASE01()   const {wxColour(255*0.34510,255*0.43137,255*0.45882)};
    const wxColour COLOR_BASE02()   const {wxColour(255*0.02745,255*0.21176,255*0.25882)};
    const wxColour COLOR_BASE03()   const {wxColour(255*0.00000,255*0.16863,255*0.21176)};
    const wxColour COLOR_BASE1()    const {wxColour(255*0.57647,255*0.63137,255*0.63137)};
    const wxColour COLOR_BASE2()    const {wxColour(255*0.93333,255*0.90980,255*0.83529)};
    const wxColour COLOR_BASE3()    const {wxColour(255*0.99216,255*0.96471,255*0.89020)};
    const wxColour COLOR_BLUE()     const {wxColour(255*0.14902,255*0.54510,255*0.82353)};
    const wxColour COLOR_CYAN()     const {wxColour(255*0.16471,255*0.63137,255*0.59608)};
    const wxColour COLOR_GREEN()    const {wxColour(255*0.52157,255*0.60000,255*0.00000)};
    const wxColour COLOR_MAGENTA()  const {wxColour(255*0.82745,255*0.21176,255*0.50980)};
    const wxColour COLOR_ORANGE()   const {wxColour(255*0.79608,255*0.29412,255*0.08627)};
    const wxColour COLOR_RED()      const {wxColour(255*0.86275,255*0.19608,255*0.18431)};
    const wxColour COLOR_VIOLET()   const {wxColour(255*0.42353,255*0.44314,255*0.76863)};
    const wxColour COLOR_YELLOW()   const {wxColour(255*0.70980,255*0.53725,255*0.00000)};

};
}} // namespace Slic3r::GUI

#endif // SOLARIZED_HPP
<commit_msg>actually do functions right<commit_after>#ifndef SOLARIZED_HPP
#define SOLARIZED_HPP
#include <wx/colour.h>

#include "ColorScheme/ColorSchemeBase.hpp"

namespace Slic3r { namespace GUI {

/// S O L A R I Z E
/// http://ethanschoonover.com/solarized
///
/// Implements a colorscheme lookup of wxColors
class Solarized : public ColorScheme {
public:
    const wxColour SELECTED_COLOR() const { return COLOR_MAGENTA(); }
    const wxColour HOVER_COLOR() const { return COLOR_VIOLET(); }
    const wxColour SUPPORT_COLOR() const { return COLOR_VIOLET(); }

    const wxColour BACKGROUND_COLOR() const { return COLOR_BASE3(); }

private:
    const wxColour COLOR_BASE0()    const {return wxColour(255*0.51373,255*0.58039,255*0.58824);}
    const wxColour COLOR_BASE00()   const {return wxColour(255*0.39608,255*0.48235,255*0.51373);}
    const wxColour COLOR_BASE01()   const {return wxColour(255*0.34510,255*0.43137,255*0.45882);}
    const wxColour COLOR_BASE02()   const {return wxColour(255*0.02745,255*0.21176,255*0.25882);}
    const wxColour COLOR_BASE03()   const {return wxColour(255*0.00000,255*0.16863,255*0.21176);}
    const wxColour COLOR_BASE1()    const {return wxColour(255*0.57647,255*0.63137,255*0.63137);}
    const wxColour COLOR_BASE2()    const {return wxColour(255*0.93333,255*0.90980,255*0.83529);}
    const wxColour COLOR_BASE3()    const {return wxColour(255*0.99216,255*0.96471,255*0.89020);}
    const wxColour COLOR_BLUE()     const {return wxColour(255*0.14902,255*0.54510,255*0.82353);}
    const wxColour COLOR_CYAN()     const {return wxColour(255*0.16471,255*0.63137,255*0.59608);}
    const wxColour COLOR_GREEN()    const {return wxColour(255*0.52157,255*0.60000,255*0.00000);}
    const wxColour COLOR_MAGENTA()  const {return wxColour(255*0.82745,255*0.21176,255*0.50980);}
    const wxColour COLOR_ORANGE()   const {return wxColour(255*0.79608,255*0.29412,255*0.08627);}
    const wxColour COLOR_RED()      const {return wxColour(255*0.86275,255*0.19608,255*0.18431);}
    const wxColour COLOR_VIOLET()   const {return wxColour(255*0.42353,255*0.44314,255*0.76863);}
    const wxColour COLOR_YELLOW()   const {return wxColour(255*0.70980,255*0.53725,255*0.00000);}

};
}} // namespace Slic3r::GUI

#endif // SOLARIZED_HPP
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "Logger.h"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN  /* somewhat limit Win32 pollution */
#include <Winsock2.h>
#undef ERROR
#undef WARNING
#include <time.h>
#else
#include <sys/time.h>
#include <syslog.h>
#endif
#include <fstream>
#include <iomanip>
#include <boost/thread.hpp>
using namespace std;

namespace avg {

const long Logger::NONE=0;
const long Logger::BLTS=1;
const long Logger::PROFILE=2;
const long Logger::PROFILE_LATEFRAMES=4;
const long Logger::EVENTS=8;
const long Logger::EVENTS2=16;
const long Logger::CONFIG=32;
const long Logger::WARNING=64;
const long Logger::ERROR=128;
const long Logger::MEMORY=256;
const long Logger::APP=512;
const long Logger::LOGGER=1024;

Logger* Logger::m_pLogger = 0;
boost::mutex log_Mutex;

Logger * Logger::get()
{

    if (!m_pLogger) {
        {
        boost::mutex::scoped_lock Lock(log_Mutex);
        m_pLogger = new Logger;
        }
        m_pLogger->trace(LOGGER, "Logging started ");
    }
    return m_pLogger;
}

Logger::Logger()
{
    m_Flags = ERROR | WARNING | APP | LOGGER;
    m_DestType = CONSOLE;
    m_pDest = &cerr;
}

Logger::~Logger()
{
    closeDest();
}

void Logger::setConsoleDest()
{
    boost::mutex::scoped_lock Lock(log_Mutex);
    closeDest();
    m_DestType = CONSOLE;
    m_pDest = &cerr;
    AVG_TRACE(LOGGER, "Logging started ");
}

void Logger::setFileDest(const std::string& sFName)
{
    boost::mutex::scoped_lock Lock(log_Mutex);
    closeDest();
    m_DestType = FILE;
    m_pDest = new ofstream(sFName.c_str(), ios::out | ios::app);
    if (!*m_pDest) {
        m_pDest = &cerr;
        m_DestType = CONSOLE;
        AVG_TRACE(LOGGER, "Could not open " << sFName
                << " as log destination.");
    } else {
        AVG_TRACE(LOGGER, "Logging started ");
    }
}

void Logger::setSyslogDest(int facility, int logopt)
{
#ifdef _WIN32
    AVG_TRACE(ERROR,
            "Logging to syslog is not supported under windows. Ignoring request.");
#else
    boost::mutex::scoped_lock Lock(log_Mutex);
    closeDest();
    m_DestType = SYSLOG;
    openlog("libavg", logopt, facility);
#endif
}

void Logger::setCategories(int flags)
{
    boost::mutex::scoped_lock Lock(log_Mutex);
    m_Flags = flags | ERROR | APP;
}

void Logger::trace(int category, const std::string& msg)
{
    boost::mutex::scoped_lock Lock(log_Mutex);
    if (category & m_Flags) {
        if (m_DestType == CONSOLE || m_DestType == FILE) {
            struct tm* pTime;
#ifdef _WIN32
            __int64 now;
            _time64(&now);
            pTime = _localtime64(&now);
            unsigned millis = unsigned((now / 1000) % 1000);
#else
            struct timeval time;
            gettimeofday(&time, NULL);
            pTime = localtime(&time.tv_sec);
            unsigned millis = time.tv_usec/1000;
#endif
            char timeString[256];
            strftime(timeString, sizeof(timeString), "%y-%m-%d %H:%M:%S", pTime);
            (*m_pDest) << "[" << timeString << "." <<
                setw(3) << setfill('0') << millis << setw(0) << "] ";
            (*m_pDest) << categoryToString(category) << ": ";
            (*m_pDest) << msg << endl;
            m_pDest->flush();
        } else {
#ifndef _WIN32
            int prio;
            switch(category) {
                case EVENTS:
                case EVENTS2:
                case BLTS:
                    prio = LOG_INFO;
                    break;
                case PROFILE:
                case PROFILE_LATEFRAMES:
                case CONFIG:
                case APP:
                case LOGGER:
                case MEMORY:
                    prio = LOG_NOTICE;
                    break;
                case WARNING:
                    prio = LOG_WARNING;
                    break;
                case ERROR:
                    prio = LOG_ERR;
                    break;
                default:
                    prio = LOG_ERR;
            }
            syslog(prio, "%s: %s", categoryToString(category),
                    msg.c_str());
#endif
        }
    }
}

const char * Logger::categoryToString(int category)
{
    switch(category) {
        case BLTS:
            return "BLIT";
        case PROFILE:
        case PROFILE_LATEFRAMES:
            return "PROFILE";
        case EVENTS:
        case EVENTS2:
            return "EVENTS";
        case CONFIG:
            return "CONFIG";
        case WARNING:
            return "WARNING";
        case ERROR:
            return "ERROR";
        case MEMORY:
            return "MEMORY";
        case APP:
            return "APP";
        case LOGGER:
            return "LOGGER";
        default:
            return "UNKNOWN";
    }
}

void Logger::closeDest()
{
    switch (m_DestType) {
        case CONSOLE:
            break;
        case FILE:
            delete m_pDest;
            m_pDest = 0;
            break;
        case SYSLOG:
#ifndef _WIN32
            closelog();
#endif
            break;
    }
}

}
<commit_msg>Fixed Logger::setFileDest()<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "Logger.h"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN  /* somewhat limit Win32 pollution */
#include <Winsock2.h>
#undef ERROR
#undef WARNING
#include <time.h>
#else
#include <sys/time.h>
#include <syslog.h>
#endif
#include <fstream>
#include <iomanip>
#include <boost/thread.hpp>
using namespace std;

namespace avg {

const long Logger::NONE=0;
const long Logger::BLTS=1;
const long Logger::PROFILE=2;
const long Logger::PROFILE_LATEFRAMES=4;
const long Logger::EVENTS=8;
const long Logger::EVENTS2=16;
const long Logger::CONFIG=32;
const long Logger::WARNING=64;
const long Logger::ERROR=128;
const long Logger::MEMORY=256;
const long Logger::APP=512;
const long Logger::LOGGER=1024;

Logger* Logger::m_pLogger = 0;
boost::mutex log_Mutex;

Logger * Logger::get()
{

    if (!m_pLogger) {
    {
        boost::mutex::scoped_lock Lock(log_Mutex);
        m_pLogger = new Logger;
    }
        m_pLogger->trace(LOGGER, "Logging started ");
    }
    return m_pLogger;
}

Logger::Logger()
{
    m_Flags = ERROR | WARNING | APP | LOGGER;
    m_DestType = CONSOLE;
    m_pDest = &cerr;
}

Logger::~Logger()
{
    closeDest();
}

void Logger::setConsoleDest()
{
    boost::mutex::scoped_lock Lock(log_Mutex);
    closeDest();
    m_DestType = CONSOLE;
    m_pDest = &cerr;
    AVG_TRACE(LOGGER, "Logging started ");
}

void Logger::setFileDest(const std::string& sFName)
{
    {
        boost::mutex::scoped_lock Lock(log_Mutex);
        closeDest();
        m_DestType = FILE;
        m_pDest = new ofstream(sFName.c_str(), ios::out | ios::app);
    }
    if (!*m_pDest) {
        m_pDest = &cerr;
        m_DestType = CONSOLE;
        AVG_TRACE(LOGGER, "Could not open " << sFName
                << " as log destination.");
    } else {
        AVG_TRACE(LOGGER, "Logging started ");
    }
}

void Logger::setSyslogDest(int facility, int logopt)
{
#ifdef _WIN32
    AVG_TRACE(ERROR,
            "Logging to syslog is not supported under windows. Ignoring request.");
#else
    boost::mutex::scoped_lock Lock(log_Mutex);
    closeDest();
    m_DestType = SYSLOG;
    openlog("libavg", logopt, facility);
#endif
}

void Logger::setCategories(int flags)
{
    boost::mutex::scoped_lock Lock(log_Mutex);
    m_Flags = flags | ERROR | APP;
}

void Logger::trace(int category, const std::string& msg)
{
    boost::mutex::scoped_lock Lock(log_Mutex);
    if (category & m_Flags) {
        if (m_DestType == CONSOLE || m_DestType == FILE) {
            struct tm* pTime;
#ifdef _WIN32
            __int64 now;
            _time64(&now);
            pTime = _localtime64(&now);
            unsigned millis = unsigned((now / 1000) % 1000);
#else
            struct timeval time;
            gettimeofday(&time, NULL);
            pTime = localtime(&time.tv_sec);
            unsigned millis = time.tv_usec/1000;
#endif
            char timeString[256];
            strftime(timeString, sizeof(timeString), "%y-%m-%d %H:%M:%S", pTime);
            (*m_pDest) << "[" << timeString << "." <<
                setw(3) << setfill('0') << millis << setw(0) << "] ";
            (*m_pDest) << categoryToString(category) << ": ";
            (*m_pDest) << msg << endl;
            m_pDest->flush();
        } else {
#ifndef _WIN32
            int prio;
            switch(category) {
                case EVENTS:
                case EVENTS2:
                case BLTS:
                    prio = LOG_INFO;
                    break;
                case PROFILE:
                case PROFILE_LATEFRAMES:
                case CONFIG:
                case APP:
                case LOGGER:
                case MEMORY:
                    prio = LOG_NOTICE;
                    break;
                case WARNING:
                    prio = LOG_WARNING;
                    break;
                case ERROR:
                    prio = LOG_ERR;
                    break;
                default:
                    prio = LOG_ERR;
            }
            syslog(prio, "%s: %s", categoryToString(category),
                    msg.c_str());
#endif
        }
    }
}

const char * Logger::categoryToString(int category)
{
    switch(category) {
        case BLTS:
            return "BLIT";
        case PROFILE:
        case PROFILE_LATEFRAMES:
            return "PROFILE";
        case EVENTS:
        case EVENTS2:
            return "EVENTS";
        case CONFIG:
            return "CONFIG";
        case WARNING:
            return "WARNING";
        case ERROR:
            return "ERROR";
        case MEMORY:
            return "MEMORY";
        case APP:
            return "APP";
        case LOGGER:
            return "LOGGER";
        default:
            return "UNKNOWN";
    }
}

void Logger::closeDest()
{
    switch (m_DestType) {
        case CONSOLE:
            break;
        case FILE:
            delete m_pDest;
            m_pDest = 0;
            break;
        case SYSLOG:
#ifndef _WIN32
            closelog();
#endif
            break;
    }
}

}
<|endoftext|>


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

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"

// Tabs is flaky on chromeos and linux views debug build.
// http://crbug.com/48920
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_Tabs FLAKY_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  ASSERT_TRUE(StartHTTPServer());

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabOnRemoved) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTab) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/capture_visible_tab")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
  ASSERT_TRUE(StartHTTPServer());

  ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<commit_msg>Marking ExtensionApiTest.TabOnRemove flaky.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"

#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"

// Tabs is flaky on chromeos and linux views debug build.
// http://crbug.com/48920
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_Tabs FLAKY_Tabs
#else
#define MAYBE_Tabs Tabs
#endif

// TabOnRemoved is flaky on chromeos and linux views debug build.
// http://crbug.com/49258
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG)
#define MAYBE_TabOnRemoved FLAKY_TabOnRemoved
#else
#define MAYBE_TabOnRemoved TabOnRemoved
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) {
  ASSERT_TRUE(StartHTTPServer());

  // The test creates a tab and checks that the URL of the new tab
  // is that of the new tab page.  Make sure the pref that controls
  // this is set.
  browser()->profile()->GetPrefs()->SetBoolean(
      prefs::kHomePageIsNewTabPage, true);

  ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTab) {
  ASSERT_TRUE(StartHTTPServer());
  ASSERT_TRUE(RunExtensionTest("tabs/capture_visible_tab")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) {
  ASSERT_TRUE(StartHTTPServer());

  ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_;
}
<|endoftext|>