<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: officeinstallationdirectories.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:54:13 $
 *
 *  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
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/

#include "osl/file.hxx"
#include "com/sun/star/beans/XPropertySet.hpp"
#include "com/sun/star/util/XMacroExpander.hpp"

#include "officeinstallationdirectories.hxx"

using namespace com::sun::star;

using namespace comphelper;

//=========================================================================
// helpers
//=========================================================================

uno::Sequence< rtl::OUString > SAL_CALL
OfficeInstallationDirectories_getSupportedServiceNames()
    throw()
{
    const rtl::OUString aServiceName(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.util.OfficeInstallationDirectories" ) );
    return uno::Sequence< rtl::OUString >( &aServiceName, 1 );
}

//=========================================================================
rtl::OUString SAL_CALL OfficeInstallationDirectories_getImplementationName()
    throw()
{
    return rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.comp.util.OfficeInstallationDirectories" ) );
}

//=========================================================================
rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonName()
    throw()
{
    return rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.util.theOfficeInstallationDirectories" ) );
}

//=========================================================================
rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonServiceName()
    throw()
{
    return rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.util.OfficeInstallationDirectories" ) );
}

//=========================================================================
uno::Reference< uno::XInterface > SAL_CALL
OfficeInstallationDirectories_createInstance(
        const uno::Reference< lang::XMultiServiceFactory > & xSMgr )
    throw( uno::Exception )
{
    OSL_ENSURE( xSMgr.is(), "No service manager!" );

    uno::Reference< uno::XComponentContext > xCtx;
    uno::Reference< beans::XPropertySet > xPropSet( xSMgr, uno::UNO_QUERY );
    if ( xPropSet.is() )
    {
        xPropSet->getPropertyValue(
            rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) ) )
        >>= xCtx;
    }

    if ( !xCtx.is() )
    {
        throw uno::RuntimeException(
            rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                "Unable to obtain component context from service manager!" ) ),
            uno::Reference< uno::XInterface >() );
    }

    return static_cast< cppu::OWeakObject * >(
        new OfficeInstallationDirectories( xCtx ) );
}

//=========================================================================
static bool makeCanonicalFileURL( rtl::OUString & rURL )
{
    OSL_ENSURE( rURL.matchAsciiL( "file:", sizeof( "file:" ) - 1 , 0 ) ,
                "File URL expected!" );

    rtl::OUString aNormalizedURL;
    if ( osl::FileBase::getAbsoluteFileURL( rtl::OUString(),
                                            rURL,
                                            aNormalizedURL )
            == osl::DirectoryItem::E_None )
    {
        osl::DirectoryItem aDirItem;
        if ( osl::DirectoryItem::get( aNormalizedURL, aDirItem )
                == osl::DirectoryItem::E_None )
        {
            osl::FileStatus aFileStatus( FileStatusMask_FileURL );

            if ( aDirItem.getFileStatus( aFileStatus )
                    == osl::DirectoryItem::E_None )
            {
                aNormalizedURL = aFileStatus.getFileURL();

                if ( aNormalizedURL.getLength() > 0 )
                {
                    if ( aNormalizedURL
                            .getStr()[ aNormalizedURL.getLength() - 1 ]
                                != sal_Unicode( '/' ) )
                        rURL = aNormalizedURL;
                    else
                        rURL = aNormalizedURL
                                .copy( 0, aNormalizedURL.getLength() - 1 );

                    return true;
                }
            }
        }
    }
    return false;
}

//=========================================================================
//=========================================================================
//
// OfficeInstallationDirectories Implementation.
//
//=========================================================================
//=========================================================================

OfficeInstallationDirectories::OfficeInstallationDirectories(
        const uno::Reference< uno::XComponentContext > & xCtx )
: m_aOfficeDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(baseinsturl)" ) ),
  m_aUserDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(userdataurl)" ) ),
  m_xCtx( xCtx ),
  m_pOfficeDir( 0 ),
  m_pUserDir( 0 )
{
}

//=========================================================================
// virtual
OfficeInstallationDirectories::~OfficeInstallationDirectories()
{
}

//=========================================================================
// util::XOfficeInstallationDirectories
//=========================================================================

// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::getOfficeInstallationDirectoryURL()
    throw ( uno::RuntimeException )
{
    // late init m_pOfficeDir and m_pUserDir
    initDirs();
    return rtl::OUString( *m_pOfficeDir );
}

//=========================================================================
// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::getOfficeUserDataDirectoryURL()
    throw ( uno::RuntimeException )
{
    // late init m_pOfficeDir and m_pUserDir
    initDirs();
    return rtl::OUString( *m_pUserDir );
}

//=========================================================================
// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::makeRelocatableURL( const rtl::OUString& URL )
    throw ( uno::RuntimeException )
{
    if ( URL.getLength() > 0 )
    {
        // late init m_pOfficeDir and m_pUserDir
        initDirs();

        rtl::OUString aCanonicalURL( URL );
        makeCanonicalFileURL( aCanonicalURL );

        sal_Int32 nIndex = aCanonicalURL.indexOf( *m_pOfficeDir );
        if ( nIndex  != -1 )
        {
            return rtl::OUString(
                URL.replaceAt( nIndex,
                               m_pOfficeDir->getLength(),
                               m_aOfficeDirMacro ) );
        }
        else
        {
            sal_Int32 nIndex = aCanonicalURL.indexOf( *m_pUserDir );
            if ( nIndex  != -1 )
            {
                return rtl::OUString(
                    URL.replaceAt( nIndex,
                                   m_pUserDir->getLength(),
                                   m_aUserDirMacro ) );
            }
        }
    }
    return rtl::OUString( URL );
}

//=========================================================================
// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::makeAbsoluteURL( const rtl::OUString& URL )
    throw ( uno::RuntimeException )
{
    if ( URL.getLength() > 0 )
    {
        sal_Int32 nIndex = URL.indexOf( m_aOfficeDirMacro );
        if ( nIndex != -1 )
        {
            // late init m_pOfficeDir and m_pUserDir
            initDirs();

            return rtl::OUString(
                URL.replaceAt( nIndex,
                               m_aOfficeDirMacro.getLength(),
                               *m_pOfficeDir ) );
        }
        else
        {
            sal_Int32 nIndex = URL.indexOf( m_aUserDirMacro );
            if ( nIndex != -1 )
            {
                // late init m_pOfficeDir and m_pUserDir
                initDirs();

                return rtl::OUString(
                    URL.replaceAt( nIndex,
                                   m_aUserDirMacro.getLength(),
                                   *m_pUserDir ) );
            }
        }
    }
    return rtl::OUString( URL );
}

//=========================================================================
// lang::XServiceInfo
//=========================================================================

// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::getImplementationName()
    throw ( uno::RuntimeException )
{
    return OfficeInstallationDirectories_getImplementationName();
}

//=========================================================================
// virtual
sal_Bool SAL_CALL
OfficeInstallationDirectories::supportsService( const rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    const uno::Sequence< rtl::OUString > & aNames
        = OfficeInstallationDirectories_getSupportedServiceNames();
    const rtl::OUString * p = aNames.getConstArray();
    for ( sal_Int32 nPos = 0; nPos < aNames.getLength(); nPos++ )
    {
        if ( p[ nPos ].equals( ServiceName ) )
            return sal_True;
    }
    return sal_False;

}

//=========================================================================
// virtual
uno::Sequence< ::rtl::OUString > SAL_CALL
OfficeInstallationDirectories::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return OfficeInstallationDirectories_getSupportedServiceNames();
}

//=========================================================================
// non-UNO
//=========================================================================

void OfficeInstallationDirectories::initDirs()
{
    if ( m_pOfficeDir == 0 )
    {
        osl::MutexGuard aGuard( m_aMutex );
        if ( m_pOfficeDir == 0 )
        {
            m_pOfficeDir = new rtl::OUString;
            m_pUserDir   = new rtl::OUString;

            uno::Reference< util::XMacroExpander > xExpander;

            m_xCtx->getValueByName(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                    "/singletons/com.sun.star.util.theMacroExpander" ) ) )
            >>= xExpander;

            OSL_ENSURE( xExpander.is(),
                        "Unable to obtain macro expander singleton!" );

            if ( xExpander.is() )
            {
                *m_pOfficeDir =
                    xExpander->expandMacros(
                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                            "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":BaseInstallation}" ) ) );

                OSL_ENSURE( m_pOfficeDir->getLength() > 0,
                        "Unable to obtain office installation directory!" );

                makeCanonicalFileURL( *m_pOfficeDir );

                *m_pUserDir =
                    xExpander->expandMacros(
                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                            "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":UserInstallation}" ) ) );

                OSL_ENSURE( m_pUserDir->getLength() > 0,
                        "Unable to obtain office user data directory!" );

                makeCanonicalFileURL( *m_pUserDir );
            }
        }
    }
}

<commit_msg>INTEGRATION: CWS warnings01 (1.3.130); FILE MERGED 2005/09/23 03:20:25 sb 1.3.130.2: RESYNC: (1.3-1.4); FILE MERGED 2005/09/08 13:16:53 sb 1.3.130.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: officeinstallationdirectories.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 22:50:11 $
 *
 *  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
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

 *************************************************************************/

#include "osl/file.hxx"
#include "com/sun/star/beans/XPropertySet.hpp"
#include "com/sun/star/util/XMacroExpander.hpp"

#include "officeinstallationdirectories.hxx"

using namespace com::sun::star;

using namespace comphelper;

//=========================================================================
// helpers
//=========================================================================

uno::Sequence< rtl::OUString > SAL_CALL
OfficeInstallationDirectories_getSupportedServiceNames()
    throw()
{
    const rtl::OUString aServiceName(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.util.OfficeInstallationDirectories" ) );
    return uno::Sequence< rtl::OUString >( &aServiceName, 1 );
}

//=========================================================================
rtl::OUString SAL_CALL OfficeInstallationDirectories_getImplementationName()
    throw()
{
    return rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.comp.util.OfficeInstallationDirectories" ) );
}

//=========================================================================
rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonName()
    throw()
{
    return rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.util.theOfficeInstallationDirectories" ) );
}

//=========================================================================
rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonServiceName()
    throw()
{
    return rtl::OUString(
        RTL_CONSTASCII_USTRINGPARAM(
            "com.sun.star.util.OfficeInstallationDirectories" ) );
}

//=========================================================================
uno::Reference< uno::XInterface > SAL_CALL
OfficeInstallationDirectories_createInstance(
        const uno::Reference< lang::XMultiServiceFactory > & xSMgr )
    throw( uno::Exception )
{
    OSL_ENSURE( xSMgr.is(), "No service manager!" );

    uno::Reference< uno::XComponentContext > xCtx;
    uno::Reference< beans::XPropertySet > xPropSet( xSMgr, uno::UNO_QUERY );
    if ( xPropSet.is() )
    {
        xPropSet->getPropertyValue(
            rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) ) )
        >>= xCtx;
    }

    if ( !xCtx.is() )
    {
        throw uno::RuntimeException(
            rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                "Unable to obtain component context from service manager!" ) ),
            uno::Reference< uno::XInterface >() );
    }

    return static_cast< cppu::OWeakObject * >(
        new OfficeInstallationDirectories( xCtx ) );
}

//=========================================================================
static bool makeCanonicalFileURL( rtl::OUString & rURL )
{
    OSL_ENSURE( rURL.matchAsciiL( "file:", sizeof( "file:" ) - 1 , 0 ) ,
                "File URL expected!" );

    rtl::OUString aNormalizedURL;
    if ( osl::FileBase::getAbsoluteFileURL( rtl::OUString(),
                                            rURL,
                                            aNormalizedURL )
            == osl::DirectoryItem::E_None )
    {
        osl::DirectoryItem aDirItem;
        if ( osl::DirectoryItem::get( aNormalizedURL, aDirItem )
                == osl::DirectoryItem::E_None )
        {
            osl::FileStatus aFileStatus( FileStatusMask_FileURL );

            if ( aDirItem.getFileStatus( aFileStatus )
                    == osl::DirectoryItem::E_None )
            {
                aNormalizedURL = aFileStatus.getFileURL();

                if ( aNormalizedURL.getLength() > 0 )
                {
                    if ( aNormalizedURL
                            .getStr()[ aNormalizedURL.getLength() - 1 ]
                                != sal_Unicode( '/' ) )
                        rURL = aNormalizedURL;
                    else
                        rURL = aNormalizedURL
                                .copy( 0, aNormalizedURL.getLength() - 1 );

                    return true;
                }
            }
        }
    }
    return false;
}

//=========================================================================
//=========================================================================
//
// OfficeInstallationDirectories Implementation.
//
//=========================================================================
//=========================================================================

OfficeInstallationDirectories::OfficeInstallationDirectories(
        const uno::Reference< uno::XComponentContext > & xCtx )
: m_aOfficeDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(baseinsturl)" ) ),
  m_aUserDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(userdataurl)" ) ),
  m_xCtx( xCtx ),
  m_pOfficeDir( 0 ),
  m_pUserDir( 0 )
{
}

//=========================================================================
// virtual
OfficeInstallationDirectories::~OfficeInstallationDirectories()
{
}

//=========================================================================
// util::XOfficeInstallationDirectories
//=========================================================================

// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::getOfficeInstallationDirectoryURL()
    throw ( uno::RuntimeException )
{
    // late init m_pOfficeDir and m_pUserDir
    initDirs();
    return rtl::OUString( *m_pOfficeDir );
}

//=========================================================================
// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::getOfficeUserDataDirectoryURL()
    throw ( uno::RuntimeException )
{
    // late init m_pOfficeDir and m_pUserDir
    initDirs();
    return rtl::OUString( *m_pUserDir );
}

//=========================================================================
// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::makeRelocatableURL( const rtl::OUString& URL )
    throw ( uno::RuntimeException )
{
    if ( URL.getLength() > 0 )
    {
        // late init m_pOfficeDir and m_pUserDir
        initDirs();

        rtl::OUString aCanonicalURL( URL );
        makeCanonicalFileURL( aCanonicalURL );

        sal_Int32 nIndex = aCanonicalURL.indexOf( *m_pOfficeDir );
        if ( nIndex  != -1 )
        {
            return rtl::OUString(
                URL.replaceAt( nIndex,
                               m_pOfficeDir->getLength(),
                               m_aOfficeDirMacro ) );
        }
        else
        {
            nIndex = aCanonicalURL.indexOf( *m_pUserDir );
            if ( nIndex  != -1 )
            {
                return rtl::OUString(
                    URL.replaceAt( nIndex,
                                   m_pUserDir->getLength(),
                                   m_aUserDirMacro ) );
            }
        }
    }
    return rtl::OUString( URL );
}

//=========================================================================
// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::makeAbsoluteURL( const rtl::OUString& URL )
    throw ( uno::RuntimeException )
{
    if ( URL.getLength() > 0 )
    {
        sal_Int32 nIndex = URL.indexOf( m_aOfficeDirMacro );
        if ( nIndex != -1 )
        {
            // late init m_pOfficeDir and m_pUserDir
            initDirs();

            return rtl::OUString(
                URL.replaceAt( nIndex,
                               m_aOfficeDirMacro.getLength(),
                               *m_pOfficeDir ) );
        }
        else
        {
            nIndex = URL.indexOf( m_aUserDirMacro );
            if ( nIndex != -1 )
            {
                // late init m_pOfficeDir and m_pUserDir
                initDirs();

                return rtl::OUString(
                    URL.replaceAt( nIndex,
                                   m_aUserDirMacro.getLength(),
                                   *m_pUserDir ) );
            }
        }
    }
    return rtl::OUString( URL );
}

//=========================================================================
// lang::XServiceInfo
//=========================================================================

// virtual
rtl::OUString SAL_CALL
OfficeInstallationDirectories::getImplementationName()
    throw ( uno::RuntimeException )
{
    return OfficeInstallationDirectories_getImplementationName();
}

//=========================================================================
// virtual
sal_Bool SAL_CALL
OfficeInstallationDirectories::supportsService( const rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    const uno::Sequence< rtl::OUString > & aNames
        = OfficeInstallationDirectories_getSupportedServiceNames();
    const rtl::OUString * p = aNames.getConstArray();
    for ( sal_Int32 nPos = 0; nPos < aNames.getLength(); nPos++ )
    {
        if ( p[ nPos ].equals( ServiceName ) )
            return sal_True;
    }
    return sal_False;

}

//=========================================================================
// virtual
uno::Sequence< ::rtl::OUString > SAL_CALL
OfficeInstallationDirectories::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return OfficeInstallationDirectories_getSupportedServiceNames();
}

//=========================================================================
// non-UNO
//=========================================================================

void OfficeInstallationDirectories::initDirs()
{
    if ( m_pOfficeDir == 0 )
    {
        osl::MutexGuard aGuard( m_aMutex );
        if ( m_pOfficeDir == 0 )
        {
            m_pOfficeDir = new rtl::OUString;
            m_pUserDir   = new rtl::OUString;

            uno::Reference< util::XMacroExpander > xExpander;

            m_xCtx->getValueByName(
                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                    "/singletons/com.sun.star.util.theMacroExpander" ) ) )
            >>= xExpander;

            OSL_ENSURE( xExpander.is(),
                        "Unable to obtain macro expander singleton!" );

            if ( xExpander.is() )
            {
                *m_pOfficeDir =
                    xExpander->expandMacros(
                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                            "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":BaseInstallation}" ) ) );

                OSL_ENSURE( m_pOfficeDir->getLength() > 0,
                        "Unable to obtain office installation directory!" );

                makeCanonicalFileURL( *m_pOfficeDir );

                *m_pUserDir =
                    xExpander->expandMacros(
                        rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                            "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":UserInstallation}" ) ) );

                OSL_ENSURE( m_pUserDir->getLength() > 0,
                        "Unable to obtain office user data directory!" );

                makeCanonicalFileURL( *m_pUserDir );
            }
        }
    }
}

<|endoftext|>


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

#include "chrome/browser/ui/views/extensions/media_galleries_dialog_views.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "chrome/browser/ui/web_contents_modal_dialog_manager.h"
#include "chrome/browser/ui/web_contents_modal_dialog_manager_delegate.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/separator.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_client_view.h"

namespace {

// Equal to the #969696 color used in spec (note WebUI color is #999).
const SkColor kDeemphasizedTextColor = SkColorSetRGB(159, 159, 159);

const int kScrollAreaHeight = 192;

// This container has the right Layout() impl to use within a ScrollView.
class ScrollableView : public views::View {
 public:
  ScrollableView() {}
  virtual ~ScrollableView() {}

  virtual void Layout() OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(ScrollableView);
};

void ScrollableView::Layout() {
  gfx::Size pref = GetPreferredSize();
  int width = pref.width();
  int height = pref.height();
  if (parent()) {
    width = std::max(parent()->width(), width);
    height = std::max(parent()->height(), height);
  }
  SetBounds(x(), y(), width, height);

  views::View::Layout();
}

}  // namespace

namespace chrome {

typedef MediaGalleriesDialogController::KnownGalleryPermissions
    GalleryPermissions;
typedef MediaGalleriesDialogController::NewGalleryPermissions
    NewGalleryPermissions;

MediaGalleriesDialogViews::MediaGalleriesDialogViews(
    MediaGalleriesDialogController* controller)
    : controller_(controller),
      window_(NULL),
      contents_(new views::View()),
      add_gallery_button_(NULL),
      confirm_available_(false),
      accepted_(false) {
  InitChildViews();

  // Ownership of |contents_| is handed off by this call. |window_| will take
  // care of deleting itself after calling DeleteDelegate().
  WebContentsModalDialogManager* web_contents_modal_dialog_manager =
      WebContentsModalDialogManager::FromWebContents(
          controller->web_contents());
  window_ = CreateWebContentsModalDialogViews(
      this,
      controller->web_contents()->GetView()->GetNativeView(),
      web_contents_modal_dialog_manager->delegate()->
          GetWebContentsModalDialogHost());
  web_contents_modal_dialog_manager->ShowDialog(window_->GetNativeView());
}

MediaGalleriesDialogViews::~MediaGalleriesDialogViews() {}

void MediaGalleriesDialogViews::InitChildViews() {
  // Outer dialog layout.
  contents_->RemoveAllChildViews(true);
  int dialog_content_width = views::Widget::GetLocalizedContentsWidth(
      IDS_MEDIA_GALLERIES_DIALOG_CONTENT_WIDTH_CHARS);
  views::GridLayout* layout = new views::GridLayout(contents_);
  layout->SetInsets(views::kPanelVertMargin, views::kPanelHorizMargin,
                    0, views::kPanelHorizMargin);

  int column_set_id = 0;
  views::ColumnSet* columns = layout->AddColumnSet(column_set_id);
  columns->AddColumn(views::GridLayout::LEADING,
                     views::GridLayout::LEADING,
                     1,
                     views::GridLayout::FIXED,
                     dialog_content_width,
                     0);
  contents_->SetLayoutManager(layout);
  contents_->set_border(views::Border::CreateEmptyBorder(
      views::kPanelSubVerticalSpacing,
      0,
      views::kPanelSubVerticalSpacing,
      0));

  // Header text.
  views::Label* header = new views::Label(controller_->GetHeader());
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  header->SetFont(rb.GetFont(ui::ResourceBundle::MediumFont));
  header->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  layout->StartRow(0, column_set_id);
  layout->AddView(header);

  // Message text.
  views::Label* subtext = new views::Label(controller_->GetSubtext());
  subtext->SetMultiLine(true);
  subtext->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  layout->StartRowWithPadding(0, column_set_id,
                              0, views::kRelatedControlVerticalSpacing);
  layout->AddView(subtext);

  // Scrollable area for checkboxes.
  ScrollableView* scroll_container = new ScrollableView();
  scroll_container->SetLayoutManager(new views::BoxLayout(
      views::BoxLayout::kVertical, 0, 0,
      views::kRelatedControlSmallVerticalSpacing));
  scroll_container->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing,
      0,
      views::kRelatedControlVerticalSpacing,
      0));

  // Add attached galleries checkboxes.
  checkbox_map_.clear();
  const GalleryPermissions& permissions = controller_->permissions();
  const NewGalleryPermissions& new_permissions = controller_->new_permissions();
  for (GalleryPermissions::const_iterator iter = permissions.begin();
       iter != permissions.end(); ++iter) {
    if (MediaGalleriesDialogController::GetGalleryAttached(
            iter->second.pref_info)) {
      AddOrUpdateGallery(&iter->second.pref_info, iter->second.allowed,
                         scroll_container);
    }
  }
  for (NewGalleryPermissions::const_iterator iter = new_permissions.begin();
       iter != new_permissions.end(); ++iter) {
    if (MediaGalleriesDialogController::GetGalleryAttached(iter->pref_info))
      AddOrUpdateGallery(&iter->pref_info, iter->allowed, scroll_container);
  }

  // Separator line.
  views::View* strut = new views::View;
  strut->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing, 0, 0, 0));
  scroll_container->AddChildView(strut);
  views::Separator* separator = new views::Separator;
  scroll_container->AddChildView(separator);

  // Unattached locations section.
  views::Label* unattached_text = new views::Label(
      controller_->GetUnattachedLocationsHeader());
  unattached_text->SetMultiLine(true);
  unattached_text->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  unattached_text->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing,
      views::kPanelHorizMargin,
      views::kRelatedControlVerticalSpacing,
      0));
  scroll_container->AddChildView(unattached_text);

  // Add unattached galleries checkboxes.
  for (GalleryPermissions::const_iterator iter = permissions.begin();
       iter != permissions.end(); ++iter) {
    if (!MediaGalleriesDialogController::GetGalleryAttached(
            iter->second.pref_info)) {
      AddOrUpdateGallery(&iter->second.pref_info, iter->second.allowed,
                         scroll_container);
    }
  }
  for (NewGalleryPermissions::const_iterator iter = new_permissions.begin();
       iter != new_permissions.end(); ++iter) {
    if (!MediaGalleriesDialogController::GetGalleryAttached(iter->pref_info))
      AddOrUpdateGallery(&iter->pref_info, iter->allowed, scroll_container);
  }

  confirm_available_ |= new_permissions.size() > 0;

  // Add the scrollable area to the outer dialog view. It will squeeze against
  // the title/subtitle and buttons to occupy all available space in the dialog.
  views::ScrollView* scroll_view =
      views::ScrollView::CreateScrollViewWithBorder();
  scroll_view->SetContents(scroll_container);
  layout->StartRowWithPadding(1, column_set_id,
                              0, views::kRelatedControlVerticalSpacing);
  layout->AddView(scroll_view, 1, 1,
                  views::GridLayout::FILL, views::GridLayout::FILL,
                  dialog_content_width, kScrollAreaHeight);

  // Add location button.
  add_gallery_button_ = new views::LabelButton(this,
      l10n_util::GetStringUTF16(IDS_MEDIA_GALLERIES_DIALOG_ADD_GALLERY));
  add_gallery_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
  views::View* add_gallery_container = new views::View();
  add_gallery_container->SetLayoutManager(
      new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0));
  add_gallery_container->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing,
      views::kPanelHorizMargin,
      views::kRelatedControlVerticalSpacing,
      0));
  add_gallery_container->AddChildView(add_gallery_button_);
  layout->StartRowWithPadding(0, column_set_id,
                              0, views::kRelatedControlVerticalSpacing);
  layout->AddView(add_gallery_container, 1, 1,
                  views::GridLayout::LEADING, views::GridLayout::LEADING);
}

void MediaGalleriesDialogViews::UpdateGallery(
    const MediaGalleryPrefInfo* gallery,
    bool permitted) {
  InitChildViews();
  contents_->Layout();
}

void MediaGalleriesDialogViews::ForgetGallery(
    const MediaGalleryPrefInfo* gallery) {
  InitChildViews();
  contents_->Layout();
}

bool MediaGalleriesDialogViews::AddOrUpdateGallery(
    const MediaGalleryPrefInfo* gallery,
    bool permitted,
    views::View* container) {
  string16 label =
      MediaGalleriesDialogController::GetGalleryDisplayNameNoAttachment(
          *gallery);
  string16 tooltip_text =
      MediaGalleriesDialogController::GetGalleryTooltip(*gallery);
  string16 details =
      MediaGalleriesDialogController::GetGalleryAdditionalDetails(*gallery);

  CheckboxMap::iterator iter = checkbox_map_.find(gallery);
  if (iter != checkbox_map_.end()) {
    views::Checkbox* checkbox = iter->second;
    checkbox->SetChecked(permitted);
    checkbox->SetText(label);
    checkbox->SetTooltipText(tooltip_text);
    // Replace the details string.
    views::View* checkbox_view = checkbox->parent();
    DCHECK_EQ(2, checkbox_view->child_count());
    views::Label* secondary_text =
        static_cast<views::Label*>(checkbox_view->child_at(1));
    secondary_text->SetText(details);

    // Why is this returning false? Looks like that will mean it doesn't paint.
    return false;
  }

  views::Checkbox* checkbox = new views::Checkbox(label);
  checkbox->set_listener(this);
  checkbox->SetTooltipText(tooltip_text);
  views::Label* secondary_text = new views::Label(details);
  secondary_text->SetTooltipText(tooltip_text);
  secondary_text->SetEnabledColor(kDeemphasizedTextColor);
  secondary_text->SetTooltipText(tooltip_text);
  secondary_text->set_border(views::Border::CreateEmptyBorder(
      0,
      views::kRelatedControlSmallHorizontalSpacing,
      0,
      views::kRelatedControlSmallHorizontalSpacing));

  views::View* checkbox_view = new views::View();
  checkbox_view->set_border(views::Border::CreateEmptyBorder(
      0,
      views::kPanelHorizMargin,
      0,
      0));
  checkbox_view->SetLayoutManager(
      new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0));
  checkbox_view->AddChildView(checkbox);
  checkbox_view->AddChildView(secondary_text);

  container->AddChildView(checkbox_view);

  checkbox->SetChecked(permitted);
  checkbox_map_[gallery] = checkbox;

  return true;
}

string16 MediaGalleriesDialogViews::GetWindowTitle() const {
  return controller_->GetHeader();
}

bool MediaGalleriesDialogViews::ShouldShowWindowTitle() const {
  return false;
}

void MediaGalleriesDialogViews::DeleteDelegate() {
  controller_->DialogFinished(accepted_);
}

views::Widget* MediaGalleriesDialogViews::GetWidget() {
  return contents_->GetWidget();
}

const views::Widget* MediaGalleriesDialogViews::GetWidget() const {
  return contents_->GetWidget();
}

views::View* MediaGalleriesDialogViews::GetContentsView() {
  return contents_;
}

string16 MediaGalleriesDialogViews::GetDialogButtonLabel(
    ui::DialogButton button) const {
  return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ?
      IDS_MEDIA_GALLERIES_DIALOG_CONFIRM :
      IDS_MEDIA_GALLERIES_DIALOG_CANCEL);
}

bool MediaGalleriesDialogViews::IsDialogButtonEnabled(
    ui::DialogButton button) const {
  return button != ui::DIALOG_BUTTON_OK || confirm_available_;
}

ui::ModalType MediaGalleriesDialogViews::GetModalType() const {
#if defined(USE_ASH)
  return ui::MODAL_TYPE_CHILD;
#else
  return views::WidgetDelegate::GetModalType();
#endif
}

bool MediaGalleriesDialogViews::Cancel() {
  return true;
}

bool MediaGalleriesDialogViews::Accept() {
  accepted_ = true;

  for (CheckboxMap::const_iterator iter = checkbox_map_.begin();
       iter != checkbox_map_.end(); ++iter) {
    controller_->DidToggleGallery(iter->first, iter->second->checked());
  }

  return true;
}

// TODO(wittman): Remove this override once we move to the new style frame view
// on all dialogs.
views::NonClientFrameView* MediaGalleriesDialogViews::CreateNonClientFrameView(
    views::Widget* widget) {
  return CreateConstrainedStyleNonClientFrameView(
      widget,
      controller_->web_contents()->GetBrowserContext());
}

void MediaGalleriesDialogViews::ButtonPressed(views::Button* sender,
                                              const ui::Event& event) {
  confirm_available_ = true;
  GetWidget()->client_view()->AsDialogClientView()->UpdateDialogButtons();

  if (sender == add_gallery_button_) {
    controller_->OnAddFolderClicked();
    return;
  }
}

// MediaGalleriesDialogViewsController -----------------------------------------

// static
MediaGalleriesDialog* MediaGalleriesDialog::Create(
    MediaGalleriesDialogController* controller) {
  return new MediaGalleriesDialogViews(controller);
}

}  // namespace chrome
<commit_msg>[Media Galleries] Send checkbox information to controller in views.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/extensions/media_galleries_dialog_views.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "chrome/browser/ui/web_contents_modal_dialog_manager.h"
#include "chrome/browser/ui/web_contents_modal_dialog_manager_delegate.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/button/checkbox.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/separator.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_client_view.h"

namespace {

// Equal to the #969696 color used in spec (note WebUI color is #999).
const SkColor kDeemphasizedTextColor = SkColorSetRGB(159, 159, 159);

const int kScrollAreaHeight = 192;

// This container has the right Layout() impl to use within a ScrollView.
class ScrollableView : public views::View {
 public:
  ScrollableView() {}
  virtual ~ScrollableView() {}

  virtual void Layout() OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(ScrollableView);
};

void ScrollableView::Layout() {
  gfx::Size pref = GetPreferredSize();
  int width = pref.width();
  int height = pref.height();
  if (parent()) {
    width = std::max(parent()->width(), width);
    height = std::max(parent()->height(), height);
  }
  SetBounds(x(), y(), width, height);

  views::View::Layout();
}

}  // namespace

namespace chrome {

typedef MediaGalleriesDialogController::KnownGalleryPermissions
    GalleryPermissions;
typedef MediaGalleriesDialogController::NewGalleryPermissions
    NewGalleryPermissions;

MediaGalleriesDialogViews::MediaGalleriesDialogViews(
    MediaGalleriesDialogController* controller)
    : controller_(controller),
      window_(NULL),
      contents_(new views::View()),
      add_gallery_button_(NULL),
      confirm_available_(false),
      accepted_(false) {
  InitChildViews();

  // Ownership of |contents_| is handed off by this call. |window_| will take
  // care of deleting itself after calling DeleteDelegate().
  WebContentsModalDialogManager* web_contents_modal_dialog_manager =
      WebContentsModalDialogManager::FromWebContents(
          controller->web_contents());
  DCHECK(web_contents_modal_dialog_manager);
  DCHECK(web_contents_modal_dialog_manager->delegate());
  window_ = CreateWebContentsModalDialogViews(
      this,
      controller->web_contents()->GetView()->GetNativeView(),
      web_contents_modal_dialog_manager->delegate()->
          GetWebContentsModalDialogHost());
  web_contents_modal_dialog_manager->ShowDialog(window_->GetNativeView());
}

MediaGalleriesDialogViews::~MediaGalleriesDialogViews() {}

void MediaGalleriesDialogViews::InitChildViews() {
  // Outer dialog layout.
  contents_->RemoveAllChildViews(true);
  int dialog_content_width = views::Widget::GetLocalizedContentsWidth(
      IDS_MEDIA_GALLERIES_DIALOG_CONTENT_WIDTH_CHARS);
  views::GridLayout* layout = new views::GridLayout(contents_);
  layout->SetInsets(views::kPanelVertMargin, views::kPanelHorizMargin,
                    0, views::kPanelHorizMargin);

  int column_set_id = 0;
  views::ColumnSet* columns = layout->AddColumnSet(column_set_id);
  columns->AddColumn(views::GridLayout::LEADING,
                     views::GridLayout::LEADING,
                     1,
                     views::GridLayout::FIXED,
                     dialog_content_width,
                     0);
  contents_->SetLayoutManager(layout);
  contents_->set_border(views::Border::CreateEmptyBorder(
      views::kPanelSubVerticalSpacing,
      0,
      views::kPanelSubVerticalSpacing,
      0));

  // Header text.
  views::Label* header = new views::Label(controller_->GetHeader());
  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
  header->SetFont(rb.GetFont(ui::ResourceBundle::MediumFont));
  header->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  layout->StartRow(0, column_set_id);
  layout->AddView(header);

  // Message text.
  views::Label* subtext = new views::Label(controller_->GetSubtext());
  subtext->SetMultiLine(true);
  subtext->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  layout->StartRowWithPadding(0, column_set_id,
                              0, views::kRelatedControlVerticalSpacing);
  layout->AddView(subtext);

  // Scrollable area for checkboxes.
  ScrollableView* scroll_container = new ScrollableView();
  scroll_container->SetLayoutManager(new views::BoxLayout(
      views::BoxLayout::kVertical, 0, 0,
      views::kRelatedControlSmallVerticalSpacing));
  scroll_container->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing,
      0,
      views::kRelatedControlVerticalSpacing,
      0));

  // Add attached galleries checkboxes.
  checkbox_map_.clear();
  const GalleryPermissions& permissions = controller_->permissions();
  const NewGalleryPermissions& new_permissions = controller_->new_permissions();
  for (GalleryPermissions::const_iterator iter = permissions.begin();
       iter != permissions.end(); ++iter) {
    if (MediaGalleriesDialogController::GetGalleryAttached(
            iter->second.pref_info)) {
      AddOrUpdateGallery(&iter->second.pref_info, iter->second.allowed,
                         scroll_container);
    }
  }
  for (NewGalleryPermissions::const_iterator iter = new_permissions.begin();
       iter != new_permissions.end(); ++iter) {
    if (MediaGalleriesDialogController::GetGalleryAttached(iter->pref_info))
      AddOrUpdateGallery(&iter->pref_info, iter->allowed, scroll_container);
  }

  // Separator line.
  views::View* strut = new views::View;
  strut->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing, 0, 0, 0));
  scroll_container->AddChildView(strut);
  views::Separator* separator = new views::Separator;
  scroll_container->AddChildView(separator);

  // Unattached locations section.
  views::Label* unattached_text = new views::Label(
      controller_->GetUnattachedLocationsHeader());
  unattached_text->SetMultiLine(true);
  unattached_text->SetHorizontalAlignment(gfx::ALIGN_LEFT);
  unattached_text->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing,
      views::kPanelHorizMargin,
      views::kRelatedControlVerticalSpacing,
      0));
  scroll_container->AddChildView(unattached_text);

  // Add unattached galleries checkboxes.
  for (GalleryPermissions::const_iterator iter = permissions.begin();
       iter != permissions.end(); ++iter) {
    if (!MediaGalleriesDialogController::GetGalleryAttached(
            iter->second.pref_info)) {
      AddOrUpdateGallery(&iter->second.pref_info, iter->second.allowed,
                         scroll_container);
    }
  }
  for (NewGalleryPermissions::const_iterator iter = new_permissions.begin();
       iter != new_permissions.end(); ++iter) {
    if (!MediaGalleriesDialogController::GetGalleryAttached(iter->pref_info))
      AddOrUpdateGallery(&iter->pref_info, iter->allowed, scroll_container);
  }

  confirm_available_ |= new_permissions.size() > 0;

  // Add the scrollable area to the outer dialog view. It will squeeze against
  // the title/subtitle and buttons to occupy all available space in the dialog.
  views::ScrollView* scroll_view =
      views::ScrollView::CreateScrollViewWithBorder();
  scroll_view->SetContents(scroll_container);
  layout->StartRowWithPadding(1, column_set_id,
                              0, views::kRelatedControlVerticalSpacing);
  layout->AddView(scroll_view, 1, 1,
                  views::GridLayout::FILL, views::GridLayout::FILL,
                  dialog_content_width, kScrollAreaHeight);

  // Add location button.
  add_gallery_button_ = new views::LabelButton(this,
      l10n_util::GetStringUTF16(IDS_MEDIA_GALLERIES_DIALOG_ADD_GALLERY));
  add_gallery_button_->SetStyle(views::Button::STYLE_NATIVE_TEXTBUTTON);
  views::View* add_gallery_container = new views::View();
  add_gallery_container->SetLayoutManager(
      new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0));
  add_gallery_container->set_border(views::Border::CreateEmptyBorder(
      views::kRelatedControlVerticalSpacing,
      views::kPanelHorizMargin,
      views::kRelatedControlVerticalSpacing,
      0));
  add_gallery_container->AddChildView(add_gallery_button_);
  layout->StartRowWithPadding(0, column_set_id,
                              0, views::kRelatedControlVerticalSpacing);
  layout->AddView(add_gallery_container, 1, 1,
                  views::GridLayout::LEADING, views::GridLayout::LEADING);
}

void MediaGalleriesDialogViews::UpdateGallery(
    const MediaGalleryPrefInfo* gallery,
    bool permitted) {
  InitChildViews();
  contents_->Layout();
}

void MediaGalleriesDialogViews::ForgetGallery(
    const MediaGalleryPrefInfo* gallery) {
  InitChildViews();
  contents_->Layout();
}

bool MediaGalleriesDialogViews::AddOrUpdateGallery(
    const MediaGalleryPrefInfo* gallery,
    bool permitted,
    views::View* container) {
  string16 label =
      MediaGalleriesDialogController::GetGalleryDisplayNameNoAttachment(
          *gallery);
  string16 tooltip_text =
      MediaGalleriesDialogController::GetGalleryTooltip(*gallery);
  string16 details =
      MediaGalleriesDialogController::GetGalleryAdditionalDetails(*gallery);

  CheckboxMap::iterator iter = checkbox_map_.find(gallery);
  if (iter != checkbox_map_.end()) {
    views::Checkbox* checkbox = iter->second;
    checkbox->SetChecked(permitted);
    checkbox->SetText(label);
    checkbox->SetTooltipText(tooltip_text);
    // Replace the details string.
    views::View* checkbox_view = checkbox->parent();
    DCHECK_EQ(2, checkbox_view->child_count());
    views::Label* secondary_text =
        static_cast<views::Label*>(checkbox_view->child_at(1));
    secondary_text->SetText(details);

    // Why is this returning false? Looks like that will mean it doesn't paint.
    return false;
  }

  views::Checkbox* checkbox = new views::Checkbox(label);
  checkbox->set_listener(this);
  checkbox->SetTooltipText(tooltip_text);
  views::Label* secondary_text = new views::Label(details);
  secondary_text->SetTooltipText(tooltip_text);
  secondary_text->SetEnabledColor(kDeemphasizedTextColor);
  secondary_text->SetTooltipText(tooltip_text);
  secondary_text->set_border(views::Border::CreateEmptyBorder(
      0,
      views::kRelatedControlSmallHorizontalSpacing,
      0,
      views::kRelatedControlSmallHorizontalSpacing));

  views::View* checkbox_view = new views::View();
  checkbox_view->set_border(views::Border::CreateEmptyBorder(
      0,
      views::kPanelHorizMargin,
      0,
      0));
  checkbox_view->SetLayoutManager(
      new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0, 0));
  checkbox_view->AddChildView(checkbox);
  checkbox_view->AddChildView(secondary_text);

  container->AddChildView(checkbox_view);

  checkbox->SetChecked(permitted);
  checkbox_map_[gallery] = checkbox;

  return true;
}

string16 MediaGalleriesDialogViews::GetWindowTitle() const {
  return controller_->GetHeader();
}

bool MediaGalleriesDialogViews::ShouldShowWindowTitle() const {
  return false;
}

void MediaGalleriesDialogViews::DeleteDelegate() {
  controller_->DialogFinished(accepted_);
}

views::Widget* MediaGalleriesDialogViews::GetWidget() {
  return contents_->GetWidget();
}

const views::Widget* MediaGalleriesDialogViews::GetWidget() const {
  return contents_->GetWidget();
}

views::View* MediaGalleriesDialogViews::GetContentsView() {
  return contents_;
}

string16 MediaGalleriesDialogViews::GetDialogButtonLabel(
    ui::DialogButton button) const {
  return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ?
      IDS_MEDIA_GALLERIES_DIALOG_CONFIRM :
      IDS_MEDIA_GALLERIES_DIALOG_CANCEL);
}

bool MediaGalleriesDialogViews::IsDialogButtonEnabled(
    ui::DialogButton button) const {
  return button != ui::DIALOG_BUTTON_OK || confirm_available_;
}

ui::ModalType MediaGalleriesDialogViews::GetModalType() const {
#if defined(USE_ASH)
  return ui::MODAL_TYPE_CHILD;
#else
  return views::WidgetDelegate::GetModalType();
#endif
}

bool MediaGalleriesDialogViews::Cancel() {
  return true;
}

bool MediaGalleriesDialogViews::Accept() {
  accepted_ = true;

  return true;
}

// TODO(wittman): Remove this override once we move to the new style frame view
// on all dialogs.
views::NonClientFrameView* MediaGalleriesDialogViews::CreateNonClientFrameView(
    views::Widget* widget) {
  return CreateConstrainedStyleNonClientFrameView(
      widget,
      controller_->web_contents()->GetBrowserContext());
}

void MediaGalleriesDialogViews::ButtonPressed(views::Button* sender,
                                              const ui::Event& event) {
  confirm_available_ = true;
  GetWidget()->client_view()->AsDialogClientView()->UpdateDialogButtons();

  if (sender == add_gallery_button_) {
    controller_->OnAddFolderClicked();
    return;
  }

  for (CheckboxMap::const_iterator iter = checkbox_map_.begin();
       iter != checkbox_map_.end(); ++iter) {
    if (sender == iter->second) {
      controller_->DidToggleGallery(iter->first, iter->second->checked());
      return;
    }
  }
}

// MediaGalleriesDialogViewsController -----------------------------------------

// static
MediaGalleriesDialog* MediaGalleriesDialog::Create(
    MediaGalleriesDialogController* controller) {
  return new MediaGalleriesDialogViews(controller);
}

}  // namespace chrome
<|endoftext|>


<commit_before>#if _WIN32
#define PLATFORM_WINDOWS
#endif

#if PLATFORM_WINDOWS
#include <WinSock2.h>
//#include "fcntl.h"
#else
#include <sys/socket.h>
#include <netinet/in.h>
// Not needed here
//#include <sys/types.h>
#include <arpa/inet.h>
//#include <netdb.h>
// close() is in here for newer gcc
#include <unistd.h>
#endif

#include <string>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <map>
#include <ctime>
#include <climits>
#include <cstring>

const unsigned int MAX_PACKET_SIZE = 255;
const unsigned int CLIENT_TIMEOUT_DELAY = 40; // seconds
const unsigned int RECEIVE_TIMEOUT = 10; // seconds, used to not hog the cpu in the main loop

// Only one packet is supported, of type 1 (player position).
// Layout:
// Byte 0: packet type (always 1)
// Byte 1..2: sequence ID
// Byte 3: car type (always 0)
// Byte 4..5, 6..7, 8..9: IEEEfloat16 x, y, z = position of car (world space)
// Byte 10..11, 12..13, 14..15: IEEEfloat16 x, y, z = orientation of car
// Byte 16..17, 18..19, 20..21: 3x IEEEfloat16 x, y, z = velocity of car
// Note that the orientation is NOT the same as the normalized velocity,
// as the velocity and heading differs when drifting, jumping etc.

struct ClientIdentifier {
    ClientIdentifier(unsigned int address, unsigned short port) :
        address(address),
        port(port) {
    }

    unsigned int address;
    unsigned short port;

    // TODO: Could make this friend operator<<
    std::string toString() const {
        std::stringstream out;

        in_addr ip;
        ip.s_addr = htonl(address);
        out << inet_ntoa(ip);// "1.2.3.4"

        out << ":";

        out << port;

        return out.str();
    }

    friend bool operator<(const ClientIdentifier & left, const ClientIdentifier & right);
};

bool operator<(const ClientIdentifier & left, const ClientIdentifier & right) {
    return left.address < right.address ||
        (left.address == right.address && left.port < right.port);
}

class ClientData {
    public:
        ClientData() :
            totalPackagesReceived(0),
            lastPositionPacketId(0),
            lastPacketArrival(0),
            playerId(NEXT_AVAILABLE_PLAYER_ID++) {
        }

        bool processPositionPacket(unsigned short packetId) {
            totalPackagesReceived++;

            unsigned short lastPacketIdShort = static_cast<unsigned short>(lastPositionPacketId);

            if(lastPacketIdShort > packetId) {
                // Possible wrap-around?
                if(lastPacketIdShort > USHRT_MAX/2 && packetId < USHRT_MAX/2) {
                    lastPositionPacketId += USHRT_MAX + 1;
                } else {
                    return false;
                }
            }

            // Keep everything except the last short, overwrite that.
            lastPositionPacketId = (lastPositionPacketId & (UINT_MAX xor USHRT_MAX)) + packetId;
            ::time(&lastPacketArrival);
            return true;
        }

        bool isClientTimedOut(const time_t& now) {
            if(lastPacketArrival == 0) {
                // No packet before
                return false;
            }
            // difftime(end, start) -> double seconds
            return difftime(now, lastPacketArrival) > CLIENT_TIMEOUT_DELAY;
        }

        int getTotalPackagesReceived() {
            return totalPackagesReceived;
        }

        unsigned short getPlayerId() {
            return playerId;
        }

    private:
        bool newClient;
        unsigned int totalPackagesReceived;
        unsigned int lastPositionPacketId;
        time_t lastPacketArrival;
        unsigned short playerId;
        static unsigned short NEXT_AVAILABLE_PLAYER_ID;
};

unsigned short ClientData::NEXT_AVAILABLE_PLAYER_ID = 0;

int startServer(unsigned short serverPort) {
#ifdef PLATFORM_WINDOWS
    WSADATA WsaData;
    if(::WSAStartup(MAKEWORD(2, 2), &WsaData) != NO_ERROR) {
        throw std::runtime_error("WSAStartup failed!");
    }
#endif

    int socket = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(socket <= 0) {
        throw std::runtime_error("Could not connect!");
    }

    // Bind to any address
    sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(serverPort);
    if(::bind(socket, (const sockaddr*) & address, sizeof(sockaddr_in)) < 0) {
        throw std::runtime_error("Could not bind to socket!");
    }

    return socket;
}

ClientIdentifier receivePacket(int socket, char* packet, int* packetSize) {
    unsigned int addressSize = sizeof(sockaddr_in); // recvfrom requires unsigned int*

    sockaddr_in address;
    int receivedBytes = ::recvfrom(socket, packet, MAX_PACKET_SIZE, 0x00000000, (sockaddr*) &address, &addressSize);

    if(receivedBytes < 0) {
        throw std::runtime_error("recvfrom() failed.");
    }

    *packetSize = receivedBytes;

    return ClientIdentifier(ntohl(address.sin_addr.s_addr), ntohs(address.sin_port));
}

void broadcastPacket(int socket, char* packet, int packetSize, ClientIdentifier sendingClientIdentifier, const std::map<ClientIdentifier, ClientData> & clients) {
    std::map<ClientIdentifier, ClientData>::const_iterator sendingClientIterator = clients.find(sendingClientIdentifier);

    // Broadcast to all clients except the sender.
    for(std::map<ClientIdentifier, ClientData>::const_iterator clientIterator = clients.begin();
            clientIterator != clients.end();
            ++clientIterator) {
        if(clientIterator != sendingClientIterator) {
            sockaddr_in destination;
            memset(&destination, 0, sizeof(destination));
            destination.sin_family = AF_INET;
            destination.sin_addr.s_addr = htonl(clientIterator->first.address);
            destination.sin_port = htons(clientIterator->first.port);

            if(::sendto(socket, packet, packetSize, 0x00000000, (struct sockaddr*) &destination, sizeof(sockaddr_in)) < 0) {
                // Note that we don't care if we couldn't send all bytes above...
                throw std::runtime_error("Socket error when broadcasting message to client " + clientIterator->first.toString());
            }
        }
    }
}

int main(int argc, char** argv) {
    int socket = 0;

    std::map<ClientIdentifier, ClientData> clients;

    try {
        // Read port from stdin
        unsigned short serverPort = 1337;
        if(argc >= 2) {
            std::istringstream parser(argv[1]);
            if(!(parser >> serverPort)) {
                throw std::runtime_error("Oops, the port specified was invalid.");
            }
        }

        std::cout << "Starting Rally server..." << std::endl;

        socket = startServer(serverPort);

        std::cout << "Rally server started!" << std::endl;

        while(true) {
            // Create a set of sockets we can block on (containing one socket), waiting for anything to happen.
            fd_set sockets;
            FD_ZERO(&sockets);
            FD_SET(socket, &sockets);

#ifdef PLATFORM_WINDOWS
            DWORD timeout = RECEIVE_TIMEOUT;
#else
            timeval timeout;
            timeout.tv_sec = RECEIVE_TIMEOUT;
            timeout.tv_usec = 0;
#endif
            ::setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));

            // Some important notes:
            // select() changes the waiting set, we need to restore it each time.
            // Also, some platforms overwrite timeout! Therefore, we need to restore it too.
            int receivedAnything = ::select(socket + 1, &sockets, NULL, NULL, &timeout);

            if(receivedAnything > 0) {
                // Receive packet
                char packet[MAX_PACKET_SIZE];
                int packetSize;
                ClientIdentifier clientIdentifier = receivePacket(socket, packet, &packetSize);

                // Process packet, possibly broadcast it
                if(packetSize == 44 && packet[0] == 1) {
                    ClientData& clientData = clients[clientIdentifier]; // Will create if not found

                    unsigned short packetId = ntohs((packet[1]<<8) + packet[2]); // char -> short big endian -> short machine endian
                    if(clientData.processPositionPacket(packetId)) {
                        // Getting here means the packet was relevant/fresh

                        // We need to splice in the sender's playerId (it's server based)
                        unsigned short playerId = htons(clientData.getPlayerId());
                        packetSize += 2;
                        memmove(packet + 6, packet + 4, 36);
                        memcpy(packet + 4, &playerId, 2);

                        broadcastPacket(socket, packet, packetSize, clientIdentifier, clients);
                    }

                    if(clientData.getTotalPackagesReceived() == 1) {
                        std::cout << "Client " << clientIdentifier.toString() << " connected." << std::endl;
                    }
                }
            } else if(receivedAnything < 0) {
                throw std::runtime_error("Error waiting on/select()ing from socket.");
            } else {
                // receivedAnything == 0 means timeout, just continue to cleanup and then retry.
            }

            // Cleanup internal map from timed out clients.
            time_t now;
            ::time(&now);
            for(std::map<ClientIdentifier, ClientData>::iterator clientIterator = clients.begin();
                    clientIterator != clients.end();
                    /*++clientIterator*/) {
                ClientData& clientData = clientIterator->second;

                if(clientData.isClientTimedOut(now)) {
                    std::cout << "Client " << clientIterator->first.toString() << " timed out, after a total of " <<
                    clientData.getTotalPackagesReceived() << " valid packages received." << std::endl;

                    std::map<ClientIdentifier, ClientData>::iterator removeIterator = clientIterator;
                    ++clientIterator;
                    clients.erase(removeIterator);
                } else {
                    ++clientIterator;
                }
            }
        }
    } catch(std::exception& error) {
        std::cerr << "Caught exception, aborting. Exception: " << error.what() << std::endl;
#ifdef PLATFORM_WINDOWS
        if(socket) ::closesocket(socket);
        ::WSACleanup();
#else
        if(socket) ::close(socket);
#endif
    }

    return 0;
}
<commit_msg>Fixed server underflow memmove error.<commit_after>#if _WIN32
#define PLATFORM_WINDOWS
#endif

#if PLATFORM_WINDOWS
#include <WinSock2.h>
//#include "fcntl.h"
#else
#include <sys/socket.h>
#include <netinet/in.h>
// Not needed here
//#include <sys/types.h>
#include <arpa/inet.h>
//#include <netdb.h>
// close() is in here for newer gcc
#include <unistd.h>
#endif

#include <string>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <map>
#include <ctime>
#include <climits>
#include <cstring>

const unsigned int MAX_PACKET_SIZE = 255;
const unsigned int CLIENT_TIMEOUT_DELAY = 40; // seconds
const unsigned int RECEIVE_TIMEOUT = 10; // seconds, used to not hog the cpu in the main loop

// Only one packet is supported, of type 1 (player position).
// Layout:
// Byte 0: packet type (always 1)
// Byte 1..2: sequence ID
// Byte 3: car type (always 0)
// Byte 4..5, 6..7, 8..9: IEEEfloat16 x, y, z = position of car (world space)
// Byte 10..11, 12..13, 14..15: IEEEfloat16 x, y, z = orientation of car
// Byte 16..17, 18..19, 20..21: 3x IEEEfloat16 x, y, z = velocity of car
// Note that the orientation is NOT the same as the normalized velocity,
// as the velocity and heading differs when drifting, jumping etc.

struct ClientIdentifier {
    ClientIdentifier(unsigned int address, unsigned short port) :
        address(address),
        port(port) {
    }

    unsigned int address;
    unsigned short port;

    // TODO: Could make this friend operator<<
    std::string toString() const {
        std::stringstream out;

        in_addr ip;
        ip.s_addr = htonl(address);
        out << inet_ntoa(ip);// "1.2.3.4"

        out << ":";

        out << port;

        return out.str();
    }

    friend bool operator<(const ClientIdentifier & left, const ClientIdentifier & right);
};

bool operator<(const ClientIdentifier & left, const ClientIdentifier & right) {
    return left.address < right.address ||
        (left.address == right.address && left.port < right.port);
}

class ClientData {
    public:
        ClientData() :
            totalPackagesReceived(0),
            lastPositionPacketId(0),
            lastPacketArrival(0),
            playerId(NEXT_AVAILABLE_PLAYER_ID++) {
        }

        bool processPositionPacket(unsigned short packetId) {
            totalPackagesReceived++;

            unsigned short lastPacketIdShort = static_cast<unsigned short>(lastPositionPacketId);

            if(lastPacketIdShort > packetId) {
                // Possible wrap-around?
                if(lastPacketIdShort > USHRT_MAX/2 && packetId < USHRT_MAX/2) {
                    lastPositionPacketId += USHRT_MAX + 1;
                } else {
                    return false;
                }
            }

            // Keep everything except the last short, overwrite that.
            lastPositionPacketId = (lastPositionPacketId & (UINT_MAX xor USHRT_MAX)) + packetId;
            ::time(&lastPacketArrival);
            return true;
        }

        bool isClientTimedOut(const time_t& now) {
            if(lastPacketArrival == 0) {
                // No packet before
                return false;
            }
            // difftime(end, start) -> double seconds
            return difftime(now, lastPacketArrival) > CLIENT_TIMEOUT_DELAY;
        }

        int getTotalPackagesReceived() {
            return totalPackagesReceived;
        }

        unsigned short getPlayerId() {
            return playerId;
        }

    private:
        bool newClient;
        unsigned int totalPackagesReceived;
        unsigned int lastPositionPacketId;
        time_t lastPacketArrival;
        unsigned short playerId;
        static unsigned short NEXT_AVAILABLE_PLAYER_ID;
};

unsigned short ClientData::NEXT_AVAILABLE_PLAYER_ID = 0;

int startServer(unsigned short serverPort) {
#ifdef PLATFORM_WINDOWS
    WSADATA WsaData;
    if(::WSAStartup(MAKEWORD(2, 2), &WsaData) != NO_ERROR) {
        throw std::runtime_error("WSAStartup failed!");
    }
#endif

    int socket = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(socket <= 0) {
        throw std::runtime_error("Could not connect!");
    }

    // Bind to any address
    sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(serverPort);
    if(::bind(socket, (const sockaddr*) & address, sizeof(sockaddr_in)) < 0) {
        throw std::runtime_error("Could not bind to socket!");
    }

    return socket;
}

ClientIdentifier receivePacket(int socket, char* packet, int* packetSize) {
    unsigned int addressSize = sizeof(sockaddr_in); // recvfrom requires unsigned int*

    sockaddr_in address;
    int receivedBytes = ::recvfrom(socket, packet, MAX_PACKET_SIZE, 0x00000000, (sockaddr*) &address, &addressSize);

    if(receivedBytes < 0) {
        throw std::runtime_error("recvfrom() failed.");
    }

    *packetSize = receivedBytes;

    return ClientIdentifier(ntohl(address.sin_addr.s_addr), ntohs(address.sin_port));
}

void broadcastPacket(int socket, char* packet, int packetSize, ClientIdentifier sendingClientIdentifier, const std::map<ClientIdentifier, ClientData> & clients) {
    std::map<ClientIdentifier, ClientData>::const_iterator sendingClientIterator = clients.find(sendingClientIdentifier);

    // Broadcast to all clients except the sender.
    for(std::map<ClientIdentifier, ClientData>::const_iterator clientIterator = clients.begin();
            clientIterator != clients.end();
            ++clientIterator) {
        if(clientIterator != sendingClientIterator) {
            sockaddr_in destination;
            memset(&destination, 0, sizeof(destination));
            destination.sin_family = AF_INET;
            destination.sin_addr.s_addr = htonl(clientIterator->first.address);
            destination.sin_port = htons(clientIterator->first.port);

            if(::sendto(socket, packet, packetSize, 0x00000000, (struct sockaddr*) &destination, sizeof(sockaddr_in)) < 0) {
                // Note that we don't care if we couldn't send all bytes above...
                throw std::runtime_error("Socket error when broadcasting message to client " + clientIterator->first.toString());
            }
        }
    }
}

int main(int argc, char** argv) {
    int socket = 0;

    std::map<ClientIdentifier, ClientData> clients;

    try {
        // Read port from stdin
        unsigned short serverPort = 1337;
        if(argc >= 2) {
            std::istringstream parser(argv[1]);
            if(!(parser >> serverPort)) {
                throw std::runtime_error("Oops, the port specified was invalid.");
            }
        }

        std::cout << "Starting Rally server..." << std::endl;

        socket = startServer(serverPort);

        std::cout << "Rally server started!" << std::endl;

        while(true) {
            // Create a set of sockets we can block on (containing one socket), waiting for anything to happen.
            fd_set sockets;
            FD_ZERO(&sockets);
            FD_SET(socket, &sockets);

#ifdef PLATFORM_WINDOWS
            DWORD timeout = RECEIVE_TIMEOUT;
#else
            timeval timeout;
            timeout.tv_sec = RECEIVE_TIMEOUT;
            timeout.tv_usec = 0;
#endif
            ::setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));

            // Some important notes:
            // select() changes the waiting set, we need to restore it each time.
            // Also, some platforms overwrite timeout! Therefore, we need to restore it too.
            int receivedAnything = ::select(socket + 1, &sockets, NULL, NULL, &timeout);

            if(receivedAnything > 0) {
                // Receive packet
                char packet[MAX_PACKET_SIZE];
                int packetSize;
                ClientIdentifier clientIdentifier = receivePacket(socket, packet, &packetSize);

                // Process packet, possibly broadcast it
                if(packetSize == 44 && packet[0] == 1) {
                    ClientData& clientData = clients[clientIdentifier]; // Will create if not found

                    unsigned short packetId = ntohs((packet[1]<<8) + packet[2]); // char -> short big endian -> short machine endian
                    if(clientData.processPositionPacket(packetId)) {
                        // Getting here means the packet was relevant/fresh

                        // We need to splice in the sender's playerId (it's server based)
                        unsigned short playerId = htons(clientData.getPlayerId());
                        packetSize += 2;
                        memmove(packet + 6, packet + 4, 40);
                        memcpy(packet + 4, &playerId, 2);

                        broadcastPacket(socket, packet, packetSize, clientIdentifier, clients);
                    }

                    if(clientData.getTotalPackagesReceived() == 1) {
                        std::cout << "Client " << clientIdentifier.toString() << " connected." << std::endl;
                    }
                }
            } else if(receivedAnything < 0) {
                throw std::runtime_error("Error waiting on/select()ing from socket.");
            } else {
                // receivedAnything == 0 means timeout, just continue to cleanup and then retry.
            }

            // Cleanup internal map from timed out clients.
            time_t now;
            ::time(&now);
            for(std::map<ClientIdentifier, ClientData>::iterator clientIterator = clients.begin();
                    clientIterator != clients.end();
                    /*++clientIterator*/) {
                ClientData& clientData = clientIterator->second;

                if(clientData.isClientTimedOut(now)) {
                    std::cout << "Client " << clientIterator->first.toString() << " timed out, after a total of " <<
                    clientData.getTotalPackagesReceived() << " valid packages received." << std::endl;

                    std::map<ClientIdentifier, ClientData>::iterator removeIterator = clientIterator;
                    ++clientIterator;
                    clients.erase(removeIterator);
                } else {
                    ++clientIterator;
                }
            }
        }
    } catch(std::exception& error) {
        std::cerr << "Caught exception, aborting. Exception: " << error.what() << std::endl;
#ifdef PLATFORM_WINDOWS
        if(socket) ::closesocket(socket);
        ::WSACleanup();
#else
        if(socket) ::close(socket);
#endif
    }

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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/file_util.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/constrained_window_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/views/event.h"
#include "net/base/net_util.h"

class InteractiveConstrainedWindowTest : public UITest {
 protected:
  InteractiveConstrainedWindowTest() {
    show_window_ = true;
  }
};

TEST_F(InteractiveConstrainedWindowTest, TestOpenAndResizeTo) {
  scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());

  scoped_ptr<WindowProxy> window(
      automation()->GetWindowForBrowser(browser.get()));
  ASSERT_TRUE(window.get());

  scoped_ptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());

  std::wstring filename(test_data_directory_);
  file_util::AppendToPath(&filename, L"constrained_files");
  file_util::AppendToPath(&filename,
                          L"constrained_window_onload_resizeto.html");
  ASSERT_TRUE(tab->NavigateToURL(net::FilePathToFileURL(filename)));

  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                    &tab_view_bounds, true));

  // Simulate a click of the actual link to force user_gesture to be
  // true; if we don't, the resulting popup will be constrained, which
  // isn't what we want to test.
  POINT link_point(tab_view_bounds.CenterPoint().ToPOINT());
  ASSERT_TRUE(window->SimulateOSClick(link_point,
                                      ChromeViews::Event::EF_LEFT_BUTTON_DOWN));

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_ptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  scoped_ptr<WindowProxy> popup_window(
      automation()->GetWindowForBrowser(popup_browser.get()));

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  ASSERT_EQ(rect.width(), 300);
  ASSERT_EQ(rect.height(), 320);

  // Send a click to the popup window to test resizeTo.
  ASSERT_TRUE(popup_window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                          &tab_view_bounds, true));
  POINT popup_link_point(tab_view_bounds.CenterPoint().ToPOINT());
  ASSERT_TRUE(popup_window->SimulateOSClick(
                  popup_link_point, ChromeViews::Event::EF_LEFT_BUTTON_DOWN));

  // No idea how to wait here other then sleeping. This timeout used to be lower,
  // then we started hitting it before it was done. :(
  Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  ASSERT_LT(rect.width(), 200);
  ASSERT_LT(rect.height(), 200);
}

<commit_msg>Create a unit test for making sure constrined popup windows close when their X is clicked. Currently this unit test fails. It should.<commit_after>// Copyright (c) 2006-2008 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/file_util.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/constrained_window_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/views/event.h"
#include "net/base/net_util.h"

const int kRightCloseButtonOffset = 55;
const int kBottomCloseButtonOffset = 25;

class InteractiveConstrainedWindowTest : public UITest {
 protected:
  InteractiveConstrainedWindowTest() {
    show_window_ = true;
  }
};

TEST_F(InteractiveConstrainedWindowTest, TestOpenAndResizeTo) {
  scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());

  scoped_ptr<WindowProxy> window(
      automation()->GetWindowForBrowser(browser.get()));
  ASSERT_TRUE(window.get());

  scoped_ptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());

  std::wstring filename(test_data_directory_);
  file_util::AppendToPath(&filename, L"constrained_files");
  file_util::AppendToPath(&filename,
                          L"constrained_window_onload_resizeto.html");
  ASSERT_TRUE(tab->NavigateToURL(net::FilePathToFileURL(filename)));

  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                    &tab_view_bounds, true));

  // Simulate a click of the actual link to force user_gesture to be
  // true; if we don't, the resulting popup will be constrained, which
  // isn't what we want to test.
  POINT link_point(tab_view_bounds.CenterPoint().ToPOINT());
  ASSERT_TRUE(window->SimulateOSClick(link_point,
                                      ChromeViews::Event::EF_LEFT_BUTTON_DOWN));

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_ptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  scoped_ptr<WindowProxy> popup_window(
      automation()->GetWindowForBrowser(popup_browser.get()));

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  ASSERT_EQ(rect.width(), 300);
  ASSERT_EQ(rect.height(), 320);

  // Send a click to the popup window to test resizeTo.
  ASSERT_TRUE(popup_window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                          &tab_view_bounds, true));
  POINT popup_link_point(tab_view_bounds.CenterPoint().ToPOINT());
  ASSERT_TRUE(popup_window->SimulateOSClick(
                  popup_link_point, ChromeViews::Event::EF_LEFT_BUTTON_DOWN));

  // No idea how to wait here other then sleeping. This timeout used to be
  // lower, then we started hitting it before it was done. :(
  Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  ASSERT_LT(rect.width(), 200);
  ASSERT_LT(rect.height(), 200);
}

TEST_F(InteractiveConstrainedWindowTest, ClickingXClosesConstrained) {
  // Clicking X on a constrained window should close the window instead of
  // unconstrain it.
  scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());

  scoped_ptr<WindowProxy> window(
      automation()->GetWindowForBrowser(browser.get()));
  ASSERT_TRUE(window.get());

  scoped_ptr<TabProxy> tab(browser->GetTab(0));
  ASSERT_TRUE(tab.get());

  std::wstring filename(test_data_directory_);
  file_util::AppendToPath(&filename, L"constrained_files");
  file_util::AppendToPath(&filename,
                          L"constrained_window.html");
  ASSERT_TRUE(tab->NavigateToURL(net::FilePathToFileURL(filename)));

  // Wait for the animation to finish.
  Sleep(1000);

  // Calculate the center of the "X"
  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                    &tab_view_bounds, true));
  gfx::Point constrained_close_button;
  constrained_close_button.set_x(
      tab_view_bounds.x() + tab_view_bounds.width() - kRightCloseButtonOffset);
  constrained_close_button.set_y(
      tab_view_bounds.y() + tab_view_bounds.height() -
      kBottomCloseButtonOffset);

  // Click that X.
  POINT click_point(constrained_close_button.ToPOINT());
  ASSERT_TRUE(window->SimulateOSClick(click_point,
                                      ChromeViews::Event::EF_LEFT_BUTTON_DOWN));

  // Check that there is only one constrained window. (There would have been
  // two pre-click).
  int constrained_window_count;
  EXPECT_TRUE(tab->WaitForChildWindowCountToChange(
                  2, &constrained_window_count, 5000));
  EXPECT_EQ(constrained_window_count, 1);

  // Check that there is still only one window (so we know we didn't activate
  // the constrained popup.)
  int browser_window_count;
  EXPECT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));
  EXPECT_EQ(browser_window_count, 1);
}
<|endoftext|>


<commit_before>/*
   Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */

#include "TelegramServerUser.hpp"
#include "DcConfiguration.hpp"
#include "LocalCluster.hpp"
#include "Session.hpp"

#include "Utils.hpp"
#include <QCoreApplication>
#include <QDebug>
#include <QStandardPaths>

using namespace Telegram::Server;

#ifdef USE_DBUS_NOTIFIER
#include <QDBusConnection>
#include <QDBusMessage>

#include "ServerApi.hpp"
#include "DefaultAuthorizationProvider.hpp"

class DBusCodeAuthProvider : public Authorization::DefaultProvider
{
protected:
    Authorization::Code generateCode(Session *session, const QString &identifier) override;
};

Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)
{
    Authorization::Code code = DefaultProvider::generateCode(session, identifier);
    QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("/org/freedesktop/Notifications"),
                                                          QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("Notify"));
    message.setArguments({
                             QCoreApplication::applicationName(),
                             QVariant::fromValue(0u),
                             QString(),
                             QStringLiteral("New auth code request"),
                             QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip),
                             QStringList(),
                             QVariantMap(),
                             3000
                         });

    // QString app_name, uint replaces_id, QString app_icon, QString summary,
    // QString body, QStringList actions, QVariantMap hints, int timeout
    QDBusConnection::sessionBus().send(message);
    return code;
}
#endif // USE_DBUS_NOTIFIER

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setOrganizationName(QStringLiteral("TelegramQt"));
    a.setApplicationName(QStringLiteral("TelegramQt Server"));
    Telegram::initialize();

    Telegram::DcConfiguration configuration;
    const QVector<Telegram::DcOption> dcOptions = {
        Telegram::DcOption(QStringLiteral("127.0.0.1"), 11441, 1),
        Telegram::DcOption(QStringLiteral("127.0.0.2"), 11442, 2),
        Telegram::DcOption(QStringLiteral("127.0.0.3"), 11443, 3),
    };
    configuration.dcOptions = dcOptions;

    const Telegram::RsaKey key = Telegram::Utils::loadRsaPrivateKeyFromFile(
                QStandardPaths::standardLocations(QStandardPaths::HomeLocation).first()
                + QStringLiteral("/TelegramServer/private_key.pem"));
    if (!key.isValid()) {
        qCritical() << "Unable to read RSA key. Please read README.md for more information.";
        return -1;
    }

    LocalCluster cluster;
    cluster.setServerPrivateRsaKey(key);
    cluster.setServerConfiguration(configuration);

#ifdef USE_DBUS_NOTIFIER
    DBusCodeAuthProvider authProvider;
    cluster.setAuthorizationProvider(&authProvider);
    qInfo() << "DBus auth code provider enabled";
#endif

    cluster.start();

    return a.exec();
}
<commit_msg>Server: use Config class to load cluster configuration<commit_after>/*
   Copyright (C) 2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */

#include "TelegramServerConfig.hpp"
#include "TelegramServerUser.hpp"
#include "DcConfiguration.hpp"
#include "LocalCluster.hpp"
#include "Session.hpp"

#include "Utils.hpp"
#include <QCoreApplication>
#include <QDebug>
#include <QStandardPaths>

using namespace Telegram::Server;

#ifdef USE_DBUS_NOTIFIER
#include <QDBusConnection>
#include <QDBusMessage>
#include "DefaultAuthorizationProvider.hpp"

class DBusCodeAuthProvider : public Authorization::DefaultProvider
{
protected:
    Authorization::Code generateCode(Session *session, const QString &identifier) override;
};

Authorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)
{
    Authorization::Code code = DefaultProvider::generateCode(session, identifier);
    QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("/org/freedesktop/Notifications"),
                                                          QStringLiteral("org.freedesktop.Notifications"),
                                                          QStringLiteral("Notify"));
    message.setArguments({
                             QCoreApplication::applicationName(),
                             QVariant::fromValue(0u),
                             QString(),
                             QStringLiteral("New auth code request"),
                             QStringLiteral("Auth code for account %1 is %2. Peer IP: %3").arg(identifier, code.code, session->ip),
                             QStringList(),
                             QVariantMap(),
                             3000
                         });

    // QString app_name, uint replaces_id, QString app_icon, QString summary,
    // QString body, QStringList actions, QVariantMap hints, int timeout
    QDBusConnection::sessionBus().send(message);
    return code;
}
#endif // USE_DBUS_NOTIFIER

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setOrganizationName(QStringLiteral("TelegramQt"));
    a.setApplicationName(QStringLiteral("TelegramQt Server"));
    Telegram::initialize();

    Config config;
    if (!config.load()) {
        // create "default" config file to ease editing
        config.save();
    }

    const Telegram::RsaKey key = Telegram::Utils::loadRsaPrivateKeyFromFile(config.privateKeyFile());
    if (!key.isValid()) {
        qCritical() << "Unable to read RSA key. Please read README.md for more information.";
        return -1;
    }

    LocalCluster cluster;
    cluster.setServerPrivateRsaKey(key);
    cluster.setServerConfiguration(config.serverConfiguration());

#ifdef USE_DBUS_NOTIFIER
    DBusCodeAuthProvider authProvider;
    cluster.setAuthorizationProvider(&authProvider);
    qInfo() << "DBus auth code provider enabled";
#endif

    cluster.start();

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