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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include <salunx.h>

#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALDISP_HXX
#include <saldisp.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _SV_SALFRAME_H
#include <salframe.h>
#endif
#ifndef _SV_SALWTYPE_HXX
#include <vcl/salwtype.hxx>
#endif
#ifndef _SV_SALATYPE_HXX
#include <vcl/salatype.hxx>
#endif
#ifndef _SV_DTINT_HXX
#include <dtint.hxx>
#endif
#ifndef _SV_SALPRN_H
#include <salprn.h>
#endif
#ifndef _VCL_SM_HXX
#include <sm.hxx>
#endif
#ifndef _SV_SALOGL_H
#include <salogl.h>
#endif

// -------------------------------------------------------------------------
//
// SalYieldMutex
//
// -------------------------------------------------------------------------

SalYieldMutex::SalYieldMutex()
{
    mnCount     = 0;
    mnThreadId  = 0;
}

void SalYieldMutex::acquire()
{
    OMutex::acquire();
    mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
    mnCount++;
}

void SalYieldMutex::release()
{
    if ( mnThreadId == NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
    {
        if ( mnCount == 1 )
            mnThreadId = 0;
        mnCount--;
    }
    OMutex::release();
}

sal_Bool SalYieldMutex::tryToAcquire()
{
    if ( OMutex::tryToAcquire() )
    {
        mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
        mnCount++;
        return True;
    }
    else
        return False;
}

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

// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

// plugin factory function
extern "C"
{
    VCL_DLLPUBLIC SalInstance* create_SalInstance()
    {
        X11SalInstance* pInstance = new X11SalInstance( new SalYieldMutex() );

        // initialize SalData
        X11SalData *pSalData = new X11SalData;
        SetSalData( pSalData );
        pSalData->m_pInstance = pInstance;
        pSalData->Init();

        return pInstance;
    }
}

X11SalInstance::~X11SalInstance()
{
    // release (possibly open) OpenGL context
    X11SalOpenGL::Release();

    // close session management
    SessionManagerClient::close();

    // dispose SalDisplay list from SalData
    // would be done in a static destructor else which is
    // a little late

    X11SalData *pSalData = GetX11SalData();
    pSalData->deInitNWF();
    delete pSalData;
    SetSalData( NULL );

    // eventually free OpenGL lib
    // this needs to be done after XCloseDisplay
    // since GL may have added extension data - including a
    // function pointer that gets called on XCloseDisplay - to
    // the display structure
    X11SalOpenGL::ReleaseLib();

      delete mpSalYieldMutex;
}

// --------------------------------------------------------
// AnyInput from sv/mow/source/app/svapp.cxx

struct PredicateReturn
{
    USHORT  nType;
    BOOL    bRet;
};

extern "C" {
Bool ImplPredicateEvent( Display *, XEvent *pEvent, char *pData )
{
    PredicateReturn *pPre = (PredicateReturn *)pData;

    if ( pPre->bRet )
        return False;

    USHORT nType;

    switch( pEvent->type )
    {
        case ButtonPress:
        case ButtonRelease:
        case MotionNotify:
        case EnterNotify:
        case LeaveNotify:
            nType = INPUT_MOUSE;
            break;

        case XLIB_KeyPress:
        //case KeyRelease:
            nType = INPUT_KEYBOARD;
            break;
        case Expose:
        case GraphicsExpose:
        case NoExpose:
            nType = INPUT_PAINT;
            break;
        default:
            nType = 0;
    }

    if ( (nType & pPre->nType) || ( ! nType && (pPre->nType & INPUT_OTHER) ) )
        pPre->bRet = TRUE;

    return False;
}
}

bool X11SalInstance::AnyInput(USHORT nType)
{
    X11SalData *pSalData = GetX11SalData();
    Display *pDisplay  = pSalData->GetDisplay()->GetDisplay();
    BOOL bRet = FALSE;

    if( (nType & INPUT_TIMER) &&
        pSalData->GetDisplay()->GetXLib()->CheckTimeout( false ) )
    {
        bRet = TRUE;
    }
    else if (XPending(pDisplay) )
    {
        PredicateReturn aInput;
        XEvent          aEvent;

        aInput.bRet     = FALSE;
        aInput.nType    = nType;

        XCheckIfEvent(pDisplay, &aEvent, ImplPredicateEvent,
                      (char *)&aInput );

        bRet = aInput.bRet;
    }
    return bRet;
}

vos::IMutex* X11SalInstance::GetYieldMutex()
{
    return mpSalYieldMutex;
}

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

ULONG X11SalInstance::ReleaseYieldMutex()
{
    SalYieldMutex* pYieldMutex = mpSalYieldMutex;
    if ( pYieldMutex->GetThreadId() ==
         NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
    {
        ULONG nCount = pYieldMutex->GetAcquireCount();
        ULONG n = nCount;
        while ( n )
        {
            pYieldMutex->release();
            n--;
        }

        return nCount;
    }
    else
        return 0;
}

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

void X11SalInstance::AcquireYieldMutex( ULONG nCount )
{
    SalYieldMutex* pYieldMutex = mpSalYieldMutex;
    while ( nCount )
    {
        pYieldMutex->acquire();
        nCount--;
    }
}

void X11SalInstance::Yield( bool bWait, bool bHandleAllCurrentEvents )
{ GetX11SalData()->GetLib()->Yield( bWait, bHandleAllCurrentEvents ); }

void* X11SalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )
{
    static const char* pDisplay = getenv( "DISPLAY" );
    rReturnedType   = AsciiCString;
    rReturnedBytes  = pDisplay ? strlen( pDisplay )+1 : 1;
    return pDisplay ? (void*)pDisplay : (void*)"";
}

SalFrame *X11SalInstance::CreateFrame( SalFrame *pParent, ULONG nSalFrameStyle )
{
    SalFrame *pFrame = new X11SalFrame( pParent, nSalFrameStyle );

    return pFrame;
}

SalFrame* X11SalInstance::CreateChildFrame( SystemParentData* pParentData, ULONG nStyle )
{
    SalFrame* pFrame = new X11SalFrame( NULL, nStyle, pParentData );

    return pFrame;
}

void X11SalInstance::DestroyFrame( SalFrame* pFrame )
{
    delete pFrame;
}

SalOpenGL* X11SalInstance::CreateSalOpenGL( SalGraphics* pGraphics )
{
    return new X11SalOpenGL( pGraphics );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.33.22); FILE MERGED 2008/04/01 13:01:58 thb 1.33.22.2: #i85898# Stripping all external header guards 2008/03/28 15:45:25 rt 1.33.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: salinst.cxx,v $
 * $Revision: 1.34 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include <salunx.h>

#ifndef _VOS_MUTEX_HXX
#include <vos/mutex.hxx>
#endif
#include <saldata.hxx>
#include <saldisp.hxx>
#include <salinst.h>
#include <salframe.h>
#include <vcl/salwtype.hxx>
#include <vcl/salatype.hxx>
#include <dtint.hxx>
#include <salprn.h>
#include <sm.hxx>
#include <salogl.h>

// -------------------------------------------------------------------------
//
// SalYieldMutex
//
// -------------------------------------------------------------------------

SalYieldMutex::SalYieldMutex()
{
    mnCount     = 0;
    mnThreadId  = 0;
}

void SalYieldMutex::acquire()
{
    OMutex::acquire();
    mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
    mnCount++;
}

void SalYieldMutex::release()
{
    if ( mnThreadId == NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
    {
        if ( mnCount == 1 )
            mnThreadId = 0;
        mnCount--;
    }
    OMutex::release();
}

sal_Bool SalYieldMutex::tryToAcquire()
{
    if ( OMutex::tryToAcquire() )
    {
        mnThreadId = NAMESPACE_VOS(OThread)::getCurrentIdentifier();
        mnCount++;
        return True;
    }
    else
        return False;
}

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

// -=-= SalInstance =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

// plugin factory function
extern "C"
{
    VCL_DLLPUBLIC SalInstance* create_SalInstance()
    {
        X11SalInstance* pInstance = new X11SalInstance( new SalYieldMutex() );

        // initialize SalData
        X11SalData *pSalData = new X11SalData;
        SetSalData( pSalData );
        pSalData->m_pInstance = pInstance;
        pSalData->Init();

        return pInstance;
    }
}

X11SalInstance::~X11SalInstance()
{
    // release (possibly open) OpenGL context
    X11SalOpenGL::Release();

    // close session management
    SessionManagerClient::close();

    // dispose SalDisplay list from SalData
    // would be done in a static destructor else which is
    // a little late

    X11SalData *pSalData = GetX11SalData();
    pSalData->deInitNWF();
    delete pSalData;
    SetSalData( NULL );

    // eventually free OpenGL lib
    // this needs to be done after XCloseDisplay
    // since GL may have added extension data - including a
    // function pointer that gets called on XCloseDisplay - to
    // the display structure
    X11SalOpenGL::ReleaseLib();

      delete mpSalYieldMutex;
}

// --------------------------------------------------------
// AnyInput from sv/mow/source/app/svapp.cxx

struct PredicateReturn
{
    USHORT  nType;
    BOOL    bRet;
};

extern "C" {
Bool ImplPredicateEvent( Display *, XEvent *pEvent, char *pData )
{
    PredicateReturn *pPre = (PredicateReturn *)pData;

    if ( pPre->bRet )
        return False;

    USHORT nType;

    switch( pEvent->type )
    {
        case ButtonPress:
        case ButtonRelease:
        case MotionNotify:
        case EnterNotify:
        case LeaveNotify:
            nType = INPUT_MOUSE;
            break;

        case XLIB_KeyPress:
        //case KeyRelease:
            nType = INPUT_KEYBOARD;
            break;
        case Expose:
        case GraphicsExpose:
        case NoExpose:
            nType = INPUT_PAINT;
            break;
        default:
            nType = 0;
    }

    if ( (nType & pPre->nType) || ( ! nType && (pPre->nType & INPUT_OTHER) ) )
        pPre->bRet = TRUE;

    return False;
}
}

bool X11SalInstance::AnyInput(USHORT nType)
{
    X11SalData *pSalData = GetX11SalData();
    Display *pDisplay  = pSalData->GetDisplay()->GetDisplay();
    BOOL bRet = FALSE;

    if( (nType & INPUT_TIMER) &&
        pSalData->GetDisplay()->GetXLib()->CheckTimeout( false ) )
    {
        bRet = TRUE;
    }
    else if (XPending(pDisplay) )
    {
        PredicateReturn aInput;
        XEvent          aEvent;

        aInput.bRet     = FALSE;
        aInput.nType    = nType;

        XCheckIfEvent(pDisplay, &aEvent, ImplPredicateEvent,
                      (char *)&aInput );

        bRet = aInput.bRet;
    }
    return bRet;
}

vos::IMutex* X11SalInstance::GetYieldMutex()
{
    return mpSalYieldMutex;
}

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

ULONG X11SalInstance::ReleaseYieldMutex()
{
    SalYieldMutex* pYieldMutex = mpSalYieldMutex;
    if ( pYieldMutex->GetThreadId() ==
         NAMESPACE_VOS(OThread)::getCurrentIdentifier() )
    {
        ULONG nCount = pYieldMutex->GetAcquireCount();
        ULONG n = nCount;
        while ( n )
        {
            pYieldMutex->release();
            n--;
        }

        return nCount;
    }
    else
        return 0;
}

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

void X11SalInstance::AcquireYieldMutex( ULONG nCount )
{
    SalYieldMutex* pYieldMutex = mpSalYieldMutex;
    while ( nCount )
    {
        pYieldMutex->acquire();
        nCount--;
    }
}

void X11SalInstance::Yield( bool bWait, bool bHandleAllCurrentEvents )
{ GetX11SalData()->GetLib()->Yield( bWait, bHandleAllCurrentEvents ); }

void* X11SalInstance::GetConnectionIdentifier( ConnectionIdentifierType& rReturnedType, int& rReturnedBytes )
{
    static const char* pDisplay = getenv( "DISPLAY" );
    rReturnedType   = AsciiCString;
    rReturnedBytes  = pDisplay ? strlen( pDisplay )+1 : 1;
    return pDisplay ? (void*)pDisplay : (void*)"";
}

SalFrame *X11SalInstance::CreateFrame( SalFrame *pParent, ULONG nSalFrameStyle )
{
    SalFrame *pFrame = new X11SalFrame( pParent, nSalFrameStyle );

    return pFrame;
}

SalFrame* X11SalInstance::CreateChildFrame( SystemParentData* pParentData, ULONG nStyle )
{
    SalFrame* pFrame = new X11SalFrame( NULL, nStyle, pParentData );

    return pFrame;
}

void X11SalInstance::DestroyFrame( SalFrame* pFrame )
{
    delete pFrame;
}

SalOpenGL* X11SalInstance::CreateSalOpenGL( SalGraphics* pGraphics )
{
    return new X11SalOpenGL( pGraphics );
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mthemedaemonserver.h"
#include <QDebug>
#include <QApplication>
#include <signal.h>

#ifdef CLOSE_ON_ENTER
#include "keypresswaiter.h"
#endif

namespace
{
    QtMsgType outputLevel = QtDebugMsg;
}

static int setup_unix_signal_handlers()
{
    struct sigaction sighup, sigterm, sigint, sigusr1;

    sighup.sa_handler = MThemeDaemonServer::hupSignalHandler;
    sigemptyset(&sighup.sa_mask);
    sighup.sa_flags = SA_RESTART;

    if (sigaction(SIGHUP, &sighup, 0) > 0)
        return 1;

    sigterm.sa_handler = MThemeDaemonServer::termSignalHandler;
    sigemptyset(&sigterm.sa_mask);
    sigterm.sa_flags = SA_RESTART;

    if (sigaction(SIGTERM, &sigterm, 0) > 0)
        return 2;

    sigint.sa_handler = MThemeDaemonServer::intSignalHandler;
    sigemptyset(&sigint.sa_mask);
    sigint.sa_flags = SA_RESTART;

    if (sigaction(SIGINT, &sigint, 0) > 0)
        return 3;

    sigusr1.sa_handler = MThemeDaemonServer::usr1SignalHandler;
    sigemptyset(&sigusr1.sa_mask);
    sigusr1.sa_flags = SA_RESTART;

    if (sigaction(SIGUSR1, &sigusr1, 0) > 0)
        return 4;

     return 0;
 }

static QtMsgType getOutputLevelFromArgs(QStringList arguments)
{
    QString argLevel;
    int index = arguments.indexOf("-output-level") + 1;
    if (index > 0 && index < arguments.length()) {
        argLevel = arguments[index];
    }

    if (argLevel == "debug")
        return QtDebugMsg;
    if (argLevel == "warning")
        return QtWarningMsg;
    if (argLevel == "critical")
        return QtCriticalMsg;

#ifdef __arm__
    return QtCriticalMsg;
#else
    return QtWarningMsg;
#endif
}

static void mMessageHandler(QtMsgType type, const char *msg)
{
    if (type < outputLevel)
        return;

   fprintf(stderr, "%s\n", msg);

   if (type == QtFatalMsg)
       abort();
}

int main(int argc, char **argv)
{
    setup_unix_signal_handlers();

    // make sure we are not loading the maemo6 qt style which
    // could interfere with us
    QApplication::setStyle("windows");
#ifndef HAVE_MEEGOGRAPHICSSYSTEM
    QApplication::setGraphicsSystem("native");
#else
    // For the moment we use the native graphicssystem to share X pixmaps if
    // nothing else is specified explicitly.
    // Later we use the shiny new meego graphicssystem features by default.
    if (qApp->arguments().indexOf("-graphicssystem") == -1) {
        QApplication::setGraphicsSystem("native");
    }
#endif // HAVE_MEEGOGRAPHICSSYSTEM

    QApplication app(argc, argv);

    outputLevel = getOutputLevelFromArgs(app.arguments());
    qInstallMsgHandler(mMessageHandler);

    // Apply custom server address, if the "-address" has been passed as argument
    QString serverAddress;
    int index = app.arguments().indexOf("-address");
    if ((index >= 0) && (index + 1 < app.arguments().count())) {
        serverAddress = app.arguments().at(index + 1);
    }

    MThemeDaemonServer server(serverAddress);

#ifdef CLOSE_ON_ENTER
    KeyPressWaiter keyWaiter;
    QObject::connect(&keyWaiter, SIGNAL(finished()), qApp, SLOT(quit()));
    keyWaiter.start();
#endif

    if (app.arguments().indexOf("-quitimmediately") >= 0) {
        QTimer::singleShot(0, &app, SLOT(quit()));
    }

    index = app.arguments().indexOf("-slowdown");
    if ((index >= 0) && (index + 1 < app.arguments().count())) {
        bool conversionOk;
        int slowDown = app.arguments().at(index + 1).toInt(&conversionOk);
        if (conversionOk) {
            server.setSlowDown(slowDown);
            qDebug() << "Slowing down theme asset requests by" << slowDown << "microseconds";
        }
    }

    return app.exec();
}
<commit_msg>Fixes: Arguments list is accessed in themedaemon before the QCoreApplication instance is created.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mthemedaemonserver.h"
#include <QDebug>
#include <QApplication>
#include <signal.h>

#ifdef CLOSE_ON_ENTER
#include "keypresswaiter.h"
#endif

namespace
{
    QtMsgType outputLevel = QtDebugMsg;
}

static int setup_unix_signal_handlers()
{
    struct sigaction sighup, sigterm, sigint, sigusr1;

    sighup.sa_handler = MThemeDaemonServer::hupSignalHandler;
    sigemptyset(&sighup.sa_mask);
    sighup.sa_flags = SA_RESTART;

    if (sigaction(SIGHUP, &sighup, 0) > 0)
        return 1;

    sigterm.sa_handler = MThemeDaemonServer::termSignalHandler;
    sigemptyset(&sigterm.sa_mask);
    sigterm.sa_flags = SA_RESTART;

    if (sigaction(SIGTERM, &sigterm, 0) > 0)
        return 2;

    sigint.sa_handler = MThemeDaemonServer::intSignalHandler;
    sigemptyset(&sigint.sa_mask);
    sigint.sa_flags = SA_RESTART;

    if (sigaction(SIGINT, &sigint, 0) > 0)
        return 3;

    sigusr1.sa_handler = MThemeDaemonServer::usr1SignalHandler;
    sigemptyset(&sigusr1.sa_mask);
    sigusr1.sa_flags = SA_RESTART;

    if (sigaction(SIGUSR1, &sigusr1, 0) > 0)
        return 4;

     return 0;
 }

static QtMsgType getOutputLevelFromArgs(QStringList arguments)
{
    QString argLevel;
    int index = arguments.indexOf("-output-level") + 1;
    if (index > 0 && index < arguments.length()) {
        argLevel = arguments[index];
    }

    if (argLevel == "debug")
        return QtDebugMsg;
    if (argLevel == "warning")
        return QtWarningMsg;
    if (argLevel == "critical")
        return QtCriticalMsg;

#ifdef __arm__
    return QtCriticalMsg;
#else
    return QtWarningMsg;
#endif
}

static void mMessageHandler(QtMsgType type, const char *msg)
{
    if (type < outputLevel)
        return;

   fprintf(stderr, "%s\n", msg);

   if (type == QtFatalMsg)
       abort();
}

int main(int argc, char **argv)
{
    setup_unix_signal_handlers();

    // make sure we are not loading the maemo6 qt style which
    // could interfere with us
    QApplication::setStyle("windows");
#ifndef HAVE_MEEGOGRAPHICSSYSTEM
    QApplication::setGraphicsSystem("native");
#else
    // For the moment we use the native graphicssystem to share X pixmaps if
    // nothing else is specified explicitly.
    // Later we use the shiny new meego graphicssystem features by default.
    bool useNativeGraphicsSystem = true;
    for (int i = 0; i < argc; i++) {
        if (strcmp(argv[i], "-graphicssystem") == 0) {
            useNativeGraphicsSystem = false;
            break;
        }
    }
    if (useNativeGraphicsSystem)
        QApplication::setGraphicsSystem("native");
#endif // HAVE_MEEGOGRAPHICSSYSTEM

    QApplication app(argc, argv);

    outputLevel = getOutputLevelFromArgs(app.arguments());
    qInstallMsgHandler(mMessageHandler);

    // Apply custom server address, if the "-address" has been passed as argument
    QString serverAddress;
    int index = app.arguments().indexOf("-address");
    if ((index >= 0) && (index + 1 < app.arguments().count())) {
        serverAddress = app.arguments().at(index + 1);
    }

    MThemeDaemonServer server(serverAddress);

#ifdef CLOSE_ON_ENTER
    KeyPressWaiter keyWaiter;
    QObject::connect(&keyWaiter, SIGNAL(finished()), qApp, SLOT(quit()));
    keyWaiter.start();
#endif

    if (app.arguments().indexOf("-quitimmediately") >= 0) {
        QTimer::singleShot(0, &app, SLOT(quit()));
    }

    index = app.arguments().indexOf("-slowdown");
    if ((index >= 0) && (index + 1 < app.arguments().count())) {
        bool conversionOk;
        int slowDown = app.arguments().at(index + 1).toInt(&conversionOk);
        if (conversionOk) {
            server.setSlowDown(slowDown);
            qDebug() << "Slowing down theme asset requests by" << slowDown << "microseconds";
        }
    }

    return app.exec();
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2009 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 "base/basictypes.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif

// URL at which data files may be found for HTTP tests.  The document root of
// this URL's server should point to data/page_cycler/.
static const char kBaseUrl[] = "http://localhost:8000/";

namespace {

class PageCyclerTest : public UITest {
 public:
  PageCyclerTest() {
    show_window_ = true;

    // Expose garbage collection for the page cycler tests.
    launch_arguments_.AppendSwitchWithValue(switches::kJavaScriptFlags,
                                            L"--expose_gc");
  }

  // For HTTP tests, the name must be safe for use in a URL without escaping.
  void RunPageCycler(const char* name, std::wstring* pages,
                     std::string* timings, bool use_http) {
    GURL test_url;
    if (use_http) {
      test_url = GURL(std::string(kBaseUrl) + name + "/start.html");
    } else {
      FilePath test_path;
      PathService::Get(base::DIR_EXE, &test_path);
      test_path = test_path.DirName();
      test_path = test_path.DirName();
      test_path = test_path.Append(FILE_PATH_LITERAL("data"));
      test_path = test_path.Append(FILE_PATH_LITERAL("page_cycler"));
      test_path = test_path.AppendASCII(name);
      test_path = test_path.Append(FILE_PATH_LITERAL("start.html"));
      test_url = net::FilePathToFileURL(test_path);
    }

    // run N iterations
    GURL::Replacements replacements;
    const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
    replacements.SetQuery(
        query_string,
        url_parse::Component(0, arraysize(query_string) - 1));
    test_url = test_url.ReplaceComponents(replacements);

    scoped_refptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
                                     3000, UITest::test_timeout_ms(), "1"));

    std::string cookie;
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
    pages->assign(UTF8ToWide(cookie));
    ASSERT_FALSE(pages->empty());
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
    timings->assign(cookie);
    ASSERT_FALSE(timings->empty());
  }

  void PrintIOPerfInfo(const char* test_name) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);
    int browser_process_pid = ChromeBrowserProcessId(data_dir);
    ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));

    ChromeProcessList::const_iterator it;
    for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
      base::ProcessHandle process_handle;
      if (!base::OpenProcessHandle(*it, &process_handle)) {
        NOTREACHED();
      }

      scoped_ptr<base::ProcessMetrics> process_metrics;
      process_metrics.reset(
          base::ProcessMetrics::CreateProcessMetrics(process_handle));
      IoCounters io_counters;
      memset(&io_counters, 0, sizeof(io_counters));

      if (process_metrics.get()->GetIOCounters(&io_counters)) {
        // Print out IO performance.  We assume that the values can be
        // converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
        std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";

        PrintResult("read_op", chrome_name,
                    "r_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadOperationCount), "",
                    false /* not important */);
        PrintResult("write_op", chrome_name,
                    "w_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteOperationCount), "",
                    false /* not important */);
        PrintResult("other_op", chrome_name,
                    "o_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherOperationCount), "",
                    false /* not important */);

        size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
                                           io_counters.WriteOperationCount +
                                           io_counters.OtherOperationCount);
        PrintResult("total_op", chrome_name,
                    "IO_op" + chrome_name + test_name,
                    total, "", true /* important */);

        PrintResult("read_byte", chrome_name,
                    "r_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadTransferCount / 1024),
                    "kb", false /* not important */);
        PrintResult("write_byte", chrome_name,
                    "w_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteTransferCount / 1024),
                    "kb", false /* not important */);
        PrintResult("other_byte", chrome_name,
                    "o_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherTransferCount / 1024),
                    "kb", false /* not important */);

        total = static_cast<size_t>((io_counters.ReadTransferCount +
                                     io_counters.WriteTransferCount +
                                     io_counters.OtherTransferCount) / 1024);
        PrintResult("total_byte", chrome_name,
                    "IO_b" + chrome_name + test_name,
                    total, "kb", true /* important */);
      }

      base::CloseProcessHandle(process_handle);
    }
  }

  void PrintMemoryUsageInfo(const char* test_name) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);
    int browser_process_pid = ChromeBrowserProcessId(data_dir);
    ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));

    ChromeProcessList::const_iterator it;
    for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
      base::ProcessHandle process_handle;
      if (!base::OpenProcessHandle(*it, &process_handle)) {
        NOTREACHED();
      }

      scoped_ptr<base::ProcessMetrics> process_metrics;
      process_metrics.reset(
          base::ProcessMetrics::CreateProcessMetrics(process_handle));

      std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";

      std::string trace_name(test_name);
#if defined(OS_WIN)
      PrintResult("vm_peak", chrome_name,
                  "vm_pk" + chrome_name + trace_name,
                  process_metrics->GetPeakPagefileUsage(), "bytes",
                  true /* important */);
      PrintResult("vm_final", chrome_name,
                  "vm_f" + chrome_name + trace_name,
                  process_metrics->GetPagefileUsage(), "bytes",
                  false /* not important */);
      PrintResult("ws_peak", chrome_name,
                  "ws_pk" + chrome_name + trace_name,
                  process_metrics->GetPeakWorkingSetSize(), "bytes",
                  true /* important */);
      PrintResult("ws_final", chrome_name,
                  "ws_f" + chrome_name + trace_name,
                  process_metrics->GetWorkingSetSize(), "bytes",
                  false /* not important */);
#elif defined(OS_LINUX)
      PrintResult("vm_size_final", chrome_name,
                  "vm_size_f" + chrome_name + trace_name,
                  process_metrics->GetPagefileUsage(), "bytes",
                  true /* important */);
      PrintResult("vm_rss_final", chrome_name,
                  "vm_rss_f" + chrome_name + trace_name,
                  process_metrics->GetWorkingSetSize(), "bytes",
                  true /* important */);
#else
      NOTIMPLEMENTED();
#endif
      base::CloseProcessHandle(process_handle);
    }
  }

  // When use_http is true, the test name passed here will be used directly in
  // the path to the test data, so it must be safe for use in a URL without
  // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
  // other funny stuff.)
  void RunTest(const char* name, bool use_http) {
    std::wstring pages;
    std::string timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo("");
    PrintIOPerfInfo("");

    wprintf(L"\nPages: [%ls]\n", pages.c_str());
    PrintResultList("times", "", "t", timings, "ms",
                    true /* important */);
  }
};

class PageCyclerReferenceTest : public PageCyclerTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    UITest::SetUp();
  }

  void RunTest(const char* name, bool use_http) {
    std::wstring pages;
    std::string timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo("_ref");
    PrintIOPerfInfo("_ref");

    PrintResultList("times", "", "t_ref", timings, "ms",
                    true /* important */);
  }
};

// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
  RunTest("moz", false);
}

TEST_F(PageCyclerReferenceTest, MozFile) {
  RunTest("moz", false);
}

#if !defined(OS_MACOSX)
// TODO(nirnimesh): Intl1File, Intl2File, Intl1Http, Intl2Http crash Chromium
// on Mac. Revisit later.
TEST_F(PageCyclerTest, Intl1File) {
  RunTest("intl1", false);
}

TEST_F(PageCyclerReferenceTest, Intl1File) {
  RunTest("intl1", false);
}

TEST_F(PageCyclerTest, Intl2File) {
  RunTest("intl2", false);
}

TEST_F(PageCyclerReferenceTest, Intl2File) {
  RunTest("intl2", false);
}
#endif  // !defined(OS_MACOSX)

TEST_F(PageCyclerTest, DomFile) {
  RunTest("dom", false);
}

TEST_F(PageCyclerReferenceTest, DomFile) {
  RunTest("dom", false);
}

TEST_F(PageCyclerTest, DhtmlFile) {
  RunTest("dhtml", false);
}

TEST_F(PageCyclerReferenceTest, DhtmlFile) {
  RunTest("dhtml", false);
}

// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
  RunTest("moz", true);
}

TEST_F(PageCyclerReferenceTest, MozHttp) {
  RunTest("moz", true);
}

#if !defined(OS_MACOSX)
TEST_F(PageCyclerTest, Intl1Http) {
  RunTest("intl1", true);
}

TEST_F(PageCyclerReferenceTest, Intl1Http) {
  RunTest("intl1", true);
}

TEST_F(PageCyclerTest, Intl2Http) {
  RunTest("intl2", true);
}

TEST_F(PageCyclerReferenceTest, Intl2Http) {
  RunTest("intl2", true);
}
#endif  // !defined(OS_MACOSX)

TEST_F(PageCyclerTest, DomHttp) {
  RunTest("dom", true);
}

TEST_F(PageCyclerReferenceTest, DomHttp) {
  RunTest("dom", true);
}

TEST_F(PageCyclerTest, BloatHttp) {
  RunTest("bloat", true);
}

TEST_F(PageCyclerReferenceTest, BloatHttp) {
  RunTest("bloat", true);
}

}  // namespace
<commit_msg>Assert that page_cycler data is present when trying to run tests, so that when it isn't the failure is obvious and easy-to-diagnose.<commit_after>// Copyright (c) 2006-2009 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 "base/basictypes.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif

// URL at which data files may be found for HTTP tests.  The document root of
// this URL's server should point to data/page_cycler/.
static const char kBaseUrl[] = "http://localhost:8000/";

namespace {

class PageCyclerTest : public UITest {
 public:
  PageCyclerTest() {
    show_window_ = true;

    // Expose garbage collection for the page cycler tests.
    launch_arguments_.AppendSwitchWithValue(switches::kJavaScriptFlags,
                                            L"--expose_gc");
  }

  // For HTTP tests, the name must be safe for use in a URL without escaping.
  void RunPageCycler(const char* name, std::wstring* pages,
                     std::string* timings, bool use_http) {
    GURL test_url;
    if (use_http) {
      test_url = GURL(std::string(kBaseUrl) + name + "/start.html");
    } else {
      FilePath test_path;
      PathService::Get(base::DIR_EXE, &test_path);
      test_path = test_path.DirName();
      test_path = test_path.DirName();
      test_path = test_path.Append(FILE_PATH_LITERAL("data"));
      test_path = test_path.Append(FILE_PATH_LITERAL("page_cycler"));
      test_path = test_path.AppendASCII(name);
      test_path = test_path.Append(FILE_PATH_LITERAL("start.html"));
      ASSERT_TRUE(file_util::PathExists(test_path)) << "Missing test data";
      test_url = net::FilePathToFileURL(test_path);
    }

    // run N iterations
    GURL::Replacements replacements;
    const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
    replacements.SetQuery(
        query_string,
        url_parse::Component(0, arraysize(query_string) - 1));
    test_url = test_url.ReplaceComponents(replacements);

    scoped_refptr<TabProxy> tab(GetActiveTab());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
                                     3000, UITest::test_timeout_ms(), "1"));

    std::string cookie;
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
    pages->assign(UTF8ToWide(cookie));
    ASSERT_FALSE(pages->empty());
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
    timings->assign(cookie);
    ASSERT_FALSE(timings->empty());
  }

  void PrintIOPerfInfo(const char* test_name) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);
    int browser_process_pid = ChromeBrowserProcessId(data_dir);
    ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));

    ChromeProcessList::const_iterator it;
    for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
      base::ProcessHandle process_handle;
      if (!base::OpenProcessHandle(*it, &process_handle)) {
        NOTREACHED();
      }

      scoped_ptr<base::ProcessMetrics> process_metrics;
      process_metrics.reset(
          base::ProcessMetrics::CreateProcessMetrics(process_handle));
      IoCounters io_counters;
      memset(&io_counters, 0, sizeof(io_counters));

      if (process_metrics.get()->GetIOCounters(&io_counters)) {
        // Print out IO performance.  We assume that the values can be
        // converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
        std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";

        PrintResult("read_op", chrome_name,
                    "r_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadOperationCount), "",
                    false /* not important */);
        PrintResult("write_op", chrome_name,
                    "w_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteOperationCount), "",
                    false /* not important */);
        PrintResult("other_op", chrome_name,
                    "o_op" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherOperationCount), "",
                    false /* not important */);

        size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
                                           io_counters.WriteOperationCount +
                                           io_counters.OtherOperationCount);
        PrintResult("total_op", chrome_name,
                    "IO_op" + chrome_name + test_name,
                    total, "", true /* important */);

        PrintResult("read_byte", chrome_name,
                    "r_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.ReadTransferCount / 1024),
                    "kb", false /* not important */);
        PrintResult("write_byte", chrome_name,
                    "w_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.WriteTransferCount / 1024),
                    "kb", false /* not important */);
        PrintResult("other_byte", chrome_name,
                    "o_b" + chrome_name + test_name,
                    static_cast<size_t>(io_counters.OtherTransferCount / 1024),
                    "kb", false /* not important */);

        total = static_cast<size_t>((io_counters.ReadTransferCount +
                                     io_counters.WriteTransferCount +
                                     io_counters.OtherTransferCount) / 1024);
        PrintResult("total_byte", chrome_name,
                    "IO_b" + chrome_name + test_name,
                    total, "kb", true /* important */);
      }

      base::CloseProcessHandle(process_handle);
    }
  }

  void PrintMemoryUsageInfo(const char* test_name) {
    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);
    int browser_process_pid = ChromeBrowserProcessId(data_dir);
    ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));

    ChromeProcessList::const_iterator it;
    for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
      base::ProcessHandle process_handle;
      if (!base::OpenProcessHandle(*it, &process_handle)) {
        NOTREACHED();
      }

      scoped_ptr<base::ProcessMetrics> process_metrics;
      process_metrics.reset(
          base::ProcessMetrics::CreateProcessMetrics(process_handle));

      std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";

      std::string trace_name(test_name);
#if defined(OS_WIN)
      PrintResult("vm_peak", chrome_name,
                  "vm_pk" + chrome_name + trace_name,
                  process_metrics->GetPeakPagefileUsage(), "bytes",
                  true /* important */);
      PrintResult("vm_final", chrome_name,
                  "vm_f" + chrome_name + trace_name,
                  process_metrics->GetPagefileUsage(), "bytes",
                  false /* not important */);
      PrintResult("ws_peak", chrome_name,
                  "ws_pk" + chrome_name + trace_name,
                  process_metrics->GetPeakWorkingSetSize(), "bytes",
                  true /* important */);
      PrintResult("ws_final", chrome_name,
                  "ws_f" + chrome_name + trace_name,
                  process_metrics->GetWorkingSetSize(), "bytes",
                  false /* not important */);
#elif defined(OS_LINUX)
      PrintResult("vm_size_final", chrome_name,
                  "vm_size_f" + chrome_name + trace_name,
                  process_metrics->GetPagefileUsage(), "bytes",
                  true /* important */);
      PrintResult("vm_rss_final", chrome_name,
                  "vm_rss_f" + chrome_name + trace_name,
                  process_metrics->GetWorkingSetSize(), "bytes",
                  true /* important */);
#else
      NOTIMPLEMENTED();
#endif
      base::CloseProcessHandle(process_handle);
    }
  }

  // When use_http is true, the test name passed here will be used directly in
  // the path to the test data, so it must be safe for use in a URL without
  // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
  // other funny stuff.)
  void RunTest(const char* name, bool use_http) {
    std::wstring pages;
    std::string timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo("");
    PrintIOPerfInfo("");

    wprintf(L"\nPages: [%ls]\n", pages.c_str());
    PrintResultList("times", "", "t", timings, "ms",
                    true /* important */);
  }
};

class PageCyclerReferenceTest : public PageCyclerTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    UITest::SetUp();
  }

  void RunTest(const char* name, bool use_http) {
    std::wstring pages;
    std::string timings;
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;

    PrintMemoryUsageInfo("_ref");
    PrintIOPerfInfo("_ref");

    PrintResultList("times", "", "t_ref", timings, "ms",
                    true /* important */);
  }
};

// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
  RunTest("moz", false);
}

TEST_F(PageCyclerReferenceTest, MozFile) {
  RunTest("moz", false);
}

#if !defined(OS_MACOSX)
// TODO(nirnimesh): Intl1File, Intl2File, Intl1Http, Intl2Http crash Chromium
// on Mac. Revisit later.
TEST_F(PageCyclerTest, Intl1File) {
  RunTest("intl1", false);
}

TEST_F(PageCyclerReferenceTest, Intl1File) {
  RunTest("intl1", false);
}

TEST_F(PageCyclerTest, Intl2File) {
  RunTest("intl2", false);
}

TEST_F(PageCyclerReferenceTest, Intl2File) {
  RunTest("intl2", false);
}
#endif  // !defined(OS_MACOSX)

TEST_F(PageCyclerTest, DomFile) {
  RunTest("dom", false);
}

TEST_F(PageCyclerReferenceTest, DomFile) {
  RunTest("dom", false);
}

TEST_F(PageCyclerTest, DhtmlFile) {
  RunTest("dhtml", false);
}

TEST_F(PageCyclerReferenceTest, DhtmlFile) {
  RunTest("dhtml", false);
}

// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
  RunTest("moz", true);
}

TEST_F(PageCyclerReferenceTest, MozHttp) {
  RunTest("moz", true);
}

#if !defined(OS_MACOSX)
TEST_F(PageCyclerTest, Intl1Http) {
  RunTest("intl1", true);
}

TEST_F(PageCyclerReferenceTest, Intl1Http) {
  RunTest("intl1", true);
}

TEST_F(PageCyclerTest, Intl2Http) {
  RunTest("intl2", true);
}

TEST_F(PageCyclerReferenceTest, Intl2Http) {
  RunTest("intl2", true);
}
#endif  // !defined(OS_MACOSX)

TEST_F(PageCyclerTest, DomHttp) {
  RunTest("dom", true);
}

TEST_F(PageCyclerReferenceTest, DomHttp) {
  RunTest("dom", true);
}

TEST_F(PageCyclerTest, BloatHttp) {
  RunTest("bloat", true);
}

TEST_F(PageCyclerReferenceTest, BloatHttp) {
  RunTest("bloat", true);
}

}  // namespace
<|endoftext|>


<commit_before>// Copyright (c) 2006-2009 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 "base/basictypes.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#if defined(OS_MACOSX)
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/resource.h>
#endif

#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif

// URL at which data files may be found for HTTP tests.  The document root of
// this URL's server should point to data/page_cycler/.
static const char kBaseUrl[] = "http://localhost:8000/";

namespace {

#if defined(OS_MACOSX)
// TODO(tvl/stuart): remove all this fd limit setting on the Mac when/if we
// replace the Mac reference build.  The trunk raises the limit within the
// browser app, but we do this here also so the current reference build without
// that code will pass the intl[12] tests.  This keeps us on an older
// reference build for all the other reference tests (javascript benchmarks,
// tab switch, etc.).
rlim_t GetFileDescriptorLimit(void) {
  struct rlimit limits;
  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
    return limits.rlim_cur;
  }
  PLOG(ERROR) << "Failed to get file descriptor limit";
  return 0;
}

void SetFileDescriptorLimit(rlim_t max_descriptors) {
  struct rlimit limits;
  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
    if (limits.rlim_max == 0) {
      limits.rlim_cur = max_descriptors;
    } else {
      limits.rlim_cur = std::min(max_descriptors, limits.rlim_max);
    }
    if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
      PLOG(ERROR) << "Failed to set file descriptor limit";
    }
  } else {
    PLOG(ERROR) << "Failed to get file descriptor limit";
  }
}

void PopulateUBC(const FilePath &test_dir) {
  // This will recursively walk the directory given and read all the files it
  // finds.  This is done so the Mac UBC is likely to have as much loaded as
  // possible.  Without this, the tests of this build gets one set of timings
  // and then the reference build test, gets slightly faster ones (even if the
  // reference build is the same binary).  The hope is by forcing all the
  // possible data into the UBC we equalize the tests for comparing timing data.

  // We don't want to walk into .svn dirs, so we have to do the tree walk
  // ourselves.

  std::vector<FilePath> dirs;
  dirs.push_back(test_dir);
  const FilePath svn_dir(FILE_PATH_LITERAL(".svn"));

  for (size_t idx = 0; idx < dirs.size(); ++idx) {
    file_util::FileEnumerator dir_enumerator(dirs[idx], false,
                                      file_util::FileEnumerator::DIRECTORIES);
    FilePath path;
    for (path = dir_enumerator.Next();
         !path.empty();
         path = dir_enumerator.Next()) {
      if (path.BaseName() != svn_dir)
        dirs.push_back(path);
    }
  }

  char buf[1024];
  unsigned int loaded = 0;

  // We seem to have some files in the data dirs that are just there for
  // reference, make a quick attempt to skip them by matching suffixes.
  std::vector<FilePath::StringType> ignore_suffixes;
  ignore_suffixes.push_back(FILE_PATH_LITERAL(".orig.html"));
  ignore_suffixes.push_back(FILE_PATH_LITERAL(".html-original"));

  std::vector<FilePath>::const_iterator iter;
  for (iter = dirs.begin(); iter != dirs.end(); ++iter) {
    file_util::FileEnumerator file_enumerator(*iter, false,
                                              file_util::FileEnumerator::FILES);
    FilePath path;
    for (path = file_enumerator.Next();
         !path.empty();
         path = file_enumerator.Next()) {
      const FilePath base_name = path.BaseName();
      const size_t base_name_size = base_name.value().size();

      bool should_skip = false;
      std::vector<FilePath::StringType>::const_iterator ignore_iter;
      for (ignore_iter = ignore_suffixes.begin();
           ignore_iter != ignore_suffixes.end();
           ++ignore_iter) {
        const FilePath::StringType &suffix = *ignore_iter;

        if ((base_name_size > suffix.size()) &&
            (base_name.value().compare(base_name_size - suffix.size(),
                                       suffix.size(), suffix) == 0)) {
          should_skip = true;
          break;
        }
      }
      if (should_skip)
        continue;

      // Read the file to get it into the UBC
      int fd = open(path.value().c_str(), O_RDONLY);
      if (fd >= 0) {
        ++loaded;
        while (HANDLE_EINTR(read(fd, buf, sizeof(buf))) > 0) {
        }
        HANDLE_EINTR(close(fd));
      }
    }
  }
  LOG(INFO) << "UBC should be loaded with " << loaded << " files.";
}
#endif  // defined(OS_MACOSX)

class PageCyclerTest : public UITest {
#if defined(OS_MACOSX)
 protected:
  rlim_t fd_limit_;
#endif
 public:
  PageCyclerTest() {
    show_window_ = true;

    // Expose garbage collection for the page cycler tests.
    launch_arguments_.AppendSwitchWithValue(switches::kJavaScriptFlags,
                                            L"--expose_gc");
#if defined(OS_MACOSX)
    static rlim_t initial_fd_limit = GetFileDescriptorLimit();
    fd_limit_ = initial_fd_limit;
#endif
  }

  void SetUp() {
#if defined(OS_MACOSX)
    SetFileDescriptorLimit(fd_limit_);
#endif
    UITest::SetUp();
  }

  // For HTTP tests, the name must be safe for use in a URL without escaping.
  void RunPageCycler(const char* name, std::wstring* pages,
                     std::string* timings, bool use_http) {
    // Make sure the test data is checked out
    FilePath test_path;
    PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("data"));
    test_path = test_path.Append(FILE_PATH_LITERAL("page_cycler"));
    test_path = test_path.AppendASCII(name);
    ASSERT_TRUE(file_util::PathExists(test_path)) << "Missing test data";

#if defined(OS_MACOSX)
    PopulateUBC(test_path);
#endif

    GURL test_url;
    if (use_http) {
      test_url = GURL(std::string(kBaseUrl) + name + "/start.html");
    } else {
      test_path = test_path.Append(FILE_PATH_LITERAL("start.html"));
      test_url = net::FilePathToFileURL(test_path);
    }

    // run N iterations
    GURL::Replacements replacements;
    const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
    replacements.SetQuery(
        query_string,
        url_parse::Component(0, arraysize(query_string) - 1));
    test_url = test_url.ReplaceComponents(replacements);

    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
                                     3000, UITest::test_timeout_ms(), "1"));

    std::string cookie;
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
    pages->assign(UTF8ToWide(cookie));
    ASSERT_FALSE(pages->empty());
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
    timings->assign(cookie);
    ASSERT_FALSE(timings->empty());
  }

  // When use_http is true, the test name passed here will be used directly in
  // the path to the test data, so it must be safe for use in a URL without
  // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
  // other funny stuff.)
  void RunTestWithSuffix(const char* name, bool use_http, const char* suffix) {
    std::wstring pages;
    std::string timings;
    size_t start_size = base::GetSystemCommitCharge();
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;
    size_t stop_size = base::GetSystemCommitCharge();

    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);

    PrintMemoryUsageInfo(suffix, data_dir);
    PrintIOPerfInfo(suffix, data_dir);
    PrintSystemCommitCharge(suffix, stop_size - start_size,
                            false /* not important */);

    std::string trace_name = "t" + std::string(suffix);
    wprintf(L"\nPages: [%ls]\n", pages.c_str());
    PrintResultList("times", "", trace_name, timings, "ms",
                    true /* important */);
  }

  void RunTest(const char* name, bool use_http) {
    RunTestWithSuffix(name, use_http, "");
  }
};

class PageCyclerReferenceTest : public PageCyclerTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
#if defined(OS_MACOSX)
    fd_limit_ = 1024;
#endif

    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    PageCyclerTest::SetUp();
  }

  void RunTest(const char* name, bool use_http) {
    std::wstring pages;
    std::string timings;
    size_t start_size = base::GetSystemCommitCharge();
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;
    size_t stop_size = base::GetSystemCommitCharge();

    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);

    PrintMemoryUsageInfo("_ref", data_dir);
    PrintIOPerfInfo("_ref", data_dir);
    PrintSystemCommitCharge("_ref", stop_size - start_size,
                            false /* not important */);

    PrintResultList("times", "", "t_ref", timings, "ms",
                    true /* important */);
  }
};

class PageCyclerExtensionTest : public PageCyclerTest {
 public:
  void SetUp() {}
  void RunTest(const char* extension_profile, const char* output_suffix,
               const char* name, bool use_http) {
    // Set up the extension profile directory.
    ASSERT_TRUE(extension_profile != NULL);
    FilePath data_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
    data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
        AppendASCII(extension_profile);
    ASSERT_TRUE(file_util::DirectoryExists(data_dir));
    set_template_user_data(data_dir);

    // Now run the test.
    PageCyclerTest::SetUp();
    PageCyclerTest::RunTestWithSuffix(name, use_http, output_suffix);
  }
};

// This macro simplifies setting up regular and reference build tests.
#define PAGE_CYCLER_TESTS(test, name, use_http) \
TEST_F(PageCyclerTest, name) { \
  RunTest(test, use_http); \
} \
TEST_F(PageCyclerReferenceTest, name) { \
  RunTest(test, use_http); \
}

// These are shorthand for File vs. Http tests.
#define PAGE_CYCLER_FILE_TESTS(test, name)\
  PAGE_CYCLER_TESTS(test, name, false)
#define PAGE_CYCLER_HTTP_TESTS(test, name)\
  PAGE_CYCLER_TESTS(test, name, true)

// This macro lets us define tests with 1 and 10 extensions with 1 content
// script each. The name for the 10-extension case is changed so as not
// to run by default on the buildbots.
#define PAGE_CYCLER_EXTENSIONS_FILE_TESTS(test, name) \
TEST_F(PageCyclerExtensionTest, name) {  \
  RunTest("content_scripts1", "_extcs1", test, false); \
} \
TEST_F(PageCyclerExtensionTest, name##10) { \
  RunTest("content_scripts10", "_extcs10", test, false); \
}

// file-URL tests
PAGE_CYCLER_FILE_TESTS("moz", MozFile);
PAGE_CYCLER_EXTENSIONS_FILE_TESTS("moz", MozFile);
PAGE_CYCLER_FILE_TESTS("intl1", Intl1File);
PAGE_CYCLER_FILE_TESTS("intl2", Intl2File);
PAGE_CYCLER_FILE_TESTS("dom", DomFile);
PAGE_CYCLER_FILE_TESTS("dhtml", DhtmlFile);
PAGE_CYCLER_FILE_TESTS("morejs", MorejsFile);
PAGE_CYCLER_EXTENSIONS_FILE_TESTS("morejs", MorejsFile);

// http (localhost) tests
PAGE_CYCLER_HTTP_TESTS("moz", MozHttp);
PAGE_CYCLER_HTTP_TESTS("intl1", Intl1Http);
PAGE_CYCLER_HTTP_TESTS("intl2", Intl2Http);
PAGE_CYCLER_HTTP_TESTS("dom", DomHttp);
PAGE_CYCLER_HTTP_TESTS("bloat", BloatHttp);

}  // namespace
<commit_msg>Sleep briefly before/after printing page cycler results.<commit_after>// Copyright (c) 2006-2009 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 "base/basictypes.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"

#if defined(OS_MACOSX)
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/resource.h>
#endif

#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif

// URL at which data files may be found for HTTP tests.  The document root of
// this URL's server should point to data/page_cycler/.
static const char kBaseUrl[] = "http://localhost:8000/";

namespace {

#if defined(OS_MACOSX)
// TODO(tvl/stuart): remove all this fd limit setting on the Mac when/if we
// replace the Mac reference build.  The trunk raises the limit within the
// browser app, but we do this here also so the current reference build without
// that code will pass the intl[12] tests.  This keeps us on an older
// reference build for all the other reference tests (javascript benchmarks,
// tab switch, etc.).
rlim_t GetFileDescriptorLimit(void) {
  struct rlimit limits;
  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
    return limits.rlim_cur;
  }
  PLOG(ERROR) << "Failed to get file descriptor limit";
  return 0;
}

void SetFileDescriptorLimit(rlim_t max_descriptors) {
  struct rlimit limits;
  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
    if (limits.rlim_max == 0) {
      limits.rlim_cur = max_descriptors;
    } else {
      limits.rlim_cur = std::min(max_descriptors, limits.rlim_max);
    }
    if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
      PLOG(ERROR) << "Failed to set file descriptor limit";
    }
  } else {
    PLOG(ERROR) << "Failed to get file descriptor limit";
  }
}

void PopulateUBC(const FilePath &test_dir) {
  // This will recursively walk the directory given and read all the files it
  // finds.  This is done so the Mac UBC is likely to have as much loaded as
  // possible.  Without this, the tests of this build gets one set of timings
  // and then the reference build test, gets slightly faster ones (even if the
  // reference build is the same binary).  The hope is by forcing all the
  // possible data into the UBC we equalize the tests for comparing timing data.

  // We don't want to walk into .svn dirs, so we have to do the tree walk
  // ourselves.

  std::vector<FilePath> dirs;
  dirs.push_back(test_dir);
  const FilePath svn_dir(FILE_PATH_LITERAL(".svn"));

  for (size_t idx = 0; idx < dirs.size(); ++idx) {
    file_util::FileEnumerator dir_enumerator(dirs[idx], false,
                                      file_util::FileEnumerator::DIRECTORIES);
    FilePath path;
    for (path = dir_enumerator.Next();
         !path.empty();
         path = dir_enumerator.Next()) {
      if (path.BaseName() != svn_dir)
        dirs.push_back(path);
    }
  }

  char buf[1024];
  unsigned int loaded = 0;

  // We seem to have some files in the data dirs that are just there for
  // reference, make a quick attempt to skip them by matching suffixes.
  std::vector<FilePath::StringType> ignore_suffixes;
  ignore_suffixes.push_back(FILE_PATH_LITERAL(".orig.html"));
  ignore_suffixes.push_back(FILE_PATH_LITERAL(".html-original"));

  std::vector<FilePath>::const_iterator iter;
  for (iter = dirs.begin(); iter != dirs.end(); ++iter) {
    file_util::FileEnumerator file_enumerator(*iter, false,
                                              file_util::FileEnumerator::FILES);
    FilePath path;
    for (path = file_enumerator.Next();
         !path.empty();
         path = file_enumerator.Next()) {
      const FilePath base_name = path.BaseName();
      const size_t base_name_size = base_name.value().size();

      bool should_skip = false;
      std::vector<FilePath::StringType>::const_iterator ignore_iter;
      for (ignore_iter = ignore_suffixes.begin();
           ignore_iter != ignore_suffixes.end();
           ++ignore_iter) {
        const FilePath::StringType &suffix = *ignore_iter;

        if ((base_name_size > suffix.size()) &&
            (base_name.value().compare(base_name_size - suffix.size(),
                                       suffix.size(), suffix) == 0)) {
          should_skip = true;
          break;
        }
      }
      if (should_skip)
        continue;

      // Read the file to get it into the UBC
      int fd = open(path.value().c_str(), O_RDONLY);
      if (fd >= 0) {
        ++loaded;
        while (HANDLE_EINTR(read(fd, buf, sizeof(buf))) > 0) {
        }
        HANDLE_EINTR(close(fd));
      }
    }
  }
  LOG(INFO) << "UBC should be loaded with " << loaded << " files.";
}
#endif  // defined(OS_MACOSX)

class PageCyclerTest : public UITest {
#if defined(OS_MACOSX)
 protected:
  rlim_t fd_limit_;
#endif
 public:
  PageCyclerTest() {
    show_window_ = true;

    // Expose garbage collection for the page cycler tests.
    launch_arguments_.AppendSwitchWithValue(switches::kJavaScriptFlags,
                                            L"--expose_gc");
#if defined(OS_MACOSX)
    static rlim_t initial_fd_limit = GetFileDescriptorLimit();
    fd_limit_ = initial_fd_limit;
#endif
  }

  void SetUp() {
#if defined(OS_MACOSX)
    SetFileDescriptorLimit(fd_limit_);
#endif
    UITest::SetUp();
  }

  // For HTTP tests, the name must be safe for use in a URL without escaping.
  void RunPageCycler(const char* name, std::wstring* pages,
                     std::string* timings, bool use_http) {
    // Make sure the test data is checked out
    FilePath test_path;
    PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("data"));
    test_path = test_path.Append(FILE_PATH_LITERAL("page_cycler"));
    test_path = test_path.AppendASCII(name);
    ASSERT_TRUE(file_util::PathExists(test_path)) << "Missing test data";

#if defined(OS_MACOSX)
    PopulateUBC(test_path);
#endif

    GURL test_url;
    if (use_http) {
      test_url = GURL(std::string(kBaseUrl) + name + "/start.html");
    } else {
      test_path = test_path.Append(FILE_PATH_LITERAL("start.html"));
      test_url = net::FilePathToFileURL(test_path);
    }

    // run N iterations
    GURL::Replacements replacements;
    const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
    replacements.SetQuery(
        query_string,
        url_parse::Component(0, arraysize(query_string) - 1));
    test_url = test_url.ReplaceComponents(replacements);

    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());
    tab->NavigateToURL(test_url);

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
                                     3000, UITest::test_timeout_ms(), "1"));

    std::string cookie;
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
    pages->assign(UTF8ToWide(cookie));
    ASSERT_FALSE(pages->empty());
    ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
    timings->assign(cookie);
    ASSERT_FALSE(timings->empty());
  }

  // When use_http is true, the test name passed here will be used directly in
  // the path to the test data, so it must be safe for use in a URL without
  // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
  // other funny stuff.)
  void RunTestWithSuffix(const char* name, bool use_http, const char* suffix) {
    std::wstring pages;
    std::string timings;
    size_t start_size = base::GetSystemCommitCharge();
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;
    // wait 2 seconds to allow automation messages to print
    PlatformThread::Sleep(2000);
    size_t stop_size = base::GetSystemCommitCharge();

    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);

    PrintMemoryUsageInfo(suffix, data_dir);
    PrintIOPerfInfo(suffix, data_dir);
    PrintSystemCommitCharge(suffix, stop_size - start_size,
                            false /* not important */);

    std::string trace_name = "t" + std::string(suffix);
    wprintf(L"\nPages: [%ls]\n", pages.c_str());
    PrintResultList("times", "", trace_name, timings, "ms",
                    true /* important */);
    // wait 2 seconds to allow automation messages to print
    PlatformThread::Sleep(2000);
  }

  void RunTest(const char* name, bool use_http) {
    RunTestWithSuffix(name, use_http, "");
  }
};

class PageCyclerReferenceTest : public PageCyclerTest {
 public:
  // override the browser directory that is used by UITest::SetUp to cause it
  // to use the reference build instead.
  void SetUp() {
#if defined(OS_MACOSX)
    fd_limit_ = 1024;
#endif

    FilePath dir;
    PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
    dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
    dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
    dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
    dir = dir.AppendASCII("chrome_mac");
#endif
    browser_directory_ = dir;
    PageCyclerTest::SetUp();
  }

  void RunTest(const char* name, bool use_http) {
    std::wstring pages;
    std::string timings;
    size_t start_size = base::GetSystemCommitCharge();
    RunPageCycler(name, &pages, &timings, use_http);
    if (timings.empty())
      return;
    size_t stop_size = base::GetSystemCommitCharge();

    FilePath data_dir;
    PathService::Get(chrome::DIR_USER_DATA, &data_dir);

    PrintMemoryUsageInfo("_ref", data_dir);
    PrintIOPerfInfo("_ref", data_dir);
    PrintSystemCommitCharge("_ref", stop_size - start_size,
                            false /* not important */);

    PrintResultList("times", "", "t_ref", timings, "ms",
                    true /* important */);
  }
};

class PageCyclerExtensionTest : public PageCyclerTest {
 public:
  void SetUp() {}
  void RunTest(const char* extension_profile, const char* output_suffix,
               const char* name, bool use_http) {
    // Set up the extension profile directory.
    ASSERT_TRUE(extension_profile != NULL);
    FilePath data_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &data_dir);
    data_dir = data_dir.AppendASCII("extensions").AppendASCII("profiles").
        AppendASCII(extension_profile);
    ASSERT_TRUE(file_util::DirectoryExists(data_dir));
    set_template_user_data(data_dir);

    // Now run the test.
    PageCyclerTest::SetUp();
    PageCyclerTest::RunTestWithSuffix(name, use_http, output_suffix);
  }
};

// This macro simplifies setting up regular and reference build tests.
#define PAGE_CYCLER_TESTS(test, name, use_http) \
TEST_F(PageCyclerTest, name) { \
  RunTest(test, use_http); \
} \
TEST_F(PageCyclerReferenceTest, name) { \
  RunTest(test, use_http); \
}

// These are shorthand for File vs. Http tests.
#define PAGE_CYCLER_FILE_TESTS(test, name)\
  PAGE_CYCLER_TESTS(test, name, false)
#define PAGE_CYCLER_HTTP_TESTS(test, name)\
  PAGE_CYCLER_TESTS(test, name, true)

// This macro lets us define tests with 1 and 10 extensions with 1 content
// script each. The name for the 10-extension case is changed so as not
// to run by default on the buildbots.
#define PAGE_CYCLER_EXTENSIONS_FILE_TESTS(test, name) \
TEST_F(PageCyclerExtensionTest, name) {  \
  RunTest("content_scripts1", "_extcs1", test, false); \
} \
TEST_F(PageCyclerExtensionTest, name##10) { \
  RunTest("content_scripts10", "_extcs10", test, false); \
}

// file-URL tests
PAGE_CYCLER_FILE_TESTS("moz", MozFile);
PAGE_CYCLER_EXTENSIONS_FILE_TESTS("moz", MozFile);
PAGE_CYCLER_FILE_TESTS("intl1", Intl1File);
PAGE_CYCLER_FILE_TESTS("intl2", Intl2File);
PAGE_CYCLER_FILE_TESTS("dom", DomFile);
PAGE_CYCLER_FILE_TESTS("dhtml", DhtmlFile);
PAGE_CYCLER_FILE_TESTS("morejs", MorejsFile);
PAGE_CYCLER_EXTENSIONS_FILE_TESTS("morejs", MorejsFile);

// http (localhost) tests
PAGE_CYCLER_HTTP_TESTS("moz", MozHttp);
PAGE_CYCLER_HTTP_TESTS("intl1", Intl1Http);
PAGE_CYCLER_HTTP_TESTS("intl2", Intl2Http);
PAGE_CYCLER_HTTP_TESTS("dom", DomHttp);
PAGE_CYCLER_HTTP_TESTS("bloat", BloatHttp);

}  // namespace
<|endoftext|>


<commit_before>// Copyright 2013 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 "chromeos/dbus/cros_disks_client.h"

#include "base/memory/scoped_ptr.h"
#include "dbus/message.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace chromeos {

namespace {

// Appends a boolean entry to a dictionary of type "a{sv}"
void AppendBoolDictEntry(dbus::MessageWriter* array_writer,
                         const std::string& key,
                         bool value) {
  dbus::MessageWriter entry_writer(NULL);
  array_writer->OpenDictEntry(&entry_writer);
  entry_writer.AppendString(key);
  entry_writer.AppendVariantOfBool(value);
  array_writer->CloseContainer(&entry_writer);
}

// Appends a string entry to a dictionary of type "a{sv}"
void AppendStringDictEntry(dbus::MessageWriter* array_writer,
                           const std::string& key,
                           const std::string& value) {
  dbus::MessageWriter entry_writer(NULL);
  array_writer->OpenDictEntry(&entry_writer);
  entry_writer.AppendString(key);
  entry_writer.AppendVariantOfString(value);
  array_writer->CloseContainer(&entry_writer);
}

}  // namespace

TEST(CrosDisksClientTest, DiskInfo) {
  const std::string kDeviceFile = "/dev/sdb1";
  const bool kDeviceIsDrive = true;
  const bool kDeviceIsMediaAvailable = true;
  const bool kDeviceIsMounted = true;
  const bool kDeviceIsOnBootDevice = true;
  const bool kDeviceIsReadOnly = true;
  const uint32 kDeviceMediaType = cros_disks::DEVICE_MEDIA_SD;
  const std::string kMountPath = "/media/removable/UNTITLED";
  const bool kDevicePresentationHide = false;
  const uint64 kDeviceSize = 16005464064;
  const std::string kDriveModel = "DriveModel";
  const std::string kIdLabel = "UNTITLED";
  const std::string kIdUuid = "XXXX-YYYY";
  const std::string kNativePath = "/sys/devices/.../sdb/sdb1";
  const std::string kProductId = "1234";
  const std::string kProductName = "Product Name";
  const std::string kVendorId = "0000";
  const std::string kVendorName = "Vendor Name";

  // Construct a fake response of GetDeviceProperties().
  scoped_ptr<dbus::Response> response(dbus::Response::CreateEmpty());
  {
    dbus::MessageWriter writer(response.get());
    dbus::MessageWriter array_writer(NULL);
    writer.OpenArray("{sv}", &array_writer);

    AppendStringDictEntry(&array_writer, cros_disks::kDeviceFile, kDeviceFile);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsDrive,
                        kDeviceIsDrive);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsMediaAvailable,
                        kDeviceIsMediaAvailable);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsMounted,
                        kDeviceIsMounted);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsOnBootDevice,
                        kDeviceIsOnBootDevice);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsReadOnly,
                        kDeviceIsReadOnly);
    {
      dbus::MessageWriter entry_writer(NULL);
      array_writer.OpenDictEntry(&entry_writer);
      entry_writer.AppendString(cros_disks::kDeviceMediaType);
      entry_writer.AppendVariantOfUint32(kDeviceMediaType);
      array_writer.CloseContainer(&entry_writer);
    }
    {
      std::vector<std::string> mounted_paths;
      mounted_paths.push_back(kMountPath);

      dbus::MessageWriter entry_writer(NULL);
      array_writer.OpenDictEntry(&entry_writer);
      entry_writer.AppendString(cros_disks::kDeviceMountPaths);
      dbus::MessageWriter variant_writer(NULL);
      entry_writer.OpenVariant("as", &variant_writer);
      variant_writer.AppendArrayOfStrings(mounted_paths);
      entry_writer.CloseContainer(&variant_writer);
      array_writer.CloseContainer(&entry_writer);
    }
    AppendBoolDictEntry(&array_writer, cros_disks::kDevicePresentationHide,
                        kDevicePresentationHide);
    {
      dbus::MessageWriter entry_writer(NULL);
      array_writer.OpenDictEntry(&entry_writer);
      entry_writer.AppendString(cros_disks::kDeviceSize);
      entry_writer.AppendVariantOfUint64(kDeviceSize);
      array_writer.CloseContainer(&entry_writer);
    }
    AppendStringDictEntry(&array_writer, cros_disks::kDriveModel, kDriveModel);
    AppendStringDictEntry(&array_writer, cros_disks::kIdLabel, kIdLabel);
    AppendStringDictEntry(&array_writer, cros_disks::kIdUuid, kIdUuid);
    AppendStringDictEntry(&array_writer, cros_disks::kNativePath, kNativePath);
    AppendStringDictEntry(&array_writer, cros_disks::kProductId, kProductId);
    AppendStringDictEntry(&array_writer, cros_disks::kProductName,
                          kProductName);
    AppendStringDictEntry(&array_writer, cros_disks::kVendorId, kVendorId);
    AppendStringDictEntry(&array_writer, cros_disks::kVendorName, kVendorName);

    writer.CloseContainer(&array_writer);
  }

  // Construct DiskInfo.
  DiskInfo result(kDeviceFile, response.get());
  EXPECT_EQ(kDeviceFile, result.device_path());
  EXPECT_EQ(kDeviceIsDrive, result.is_drive());
  EXPECT_EQ(kDeviceIsReadOnly, result.is_read_only());
  EXPECT_EQ(kDevicePresentationHide, result.is_hidden());
  EXPECT_EQ(kDeviceIsMediaAvailable, result.has_media());
  EXPECT_EQ(kDeviceIsOnBootDevice, result.on_boot_device());
  EXPECT_EQ(kNativePath, result.system_path());
  EXPECT_EQ(kDeviceFile, result.file_path());
  EXPECT_EQ(kVendorId, result.vendor_id());
  EXPECT_EQ(kVendorName, result.vendor_name());
  EXPECT_EQ(kProductId, result.product_id());
  EXPECT_EQ(kProductName, result.product_name());
  EXPECT_EQ(kDriveModel, result.drive_label());
  EXPECT_EQ(kIdLabel, result.label());
  EXPECT_EQ(kIdUuid, result.uuid());
  EXPECT_EQ(kDeviceSize, result.total_size_in_bytes());
  EXPECT_EQ(DEVICE_TYPE_SD, result.device_type());
  EXPECT_EQ(kMountPath, result.mount_path());
}

}  // namespace chromeos
<commit_msg>Fix gcc 4.7 compilation errors in chromeos_unittests<commit_after>// Copyright 2013 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 "chromeos/dbus/cros_disks_client.h"

#include "base/memory/scoped_ptr.h"
#include "dbus/message.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace chromeos {

namespace {

// Appends a boolean entry to a dictionary of type "a{sv}"
void AppendBoolDictEntry(dbus::MessageWriter* array_writer,
                         const std::string& key,
                         bool value) {
  dbus::MessageWriter entry_writer(NULL);
  array_writer->OpenDictEntry(&entry_writer);
  entry_writer.AppendString(key);
  entry_writer.AppendVariantOfBool(value);
  array_writer->CloseContainer(&entry_writer);
}

// Appends a string entry to a dictionary of type "a{sv}"
void AppendStringDictEntry(dbus::MessageWriter* array_writer,
                           const std::string& key,
                           const std::string& value) {
  dbus::MessageWriter entry_writer(NULL);
  array_writer->OpenDictEntry(&entry_writer);
  entry_writer.AppendString(key);
  entry_writer.AppendVariantOfString(value);
  array_writer->CloseContainer(&entry_writer);
}

}  // namespace

TEST(CrosDisksClientTest, DiskInfo) {
  const std::string kDeviceFile = "/dev/sdb1";
  const bool kDeviceIsDrive = true;
  const bool kDeviceIsMediaAvailable = true;
  const bool kDeviceIsMounted = true;
  const bool kDeviceIsOnBootDevice = true;
  const bool kDeviceIsReadOnly = true;
  const uint32 kDeviceMediaType = cros_disks::DEVICE_MEDIA_SD;
  const std::string kMountPath = "/media/removable/UNTITLED";
  const bool kDevicePresentationHide = false;
  const uint64 kDeviceSize = 16005464064;
  const std::string kDriveModel = "DriveModel";
  const std::string kIdLabel = "UNTITLED";
  const std::string kIdUuid = "XXXX-YYYY";
  const std::string kNativePath = "/sys/devices/.../sdb/sdb1";
  const std::string kProductId = "1234";
  const std::string kProductName = "Product Name";
  const std::string kVendorId = "0000";
  const std::string kVendorName = "Vendor Name";

  // Construct a fake response of GetDeviceProperties().
  scoped_ptr<dbus::Response> response(dbus::Response::CreateEmpty());
  {
    dbus::MessageWriter writer(response.get());
    dbus::MessageWriter array_writer(NULL);
    writer.OpenArray("{sv}", &array_writer);

    AppendStringDictEntry(&array_writer, cros_disks::kDeviceFile, kDeviceFile);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsDrive,
                        kDeviceIsDrive);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsMediaAvailable,
                        kDeviceIsMediaAvailable);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsMounted,
                        kDeviceIsMounted);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsOnBootDevice,
                        kDeviceIsOnBootDevice);
    AppendBoolDictEntry(&array_writer, cros_disks::kDeviceIsReadOnly,
                        kDeviceIsReadOnly);
    {
      dbus::MessageWriter entry_writer(NULL);
      array_writer.OpenDictEntry(&entry_writer);
      entry_writer.AppendString(cros_disks::kDeviceMediaType);
      entry_writer.AppendVariantOfUint32(kDeviceMediaType);
      array_writer.CloseContainer(&entry_writer);
    }
    {
      std::vector<std::string> mounted_paths;
      mounted_paths.push_back(kMountPath);

      dbus::MessageWriter entry_writer(NULL);
      array_writer.OpenDictEntry(&entry_writer);
      entry_writer.AppendString(cros_disks::kDeviceMountPaths);
      dbus::MessageWriter variant_writer(NULL);
      entry_writer.OpenVariant("as", &variant_writer);
      variant_writer.AppendArrayOfStrings(mounted_paths);
      entry_writer.CloseContainer(&variant_writer);
      array_writer.CloseContainer(&entry_writer);
    }
    AppendBoolDictEntry(&array_writer, cros_disks::kDevicePresentationHide,
                        kDevicePresentationHide);
    {
      dbus::MessageWriter entry_writer(NULL);
      array_writer.OpenDictEntry(&entry_writer);
      entry_writer.AppendString(cros_disks::kDeviceSize);
      entry_writer.AppendVariantOfUint64(kDeviceSize);
      array_writer.CloseContainer(&entry_writer);
    }
    AppendStringDictEntry(&array_writer, cros_disks::kDriveModel, kDriveModel);
    AppendStringDictEntry(&array_writer, cros_disks::kIdLabel, kIdLabel);
    AppendStringDictEntry(&array_writer, cros_disks::kIdUuid, kIdUuid);
    AppendStringDictEntry(&array_writer, cros_disks::kNativePath, kNativePath);
    AppendStringDictEntry(&array_writer, cros_disks::kProductId, kProductId);
    AppendStringDictEntry(&array_writer, cros_disks::kProductName,
                          kProductName);
    AppendStringDictEntry(&array_writer, cros_disks::kVendorId, kVendorId);
    AppendStringDictEntry(&array_writer, cros_disks::kVendorName, kVendorName);

    writer.CloseContainer(&array_writer);
  }

  // Construct DiskInfo.
  DiskInfo result(kDeviceFile, response.get());
  EXPECT_EQ(kDeviceFile, result.device_path());
  EXPECT_EQ(kDeviceIsDrive, result.is_drive());
  EXPECT_EQ(kDeviceIsReadOnly, result.is_read_only());
  // Use EXPECT_TRUE(kDevicePresentationHide == result.is_hidden()) instead of
  // EXPECT_EQ(kDevicePresentationHide, result.is_hidden()) as gcc 4.7 issues
  // the following warning on EXPECT_EQ(false, x), which is turned into an error
  // with -Werror=conversion-null:
  //
  //   converting 'false' to pointer type for argument 1 of
  //   'char testing::internal::IsNullLiteralHelper(testing::internal::Secret*)'
  EXPECT_TRUE(kDevicePresentationHide == result.is_hidden());
  EXPECT_EQ(kDeviceIsMediaAvailable, result.has_media());
  EXPECT_EQ(kDeviceIsOnBootDevice, result.on_boot_device());
  EXPECT_EQ(kNativePath, result.system_path());
  EXPECT_EQ(kDeviceFile, result.file_path());
  EXPECT_EQ(kVendorId, result.vendor_id());
  EXPECT_EQ(kVendorName, result.vendor_name());
  EXPECT_EQ(kProductId, result.product_id());
  EXPECT_EQ(kProductName, result.product_name());
  EXPECT_EQ(kDriveModel, result.drive_label());
  EXPECT_EQ(kIdLabel, result.label());
  EXPECT_EQ(kIdUuid, result.uuid());
  EXPECT_EQ(kDeviceSize, result.total_size_in_bytes());
  EXPECT_EQ(DEVICE_TYPE_SD, result.device_type());
  EXPECT_EQ(kMountPath, result.mount_path());
}

}  // namespace chromeos
<|endoftext|>


<commit_before><commit_msg>Reorder `#include` lines into canonical order.<commit_after><|endoftext|>