<commit_before>/**
 * @copyright
 * ====================================================================
 * Copyright (c) 2007 CollabNet.  All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.  The terms
 * are also available at http://subversion.tigris.org/license-1.html.
 * If newer versions of this license are posted there, you may use a
 * newer version instead, at your option.
 *
 * This software consists of voluntary contributions made by many
 * individuals.  For exact contribution history, see the revision
 * history and logs, available at http://subversion.tigris.org/.
 * ====================================================================
 * @endcopyright
 *
 * @file ConflictResolverCallback.cpp
 * @brief Implementation of the class ConflictResolverCallback.
 */

#include "svn_error.h"

#include "../include/org_tigris_subversion_javahl_ConflictResult.h"
#include "JNIUtil.h"
#include "JNIStringHolder.h"
#include "EnumMapper.h"
#include "ConflictResolverCallback.h"

ConflictResolverCallback::ConflictResolverCallback(jobject jconflictResolver)
{
  m_conflictResolver = jconflictResolver;
}

ConflictResolverCallback::~ConflictResolverCallback()
{
  if (m_conflictResolver != NULL)
    {
      JNIEnv *env = JNIUtil::getEnv();
      env->DeleteGlobalRef(m_conflictResolver);
    }
}

ConflictResolverCallback *
ConflictResolverCallback::makeCConflictResolverCallback(jobject jconflictResolver)
{
  if (jconflictResolver == NULL)
    return NULL;

  JNIEnv *env = JNIUtil::getEnv();

  // Sanity check that the object implements the ConflictResolverCallback
  // Java interface.
  jclass clazz = env->FindClass(JAVA_PACKAGE "/ConflictResolverCallback");
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  if (!env->IsInstanceOf(jconflictResolver, clazz))
    {
      env->DeleteLocalRef(clazz);
      return NULL;
    }
  env->DeleteLocalRef(clazz);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  // Retain a global reference to our Java peer.
  jobject myListener = env->NewGlobalRef(jconflictResolver);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  // Create the peer.
  return new ConflictResolverCallback(myListener);
}

svn_error_t *
ConflictResolverCallback::resolveConflict(svn_wc_conflict_result_t **result,
                                          const svn_wc_conflict_description_t *
                                          desc,
                                          void *baton,
                                          apr_pool_t *pool)
{
  if (baton)
    return ((ConflictResolverCallback *) baton)->resolve(result, desc, pool);
  else
    return SVN_NO_ERROR;
}

svn_error_t *
ConflictResolverCallback::resolve(svn_wc_conflict_result_t **result,
                                  const svn_wc_conflict_description_t *desc,
                                  apr_pool_t *pool)
{
  JNIEnv *env = JNIUtil::getEnv();

  // As Java method IDs will not change during the time this library
  // is loaded, they can be cached.
  static jmethodID mid = 0;
  if (mid == 0)
    {
      // Initialize the callback method ID.
      jclass clazz = env->FindClass(JAVA_PACKAGE "/ConflictResolverCallback");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      mid = env->GetMethodID(clazz, "resolve",
                             "(L" JAVA_PACKAGE "/ConflictDescriptor;)"
                             "L" JAVA_PACKAGE "/ConflictResult;");
      if (JNIUtil::isJavaExceptionThrown() || mid == 0)
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  // Create an instance of the conflict descriptor.
  static jmethodID ctor = 0;
  jclass clazz = env->FindClass(JAVA_PACKAGE "/ConflictDescriptor");
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  if (ctor == 0)
    {
      ctor = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;II"
                              "Ljava/lang/String;ZLjava/lang/String;II"
                              "Ljava/lang/String;Ljava/lang/String;"
                              "Ljava/lang/String;Ljava/lang/String;)V");
      if (JNIUtil::isJavaExceptionThrown() || ctor == 0)
        return SVN_NO_ERROR;
    }

  jstring jpath = JNIUtil::makeJString(desc->path);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jpropertyName = JNIUtil::makeJString(desc->property_name);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jmimeType = JNIUtil::makeJString(desc->mime_type);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jbasePath = JNIUtil::makeJString(desc->base_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jreposPath = JNIUtil::makeJString(desc->their_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring juserPath = JNIUtil::makeJString(desc->my_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jmergedPath = JNIUtil::makeJString(desc->merged_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // Instantiate the conflict descriptor.
  jobject jdesc = env->NewObject(clazz, ctor, jpath,
                                 EnumMapper::mapConflictKind(desc->kind),
                                 EnumMapper::mapNodeKind(desc->node_kind),
                                 jpropertyName,
                                 (jboolean) desc->is_binary, jmimeType,
                                 EnumMapper::mapConflictAction(desc->action),
                                 EnumMapper::mapConflictReason(desc->reason),
                                 jbasePath, jreposPath, juserPath,
                                 jmergedPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(clazz);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // Invoke the Java conflict resolver callback method using the descriptor.
  jobject jresult = env->CallObjectMethod(m_conflictResolver, mid, jdesc);
  if (JNIUtil::isJavaExceptionThrown())
    {
      // If an exception is thrown by our conflict resolver, remove it
      // from the JNI env, and convert it into a Subversion error.
      const char *msg = JNIUtil::thrownExceptionToCString();
      return svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, msg);
    }
  *result = javaResultToC(jresult, pool);
  if (*result == NULL)
    // Unable to convert the result into a C representation.
    return svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, NULL);

  env->DeleteLocalRef(jpath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jpropertyName);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jmimeType);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jbasePath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jreposPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(juserPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jmergedPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(jdesc);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  return SVN_NO_ERROR;
}

svn_wc_conflict_result_t *
ConflictResolverCallback::javaResultToC(jobject jresult, apr_pool_t *pool)
{
  JNIEnv *env = JNIUtil::getEnv();
  static jmethodID getChoice = 0;
  static jmethodID getMergedPath = 0;

  jclass clazz = NULL;
  if (getChoice == 0 || getMergedPath == 0)
    {
      clazz = env->FindClass(JAVA_PACKAGE "/ConflictResult");
      if (JNIUtil::isJavaExceptionThrown())
        return NULL;
    }

  if (getChoice == 0)
    {
      getChoice = env->GetMethodID(clazz, "getChoice", "()I");
      if (JNIUtil::isJavaExceptionThrown() || getChoice == 0)
        return NULL;
    }
  if (getMergedPath == 0)
    {
      getMergedPath = env->GetMethodID(clazz, "getMergedPath",
                                       "()Ljava/lang/String;");
      if (JNIUtil::isJavaExceptionThrown() || getMergedPath == 0)
        return NULL;
    }

  if (clazz)
    {
      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return NULL;
    }

  jint jchoice = env->CallIntMethod(jresult, getChoice);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  jstring jmergedPath =
    (jstring) env->CallObjectMethod(jresult, getMergedPath);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;
  JNIStringHolder mergedPath(jmergedPath);

  return svn_wc_create_conflict_result(javaChoiceToC(jchoice),
                                       mergedPath.pstrdup(pool),
                                       pool);
}

svn_wc_conflict_choice_t ConflictResolverCallback::javaChoiceToC(jint jchoice)
{
  switch (jchoice)
    {
    case org_tigris_subversion_javahl_ConflictResult_postpone:
    default:
      return svn_wc_conflict_choose_postpone;
    case org_tigris_subversion_javahl_ConflictResult_chooseBase:
      return svn_wc_conflict_choose_base;
    case org_tigris_subversion_javahl_ConflictResult_chooseTheirsFull:
      return svn_wc_conflict_choose_theirs_full;
    case org_tigris_subversion_javahl_ConflictResult_chooseMineFull:
      return svn_wc_conflict_choose_mine_full;
    case org_tigris_subversion_javahl_ConflictResult_chooseTheirs:
      return svn_wc_conflict_choose_theirs_conflict;
    case org_tigris_subversion_javahl_ConflictResult_chooseMine:
      return svn_wc_conflict_choose_mine_conflict;
    case org_tigris_subversion_javahl_ConflictResult_chooseMerged:
      return svn_wc_conflict_choose_merged;
    }
}
<commit_msg>Follow up to r29650 with further name consistification:<commit_after>/**
 * @copyright
 * ====================================================================
 * Copyright (c) 2007 CollabNet.  All rights reserved.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution.  The terms
 * are also available at http://subversion.tigris.org/license-1.html.
 * If newer versions of this license are posted there, you may use a
 * newer version instead, at your option.
 *
 * This software consists of voluntary contributions made by many
 * individuals.  For exact contribution history, see the revision
 * history and logs, available at http://subversion.tigris.org/.
 * ====================================================================
 * @endcopyright
 *
 * @file ConflictResolverCallback.cpp
 * @brief Implementation of the class ConflictResolverCallback.
 */

#include "svn_error.h"

#include "../include/org_tigris_subversion_javahl_ConflictResult.h"
#include "JNIUtil.h"
#include "JNIStringHolder.h"
#include "EnumMapper.h"
#include "ConflictResolverCallback.h"

ConflictResolverCallback::ConflictResolverCallback(jobject jconflictResolver)
{
  m_conflictResolver = jconflictResolver;
}

ConflictResolverCallback::~ConflictResolverCallback()
{
  if (m_conflictResolver != NULL)
    {
      JNIEnv *env = JNIUtil::getEnv();
      env->DeleteGlobalRef(m_conflictResolver);
    }
}

ConflictResolverCallback *
ConflictResolverCallback::makeCConflictResolverCallback(jobject jconflictResolver)
{
  if (jconflictResolver == NULL)
    return NULL;

  JNIEnv *env = JNIUtil::getEnv();

  // Sanity check that the object implements the ConflictResolverCallback
  // Java interface.
  jclass clazz = env->FindClass(JAVA_PACKAGE "/ConflictResolverCallback");
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  if (!env->IsInstanceOf(jconflictResolver, clazz))
    {
      env->DeleteLocalRef(clazz);
      return NULL;
    }
  env->DeleteLocalRef(clazz);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  // Retain a global reference to our Java peer.
  jobject myListener = env->NewGlobalRef(jconflictResolver);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  // Create the peer.
  return new ConflictResolverCallback(myListener);
}

svn_error_t *
ConflictResolverCallback::resolveConflict(svn_wc_conflict_result_t **result,
                                          const svn_wc_conflict_description_t *
                                          desc,
                                          void *baton,
                                          apr_pool_t *pool)
{
  if (baton)
    return ((ConflictResolverCallback *) baton)->resolve(result, desc, pool);
  else
    return SVN_NO_ERROR;
}

svn_error_t *
ConflictResolverCallback::resolve(svn_wc_conflict_result_t **result,
                                  const svn_wc_conflict_description_t *desc,
                                  apr_pool_t *pool)
{
  JNIEnv *env = JNIUtil::getEnv();

  // As Java method IDs will not change during the time this library
  // is loaded, they can be cached.
  static jmethodID mid = 0;
  if (mid == 0)
    {
      // Initialize the callback method ID.
      jclass clazz = env->FindClass(JAVA_PACKAGE "/ConflictResolverCallback");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      mid = env->GetMethodID(clazz, "resolve",
                             "(L" JAVA_PACKAGE "/ConflictDescriptor;)"
                             "L" JAVA_PACKAGE "/ConflictResult;");
      if (JNIUtil::isJavaExceptionThrown() || mid == 0)
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  // Create an instance of the conflict descriptor.
  static jmethodID ctor = 0;
  jclass clazz = env->FindClass(JAVA_PACKAGE "/ConflictDescriptor");
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  if (ctor == 0)
    {
      ctor = env->GetMethodID(clazz, "<init>", "(Ljava/lang/String;II"
                              "Ljava/lang/String;ZLjava/lang/String;II"
                              "Ljava/lang/String;Ljava/lang/String;"
                              "Ljava/lang/String;Ljava/lang/String;)V");
      if (JNIUtil::isJavaExceptionThrown() || ctor == 0)
        return SVN_NO_ERROR;
    }

  jstring jpath = JNIUtil::makeJString(desc->path);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jpropertyName = JNIUtil::makeJString(desc->property_name);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jmimeType = JNIUtil::makeJString(desc->mime_type);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jbasePath = JNIUtil::makeJString(desc->base_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jreposPath = JNIUtil::makeJString(desc->their_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring juserPath = JNIUtil::makeJString(desc->my_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  jstring jmergedPath = JNIUtil::makeJString(desc->merged_file);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // Instantiate the conflict descriptor.
  jobject jdesc = env->NewObject(clazz, ctor, jpath,
                                 EnumMapper::mapConflictKind(desc->kind),
                                 EnumMapper::mapNodeKind(desc->node_kind),
                                 jpropertyName,
                                 (jboolean) desc->is_binary, jmimeType,
                                 EnumMapper::mapConflictAction(desc->action),
                                 EnumMapper::mapConflictReason(desc->reason),
                                 jbasePath, jreposPath, juserPath,
                                 jmergedPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(clazz);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // Invoke the Java conflict resolver callback method using the descriptor.
  jobject jresult = env->CallObjectMethod(m_conflictResolver, mid, jdesc);
  if (JNIUtil::isJavaExceptionThrown())
    {
      // If an exception is thrown by our conflict resolver, remove it
      // from the JNI env, and convert it into a Subversion error.
      const char *msg = JNIUtil::thrownExceptionToCString();
      return svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, msg);
    }
  *result = javaResultToC(jresult, pool);
  if (*result == NULL)
    // Unable to convert the result into a C representation.
    return svn_error_create(SVN_ERR_WC_CONFLICT_RESOLVER_FAILURE, NULL, NULL);

  env->DeleteLocalRef(jpath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jpropertyName);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jmimeType);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jbasePath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jreposPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(juserPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;
  env->DeleteLocalRef(jmergedPath);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(jdesc);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  return SVN_NO_ERROR;
}

svn_wc_conflict_result_t *
ConflictResolverCallback::javaResultToC(jobject jresult, apr_pool_t *pool)
{
  JNIEnv *env = JNIUtil::getEnv();
  static jmethodID getChoice = 0;
  static jmethodID getMergedPath = 0;

  jclass clazz = NULL;
  if (getChoice == 0 || getMergedPath == 0)
    {
      clazz = env->FindClass(JAVA_PACKAGE "/ConflictResult");
      if (JNIUtil::isJavaExceptionThrown())
        return NULL;
    }

  if (getChoice == 0)
    {
      getChoice = env->GetMethodID(clazz, "getChoice", "()I");
      if (JNIUtil::isJavaExceptionThrown() || getChoice == 0)
        return NULL;
    }
  if (getMergedPath == 0)
    {
      getMergedPath = env->GetMethodID(clazz, "getMergedPath",
                                       "()Ljava/lang/String;");
      if (JNIUtil::isJavaExceptionThrown() || getMergedPath == 0)
        return NULL;
    }

  if (clazz)
    {
      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return NULL;
    }

  jint jchoice = env->CallIntMethod(jresult, getChoice);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;

  jstring jmergedPath =
    (jstring) env->CallObjectMethod(jresult, getMergedPath);
  if (JNIUtil::isJavaExceptionThrown())
    return NULL;
  JNIStringHolder mergedPath(jmergedPath);

  return svn_wc_create_conflict_result(javaChoiceToC(jchoice),
                                       mergedPath.pstrdup(pool),
                                       pool);
}

svn_wc_conflict_choice_t ConflictResolverCallback::javaChoiceToC(jint jchoice)
{
  switch (jchoice)
    {
    case org_tigris_subversion_javahl_ConflictResult_postpone:
    default:
      return svn_wc_conflict_choose_postpone;
    case org_tigris_subversion_javahl_ConflictResult_chooseBase:
      return svn_wc_conflict_choose_base;
    case org_tigris_subversion_javahl_ConflictResult_chooseTheirsFull:
      return svn_wc_conflict_choose_theirs_full;
    case org_tigris_subversion_javahl_ConflictResult_chooseMineFull:
      return svn_wc_conflict_choose_mine_full;
    case org_tigris_subversion_javahl_ConflictResult_chooseTheirsConflict:
      return svn_wc_conflict_choose_theirs_conflict;
    case org_tigris_subversion_javahl_ConflictResult_chooseMineConflict:
      return svn_wc_conflict_choose_mine_conflict;
    case org_tigris_subversion_javahl_ConflictResult_chooseMerged:
      return svn_wc_conflict_choose_merged;
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QDebug>

#include <multimedia/qmediaserviceprovider.h>

class MockMediaServiceProvider : public QMediaServiceProvider
{
    QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)
    {
        Q_UNUSED(type);
        return 0;
    }

    void releaseService(QMediaService *service)
    {
        Q_UNUSED(service);
    }
};

class tst_QMediaServiceProvider : public QObject
{
    Q_OBJECT

private slots:
    void testDefaultProviderAvailable();
    void testObtainService();
    void testHasSupport();
    void testDevices();
    void testProviderHints();
};

void tst_QMediaServiceProvider::testDefaultProviderAvailable()
{
    // Must always be a default provider available
    QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);
}

void tst_QMediaServiceProvider::testObtainService()
{
    QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();

    if (provider == 0)
        QSKIP("No default provider", SkipSingle);

    QMediaService *service = 0;

    // Player
    service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);
    QVERIFY(service != 0);
    provider->releaseService(service);
}

void tst_QMediaServiceProvider::testHasSupport()
{
    MockMediaServiceProvider mockProvider;
    QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
             QtMedia::MaybeSupported);

    QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();

    if (provider == 0)
        QSKIP("No default provider", SkipSingle);

    QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
             QtMedia::MaybeSupported);

    QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()),
             QtMedia::NotSupported);
}

void tst_QMediaServiceProvider::testDevices()
{
    MockMediaServiceProvider mockProvider;
    QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());

    QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();

    if (provider == 0)
        QSKIP("No default provider", SkipSingle);

    //how to test this properly?
    //it depends on plugins installed
    //QVERIFY(!provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());

    QVERIFY(provider->devices(QByteArray("non existing service")).isEmpty());
}

void tst_QMediaServiceProvider::testProviderHints()
{
    {
        QMediaServiceProviderHint hint;
        QVERIFY(hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);
        QVERIFY(hint.device().isEmpty());
        QVERIFY(hint.mimeType().isEmpty());
        QVERIFY(hint.codecs().isEmpty());
        QCOMPARE(hint.features(), 0);
    }

    {
        QByteArray deviceName(QByteArray("testDevice"));
        QMediaServiceProviderHint hint(deviceName);
        QVERIFY(!hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);
        QCOMPARE(hint.device(), deviceName);
        QVERIFY(hint.mimeType().isEmpty());
        QVERIFY(hint.codecs().isEmpty());
        QCOMPARE(hint.features(), 0);
    }

    {
        QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);
        QVERIFY(!hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);
        QVERIFY(hint.device().isEmpty());
        QVERIFY(hint.mimeType().isEmpty());
        QVERIFY(hint.codecs().isEmpty());
        QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);
    }

    {
        QString mimeType(QLatin1String("video/ogg"));
        QStringList codecs;
        codecs << "theora" << "vorbis";

        QMediaServiceProviderHint hint(mimeType,codecs);
        QVERIFY(!hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);
        QVERIFY(hint.device().isEmpty());
        QCOMPARE(hint.mimeType(), mimeType);
        QCOMPARE(hint.codecs(), codecs);

        QMediaServiceProviderHint hint2(hint);

        QVERIFY(!hint2.isNull());
        QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);
        QVERIFY(hint2.device().isEmpty());
        QCOMPARE(hint2.mimeType(), mimeType);
        QCOMPARE(hint2.codecs(), codecs);

        QMediaServiceProviderHint hint3;
        QVERIFY(hint3.isNull());
        hint3 = hint;
        QVERIFY(!hint3.isNull());
        QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);
        QVERIFY(hint3.device().isEmpty());
        QCOMPARE(hint3.mimeType(), mimeType);
        QCOMPARE(hint3.codecs(), codecs);

        QCOMPARE(hint, hint2);
        QCOMPARE(hint3, hint2);

        QMediaServiceProviderHint hint4(mimeType,codecs);
        QCOMPARE(hint, hint4);

        QMediaServiceProviderHint hint5(mimeType,QStringList());
        QVERIFY(hint != hint5);
    }
}

QTEST_MAIN(tst_QMediaServiceProvider)

#include "tst_qmediaserviceprovider.moc"
<commit_msg>Added test for default QMediaServiceProvider::deviceDescription() implementation.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QDebug>

#include <multimedia/qmediaserviceprovider.h>

class MockMediaServiceProvider : public QMediaServiceProvider
{
    QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)
    {
        Q_UNUSED(type);
        return 0;
    }

    void releaseService(QMediaService *service)
    {
        Q_UNUSED(service);
    }
};

class tst_QMediaServiceProvider : public QObject
{
    Q_OBJECT

private slots:
    void testDefaultProviderAvailable();
    void testObtainService();
    void testHasSupport();
    void testDevices();
    void testProviderHints();
};

void tst_QMediaServiceProvider::testDefaultProviderAvailable()
{
    // Must always be a default provider available
    QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);
}

void tst_QMediaServiceProvider::testObtainService()
{
    QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();

    if (provider == 0)
        QSKIP("No default provider", SkipSingle);

    QMediaService *service = 0;

    // Player
    service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);
    QVERIFY(service != 0);
    provider->releaseService(service);
}

void tst_QMediaServiceProvider::testHasSupport()
{
    MockMediaServiceProvider mockProvider;
    QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
             QtMedia::MaybeSupported);

    QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();

    if (provider == 0)
        QSKIP("No default provider", SkipSingle);

    QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
             QtMedia::MaybeSupported);

    QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()),
             QtMedia::NotSupported);
}

void tst_QMediaServiceProvider::testDevices()
{
    MockMediaServiceProvider mockProvider;
    QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());
    QVERIFY(mockProvider.deviceDescription(QByteArray(Q_MEDIASERVICE_CAMERA),
                                           QByteArray()).isEmpty());

    QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();

    if (provider == 0)
        QSKIP("No default provider", SkipSingle);

    //how to test this properly?
    //it depends on plugins installed
    //QVERIFY(!provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());

    QVERIFY(provider->devices(QByteArray("non existing service")).isEmpty());
}

void tst_QMediaServiceProvider::testProviderHints()
{
    {
        QMediaServiceProviderHint hint;
        QVERIFY(hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);
        QVERIFY(hint.device().isEmpty());
        QVERIFY(hint.mimeType().isEmpty());
        QVERIFY(hint.codecs().isEmpty());
        QCOMPARE(hint.features(), 0);
    }

    {
        QByteArray deviceName(QByteArray("testDevice"));
        QMediaServiceProviderHint hint(deviceName);
        QVERIFY(!hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);
        QCOMPARE(hint.device(), deviceName);
        QVERIFY(hint.mimeType().isEmpty());
        QVERIFY(hint.codecs().isEmpty());
        QCOMPARE(hint.features(), 0);
    }

    {
        QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);
        QVERIFY(!hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);
        QVERIFY(hint.device().isEmpty());
        QVERIFY(hint.mimeType().isEmpty());
        QVERIFY(hint.codecs().isEmpty());
        QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);
    }

    {
        QString mimeType(QLatin1String("video/ogg"));
        QStringList codecs;
        codecs << "theora" << "vorbis";

        QMediaServiceProviderHint hint(mimeType,codecs);
        QVERIFY(!hint.isNull());
        QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);
        QVERIFY(hint.device().isEmpty());
        QCOMPARE(hint.mimeType(), mimeType);
        QCOMPARE(hint.codecs(), codecs);

        QMediaServiceProviderHint hint2(hint);

        QVERIFY(!hint2.isNull());
        QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);
        QVERIFY(hint2.device().isEmpty());
        QCOMPARE(hint2.mimeType(), mimeType);
        QCOMPARE(hint2.codecs(), codecs);

        QMediaServiceProviderHint hint3;
        QVERIFY(hint3.isNull());
        hint3 = hint;
        QVERIFY(!hint3.isNull());
        QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);
        QVERIFY(hint3.device().isEmpty());
        QCOMPARE(hint3.mimeType(), mimeType);
        QCOMPARE(hint3.codecs(), codecs);

        QCOMPARE(hint, hint2);
        QCOMPARE(hint3, hint2);

        QMediaServiceProviderHint hint4(mimeType,codecs);
        QCOMPARE(hint, hint4);

        QMediaServiceProviderHint hint5(mimeType,QStringList());
        QVERIFY(hint != hint5);
    }
}

QTEST_MAIN(tst_QMediaServiceProvider)

#include "tst_qmediaserviceprovider.moc"
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   TreeView.cpp
    created:    Fri Jun 06 2014
    author:     Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/WindowRendererSets/Core/TreeView.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/falagard/WidgetLookFeel.h"
#include "CEGUI/Image.h"

namespace CEGUI
{

//----------------------------------------------------------------------------//
const String FalagardTreeView::TypeName("Core/TreeView");

//----------------------------------------------------------------------------//
FalagardTreeView::FalagardTreeView(const String& type) :
    TreeViewWindowRenderer(type),
    d_subtreeExpanderImagery(0),
    d_subtreeCollapserImagery(0),
    d_subtreeExpanderImagerySize(0, 0)
{
}

//----------------------------------------------------------------------------//
void FalagardTreeView::render()
{
    const WidgetLookFeel& wlf = getLookNFeel();
    TreeView* tree_view = static_cast<TreeView*>(d_window);

    tree_view->prepareForRender();

    const StateImagery* imagery = &wlf.getStateImagery(
        tree_view->isEffectiveDisabled() ? "Disabled" : "Enabled");
    imagery->render(*tree_view);

    Rectf items_area(getViewRenderArea());
    Vector2f item_pos(getItemRenderStartPosition(tree_view, items_area));
    renderTreeItem(tree_view, items_area, item_pos, tree_view->getRootItemState());
}

//----------------------------------------------------------------------------//
void FalagardTreeView::renderTreeItem(TreeView* tree_view, const Rectf& items_area,
    Vector2f& item_pos, const TreeViewItemRenderingState& item_to_render)
{
    const float SUBTREE_IDENT = d_subtreeExpanderImagerySize.d_width;
    const float OPEN_CLOSE_BUTTON_MARGIN = 5.0f;
    for (size_t i = 0; i < item_to_render.d_renderedChildren.size(); ++i)
    {
        TreeViewItemRenderingState item = item_to_render.d_renderedChildren.at(i);
        RenderedString& rendered_string = item.d_string;
        Sizef size(item.d_size);

        size.d_width = ceguimax(items_area.getWidth(), size.d_width);
        if (item.d_totalChildCount > 0)
        {
            const ImagerySection* section = item.d_subtreeIsExpanded
                ? d_subtreeExpanderImagery : d_subtreeCollapserImagery;

            Rectf button_rect;
            button_rect.left(item_pos.d_x + OPEN_CLOSE_BUTTON_MARGIN);
            button_rect.top(item_pos.d_y + OPEN_CLOSE_BUTTON_MARGIN);
            button_rect.setSize(d_subtreeExpanderImagerySize);

            Rectf button_clipper(button_rect.getIntersection(items_area));
            section->render(*tree_view, button_rect, 0, &button_clipper);
        }

        Rectf item_rect;
        item_rect.left(item_pos.d_x + d_subtreeExpanderImagerySize.d_width + 2 * OPEN_CLOSE_BUTTON_MARGIN);
        item_rect.top(item_pos.d_y);
        item_rect.setSize(size);

        Rectf item_clipper(item_rect.getIntersection(items_area));
        renderString(tree_view, rendered_string, item_rect,
            tree_view->getFont(), &item_clipper, item.d_isSelected);

        item_pos.d_y += size.d_height;

        if (item.d_renderedChildren.empty())
            continue;

        item_pos.d_x += SUBTREE_IDENT;

        if (item.d_subtreeIsExpanded)
        {
            renderTreeItem(tree_view, items_area, item_pos, item);
        }

        item_pos.d_x -= SUBTREE_IDENT;
    }
}

static Sizef getImagerySize(const ImagerySection* section)
{
    ImageryComponent& component = section->getImageryComponentIterator().getCurrentValue();
    const Image* img = component.getImage();
    return img->getRenderedSize();
}

//----------------------------------------------------------------------------//
void FalagardTreeView::onLookNFeelAssigned()
{
    const WidgetLookFeel& wlf = getLookNFeel();
    d_subtreeExpanderImagery = &wlf.getImagerySection("SubtreeExpander");
    d_subtreeCollapserImagery = &wlf.getImagerySection("SubtreeCollapser");

    Sizef open_size = getImagerySize(d_subtreeExpanderImagery);
    Sizef close_size = getImagerySize(d_subtreeCollapserImagery);
    d_subtreeExpanderImagerySize = Sizef(
        ceguimax(open_size.d_width, close_size.d_width),
        ceguimax(open_size.d_height, close_size.d_height));

}

//----------------------------------------------------------------------------//
Sizef FalagardTreeView::getSubtreeExpanderSize(void) const
{
    return d_subtreeExpanderImagerySize;
}

//----------------------------------------------------------------------------//
Rectf FalagardTreeView::getViewRenderArea(void) const
{
    return ItemViewRenderer::getViewRenderArea(this);
}
}
<commit_msg>Fix compilation on MinGW<commit_after>/***********************************************************************
    filename:   TreeView.cpp
    created:    Fri Jun 06 2014
    author:     Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/WindowRendererSets/Core/TreeView.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/falagard/WidgetLookFeel.h"
#include "CEGUI/Image.h"

namespace CEGUI
{

//----------------------------------------------------------------------------//
const String FalagardTreeView::TypeName("Core/TreeView");

//----------------------------------------------------------------------------//
FalagardTreeView::FalagardTreeView(const String& type) :
    TreeViewWindowRenderer(type),
    d_subtreeExpanderImagery(0),
    d_subtreeCollapserImagery(0),
    d_subtreeExpanderImagerySize(0, 0)
{
}

//----------------------------------------------------------------------------//
void FalagardTreeView::render()
{
    const WidgetLookFeel& wlf = getLookNFeel();
    TreeView* tree_view = static_cast<TreeView*>(d_window);

    tree_view->prepareForRender();

    const StateImagery* imagery = &wlf.getStateImagery(
        tree_view->isEffectiveDisabled() ? "Disabled" : "Enabled");
    imagery->render(*tree_view);

    Rectf items_area(getViewRenderArea());
    Vector2f item_pos(getItemRenderStartPosition(tree_view, items_area));
    renderTreeItem(tree_view, items_area, item_pos, tree_view->getRootItemState());
}

//----------------------------------------------------------------------------//
void FalagardTreeView::renderTreeItem(TreeView* tree_view, const Rectf& items_area,
    Vector2f& item_pos, const TreeViewItemRenderingState& item_to_render)
{
    const float SUBTREE_IDENT = d_subtreeExpanderImagerySize.d_width;
    const float OPEN_CLOSE_BUTTON_MARGIN = 5.0f;
    for (size_t i = 0; i < item_to_render.d_renderedChildren.size(); ++i)
    {
        TreeViewItemRenderingState item = item_to_render.d_renderedChildren.at(i);
        RenderedString& rendered_string = item.d_string;
        Sizef size(item.d_size);

        size.d_width = ceguimax(items_area.getWidth(), size.d_width);
        if (item.d_totalChildCount > 0)
        {
            const ImagerySection* section = item.d_subtreeIsExpanded
                ? d_subtreeExpanderImagery : d_subtreeCollapserImagery;

            Rectf button_rect;
            button_rect.left(item_pos.d_x + OPEN_CLOSE_BUTTON_MARGIN);
            button_rect.top(item_pos.d_y + OPEN_CLOSE_BUTTON_MARGIN);
            button_rect.setSize(d_subtreeExpanderImagerySize);

            Rectf button_clipper(button_rect.getIntersection(items_area));
            section->render(*tree_view, button_rect, 0, &button_clipper);
        }

        Rectf item_rect;
        item_rect.left(item_pos.d_x + d_subtreeExpanderImagerySize.d_width + 2 * OPEN_CLOSE_BUTTON_MARGIN);
        item_rect.top(item_pos.d_y);
        item_rect.setSize(size);

        Rectf item_clipper(item_rect.getIntersection(items_area));
        renderString(tree_view, rendered_string, item_rect,
            tree_view->getFont(), &item_clipper, item.d_isSelected);

        item_pos.d_y += size.d_height;

        if (item.d_renderedChildren.empty())
            continue;

        item_pos.d_x += SUBTREE_IDENT;

        if (item.d_subtreeIsExpanded)
        {
            renderTreeItem(tree_view, items_area, item_pos, item);
        }

        item_pos.d_x -= SUBTREE_IDENT;
    }
}

static Sizef getImagerySize(const ImagerySection* section)
{
    const ImageryComponent& component = section->getImageryComponentIterator().getCurrentValue();
    const Image* img = component.getImage();
    return img->getRenderedSize();
}

//----------------------------------------------------------------------------//
void FalagardTreeView::onLookNFeelAssigned()
{
    const WidgetLookFeel& wlf = getLookNFeel();
    d_subtreeExpanderImagery = &wlf.getImagerySection("SubtreeExpander");
    d_subtreeCollapserImagery = &wlf.getImagerySection("SubtreeCollapser");

    Sizef open_size = getImagerySize(d_subtreeExpanderImagery);
    Sizef close_size = getImagerySize(d_subtreeCollapserImagery);
    d_subtreeExpanderImagerySize = Sizef(
        ceguimax(open_size.d_width, close_size.d_width),
        ceguimax(open_size.d_height, close_size.d_height));

}

//----------------------------------------------------------------------------//
Sizef FalagardTreeView::getSubtreeExpanderSize(void) const
{
    return d_subtreeExpanderImagerySize;
}

//----------------------------------------------------------------------------//
Rectf FalagardTreeView::getViewRenderArea(void) const
{
    return ItemViewRenderer::getViewRenderArea(this);
}
}
<|endoftext|>


<commit_before>//===--- utils/unittest/UnitTestMain/TestMain.cpp - unittest driver -------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Config/config.h"
#include "llvm/System/Signals.h"
#include "gtest/gtest.h"

#if defined(LLVM_ON_WIN32)
# include <Windows.h>
# if defined(_MSC_VER)
#   include <crtdbg.h>
# endif
#endif

int main(int argc, char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  testing::InitGoogleTest(&argc, argv);

# if defined(LLVM_ON_WIN32)
  // Disable all of the possible ways Windows conspires to make automated
  // testing impossible.
  ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#   if defined(_MSC_VER)
    ::_set_error_mode(_OUT_TO_STDERR);
    ::_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
    ::_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
    ::_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
    ::_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    ::_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
    ::_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#   endif
# endif

  return RUN_ALL_TESTS();
}
<commit_msg>Fix line endings from my last commit.<commit_after>//===--- utils/unittest/UnitTestMain/TestMain.cpp - unittest driver -------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Config/config.h"
#include "llvm/System/Signals.h"
#include "gtest/gtest.h"

#if defined(LLVM_ON_WIN32)
# include <Windows.h>
# if defined(_MSC_VER)
#   include <crtdbg.h>
# endif
#endif

int main(int argc, char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  testing::InitGoogleTest(&argc, argv);

# if defined(LLVM_ON_WIN32)
  // Disable all of the possible ways Windows conspires to make automated
  // testing impossible.
  ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#   if defined(_MSC_VER)
    ::_set_error_mode(_OUT_TO_STDERR);
    ::_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
    ::_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
    ::_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
    ::_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    ::_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
    ::_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
#   endif
# endif

  return RUN_ALL_TESTS();
}
<|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 "chrome/browser/dom_ui/downloads_dom_handler.h"

#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/gfx/png_encoder.h"
#include "base/string_piece.h"
#include "base/thread.h"
#include "base/time_format.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "chrome/browser/dom_ui/fileicon_source.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/profile.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/time_format.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"

#if defined(TOOLKIT_VIEWS)
// TODO(port): re-enable when download_util is ported
#include "chrome/browser/download/download_util.h"
#else
#include "chrome/common/temp_scaffolding_stubs.h"
#endif

namespace {

// Maximum number of downloads to show. TODO(glen): Remove this and instead
// stuff the downloads down the pipe slowly.
static const int kMaxDownloads = 150;

// Sort DownloadItems into descending order by their start time.
class DownloadItemSorter : public std::binary_function<DownloadItem*,
                                                       DownloadItem*,
                                                       bool> {
 public:
  bool operator()(const DownloadItem* lhs, const DownloadItem* rhs) {
    return lhs->start_time() > rhs->start_time();
  }
};

} // namespace

DownloadsDOMHandler::DownloadsDOMHandler(DOMUI* dom_ui, DownloadManager* dlm)
    : DOMMessageHandler(dom_ui),
      search_text_(),
      download_manager_(dlm) {
  dom_ui_->RegisterMessageCallback("getDownloads",
      NewCallback(this, &DownloadsDOMHandler::HandleGetDownloads));
  dom_ui_->RegisterMessageCallback("openFile",
      NewCallback(this, &DownloadsDOMHandler::HandleOpenFile));

  dom_ui_->RegisterMessageCallback("drag",
      NewCallback(this, &DownloadsDOMHandler::HandleDrag));

  dom_ui_->RegisterMessageCallback("saveDangerous",
      NewCallback(this, &DownloadsDOMHandler::HandleSaveDangerous));
  dom_ui_->RegisterMessageCallback("discardDangerous",
      NewCallback(this, &DownloadsDOMHandler::HandleDiscardDangerous));
  dom_ui_->RegisterMessageCallback("show",
      NewCallback(this, &DownloadsDOMHandler::HandleShow));
  dom_ui_->RegisterMessageCallback("togglepause",
      NewCallback(this, &DownloadsDOMHandler::HandlePause));
  dom_ui_->RegisterMessageCallback("resume",
      NewCallback(this, &DownloadsDOMHandler::HandlePause));
  dom_ui_->RegisterMessageCallback("cancel",
      NewCallback(this, &DownloadsDOMHandler::HandleCancel));
  dom_ui_->RegisterMessageCallback("clearAll",
      NewCallback(this, &DownloadsDOMHandler::HandleClearAll));

  // Create our fileicon data source.
  g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(&chrome_url_data_manager,
                        &ChromeURLDataManager::AddDataSource,
                        new FileIconSource()));
}

DownloadsDOMHandler::~DownloadsDOMHandler() {
  ClearDownloadItems();
  download_manager_->RemoveObserver(this);
}

// DownloadsDOMHandler, public: -----------------------------------------------

void DownloadsDOMHandler::Init() {
  download_manager_->AddObserver(this);
}

void DownloadsDOMHandler::OnDownloadUpdated(DownloadItem* download) {
  // Get the id for the download. Our downloads are sorted latest to first,
  // and the id is the index into that list. We should be careful of sync
  // errors between the UI and the download_items_ list (we may wish to use
  // something other than 'id').
  OrderedDownloads::iterator it = find(download_items_.begin(),
                                       download_items_.end(),
                                       download);
  if (it == download_items_.end())
    return;
  const int id = static_cast<int>(it - download_items_.begin());

  ListValue results_value;
  results_value.Append(CreateDownloadItemValue(download, id));
  dom_ui_->CallJavascriptFunction(L"downloadUpdated", results_value);
}

// A download has started or been deleted. Query our DownloadManager for the
// current set of downloads, which will call us back in SetDownloads once it
// has retrieved them.
void DownloadsDOMHandler::ModelChanged() {
  ClearDownloadItems();
  download_manager_->GetDownloads(this, search_text_);
}

void DownloadsDOMHandler::SetDownloads(
    std::vector<DownloadItem*>& downloads) {
  ClearDownloadItems();

  // Swap new downloads in.
  download_items_.swap(downloads);
  sort(download_items_.begin(), download_items_.end(), DownloadItemSorter());

  // Scan for any in progress downloads and add ourself to them as an observer.
  for (OrderedDownloads::iterator it = download_items_.begin();
       it != download_items_.end(); ++it) {
    if (static_cast<int>(it - download_items_.begin()) > kMaxDownloads)
      break;

    DownloadItem* download = *it;
    if (download->state() == DownloadItem::IN_PROGRESS) {
      // We want to know what happens as the download progresses.
      download->AddObserver(this);
    } else if (download->safety_state() == DownloadItem::DANGEROUS) {
      // We need to be notified when the user validates the dangerous download.
      download->AddObserver(this);
    }
  }

  SendCurrentDownloads();
}

void DownloadsDOMHandler::HandleGetDownloads(const Value* value) {
  std::wstring new_search = ExtractStringValue(value);
  if (search_text_.compare(new_search) != 0) {
    search_text_ = new_search;
    ClearDownloadItems();
    download_manager_->GetDownloads(this, search_text_);
  } else {
    SendCurrentDownloads();
  }
}

void DownloadsDOMHandler::HandleOpenFile(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    download_manager_->OpenDownload(file, NULL);
}

void DownloadsDOMHandler::HandleDrag(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file) {
    IconManager* im = g_browser_process->icon_manager();
    SkBitmap* icon = im->LookupIcon(file->full_path(), IconLoader::NORMAL);
    download_util::DragDownload(file, icon);
  }
}

void DownloadsDOMHandler::HandleSaveDangerous(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    download_manager_->DangerousDownloadValidated(file);
}

void DownloadsDOMHandler::HandleDiscardDangerous(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    file->Remove(true);
}

void DownloadsDOMHandler::HandleShow(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
      download_manager_->ShowDownloadInShell(file);
}

void DownloadsDOMHandler::HandlePause(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    file->TogglePause();
}

void DownloadsDOMHandler::HandleCancel(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    file->Cancel(true);
}

void DownloadsDOMHandler::HandleClearAll(const Value* value) {
  download_manager_->RemoveAllDownloads();
}

// DownloadsDOMHandler, private: ----------------------------------------------

void DownloadsDOMHandler::SendCurrentDownloads() {
  ListValue results_value;
  for (OrderedDownloads::iterator it = download_items_.begin();
      it != download_items_.end(); ++it) {
    int index = static_cast<int>(it - download_items_.begin());
    if (index > kMaxDownloads)
      break;
    results_value.Append(CreateDownloadItemValue(*it,index));
  }

  dom_ui_->CallJavascriptFunction(L"downloadsList", results_value);
}

DictionaryValue* DownloadsDOMHandler::CreateDownloadItemValue(
    DownloadItem* download, int id) {
  DictionaryValue* file_value = new DictionaryValue();

  file_value->SetInteger(L"started",
    static_cast<int>(download->start_time().ToTimeT()));
  file_value->SetString(L"since_string",
    TimeFormat::RelativeDate(download->start_time(), NULL));
  file_value->SetString(L"date_string",
    base::TimeFormatShortDate(download->start_time()));
  file_value->SetInteger(L"id", id);
  file_value->SetString(L"file_path", download->full_path().ToWStringHack());
  file_value->SetString(L"file_name", download->GetFileName().ToWStringHack());
  file_value->SetString(L"url", download->url().spec());

  if (download->state() == DownloadItem::IN_PROGRESS) {
    if (download->safety_state() == DownloadItem::DANGEROUS) {
      file_value->SetString(L"state", L"DANGEROUS");
    } else if (download->is_paused()) {
      file_value->SetString(L"state", L"PAUSED");
    } else {
      file_value->SetString(L"state", L"IN_PROGRESS");
    }

    file_value->SetString(L"progress_status_text",
       GetProgressStatusText(download));

    file_value->SetInteger(L"percent",
        static_cast<int>(download->PercentComplete()));
    file_value->SetInteger(L"received",
        static_cast<int>(download->received_bytes()));
  } else if (download->state() == DownloadItem::CANCELLED) {
    file_value->SetString(L"state", L"CANCELLED");
  } else if (download->state() == DownloadItem::COMPLETE) {
    if (download->safety_state() == DownloadItem::DANGEROUS) {
      file_value->SetString(L"state", L"DANGEROUS");
    } else {
      file_value->SetString(L"state", L"COMPLETE");
    }
  }

  file_value->SetInteger(L"total",
      static_cast<int>(download->total_bytes()));

  return file_value;
}

void DownloadsDOMHandler::ClearDownloadItems() {
  // Clear out old state and remove self as observer for each download.
  for (OrderedDownloads::iterator it = download_items_.begin();
      it != download_items_.end(); ++it) {
    (*it)->RemoveObserver(this);
  }
  download_items_.clear();
}

DownloadItem* DownloadsDOMHandler::GetDownloadById(int id) {
  for (OrderedDownloads::iterator it = download_items_.begin();
      it != download_items_.end(); ++it) {
    if (static_cast<int>(it - download_items_.begin() == id)) {
      return (*it);
    }
  }

  return NULL;
}

DownloadItem* DownloadsDOMHandler::GetDownloadByValue(const Value* value) {
  int id;
  if (ExtractIntegerValue(value, &id)) {
    return GetDownloadById(id);
  }
  return NULL;
}

std::wstring DownloadsDOMHandler::GetProgressStatusText(
    DownloadItem* download) {
  int64 total = download->total_bytes();
  int64 size = download->received_bytes();
  DataUnits amount_units = GetByteDisplayUnits(size);
  std::wstring received_size = FormatBytes(size, amount_units, true);
  std::wstring amount = received_size;

  // Adjust both strings for the locale direction since we don't yet know which
  // string we'll end up using for constructing the final progress string.
  std::wstring amount_localized;
  if (l10n_util::AdjustStringForLocaleDirection(amount, &amount_localized)) {
    amount.assign(amount_localized);
    received_size.assign(amount_localized);
  }

  if (total) {
    amount_units = GetByteDisplayUnits(total);
    std::wstring total_text = FormatBytes(total, amount_units, true);
    std::wstring total_text_localized;
    if (l10n_util::AdjustStringForLocaleDirection(total_text,
                                                  &total_text_localized))
      total_text.assign(total_text_localized);

    amount = l10n_util::GetStringF(IDS_DOWNLOAD_TAB_PROGRESS_SIZE,
                                   received_size,
                                   total_text);
  } else {
    amount.assign(received_size);
  }
  amount_units = GetByteDisplayUnits(download->CurrentSpeed());
  std::wstring speed_text = FormatSpeed(download->CurrentSpeed(),
                                        amount_units, true);
  std::wstring speed_text_localized;
  if (l10n_util::AdjustStringForLocaleDirection(speed_text,
                                                &speed_text_localized))
    speed_text.assign(speed_text_localized);

  base::TimeDelta remaining;
  std::wstring time_remaining;
  if (download->is_paused())
    time_remaining = l10n_util::GetString(IDS_DOWNLOAD_PROGRESS_PAUSED);
  else if (download->TimeRemaining(&remaining))
    time_remaining = TimeFormat::TimeRemaining(remaining);

  if (time_remaining.empty()) {
    return l10n_util::GetStringF(IDS_DOWNLOAD_TAB_PROGRESS_STATUS_TIME_UNKNOWN,
                                 speed_text, amount);
  }
  return l10n_util::GetStringF(IDS_DOWNLOAD_TAB_PROGRESS_STATUS, amount,
                               time_remaining);
}
<commit_msg>Show the remaining time in the downloads page.<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 "chrome/browser/dom_ui/downloads_dom_handler.h"

#include "app/l10n_util.h"
#include "base/basictypes.h"
#include "base/gfx/png_encoder.h"
#include "base/string_piece.h"
#include "base/thread.h"
#include "base/time_format.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/dom_ui/chrome_url_data_manager.h"
#include "chrome/browser/dom_ui/fileicon_source.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/profile.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/time_format.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/generated_resources.h"

#if defined(TOOLKIT_VIEWS)
// TODO(port): re-enable when download_util is ported
#include "chrome/browser/download/download_util.h"
#else
#include "chrome/common/temp_scaffolding_stubs.h"
#endif

namespace {

// Maximum number of downloads to show. TODO(glen): Remove this and instead
// stuff the downloads down the pipe slowly.
static const int kMaxDownloads = 150;

// Sort DownloadItems into descending order by their start time.
class DownloadItemSorter : public std::binary_function<DownloadItem*,
                                                       DownloadItem*,
                                                       bool> {
 public:
  bool operator()(const DownloadItem* lhs, const DownloadItem* rhs) {
    return lhs->start_time() > rhs->start_time();
  }
};

} // namespace

DownloadsDOMHandler::DownloadsDOMHandler(DOMUI* dom_ui, DownloadManager* dlm)
    : DOMMessageHandler(dom_ui),
      search_text_(),
      download_manager_(dlm) {
  dom_ui_->RegisterMessageCallback("getDownloads",
      NewCallback(this, &DownloadsDOMHandler::HandleGetDownloads));
  dom_ui_->RegisterMessageCallback("openFile",
      NewCallback(this, &DownloadsDOMHandler::HandleOpenFile));

  dom_ui_->RegisterMessageCallback("drag",
      NewCallback(this, &DownloadsDOMHandler::HandleDrag));

  dom_ui_->RegisterMessageCallback("saveDangerous",
      NewCallback(this, &DownloadsDOMHandler::HandleSaveDangerous));
  dom_ui_->RegisterMessageCallback("discardDangerous",
      NewCallback(this, &DownloadsDOMHandler::HandleDiscardDangerous));
  dom_ui_->RegisterMessageCallback("show",
      NewCallback(this, &DownloadsDOMHandler::HandleShow));
  dom_ui_->RegisterMessageCallback("togglepause",
      NewCallback(this, &DownloadsDOMHandler::HandlePause));
  dom_ui_->RegisterMessageCallback("resume",
      NewCallback(this, &DownloadsDOMHandler::HandlePause));
  dom_ui_->RegisterMessageCallback("cancel",
      NewCallback(this, &DownloadsDOMHandler::HandleCancel));
  dom_ui_->RegisterMessageCallback("clearAll",
      NewCallback(this, &DownloadsDOMHandler::HandleClearAll));

  // Create our fileicon data source.
  g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE,
      NewRunnableMethod(&chrome_url_data_manager,
                        &ChromeURLDataManager::AddDataSource,
                        new FileIconSource()));
}

DownloadsDOMHandler::~DownloadsDOMHandler() {
  ClearDownloadItems();
  download_manager_->RemoveObserver(this);
}

// DownloadsDOMHandler, public: -----------------------------------------------

void DownloadsDOMHandler::Init() {
  download_manager_->AddObserver(this);
}

void DownloadsDOMHandler::OnDownloadUpdated(DownloadItem* download) {
  // Get the id for the download. Our downloads are sorted latest to first,
  // and the id is the index into that list. We should be careful of sync
  // errors between the UI and the download_items_ list (we may wish to use
  // something other than 'id').
  OrderedDownloads::iterator it = find(download_items_.begin(),
                                       download_items_.end(),
                                       download);
  if (it == download_items_.end())
    return;
  const int id = static_cast<int>(it - download_items_.begin());

  ListValue results_value;
  results_value.Append(CreateDownloadItemValue(download, id));
  dom_ui_->CallJavascriptFunction(L"downloadUpdated", results_value);
}

// A download has started or been deleted. Query our DownloadManager for the
// current set of downloads, which will call us back in SetDownloads once it
// has retrieved them.
void DownloadsDOMHandler::ModelChanged() {
  ClearDownloadItems();
  download_manager_->GetDownloads(this, search_text_);
}

void DownloadsDOMHandler::SetDownloads(
    std::vector<DownloadItem*>& downloads) {
  ClearDownloadItems();

  // Swap new downloads in.
  download_items_.swap(downloads);
  sort(download_items_.begin(), download_items_.end(), DownloadItemSorter());

  // Scan for any in progress downloads and add ourself to them as an observer.
  for (OrderedDownloads::iterator it = download_items_.begin();
       it != download_items_.end(); ++it) {
    if (static_cast<int>(it - download_items_.begin()) > kMaxDownloads)
      break;

    DownloadItem* download = *it;
    if (download->state() == DownloadItem::IN_PROGRESS) {
      // We want to know what happens as the download progresses.
      download->AddObserver(this);
    } else if (download->safety_state() == DownloadItem::DANGEROUS) {
      // We need to be notified when the user validates the dangerous download.
      download->AddObserver(this);
    }
  }

  SendCurrentDownloads();
}

void DownloadsDOMHandler::HandleGetDownloads(const Value* value) {
  std::wstring new_search = ExtractStringValue(value);
  if (search_text_.compare(new_search) != 0) {
    search_text_ = new_search;
    ClearDownloadItems();
    download_manager_->GetDownloads(this, search_text_);
  } else {
    SendCurrentDownloads();
  }
}

void DownloadsDOMHandler::HandleOpenFile(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    download_manager_->OpenDownload(file, NULL);
}

void DownloadsDOMHandler::HandleDrag(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file) {
    IconManager* im = g_browser_process->icon_manager();
    SkBitmap* icon = im->LookupIcon(file->full_path(), IconLoader::NORMAL);
    download_util::DragDownload(file, icon);
  }
}

void DownloadsDOMHandler::HandleSaveDangerous(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    download_manager_->DangerousDownloadValidated(file);
}

void DownloadsDOMHandler::HandleDiscardDangerous(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    file->Remove(true);
}

void DownloadsDOMHandler::HandleShow(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
      download_manager_->ShowDownloadInShell(file);
}

void DownloadsDOMHandler::HandlePause(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    file->TogglePause();
}

void DownloadsDOMHandler::HandleCancel(const Value* value) {
  DownloadItem* file = GetDownloadByValue(value);
  if (file)
    file->Cancel(true);
}

void DownloadsDOMHandler::HandleClearAll(const Value* value) {
  download_manager_->RemoveAllDownloads();
}

// DownloadsDOMHandler, private: ----------------------------------------------

void DownloadsDOMHandler::SendCurrentDownloads() {
  ListValue results_value;
  for (OrderedDownloads::iterator it = download_items_.begin();
      it != download_items_.end(); ++it) {
    int index = static_cast<int>(it - download_items_.begin());
    if (index > kMaxDownloads)
      break;
    results_value.Append(CreateDownloadItemValue(*it,index));
  }

  dom_ui_->CallJavascriptFunction(L"downloadsList", results_value);
}

DictionaryValue* DownloadsDOMHandler::CreateDownloadItemValue(
    DownloadItem* download, int id) {
  DictionaryValue* file_value = new DictionaryValue();

  file_value->SetInteger(L"started",
    static_cast<int>(download->start_time().ToTimeT()));
  file_value->SetString(L"since_string",
    TimeFormat::RelativeDate(download->start_time(), NULL));
  file_value->SetString(L"date_string",
    base::TimeFormatShortDate(download->start_time()));
  file_value->SetInteger(L"id", id);
  file_value->SetString(L"file_path", download->full_path().ToWStringHack());
  file_value->SetString(L"file_name", download->GetFileName().ToWStringHack());
  file_value->SetString(L"url", download->url().spec());

  if (download->state() == DownloadItem::IN_PROGRESS) {
    if (download->safety_state() == DownloadItem::DANGEROUS) {
      file_value->SetString(L"state", L"DANGEROUS");
    } else if (download->is_paused()) {
      file_value->SetString(L"state", L"PAUSED");
    } else {
      file_value->SetString(L"state", L"IN_PROGRESS");
    }

    file_value->SetString(L"progress_status_text",
       GetProgressStatusText(download));

    file_value->SetInteger(L"percent",
        static_cast<int>(download->PercentComplete()));
    file_value->SetInteger(L"received",
        static_cast<int>(download->received_bytes()));
  } else if (download->state() == DownloadItem::CANCELLED) {
    file_value->SetString(L"state", L"CANCELLED");
  } else if (download->state() == DownloadItem::COMPLETE) {
    if (download->safety_state() == DownloadItem::DANGEROUS) {
      file_value->SetString(L"state", L"DANGEROUS");
    } else {
      file_value->SetString(L"state", L"COMPLETE");
    }
  }

  file_value->SetInteger(L"total",
      static_cast<int>(download->total_bytes()));

  return file_value;
}

void DownloadsDOMHandler::ClearDownloadItems() {
  // Clear out old state and remove self as observer for each download.
  for (OrderedDownloads::iterator it = download_items_.begin();
      it != download_items_.end(); ++it) {
    (*it)->RemoveObserver(this);
  }
  download_items_.clear();
}

DownloadItem* DownloadsDOMHandler::GetDownloadById(int id) {
  for (OrderedDownloads::iterator it = download_items_.begin();
      it != download_items_.end(); ++it) {
    if (static_cast<int>(it - download_items_.begin() == id)) {
      return (*it);
    }
  }

  return NULL;
}

DownloadItem* DownloadsDOMHandler::GetDownloadByValue(const Value* value) {
  int id;
  if (ExtractIntegerValue(value, &id)) {
    return GetDownloadById(id);
  }
  return NULL;
}

std::wstring DownloadsDOMHandler::GetProgressStatusText(
    DownloadItem* download) {
  int64 total = download->total_bytes();
  int64 size = download->received_bytes();
  DataUnits amount_units = GetByteDisplayUnits(size);
  std::wstring received_size = FormatBytes(size, amount_units, true);
  std::wstring amount = received_size;

  // Adjust both strings for the locale direction since we don't yet know which
  // string we'll end up using for constructing the final progress string.
  std::wstring amount_localized;
  if (l10n_util::AdjustStringForLocaleDirection(amount, &amount_localized)) {
    amount.assign(amount_localized);
    received_size.assign(amount_localized);
  }

  if (total) {
    amount_units = GetByteDisplayUnits(total);
    std::wstring total_text = FormatBytes(total, amount_units, true);
    std::wstring total_text_localized;
    if (l10n_util::AdjustStringForLocaleDirection(total_text,
                                                  &total_text_localized))
      total_text.assign(total_text_localized);

    amount = l10n_util::GetStringF(IDS_DOWNLOAD_TAB_PROGRESS_SIZE,
                                   received_size,
                                   total_text);
  } else {
    amount.assign(received_size);
  }
  amount_units = GetByteDisplayUnits(download->CurrentSpeed());
  std::wstring speed_text = FormatSpeed(download->CurrentSpeed(),
                                        amount_units, true);
  std::wstring speed_text_localized;
  if (l10n_util::AdjustStringForLocaleDirection(speed_text,
                                                &speed_text_localized))
    speed_text.assign(speed_text_localized);

  base::TimeDelta remaining;
  std::wstring time_remaining;
  if (download->is_paused())
    time_remaining = l10n_util::GetString(IDS_DOWNLOAD_PROGRESS_PAUSED);
  else if (download->TimeRemaining(&remaining))
    time_remaining = TimeFormat::TimeRemaining(remaining);

  if (time_remaining.empty()) {
    return l10n_util::GetStringF(IDS_DOWNLOAD_TAB_PROGRESS_STATUS_TIME_UNKNOWN,
                                 speed_text, amount);
  }
  return l10n_util::GetStringF(IDS_DOWNLOAD_TAB_PROGRESS_STATUS, speed_text,
                               amount, time_remaining);
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-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 <string>

#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/metrics/metrics_log.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::TimeDelta;

namespace {
  class MetricsLogTest : public testing::Test {
  };
};

// Since buildtime is highly variable, this function will scan an output log and
// replace it with a consistent number.
static void NormalizeBuildtime(std::string* xml_encoded) {
  std::string prefix = "buildtime=\"";
  const char postfix = '\"';
  size_t offset = xml_encoded->find(prefix);
  ASSERT_GT(offset, 0u);
  offset += prefix.size();
  size_t postfix_position = xml_encoded->find(postfix, offset);
  ASSERT_GT(postfix_position, offset);
  for (size_t i = offset; i < postfix_position; ++i) {
    char digit = xml_encoded->at(i);
    ASSERT_GE(digit, '0');
    ASSERT_LE(digit, '9');
  }

  // Insert a single fake buildtime.
  xml_encoded->replace(offset, postfix_position - offset, "123246");
}

TEST(MetricsLogTest, EmptyRecord) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
      "appversion=\"%s\"/>", MetricsLog::GetVersionString().c_str());

  MetricsLog log("bogus client ID", 0);
  log.CloseLog();

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}

#if defined(OS_CHROMEOS)
TEST(MetricsLogTest, ChromeOSEmptyRecord) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
      "appversion=\"%s\" hardwareclass=\"sample-class\"/>",
      MetricsLog::GetVersionString().c_str());

  MetricsLog log("bogus client ID", 0);
  log.set_hardware_class("sample-class");
  log.CloseLog();

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}
#endif  // OS_CHROMEOS

namespace {

class NoTimeMetricsLog : public MetricsLog {
 public:
  NoTimeMetricsLog(std::string client_id, int session_id):
      MetricsLog(client_id, session_id) {}
  virtual ~NoTimeMetricsLog() {}

  // Override this so that output is testable.
  virtual std::string GetCurrentTimeString() {
    return std::string();
  }
};

};  // namespace

TEST(MetricsLogTest, WindowEvent) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
          "appversion=\"%s\">\n"
      " <window action=\"create\" windowid=\"0\" session=\"0\" time=\"\"/>\n"
      " <window action=\"open\" windowid=\"1\" parent=\"0\" "
          "session=\"0\" time=\"\"/>\n"
      " <window action=\"close\" windowid=\"1\" parent=\"0\" "
          "session=\"0\" time=\"\"/>\n"
      " <window action=\"destroy\" windowid=\"0\" session=\"0\" time=\"\"/>\n"
      "</log>", MetricsLog::GetVersionString().c_str());

  NoTimeMetricsLog log("bogus client ID", 0);
  log.RecordWindowEvent(MetricsLog::WINDOW_CREATE, 0, -1);
  log.RecordWindowEvent(MetricsLog::WINDOW_OPEN, 1, 0);
  log.RecordWindowEvent(MetricsLog::WINDOW_CLOSE, 1, 0);
  log.RecordWindowEvent(MetricsLog::WINDOW_DESTROY, 0, -1);
  log.CloseLog();

  ASSERT_EQ(4, log.num_events());

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}

TEST(MetricsLogTest, LoadEvent) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
          "appversion=\"%s\">\n"
      " <document action=\"load\" docid=\"1\" window=\"3\" loadtime=\"7219\" "
          "origin=\"link\" session=\"0\" time=\"\"/>\n"
      "</log>", MetricsLog::GetVersionString().c_str());

  NoTimeMetricsLog log("bogus client ID", 0);
  log.RecordLoadEvent(3, GURL("http://google.com"), PageTransition::LINK,
                      1, TimeDelta::FromMilliseconds(7219));

  log.CloseLog();

  ASSERT_EQ(1, log.num_events());

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}

// Make sure our ID hashes are the same as what we see on the server side.
TEST(MetricsLogTest, CreateHash) {
  static const struct {
    std::string input;
    std::string output;
  } cases[] = {
    {"Back", "0x0557fa923dcee4d0"},
    {"Forward", "0x67d2f6740a8eaebf"},
    {"NewTab", "0x290eb683f96572f1"},
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
    std::string hash_string = MetricsLog::CreateHash(cases[i].input);

    // Convert to hex string
    // We're only checking the first 8 bytes, because that's what
    // the metrics server uses.
    std::string hash_hex = "0x";
    for (size_t j = 0; j < 8; j++) {
      StringAppendF(&hash_hex, "%02x",
                    static_cast<uint8>(hash_string.data()[j]));
    }
    EXPECT_EQ(cases[i].output, hash_hex);
  }
};
<commit_msg>Landing CL http://codereview.chromium.org/2767013/show on behalf of petkov@chromium.org:<commit_after>// Copyright (c) 2006-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 <string>

#include "base/string_util.h"
#include "base/time.h"
#include "chrome/browser/metrics/metrics_log.h"
#include "googleurl/src/gurl.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::TimeDelta;

namespace {
  class MetricsLogTest : public testing::Test {
  };
};

// Since buildtime is highly variable, this function will scan an output log and
// replace it with a consistent number.
static void NormalizeBuildtime(std::string* xml_encoded) {
  std::string prefix = "buildtime=\"";
  const char postfix = '\"';
  size_t offset = xml_encoded->find(prefix);
  ASSERT_GT(offset, 0u);
  offset += prefix.size();
  size_t postfix_position = xml_encoded->find(postfix, offset);
  ASSERT_GT(postfix_position, offset);
  for (size_t i = offset; i < postfix_position; ++i) {
    char digit = xml_encoded->at(i);
    ASSERT_GE(digit, '0');
    ASSERT_LE(digit, '9');
  }

  // Insert a single fake buildtime.
  xml_encoded->replace(offset, postfix_position - offset, "123246");
}

TEST(MetricsLogTest, EmptyRecord) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
      "appversion=\"%s\"/>", MetricsLog::GetVersionString().c_str());

  MetricsLog log("bogus client ID", 0);
  log.CloseLog();

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}

#if defined(OS_CHROMEOS)
TEST(MetricsLogTest, ChromeOSEmptyRecord) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
      "appversion=\"%s\" hardwareclass=\"sample-class\"/>",
      MetricsLog::GetVersionString().c_str());

  MetricsLog log("bogus client ID", 0);
  log.set_hardware_class("sample-class");
  log.CloseLog();

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}
#endif  // OS_CHROMEOS

namespace {

class NoTimeMetricsLog : public MetricsLog {
 public:
  NoTimeMetricsLog(std::string client_id, int session_id):
      MetricsLog(client_id, session_id) {}
  virtual ~NoTimeMetricsLog() {}

  // Override this so that output is testable.
  virtual std::string GetCurrentTimeString() {
    return std::string();
  }
};

};  // namespace

TEST(MetricsLogTest, WindowEvent) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
          "appversion=\"%s\">\n"
      " <window action=\"create\" windowid=\"0\" session=\"0\" time=\"\"/>\n"
      " <window action=\"open\" windowid=\"1\" parent=\"0\" "
          "session=\"0\" time=\"\"/>\n"
      " <window action=\"close\" windowid=\"1\" parent=\"0\" "
          "session=\"0\" time=\"\"/>\n"
      " <window action=\"destroy\" windowid=\"0\" session=\"0\" time=\"\"/>\n"
      "</log>", MetricsLog::GetVersionString().c_str());

  NoTimeMetricsLog log("bogus client ID", 0);
  log.RecordWindowEvent(MetricsLog::WINDOW_CREATE, 0, -1);
  log.RecordWindowEvent(MetricsLog::WINDOW_OPEN, 1, 0);
  log.RecordWindowEvent(MetricsLog::WINDOW_CLOSE, 1, 0);
  log.RecordWindowEvent(MetricsLog::WINDOW_DESTROY, 0, -1);
  log.CloseLog();

  ASSERT_EQ(4, log.num_events());

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}

TEST(MetricsLogTest, LoadEvent) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
          "appversion=\"%s\">\n"
      " <document action=\"load\" docid=\"1\" window=\"3\" loadtime=\"7219\" "
          "origin=\"link\" session=\"0\" time=\"\"/>\n"
      "</log>", MetricsLog::GetVersionString().c_str());

  NoTimeMetricsLog log("bogus client ID", 0);
  log.RecordLoadEvent(3, GURL("http://google.com"), PageTransition::LINK,
                      1, TimeDelta::FromMilliseconds(7219));

  log.CloseLog();

  ASSERT_EQ(1, log.num_events());

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}

#if defined(OS_CHROMEOS)
TEST(MetricsLogTest, ChromeOSLoadEvent) {
  std::string expected_output = StringPrintf(
      "<log clientid=\"bogus client ID\" buildtime=\"123456789\" "
          "appversion=\"%s\" hardwareclass=\"sample-class\">\n"
      " <document action=\"load\" docid=\"1\" window=\"3\" loadtime=\"7219\" "
          "origin=\"link\" session=\"0\" time=\"\"/>\n"
      "</log>", MetricsLog::GetVersionString().c_str());

  NoTimeMetricsLog log("bogus client ID", 0);
  log.RecordLoadEvent(3, GURL("http://google.com"), PageTransition::LINK,
                      1, TimeDelta::FromMilliseconds(7219));
  log.set_hardware_class("sample-class");
  log.CloseLog();

  ASSERT_EQ(1, log.num_events());

  int size = log.GetEncodedLogSize();
  ASSERT_GT(size, 0);

  std::string encoded;
  // Leave room for the NUL terminator.
  ASSERT_TRUE(log.GetEncodedLog(WriteInto(&encoded, size + 1), size));
  TrimWhitespaceASCII(encoded, TRIM_ALL, &encoded);
  NormalizeBuildtime(&encoded);
  NormalizeBuildtime(&expected_output);

  ASSERT_EQ(expected_output, encoded);
}
#endif  // OS_CHROMEOS

// Make sure our ID hashes are the same as what we see on the server side.
TEST(MetricsLogTest, CreateHash) {
  static const struct {
    std::string input;
    std::string output;
  } cases[] = {
    {"Back", "0x0557fa923dcee4d0"},
    {"Forward", "0x67d2f6740a8eaebf"},
    {"NewTab", "0x290eb683f96572f1"},
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(cases); i++) {
    std::string hash_string = MetricsLog::CreateHash(cases[i].input);

    // Convert to hex string
    // We're only checking the first 8 bytes, because that's what
    // the metrics server uses.
    std::string hash_hex = "0x";
    for (size_t j = 0; j < 8; j++) {
      StringAppendF(&hash_hex, "%02x",
                    static_cast<uint8>(hash_string.data()[j]));
    }
    EXPECT_EQ(cases[i].output, hash_hex);
  }
};
<|endoftext|>