<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program 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 program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#ifndef HAVE_LIBVLC
# error This file requires libvlc
#endif

#include "Directory.h"
#include "File.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/VLCInstance.h"
#include "medialibrary/filesystem/Errors.h"
#include "logging/Logger.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"

#include "compat/ConditionVariable.h"
#include "compat/Mutex.h"

#include <sys/types.h>
#include <sys/stat.h>

#ifdef _WIN32
# include "utils/Charsets.h"
#endif

#include <vlcpp/vlc.hpp>

namespace medialibrary
{
namespace fs
{
namespace libvlc
{

Directory::Directory( std::string mrl, fs::IFileSystemFactory& fsFactory )
    : CommonDirectory( fsFactory )
    , m_mrl( utils::file::toFolderPath(
                 utils::url::encode(
                     utils::url::decode( std::move( mrl ) ) ) ) )
{
}

const std::string& Directory::mrl() const
{
    return m_mrl;
}

void Directory::read() const
{
    VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation );
    assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done );

    compat::Mutex mutex;
    compat::ConditionVariable cond;
    VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped;

    media.addOption( ":show-hiddenfiles=true" );
    media.addOption( ":ignore-filetypes=''" );
    media.addOption( ":sub-autodetect-fuzzy=2" );

    auto eventHandler = media.eventManager().onParsedChanged(
        [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) {
            std::lock_guard<compat::Mutex> lock( mutex );
            res = status;
            cond.notify_all();
        });

    bool success;
    {
        std::unique_lock<compat::Mutex> lock( mutex );
        media.parseWithOptions( VLC::Media::ParseFlags::Network |
                                VLC::Media::ParseFlags::Local, -1 );
        success = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() {
            return res != VLC::Media::ParsedStatus::Skipped;
        });
    }
    eventHandler->unregister();
    if ( success == false )
        throw errors::System{ ETIMEDOUT,
                              "Failed to browse network directory: Network is too slow" };
    if ( res == VLC::Media::ParsedStatus::Failed )
        throw errors::System{ EIO,
                              "Failed to browse network directory: Unknown error" };
    auto subItems = media.subitems();
    for ( auto i = 0; i < subItems->count(); ++i )
    {
        auto m = subItems->itemAtIndex( i );
        auto fileName = utils::file::fileName( m->mrl() );
        if ( fileName[0] == '.' )
        {
            /*
             * We need to expose the .nomedia file to the discoverer, but we don't
             * want to bother with hidden files & folders since they would be ignored
             * later on.
             * However, we consider something starting with '..' as a non-hidden
             * file or folder, see #218
             */
            if ( strcasecmp( fileName.c_str(), ".nomedia" ) != 0 &&
                 fileName.compare( 0, 2, ".." ) != 0 )
                continue;
        }
        if ( m->type() == VLC::Media::Type::Directory )
            m_dirs.push_back( std::make_shared<Directory>( m->mrl(), m_fsFactory ) );
        else
        {
            int64_t fileSize = 0;
            int64_t fileMtime = 0;
#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)
            auto fileSizeTpl = m->fileStat( VLC::Media::FileStat::Size );
            auto fileMtimeTpl = m->fileStat( VLC::Media::FileStat::Mtime );
            fileSize = std::get<1>( fileSizeTpl );
            fileMtime = std::get<1>( fileMtimeTpl );
#endif
            addFile( m->mrl(), IFile::LinkedFileType::None, {}, fileMtime, fileSize );
            for ( const auto& am : m->slaves() )
            {
                IFile::LinkedFileType linkedType;
                if ( am.type() == VLC::MediaSlave::Type::Audio )
                    linkedType = IFile::LinkedFileType::SoundTrack;
                else
                {
                    assert( am.type() == VLC::MediaSlave::Type::Subtitle );
                    linkedType = IFile::LinkedFileType::Subtitles;
                }
                addFile( am.uri(), linkedType, m->mrl(), 0, 0 );
            }
        }
    }
}

void Directory::addFile( std::string mrl, fs::IFile::LinkedFileType linkedType,
                         std::string linkedWith, time_t lastModificationDate,
                         int64_t fileSize ) const
{
    if ( m_fsFactory.isNetworkFileSystem() == false && lastModificationDate == 0 &&
         fileSize == 0 )
    {
        auto path = utils::url::toLocalPath( mrl );

#ifdef _WIN32
        /* We can't use _wstat here, see #323 */
        WIN32_FILE_ATTRIBUTE_DATA attributes;
        if ( GetFileAttributesExW( charset::ToWide( path.c_str() ).get(),
                                   GetFileExInfoStandard, &attributes ) == 0 )
        {
            LOG_ERROR( "Failed to get ", path, " attributes" );
            throw errors::System{ GetLastError(), "Failed to get stats" };
        }
        LARGE_INTEGER li;
        li.u.LowPart = attributes.ftLastWriteTime.dwLowDateTime;
        li.u.HighPart = attributes.ftLastWriteTime.dwHighDateTime;
        lastModificationDate = li.QuadPart / 10000000ULL - 11644473600ULL;
        if ( ( attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
            fileSize = 0;
        else
        {
            li.u.LowPart = attributes.nFileSizeLow;
            li.u.HighPart = attributes.nFileSizeHigh;
            fileSize = li.QuadPart;
        }
#else
        struct stat s;
        if ( lstat( path.c_str(), &s ) != 0 )
        {
            if ( errno == EACCES )
                return;
            // some Android devices will list folder content, but will yield
            // ENOENT when accessing those.
            // See https://trac.videolan.org/vlc/ticket/19909
            if ( errno == ENOENT )
            {
                LOG_WARN( "Ignoring unexpected ENOENT while listing folder content." );
                return;
            }
            LOG_ERROR( "Failed to get file ", mrl, " info" );
            throw errors::System{ errno, "Failed to get file info" };
        }
        lastModificationDate = s.st_mtime;
        fileSize = s.st_size;
#endif
    }
    if ( linkedType == IFile::LinkedFileType::None )
        m_files.push_back( std::make_shared<File>( std::move( mrl ),
                           m_fsFactory, lastModificationDate, fileSize ) );
    else
        m_files.push_back( std::make_shared<File>( std::move( mrl ),
                           m_fsFactory, lastModificationDate, fileSize,
                           linkedType, std::move( linkedWith ) ) );
}

}
}
}
<commit_msg>fs: libvlc: Fix API usage<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program 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 program 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 program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#ifndef HAVE_LIBVLC
# error This file requires libvlc
#endif

#include "Directory.h"
#include "File.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "utils/VLCInstance.h"
#include "medialibrary/filesystem/Errors.h"
#include "logging/Logger.h"
#include "medialibrary/filesystem/IFileSystemFactory.h"

#include "compat/ConditionVariable.h"
#include "compat/Mutex.h"

#include <sys/types.h>
#include <sys/stat.h>

#ifdef _WIN32
# include "utils/Charsets.h"
#endif

#include <vlcpp/vlc.hpp>

namespace medialibrary
{
namespace fs
{
namespace libvlc
{

Directory::Directory( std::string mrl, fs::IFileSystemFactory& fsFactory )
    : CommonDirectory( fsFactory )
    , m_mrl( utils::file::toFolderPath(
                 utils::url::encode(
                     utils::url::decode( std::move( mrl ) ) ) ) )
{
}

const std::string& Directory::mrl() const
{
    return m_mrl;
}

void Directory::read() const
{
#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)
    VLC::Media media( m_mrl, VLC::Media::FromLocation );
    assert( media.parsedStatus( VLCInstance::get() ) != VLC::Media::ParsedStatus::Done );
#else
    VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation );
    assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done );
#endif

    compat::Mutex mutex;
    compat::ConditionVariable cond;
    VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped;

    media.addOption( ":show-hiddenfiles=true" );
    media.addOption( ":ignore-filetypes=''" );
    media.addOption( ":sub-autodetect-fuzzy=2" );

    auto eventHandler = media.eventManager().onParsedChanged(
        [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) {
            std::lock_guard<compat::Mutex> lock( mutex );
            res = status;
            cond.notify_all();
        });

    bool success;
    {
        std::unique_lock<compat::Mutex> lock( mutex );
#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)
        media.parseRequest( VLCInstance::get(), VLC::Media::ParseFlags::Network |
                            VLC::Media::ParseFlags::Local, -1 );
#else
        media.parseWithOptions( VLC::Media::ParseFlags::Network |
                                VLC::Media::ParseFlags::Local, -1 );
#endif
        success = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() {
            return res != VLC::Media::ParsedStatus::Skipped;
        });
    }
    eventHandler->unregister();
    if ( success == false )
        throw errors::System{ ETIMEDOUT,
                              "Failed to browse network directory: Network is too slow" };
    if ( res == VLC::Media::ParsedStatus::Failed )
        throw errors::System{ EIO,
                              "Failed to browse network directory: Unknown error" };
    auto subItems = media.subitems();
    for ( auto i = 0; i < subItems->count(); ++i )
    {
        auto m = subItems->itemAtIndex( i );
        auto fileName = utils::file::fileName( m->mrl() );
        if ( fileName[0] == '.' )
        {
            /*
             * We need to expose the .nomedia file to the discoverer, but we don't
             * want to bother with hidden files & folders since they would be ignored
             * later on.
             * However, we consider something starting with '..' as a non-hidden
             * file or folder, see #218
             */
            if ( strcasecmp( fileName.c_str(), ".nomedia" ) != 0 &&
                 fileName.compare( 0, 2, ".." ) != 0 )
                continue;
        }
        if ( m->type() == VLC::Media::Type::Directory )
            m_dirs.push_back( std::make_shared<Directory>( m->mrl(), m_fsFactory ) );
        else
        {
            int64_t fileSize = 0;
            int64_t fileMtime = 0;
#if LIBVLC_VERSION_INT >= LIBVLC_VERSION(4, 0, 0, 0)
            auto fileSizeTpl = m->fileStat( VLC::Media::FileStat::Size );
            auto fileMtimeTpl = m->fileStat( VLC::Media::FileStat::Mtime );
            fileSize = std::get<1>( fileSizeTpl );
            fileMtime = std::get<1>( fileMtimeTpl );
#endif
            addFile( m->mrl(), IFile::LinkedFileType::None, {}, fileMtime, fileSize );
            for ( const auto& am : m->slaves() )
            {
                IFile::LinkedFileType linkedType;
                if ( am.type() == VLC::MediaSlave::Type::Audio )
                    linkedType = IFile::LinkedFileType::SoundTrack;
                else
                {
                    assert( am.type() == VLC::MediaSlave::Type::Subtitle );
                    linkedType = IFile::LinkedFileType::Subtitles;
                }
                addFile( am.uri(), linkedType, m->mrl(), 0, 0 );
            }
        }
    }
}

void Directory::addFile( std::string mrl, fs::IFile::LinkedFileType linkedType,
                         std::string linkedWith, time_t lastModificationDate,
                         int64_t fileSize ) const
{
    if ( m_fsFactory.isNetworkFileSystem() == false && lastModificationDate == 0 &&
         fileSize == 0 )
    {
        auto path = utils::url::toLocalPath( mrl );

#ifdef _WIN32
        /* We can't use _wstat here, see #323 */
        WIN32_FILE_ATTRIBUTE_DATA attributes;
        if ( GetFileAttributesExW( charset::ToWide( path.c_str() ).get(),
                                   GetFileExInfoStandard, &attributes ) == 0 )
        {
            LOG_ERROR( "Failed to get ", path, " attributes" );
            throw errors::System{ GetLastError(), "Failed to get stats" };
        }
        LARGE_INTEGER li;
        li.u.LowPart = attributes.ftLastWriteTime.dwLowDateTime;
        li.u.HighPart = attributes.ftLastWriteTime.dwHighDateTime;
        lastModificationDate = li.QuadPart / 10000000ULL - 11644473600ULL;
        if ( ( attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )
            fileSize = 0;
        else
        {
            li.u.LowPart = attributes.nFileSizeLow;
            li.u.HighPart = attributes.nFileSizeHigh;
            fileSize = li.QuadPart;
        }
#else
        struct stat s;
        if ( lstat( path.c_str(), &s ) != 0 )
        {
            if ( errno == EACCES )
                return;
            // some Android devices will list folder content, but will yield
            // ENOENT when accessing those.
            // See https://trac.videolan.org/vlc/ticket/19909
            if ( errno == ENOENT )
            {
                LOG_WARN( "Ignoring unexpected ENOENT while listing folder content." );
                return;
            }
            LOG_ERROR( "Failed to get file ", mrl, " info" );
            throw errors::System{ errno, "Failed to get file info" };
        }
        lastModificationDate = s.st_mtime;
        fileSize = s.st_size;
#endif
    }
    if ( linkedType == IFile::LinkedFileType::None )
        m_files.push_back( std::make_shared<File>( std::move( mrl ),
                           m_fsFactory, lastModificationDate, fileSize ) );
    else
        m_files.push_back( std::make_shared<File>( std::move( mrl ),
                           m_fsFactory, lastModificationDate, fileSize,
                           linkedType, std::move( linkedWith ) ) );
}

}
}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Shanghai Jiao Tong University.
 *     All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS
 *  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.  See the License for the specific language
 *  governing permissions and limitations under the License.
 *
 * For more about this software visit:
 *
 *      http://ipads.se.sjtu.edu.cn/projects/wukong
 *
 */

#pragma once

#include <hwloc.h>
#include <boost/algorithm/string/predicate.hpp>

using namespace std;

/*
 * The processor architecture of machines in our cluster (Cube0-5)
 *
 * $numactl --hardware
 * available: 2 nodes (0-1)
 * node 0 cpus: 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
 * node 0 size: 64265 MB
 * node 0 free: 19744 MB
 * node 1 cpus: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
 * node 1 size: 64503 MB
 * node 1 free: 53586 MB
 * node distances:
 * node   0   1
 *   0:  10  21
 *   1:  21  10
 *
 *
 * $cat config
 * global_num_proxies 4
 * global_num_engines 16
 *
 * $cat core.bind
 * 0  1  4  5  6  7  8  9 10 11
 * 2  3 12 13 14 15 16 17 18 19
 *
 */

vector<vector<int>> cpu_topo;
vector<int> default_bindings;
int num_cores = 0;

void dump_node_topo(vector<vector<int>> topo)
{
	cout << "TOPO: " << topo.size() << "nodes" << endl;
	for (int nid = 0; nid < topo.size(); nid++) {
		cout << "  node " << nid << " cores: ";
		for (int cid = 0; cid < topo[nid].size(); cid++)
			cout << topo[nid][cid] << " ";
		cout << endl;
	}
}

void load_node_topo(void)
{
	hwloc_topology_t topology;

	hwloc_topology_init(&topology);
	hwloc_topology_load(topology);

	int nnodes = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_NUMANODE);
	cpu_topo.resize(nnodes);
	for (int i = 0; i < nnodes; i++) {
		hwloc_obj_t obj = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NUMANODE, i);
		hwloc_cpuset_t cpuset = hwloc_bitmap_dup(obj->cpuset);

		unsigned int core = 0;
		hwloc_bitmap_foreach_begin(core, cpuset);
		cpu_topo[i].push_back(core);
		default_bindings.push_back(core);
		hwloc_bitmap_foreach_end();

		hwloc_bitmap_free(cpuset);
	}
	num_cores = default_bindings.size();

	dump_node_topo(cpu_topo);
}

bool enable_binding = false;
map<int, int> core_bindings;

bool load_core_binding(string fname)
{
	int nbs = 0;

	//load file of core binding
	ifstream file(fname.c_str());
	if (!file) {
		cout << "ERROR: " << fname << " does not exist." << endl;
		return false;
	}

	int nnodes = cpu_topo.size(), i = 0;
	string line;
	while (std::getline(file, line)) {
		if (boost::starts_with(line, "#"))
			continue; // skip comments and blank lines

		istringstream iss(line); // one node per line
		int ncores = cpu_topo[i].size(), j = 0, tid;
		while (iss >> tid) {
			//cout << tid << " " << cpu_topo[i % nnodes][j % ncores] << endl;
			core_bindings[tid] = cpu_topo[i % nnodes][j++ % ncores];
			nbs++;
		}

		i++; // next node
	}

	if (nbs < global_num_threads)
		cout << "WARNING: #threads (in \'config\') exceeds #bindings (in \'bind\')!" << endl;

	return true;
}

void bind_to_core(size_t core)
{
	cpu_set_t mask;
	CPU_ZERO(&mask);
	CPU_SET(core, &mask);
	if (sched_setaffinity(0, sizeof(mask), &mask) != 0)
		cout << "Failed to set affinity (core: " << core << ")" << endl;
}

<commit_msg>core binding bug fixed<commit_after>/*
 * Copyright (c) 2016 Shanghai Jiao Tong University.
 *     All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an "AS
 *  IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 *  express or implied.  See the License for the specific language
 *  governing permissions and limitations under the License.
 *
 * For more about this software visit:
 *
 *      http://ipads.se.sjtu.edu.cn/projects/wukong
 *
 */

#pragma once

#include <hwloc.h>
#include <boost/algorithm/string/predicate.hpp>

using namespace std;

/*
 * The processor architecture of machines in our cluster (Cube0-5)
 *
 * $numactl --hardware
 * available: 2 nodes (0-1)
 * node 0 cpus: 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
 * node 0 size: 64265 MB
 * node 0 free: 19744 MB
 * node 1 cpus: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
 * node 1 size: 64503 MB
 * node 1 free: 53586 MB
 * node distances:
 * node   0   1
 *   0:  10  21
 *   1:  21  10
 *
 *
 * $cat config
 * global_num_proxies 4
 * global_num_engines 16
 *
 * $cat core.bind
 * 0  1  4  5  6  7  8  9 10 11
 * 2  3 12 13 14 15 16 17 18 19
 *
 */

vector<vector<int>> cpu_topo;
vector<int> default_bindings;
int num_cores = 0;

void dump_node_topo(vector<vector<int>> topo)
{
	cout << "TOPO: " << topo.size() << "nodes" << endl;
	for (int nid = 0; nid < topo.size(); nid++) {
		cout << "  node " << nid << " cores: ";
		for (int cid = 0; cid < topo[nid].size(); cid++)
			cout << topo[nid][cid] << " ";
		cout << endl;
	}
}

void load_node_topo(void)
{
	hwloc_topology_t topology;

	hwloc_topology_init(&topology);
	hwloc_topology_load(topology);

	//currently, nnodes may return 0 while the NUMANODEs in cpulist is 1(hwloc think there is actually no numa-node)
	//but it can detect the number of processing units(PU) correctly
	//when multi-thread processing is on, the number of PU will be twice as number of cores
	int nnodes = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_NUMANODE);
	if(nnodes != 0){
		cpu_topo.resize(nnodes);
		for (int i = 0; i < nnodes; i++) {
			hwloc_obj_t obj = hwloc_get_obj_by_type(topology, HWLOC_OBJ_NUMANODE, i);
			hwloc_cpuset_t cpuset = hwloc_bitmap_dup(obj->cpuset);

			unsigned int core = 0;
			hwloc_bitmap_foreach_begin(core, cpuset);
			cpu_topo[i].push_back(core);
			default_bindings.push_back(core);
			hwloc_bitmap_foreach_end();

			hwloc_bitmap_free(cpuset);
		}
	}
	else{
		cpu_topo.resize(1);
		int nPUs = hwloc_get_nbobjs_by_type(topology, HWLOC_OBJ_PU);
		for (int i = 0; i < nPUs; i++) {
			hwloc_obj_t obj = hwloc_get_obj_by_type(topology, HWLOC_OBJ_PU, i);
			hwloc_cpuset_t cpuset = hwloc_bitmap_dup(obj->cpuset);

			unsigned int core = 0;
			hwloc_bitmap_foreach_begin(core, cpuset);
			cpu_topo[0].push_back(core);
			default_bindings.push_back(core);
			hwloc_bitmap_foreach_end();

			hwloc_bitmap_free(cpuset);
		}
	}
	num_cores = default_bindings.size();

	dump_node_topo(cpu_topo);
}

bool enable_binding = false;
map<int, int> core_bindings;

bool load_core_binding(string fname)
{
	int nbs = 0;

	//load file of core binding
	ifstream file(fname.c_str());
	if (!file) {
		cout << "ERROR: " << fname << " does not exist." << endl;
		return false;
	}

	int nnodes = cpu_topo.size(), i = 0;
	string line;
	while (std::getline(file, line)) {
		if (boost::starts_with(line, "#"))
			continue; // skip comments and blank lines

		istringstream iss(line); // one node per line
		int ncores = cpu_topo[i].size(), j = 0, tid;
		while (iss >> tid) {
			//cout << tid << " " << cpu_topo[i % nnodes][j % ncores] << endl;
			core_bindings[tid] = cpu_topo[i % nnodes][j++ % ncores];
			nbs++;
		}

		i++; // next node
	}

	if(i < nnodes){
		cout << "WARNING: #bindings (in \'core.bind\') did not use all of the NUMANODEs!" << endl;
	}
	if(i > nnodes){
		cout << "WARNING: #bindings (in \'core.bind\') exceeds number of the NUMANODEs!" << endl;
	}
	if (nbs < global_num_threads)
		cout << "WARNING: #threads (in \'config\') exceeds #bindings (in \'bind\')!" << endl;

	return true;
}

void bind_to_core(size_t core)
{
	cpu_set_t mask;
	CPU_ZERO(&mask);
	CPU_SET(core, &mask);
	if (sched_setaffinity(0, sizeof(mask), &mask) != 0)
		cout << "Failed to set affinity (core: " << core << ")" << endl;
}

<|endoftext|>


<commit_before>// Copyright 2014 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 "components/enhanced_bookmarks/image_store.h"

#include "base/files/scoped_temp_dir.h"
#include "base/strings/string_number_conversions.h"
#include "components/enhanced_bookmarks/image_store_util.h"
#include "components/enhanced_bookmarks/persistent_image_store.h"
#include "components/enhanced_bookmarks/test_image_store.h"
#include "testing/platform_test.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "url/gurl.h"

namespace {

gfx::Image CreateImage(int width, int height, int a, int r, int g, int b) {
  SkBitmap bitmap;
  bitmap.allocN32Pixels(width, height);
  bitmap.eraseARGB(a, r, g, b);
  gfx::Image image(gfx::Image::CreateFrom1xBitmap(bitmap));

#if defined(OS_IOS)
  // Make sure the image has a kImageRepCocoaTouch.
  image.ToUIImage();
#endif  // defined(OS_IOS)

  return image;
}

gfx::Image GenerateWhiteImage() {
  return CreateImage(42, 24, 255, 255, 255, 255);
}

gfx::Image GenerateBlackImage(int width, int height) {
  return CreateImage(width, height, 255, 0, 0, 0);
}

gfx::Image GenerateBlackImage() {
  return GenerateBlackImage(42, 24);
}

// Returns true if the two images are identical.
bool CompareImages(const gfx::Image& image_1, const gfx::Image& image_2) {
  if (image_1.IsEmpty() && image_2.IsEmpty())
    return true;

  if (image_1.IsEmpty() || image_2.IsEmpty())
    return false;

  scoped_refptr<base::RefCountedMemory> image_1_bytes =
      enhanced_bookmarks::BytesForImage(image_1);
  scoped_refptr<base::RefCountedMemory> image_2_bytes =
      enhanced_bookmarks::BytesForImage(image_2);

  if (image_1_bytes->size() != image_2_bytes->size())
    return false;

  return !memcmp(image_1_bytes->front(),
                 image_2_bytes->front(),
                 image_1_bytes->size());
}

// Factory functions for creating instances of the implementations.
template <class T>
ImageStore* CreateStore(base::ScopedTempDir& folder);

template <>
ImageStore* CreateStore<TestImageStore>(
    base::ScopedTempDir& folder) {
  return new TestImageStore();
}

template <>
ImageStore* CreateStore<PersistentImageStore>(
    base::ScopedTempDir& folder) {
  return new PersistentImageStore(folder.path());
}

// Methods to check if persistence is on or not.
template <class T> bool ShouldPersist();
template <> bool ShouldPersist<TestImageStore>() { return false; }
template <> bool ShouldPersist<PersistentImageStore>() { return true; }

// Test fixture class template for the abstract API.
template <class T>
class ImageStoreUnitTest : public PlatformTest {
 protected:
  ImageStoreUnitTest() {}
  virtual ~ImageStoreUnitTest() {}

  virtual void SetUp() override {
    bool success = tempDir_.CreateUniqueTempDir();
    ASSERT_TRUE(success);
    store_.reset(CreateStore<T>(tempDir_));
  }

  virtual void TearDown() override {
    if (store_ && use_persistent_store())
      store_->ClearAll();
  }

  bool use_persistent_store() const { return ShouldPersist<T>(); }
  void ResetStore() { store_.reset(CreateStore<T>(tempDir_)); }

  // The directory the database is saved into.
  base::ScopedTempDir tempDir_;
  // The object the fixture is testing, via its base interface.
  scoped_ptr<ImageStore> store_;

 private:
  DISALLOW_COPY_AND_ASSIGN(ImageStoreUnitTest);
};

// The list of implementations of the abstract API that are going to be tested.
typedef testing::Types<TestImageStore,
                       PersistentImageStore> Implementations;

TYPED_TEST_CASE(ImageStoreUnitTest, Implementations);

// All those tests are run on all the implementations.
TYPED_TEST(ImageStoreUnitTest, StartsEmpty) {
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(0u, all_urls.size());
}

TYPED_TEST(ImageStoreUnitTest, StoreOne) {
  this->store_->Insert(GURL("foo://bar"), GURL("a.jpg"), GenerateBlackImage());

  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(1u, all_urls.size());
  EXPECT_EQ(GURL("foo://bar"), *all_urls.begin());
  EXPECT_TRUE(this->store_->HasKey(GURL("foo://bar")));
}

TYPED_TEST(ImageStoreUnitTest, Retrieve) {
  gfx::Image src_image = GenerateBlackImage(42, 24);
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");
  this->store_->Insert(url, image_url, src_image);

  std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);
  gfx::Size size = this->store_->GetSize(url);

  EXPECT_EQ(size.width(), 42);
  EXPECT_EQ(size.height(), 24);
  EXPECT_EQ(image_url, image_info.second);
  EXPECT_TRUE(CompareImages(src_image, image_info.first));
}

TYPED_TEST(ImageStoreUnitTest, Erase) {
  gfx::Image src_image = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");
  this->store_->Insert(url, image_url, src_image);
  this->store_->Erase(url);

  EXPECT_FALSE(this->store_->HasKey(url));
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(0u, all_urls.size());
}

TYPED_TEST(ImageStoreUnitTest, ClearAll) {
  const GURL url_foo("http://foo");
  this->store_->Insert(url_foo, GURL("foo.jpg"), GenerateBlackImage());
  const GURL url_bar("http://bar");
  this->store_->Insert(url_foo, GURL("bar.jpg"), GenerateWhiteImage());

  this->store_->ClearAll();

  EXPECT_FALSE(this->store_->HasKey(url_foo));
  EXPECT_FALSE(this->store_->HasKey(url_bar));
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(0u, all_urls.size());
}

TYPED_TEST(ImageStoreUnitTest, Update) {
  gfx::Image src_image1 = GenerateWhiteImage();
  gfx::Image src_image2 = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url1("1.jpg");
  this->store_->Insert(url, image_url1, src_image1);

  const GURL image_url2("2.jpg");
  this->store_->Insert(url, image_url2, src_image2);

  std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);

  EXPECT_TRUE(this->store_->HasKey(url));
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(1u, all_urls.size());
  EXPECT_EQ(image_url2, image_info.second);
  EXPECT_TRUE(CompareImages(src_image2, image_info.first));
}

TYPED_TEST(ImageStoreUnitTest, Persistence) {
  gfx::Image src_image = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");
  this->store_->Insert(url, image_url, src_image);

  this->ResetStore();
  if (this->use_persistent_store()) {
    std::set<GURL> all_urls;
    this->store_->GetAllPageUrls(&all_urls);
    EXPECT_EQ(1u, all_urls.size());
    EXPECT_EQ(GURL("foo://bar"), *all_urls.begin());
    EXPECT_TRUE(this->store_->HasKey(GURL("foo://bar")));
    std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);

    EXPECT_EQ(image_url, image_info.second);
    EXPECT_TRUE(CompareImages(src_image, image_info.first));
  } else {
    std::set<GURL> all_urls;
    this->store_->GetAllPageUrls(&all_urls);
    EXPECT_EQ(0u, all_urls.size());
    EXPECT_FALSE(this->store_->HasKey(GURL("foo://bar")));
  }
}

TYPED_TEST(ImageStoreUnitTest, GetSize) {
  gfx::Image src_image = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");

  int64 size = 0;
  if (this->use_persistent_store()) {
    // File shouldn't exist before we actually start using it since we do lazy
    // initialization.
    EXPECT_EQ(this->store_->GetStoreSizeInBytes(), -1);
  } else {
    EXPECT_LE(this->store_->GetStoreSizeInBytes(), 1024);
  }
  for (int i = 0; i < 100; ++i) {
    this->store_->Insert(
        GURL(url.spec() + '/' + base::IntToString(i)), image_url, src_image);
    EXPECT_GE(this->store_->GetStoreSizeInBytes(), size);
    size = this->store_->GetStoreSizeInBytes();
  }

  if (this->use_persistent_store()) {
    EXPECT_GE(this->store_->GetStoreSizeInBytes(),  90 * 1024); //  90kb
    EXPECT_LE(this->store_->GetStoreSizeInBytes(), 200 * 1024); // 200kb
  } else {
    EXPECT_GE(this->store_->GetStoreSizeInBytes(), 400 * 1024); // 400kb
    EXPECT_LE(this->store_->GetStoreSizeInBytes(), 500 * 1024); // 500kb
  }
}

}  // namespace
<commit_msg>Fix ImageStoreUnitTest.GetSize on iOS<commit_after>// Copyright 2014 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 "components/enhanced_bookmarks/image_store.h"

#include "base/files/scoped_temp_dir.h"
#include "base/strings/string_number_conversions.h"
#include "components/enhanced_bookmarks/image_store_util.h"
#include "components/enhanced_bookmarks/persistent_image_store.h"
#include "components/enhanced_bookmarks/test_image_store.h"
#include "testing/platform_test.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "url/gurl.h"

namespace {

gfx::Image CreateImage(int width, int height, int a, int r, int g, int b) {
  SkBitmap bitmap;
  bitmap.allocN32Pixels(width, height);
  bitmap.eraseARGB(a, r, g, b);
  gfx::Image image(gfx::Image::CreateFrom1xBitmap(bitmap));

#if defined(OS_IOS)
  // Make sure the image has a kImageRepCocoaTouch.
  image.ToUIImage();
#endif  // defined(OS_IOS)

  return image;
}

gfx::Image GenerateWhiteImage() {
  return CreateImage(42, 24, 255, 255, 255, 255);
}

gfx::Image GenerateBlackImage(int width, int height) {
  return CreateImage(width, height, 255, 0, 0, 0);
}

gfx::Image GenerateBlackImage() {
  return GenerateBlackImage(42, 24);
}

// Returns true if the two images are identical.
bool CompareImages(const gfx::Image& image_1, const gfx::Image& image_2) {
  if (image_1.IsEmpty() && image_2.IsEmpty())
    return true;

  if (image_1.IsEmpty() || image_2.IsEmpty())
    return false;

  scoped_refptr<base::RefCountedMemory> image_1_bytes =
      enhanced_bookmarks::BytesForImage(image_1);
  scoped_refptr<base::RefCountedMemory> image_2_bytes =
      enhanced_bookmarks::BytesForImage(image_2);

  if (image_1_bytes->size() != image_2_bytes->size())
    return false;

  return !memcmp(image_1_bytes->front(),
                 image_2_bytes->front(),
                 image_1_bytes->size());
}

// Factory functions for creating instances of the implementations.
template <class T>
ImageStore* CreateStore(base::ScopedTempDir& folder);

template <>
ImageStore* CreateStore<TestImageStore>(
    base::ScopedTempDir& folder) {
  return new TestImageStore();
}

template <>
ImageStore* CreateStore<PersistentImageStore>(
    base::ScopedTempDir& folder) {
  return new PersistentImageStore(folder.path());
}

// Methods to check if persistence is on or not.
template <class T> bool ShouldPersist();
template <> bool ShouldPersist<TestImageStore>() { return false; }
template <> bool ShouldPersist<PersistentImageStore>() { return true; }

// Test fixture class template for the abstract API.
template <class T>
class ImageStoreUnitTest : public PlatformTest {
 protected:
  ImageStoreUnitTest() {}
  virtual ~ImageStoreUnitTest() {}

  virtual void SetUp() override {
    bool success = tempDir_.CreateUniqueTempDir();
    ASSERT_TRUE(success);
    store_.reset(CreateStore<T>(tempDir_));
  }

  virtual void TearDown() override {
    if (store_ && use_persistent_store())
      store_->ClearAll();
  }

  bool use_persistent_store() const { return ShouldPersist<T>(); }
  void ResetStore() { store_.reset(CreateStore<T>(tempDir_)); }

  // The directory the database is saved into.
  base::ScopedTempDir tempDir_;
  // The object the fixture is testing, via its base interface.
  scoped_ptr<ImageStore> store_;

 private:
  DISALLOW_COPY_AND_ASSIGN(ImageStoreUnitTest);
};

// The list of implementations of the abstract API that are going to be tested.
typedef testing::Types<TestImageStore,
                       PersistentImageStore> Implementations;

TYPED_TEST_CASE(ImageStoreUnitTest, Implementations);

// All those tests are run on all the implementations.
TYPED_TEST(ImageStoreUnitTest, StartsEmpty) {
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(0u, all_urls.size());
}

TYPED_TEST(ImageStoreUnitTest, StoreOne) {
  this->store_->Insert(GURL("foo://bar"), GURL("a.jpg"), GenerateBlackImage());

  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(1u, all_urls.size());
  EXPECT_EQ(GURL("foo://bar"), *all_urls.begin());
  EXPECT_TRUE(this->store_->HasKey(GURL("foo://bar")));
}

TYPED_TEST(ImageStoreUnitTest, Retrieve) {
  gfx::Image src_image = GenerateBlackImage(42, 24);
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");
  this->store_->Insert(url, image_url, src_image);

  std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);
  gfx::Size size = this->store_->GetSize(url);

  EXPECT_EQ(size.width(), 42);
  EXPECT_EQ(size.height(), 24);
  EXPECT_EQ(image_url, image_info.second);
  EXPECT_TRUE(CompareImages(src_image, image_info.first));
}

TYPED_TEST(ImageStoreUnitTest, Erase) {
  gfx::Image src_image = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");
  this->store_->Insert(url, image_url, src_image);
  this->store_->Erase(url);

  EXPECT_FALSE(this->store_->HasKey(url));
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(0u, all_urls.size());
}

TYPED_TEST(ImageStoreUnitTest, ClearAll) {
  const GURL url_foo("http://foo");
  this->store_->Insert(url_foo, GURL("foo.jpg"), GenerateBlackImage());
  const GURL url_bar("http://bar");
  this->store_->Insert(url_foo, GURL("bar.jpg"), GenerateWhiteImage());

  this->store_->ClearAll();

  EXPECT_FALSE(this->store_->HasKey(url_foo));
  EXPECT_FALSE(this->store_->HasKey(url_bar));
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(0u, all_urls.size());
}

TYPED_TEST(ImageStoreUnitTest, Update) {
  gfx::Image src_image1 = GenerateWhiteImage();
  gfx::Image src_image2 = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url1("1.jpg");
  this->store_->Insert(url, image_url1, src_image1);

  const GURL image_url2("2.jpg");
  this->store_->Insert(url, image_url2, src_image2);

  std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);

  EXPECT_TRUE(this->store_->HasKey(url));
  std::set<GURL> all_urls;
  this->store_->GetAllPageUrls(&all_urls);
  EXPECT_EQ(1u, all_urls.size());
  EXPECT_EQ(image_url2, image_info.second);
  EXPECT_TRUE(CompareImages(src_image2, image_info.first));
}

TYPED_TEST(ImageStoreUnitTest, Persistence) {
  gfx::Image src_image = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");
  this->store_->Insert(url, image_url, src_image);

  this->ResetStore();
  if (this->use_persistent_store()) {
    std::set<GURL> all_urls;
    this->store_->GetAllPageUrls(&all_urls);
    EXPECT_EQ(1u, all_urls.size());
    EXPECT_EQ(GURL("foo://bar"), *all_urls.begin());
    EXPECT_TRUE(this->store_->HasKey(GURL("foo://bar")));
    std::pair<gfx::Image, GURL> image_info = this->store_->Get(url);

    EXPECT_EQ(image_url, image_info.second);
    EXPECT_TRUE(CompareImages(src_image, image_info.first));
  } else {
    std::set<GURL> all_urls;
    this->store_->GetAllPageUrls(&all_urls);
    EXPECT_EQ(0u, all_urls.size());
    EXPECT_FALSE(this->store_->HasKey(GURL("foo://bar")));
  }
}

TYPED_TEST(ImageStoreUnitTest, GetSize) {
  gfx::Image src_image = GenerateBlackImage();
  const GURL url("foo://bar");
  const GURL image_url("a.jpg");

  int64 size = 0;
  if (this->use_persistent_store()) {
    // File shouldn't exist before we actually start using it since we do lazy
    // initialization.
    EXPECT_EQ(this->store_->GetStoreSizeInBytes(), -1);
  } else {
    EXPECT_LE(this->store_->GetStoreSizeInBytes(), 1024);
  }
  for (int i = 0; i < 100; ++i) {
    this->store_->Insert(
        GURL(url.spec() + '/' + base::IntToString(i)), image_url, src_image);
    EXPECT_GE(this->store_->GetStoreSizeInBytes(), size);
    size = this->store_->GetStoreSizeInBytes();
  }

  if (this->use_persistent_store()) {
    EXPECT_GE(this->store_->GetStoreSizeInBytes(),  80 * 1024); //  80kb
    EXPECT_LE(this->store_->GetStoreSizeInBytes(), 200 * 1024); // 200kb
  } else {
    EXPECT_GE(this->store_->GetStoreSizeInBytes(), 400 * 1024); // 400kb
    EXPECT_LE(this->store_->GetStoreSizeInBytes(), 500 * 1024); // 500kb
  }
}

}  // namespace
<|endoftext|>


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

#include <string>

#include "app/combobox_model.h"
#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/mock_login_library.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/login/mock_screen_observer.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/network_selection_view.h"
#include "chrome/browser/chromeos/login/view_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/browser/chromeos/login/wizard_screen.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/button/text_button.h"
#include "views/controls/combobox/combobox.h"

namespace chromeos {
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;
using ::testing::A;
using views::Button;

class DummyButtonListener : public views::ButtonListener {
 public:
  virtual void ButtonPressed(views::Button* sender,
                             const views::Event& event) {}
};

class NetworkScreenTest : public WizardInProcessBrowserTest {
 public:
  NetworkScreenTest(): WizardInProcessBrowserTest("network"),
                       mock_login_library_(NULL),
                       mock_network_library_(NULL) {
  }

 protected:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    mock_network_library_ = cros_mock_->mock_network_library();
    mock_login_library_ = new MockLoginLibrary();
    cros_mock_->test_api()->SetLoginLibrary(mock_login_library_, true);
    EXPECT_CALL(*mock_login_library_, EmitLoginPromptReady())
        .Times(1);

    // Minimal set of expectations needed on NetworkScreen initialization.
    // Status bar expectations are defined with RetiresOnSaturation() so
    // these mocks will be active once status bar is initialized.
    EXPECT_CALL(*mock_network_library_, active_network())
        .Times(1)
        .WillRepeatedly((Return((const Network*)(NULL))))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, ethernet_connected())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, ethernet_connecting())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, wifi_connected())
        .Times(1)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, wifi_connecting())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, cellular_connected())
        .Times(1)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, cellular_connecting())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, ethernet_available())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, ethernet_enabled())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, wifi_available())
        .Times(1)
        .WillRepeatedly((Return(false)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, wifi_enabled())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, cellular_available())
        .Times(1)
        .WillRepeatedly((Return(false)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, cellular_enabled())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();

    // Add a Connecting for prewarming auth url check.
    EXPECT_CALL(*mock_network_library_, Connecting())
        .Times(1)
        .WillRepeatedly(Return(false));
    // Add a Connected for prewarming auth url check.
    EXPECT_CALL(*mock_network_library_, Connected())
        .Times(4)
        .WillRepeatedly(Return(false));
    // Add an Observer for prewarming auth url check.
    EXPECT_CALL(*mock_network_library_, AddNetworkManagerObserver(_))
        .Times(3);
    EXPECT_CALL(*mock_network_library_, RemoveNetworkManagerObserver(_))
        .Times(2);

    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void TearDownInProcessBrowserTestFixture() {
    CrosInProcessBrowserTest::TearDownInProcessBrowserTestFixture();
    cros_mock_->test_api()->SetLoginLibrary(NULL, false);
  }

  void EmulateContinueButtonExit(NetworkScreen* network_screen) {
    scoped_ptr<MockScreenObserver>
        mock_screen_observer(new MockScreenObserver());
    EXPECT_CALL(*mock_screen_observer,
                OnExit(ScreenObserver::NETWORK_CONNECTED))
        .Times(1);
    EXPECT_CALL(*mock_network_library_, Connected())
        .WillOnce(Return(true));
    controller()->set_observer(mock_screen_observer.get());
    DummyButtonListener button_listener;
    views::TextButton button(&button_listener, L"Button");
    views::MouseEvent event(views::Event::ET_MOUSE_RELEASED,
                            0, 0,
                            views::Event::EF_LEFT_BUTTON_DOWN);
    network_screen->ButtonPressed(&button, event);
    ui_test_utils::RunAllPendingInMessageLoop();
    controller()->set_observer(NULL);
  }

  MockLoginLibrary* mock_login_library_;
  MockNetworkLibrary* mock_network_library_;

 private:
  DISALLOW_COPY_AND_ASSIGN(NetworkScreenTest);
};

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Ethernet) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(true)));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(true));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_TRUE(network_view->IsContinueEnabled());

  EmulateContinueButtonExit(network_screen);
}

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Wifi) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connecting())
      .WillOnce((Return(true)));
  scoped_ptr<WifiNetwork> wifi(new WifiNetwork());
  EXPECT_CALL(*mock_network_library_, wifi_network())
      .WillOnce(Return(wifi.get()));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(true));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_TRUE(network_view->IsContinueEnabled());

  EmulateContinueButtonExit(network_screen);
}

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Cellular) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connecting())
      .WillOnce((Return(true)));
  scoped_ptr<CellularNetwork> cellular(new CellularNetwork());
  EXPECT_CALL(*mock_network_library_, cellular_network())
      .WillOnce(Return(cellular.get()));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(true));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_TRUE(network_view->IsContinueEnabled());

  EmulateContinueButtonExit(network_screen);
}

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Timeout) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connecting())
      .WillOnce((Return(true)));
  scoped_ptr<WifiNetwork> wifi(new WifiNetwork());
  EXPECT_CALL(*mock_network_library_, wifi_network())
      .WillOnce(Return(wifi.get()));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(false));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  network_screen->OnConnectionTimeout();
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  // Close infobubble with error message - it makes test stable.
  network_screen->ClearErrors();
}

}  // namespace chromeos
<commit_msg>Fix another test. BUG=None TEST=None TBR=stevenjb@chromium.org Review URL: http://codereview.chromium.org/5145005<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "app/combobox_model.h"
#include "app/l10n_util.h"
#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/mock_login_library.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/login/mock_screen_observer.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/network_selection_view.h"
#include "chrome/browser/chromeos/login/view_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/browser/chromeos/login/wizard_screen.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/button/text_button.h"
#include "views/controls/combobox/combobox.h"

namespace chromeos {
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;
using ::testing::A;
using views::Button;

class DummyButtonListener : public views::ButtonListener {
 public:
  virtual void ButtonPressed(views::Button* sender,
                             const views::Event& event) {}
};

class NetworkScreenTest : public WizardInProcessBrowserTest {
 public:
  NetworkScreenTest(): WizardInProcessBrowserTest("network"),
                       mock_login_library_(NULL),
                       mock_network_library_(NULL) {
  }

 protected:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    mock_network_library_ = cros_mock_->mock_network_library();
    mock_login_library_ = new MockLoginLibrary();
    cros_mock_->test_api()->SetLoginLibrary(mock_login_library_, true);
    EXPECT_CALL(*mock_login_library_, EmitLoginPromptReady())
        .Times(1);

    // Minimal set of expectations needed on NetworkScreen initialization.
    // Status bar expectations are defined with RetiresOnSaturation() so
    // these mocks will be active once status bar is initialized.
    EXPECT_CALL(*mock_network_library_, active_network())
        .Times(AnyNumber())
        .WillRepeatedly((Return((const Network*)(NULL))))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, ethernet_connected())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, ethernet_connecting())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, wifi_connected())
        .Times(1)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, wifi_connecting())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, cellular_connected())
        .Times(1)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, cellular_connecting())
        .Times(2)
        .WillRepeatedly(Return(false));
    EXPECT_CALL(*mock_network_library_, ethernet_available())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, ethernet_enabled())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, wifi_available())
        .Times(1)
        .WillRepeatedly((Return(false)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, wifi_enabled())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, cellular_available())
        .Times(1)
        .WillRepeatedly((Return(false)))
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_network_library_, cellular_enabled())
        .Times(1)
        .WillRepeatedly((Return(true)))
        .RetiresOnSaturation();

    // Add a Connecting for prewarming auth url check.
    EXPECT_CALL(*mock_network_library_, Connecting())
        .Times(1)
        .WillRepeatedly(Return(false));
    // Add a Connected for prewarming auth url check.
    EXPECT_CALL(*mock_network_library_, Connected())
        .Times(4)
        .WillRepeatedly(Return(false));
    // Add an Observer for prewarming auth url check.
    EXPECT_CALL(*mock_network_library_, AddNetworkManagerObserver(_))
        .Times(3);
    EXPECT_CALL(*mock_network_library_, RemoveNetworkManagerObserver(_))
        .Times(2);

    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void TearDownInProcessBrowserTestFixture() {
    CrosInProcessBrowserTest::TearDownInProcessBrowserTestFixture();
    cros_mock_->test_api()->SetLoginLibrary(NULL, false);
  }

  void EmulateContinueButtonExit(NetworkScreen* network_screen) {
    scoped_ptr<MockScreenObserver>
        mock_screen_observer(new MockScreenObserver());
    EXPECT_CALL(*mock_screen_observer,
                OnExit(ScreenObserver::NETWORK_CONNECTED))
        .Times(1);
    EXPECT_CALL(*mock_network_library_, Connected())
        .WillOnce(Return(true));
    controller()->set_observer(mock_screen_observer.get());
    DummyButtonListener button_listener;
    views::TextButton button(&button_listener, L"Button");
    views::MouseEvent event(views::Event::ET_MOUSE_RELEASED,
                            0, 0,
                            views::Event::EF_LEFT_BUTTON_DOWN);
    network_screen->ButtonPressed(&button, event);
    ui_test_utils::RunAllPendingInMessageLoop();
    controller()->set_observer(NULL);
  }

  MockLoginLibrary* mock_login_library_;
  MockNetworkLibrary* mock_network_library_;

 private:
  DISALLOW_COPY_AND_ASSIGN(NetworkScreenTest);
};

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Ethernet) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(true)));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(true));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_TRUE(network_view->IsContinueEnabled());

  EmulateContinueButtonExit(network_screen);
}

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Wifi) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connecting())
      .WillOnce((Return(true)));
  scoped_ptr<WifiNetwork> wifi(new WifiNetwork());
  EXPECT_CALL(*mock_network_library_, wifi_network())
      .WillOnce(Return(wifi.get()));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(true));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_TRUE(network_view->IsContinueEnabled());

  EmulateContinueButtonExit(network_screen);
}

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Cellular) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connecting())
      .WillOnce((Return(true)));
  scoped_ptr<CellularNetwork> cellular(new CellularNetwork());
  EXPECT_CALL(*mock_network_library_, cellular_network())
      .WillOnce(Return(cellular.get()));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(true));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_TRUE(network_view->IsContinueEnabled());

  EmulateContinueButtonExit(network_screen);
}

IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Timeout) {
  ASSERT_TRUE(controller());
  NetworkScreen* network_screen = controller()->GetNetworkScreen();
  ASSERT_TRUE(network_screen != NULL);
  ASSERT_EQ(network_screen, controller()->current_screen());

  NetworkSelectionView* network_view = network_screen->view();
  ASSERT_TRUE(network_view != NULL);
  EXPECT_FALSE(network_view->IsContinueEnabled());

  EXPECT_CALL(*mock_network_library_, ethernet_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, cellular_connected())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, ethernet_connecting())
      .WillOnce((Return(false)));
  EXPECT_CALL(*mock_network_library_, wifi_connecting())
      .WillOnce((Return(true)));
  scoped_ptr<WifiNetwork> wifi(new WifiNetwork());
  EXPECT_CALL(*mock_network_library_, wifi_network())
      .WillOnce(Return(wifi.get()));
  EXPECT_CALL(*mock_network_library_, Connected())
      .WillOnce(Return(false));

  network_screen->OnNetworkManagerChanged(mock_network_library_);
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  network_screen->OnConnectionTimeout();
  EXPECT_FALSE(network_view->IsContinueEnabled());
  EXPECT_FALSE(network_view->IsConnecting());

  // Close infobubble with error message - it makes test stable.
  network_screen->ClearErrors();
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/**
 * AuthModule
 *
 * Copyright 2013 Thincast Technologies GmbH
 * Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/wlog.h>
#include <winpr/library.h>

#include <freerds/auth.h>

#include "appcontext/ApplicationContext.h"

#include "AuthModule.h"

namespace freerds
{
	namespace sessionmanager
	{
		namespace module
		{
			static wLog* logger_Module = WLog_Get("freerds.sessionmanager.module.authmodule");

			AuthModule::AuthModule()
				: mAuth(NULL),
				  mModuleEntry(NULL)
			{
				ZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));
			}

			int AuthModule::initModule(pRdsAuthModuleEntry moduleEntry)
			{
				int status = 0;
				mModuleEntry = moduleEntry;

				ZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));
				mEntryPoints.Version = RDS_AUTH_MODULE_INTERFACE_VERSION;

				status = mModuleEntry(&mEntryPoints);

				if (status < 0)
					return -1;

				mAuth = mEntryPoints.New();

				if (!mAuth)
					return -1;

				return 0;
			}

			AuthModule::~AuthModule()
			{
				if (mEntryPoints.Free)
				{
					mEntryPoints.Free(mAuth);
					mAuth = NULL;
				}
			}

			int AuthModule::logonUser(std::string username, std::string domain, std::string password)
			{
				int status;

				if (!mEntryPoints.LogonUser)
					return -1;

				status = mEntryPoints.LogonUser(mAuth, username.c_str(), domain.size() == 0 ? NULL : domain.c_str(), password.size() == 0 ? NULL : password.c_str());

				return status;
			}

			pRdsAuthModuleEntry AuthModule::loadModuleEntry(std::string filename)
			{
				HINSTANCE library;
				pRdsAuthModuleEntry moduleEntry;

				library = LoadLibraryA(filename.c_str());

				if (!library)
					return (pRdsAuthModuleEntry) NULL;

				moduleEntry = (pRdsAuthModuleEntry) GetProcAddress(library, RDS_AUTH_MODULE_ENTRY_POINT_NAME);

				if (moduleEntry)
					return moduleEntry;

				FreeLibrary(library);

				return (pRdsAuthModuleEntry) NULL;
			}

			AuthModule* AuthModule::loadFromFileName(std::string filename)
			{
				AuthModule* module;
				pRdsAuthModuleEntry moduleEntry;

				moduleEntry = AuthModule::loadModuleEntry(filename.c_str());

				if (!moduleEntry)
					return (AuthModule*) NULL;

				module = new AuthModule();
				module->initModule(moduleEntry);

				return module;
			}

			AuthModule* AuthModule::loadFromName(std::string name)
			{
				int length;
				char* filename;
				char* lowerName;
				std::string libraryPath;
				AuthModule* module;
				pRdsAuthModuleEntry moduleEntry;

				libraryPath = APP_CONTEXT.getLibraryPath();

				lowerName = _strdup(name.c_str());
				CharLowerA(lowerName);

				length = strlen(lowerName) + libraryPath.size() + 64;
				filename = (char*) malloc(length + 1);

				sprintf_s(filename, length, "%s/libfreerds-auth-%s.so", libraryPath.c_str(), lowerName);
				free(lowerName);

				module = AuthModule::loadFromFileName(filename);

				free(filename);

				return module;
			}
		}
	}
}

<commit_msg>Prevented the LogonUser entry point from getting called if the username is empty.<commit_after>/**
 * AuthModule
 *
 * Copyright 2013 Thincast Technologies GmbH
 * Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/wlog.h>
#include <winpr/library.h>

#include <freerds/auth.h>

#include "appcontext/ApplicationContext.h"

#include "AuthModule.h"

namespace freerds
{
	namespace sessionmanager
	{
		namespace module
		{
			static wLog* logger_Module = WLog_Get("freerds.sessionmanager.module.authmodule");

			AuthModule::AuthModule()
				: mAuth(NULL),
				  mModuleEntry(NULL)
			{
				ZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));
			}

			int AuthModule::initModule(pRdsAuthModuleEntry moduleEntry)
			{
				int status = 0;
				mModuleEntry = moduleEntry;

				ZeroMemory(&mEntryPoints, sizeof(RDS_AUTH_MODULE_ENTRY_POINTS));
				mEntryPoints.Version = RDS_AUTH_MODULE_INTERFACE_VERSION;

				status = mModuleEntry(&mEntryPoints);

				if (status < 0)
					return -1;

				mAuth = mEntryPoints.New();

				if (!mAuth)
					return -1;

				return 0;
			}

			AuthModule::~AuthModule()
			{
				if (mEntryPoints.Free)
				{
					mEntryPoints.Free(mAuth);
					mAuth = NULL;
				}
			}

			int AuthModule::logonUser(std::string username, std::string domain, std::string password)
			{
				int status;

				if (!mEntryPoints.LogonUser)
					return -1;

				if (username.empty())
					return -1;

				status = mEntryPoints.LogonUser(mAuth, username.c_str(), domain.size() == 0 ? NULL : domain.c_str(), password.size() == 0 ? NULL : password.c_str());

				return status;
			}

			pRdsAuthModuleEntry AuthModule::loadModuleEntry(std::string filename)
			{
				HINSTANCE library;
				pRdsAuthModuleEntry moduleEntry;

				library = LoadLibraryA(filename.c_str());

				if (!library)
					return (pRdsAuthModuleEntry) NULL;

				moduleEntry = (pRdsAuthModuleEntry) GetProcAddress(library, RDS_AUTH_MODULE_ENTRY_POINT_NAME);

				if (moduleEntry)
					return moduleEntry;

				FreeLibrary(library);

				return (pRdsAuthModuleEntry) NULL;
			}

			AuthModule* AuthModule::loadFromFileName(std::string filename)
			{
				AuthModule* module;
				pRdsAuthModuleEntry moduleEntry;

				moduleEntry = AuthModule::loadModuleEntry(filename.c_str());

				if (!moduleEntry)
					return (AuthModule*) NULL;

				module = new AuthModule();
				module->initModule(moduleEntry);

				return module;
			}

			AuthModule* AuthModule::loadFromName(std::string name)
			{
				int length;
				char* filename;
				char* lowerName;
				std::string libraryPath;
				AuthModule* module;
				pRdsAuthModuleEntry moduleEntry;

				libraryPath = APP_CONTEXT.getLibraryPath();

				lowerName = _strdup(name.c_str());
				CharLowerA(lowerName);

				length = strlen(lowerName) + libraryPath.size() + 64;
				filename = (char*) malloc(length + 1);

				sprintf_s(filename, length, "%s/libfreerds-auth-%s.so", libraryPath.c_str(), lowerName);
				free(lowerName);

				module = AuthModule::loadFromFileName(filename);

				free(filename);

				return module;
			}
		}
	}
}

<|endoftext|>


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

#include "chrome/browser/ui/webui/options/password_manager_handler.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile.h"
#if defined(OS_WIN) && defined(USE_ASH)
#include "chrome/browser/ui/ash/ash_util.h"
#endif
#include "chrome/browser/ui/passwords/manage_passwords_view_utils.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "components/autofill/core/common/password_form.h"
#include "components/password_manager/core/common/experiments.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/content_switches.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"

namespace options {

PasswordManagerHandler::PasswordManagerHandler()
    : password_manager_presenter_(this) {}

PasswordManagerHandler::~PasswordManagerHandler() {}

Profile* PasswordManagerHandler::GetProfile() {
  return Profile::FromWebUI(web_ui());
}

#if !defined(OS_ANDROID)
gfx::NativeWindow PasswordManagerHandler::GetNativeWindow() const {
  return web_ui()->GetWebContents()->GetTopLevelNativeWindow();
}
#endif

void PasswordManagerHandler::GetLocalizedValues(
    base::DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  static const OptionsStringResource resources[] = {
    { "autoSigninTitle",
      IDS_PASSWORDS_AUTO_SIGNIN_TITLE },
    { "autoSigninDescription",
      IDS_PASSWORDS_AUTO_SIGNIN_DESCRIPTION },
    { "savedPasswordsTitle",
      IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
    { "passwordExceptionsTitle",
      IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
    { "passwordSearchPlaceholder",
      IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
    { "passwordShowButton",
      IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
    { "passwordHideButton",
      IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
    { "passwordsNoPasswordsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
    { "passwordsNoExceptionsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
  };

  RegisterStrings(localized_strings, resources, arraysize(resources));
  RegisterTitle(localized_strings, "passwordsPage",
                IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);

  localized_strings->SetString("passwordManagerLearnMoreURL",
                               chrome::kPasswordManagerLearnMoreURL);
  localized_strings->SetString("passwordsManagePasswordsLink",
                               chrome::kPasswordManagerAccountDashboardURL);

  std::vector<base::string16> pieces;
  base::SplitStringDontTrim(
      l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_REMOTE_TEXT),
      '|',  // separator
      &pieces);
  DCHECK_EQ(3U, pieces.size());
  localized_strings->SetString("passwordsManagePasswordsBeforeLinkText",
                               pieces[0]);
  localized_strings->SetString("passwordsManagePasswordsLinkText", pieces[1]);
  localized_strings->SetString("passwordsManagePasswordsAfterLinkText",
                               pieces[2]);

  bool disable_show_passwords = false;

#if defined(OS_WIN) && defined(USE_ASH)
  // We disable the ability to show passwords when running in Windows Metro
  // interface.  This is because we cannot pop native Win32 dialogs from the
  // Metro process.
  // TODO(wfh): Revisit this if Metro usage grows.
  if (chrome::IsNativeWindowInAsh(GetNativeWindow()))
    disable_show_passwords = true;
#endif

  localized_strings->SetBoolean("disableShowPasswords", disable_show_passwords);
  localized_strings->SetBoolean(
      "enableCredentialManagerAPI",
      base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableCredentialManagerAPI));
}

void PasswordManagerHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "updatePasswordLists",
      base::Bind(&PasswordManagerHandler::HandleUpdatePasswordLists,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "removeSavedPassword",
      base::Bind(&PasswordManagerHandler::HandleRemoveSavedPassword,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "removePasswordException",
      base::Bind(&PasswordManagerHandler::HandleRemovePasswordException,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "requestShowPassword",
      base::Bind(&PasswordManagerHandler::HandleRequestShowPassword,
                 base::Unretained(this)));
}

void PasswordManagerHandler::InitializeHandler() {
  password_manager_presenter_.Initialize();
}

void PasswordManagerHandler::InitializePage() {
  base::FundamentalValue visible(
      password_manager::ManageAccountLinkExperimentEnabled());
  web_ui()->CallJavascriptFunction(
      "PasswordManager.setManageAccountLinkVisibility", visible);
}

void PasswordManagerHandler::HandleRemoveSavedPassword(
    const base::ListValue* args) {
  std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0) {
    password_manager_presenter_.RemoveSavedPassword(static_cast<size_t>(index));
  }
}

void PasswordManagerHandler::HandleRemovePasswordException(
    const base::ListValue* args) {
  std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0) {
    password_manager_presenter_.RemovePasswordException(
        static_cast<size_t>(index));
  }
}

void PasswordManagerHandler::HandleRequestShowPassword(
    const base::ListValue* args) {
  int index;
  if (!ExtractIntegerValue(args, &index))
    NOTREACHED();

  password_manager_presenter_.RequestShowPassword(static_cast<size_t>(index));
}

void PasswordManagerHandler::ShowPassword(
    size_t index,
    const base::string16& password_value) {
  // Call back the front end to reveal the password.
  web_ui()->CallJavascriptFunction(
      "PasswordManager.showPassword",
      base::FundamentalValue(static_cast<int>(index)),
      base::StringValue(password_value));
}

void PasswordManagerHandler::HandleUpdatePasswordLists(
    const base::ListValue* args) {
  password_manager_presenter_.UpdatePasswordLists();
}

void PasswordManagerHandler::SetPasswordList(
    const ScopedVector<autofill::PasswordForm>& password_list,
    bool show_passwords) {
  base::ListValue entries;
  languages_ = GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
  base::string16 placeholder(base::ASCIIToUTF16("        "));
  for (size_t i = 0; i < password_list.size(); ++i) {
    base::ListValue* entry = new base::ListValue();
    entry->AppendString(GetHumanReadableOrigin(*password_list[i], languages_));
    entry->AppendString(password_list[i]->username_value);
    if (show_passwords) {
      entry->AppendString(password_list[i]->password_value);
    } else {
      // Use a placeholder value with the same length as the password.
      entry->AppendString(
          base::string16(password_list[i]->password_value.length(), ' '));
    }
    const GURL& federation_url = password_list[i]->federation_url;
    if (!federation_url.is_empty()) {
      entry->AppendString(l10n_util::GetStringFUTF16(
          IDS_PASSWORDS_VIA_FEDERATION,
          base::UTF8ToUTF16(federation_url.host())));
    }
    entries.Append(entry);
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
                                   entries);
}

void PasswordManagerHandler::SetPasswordExceptionList(
    const ScopedVector<autofill::PasswordForm>& password_exception_list) {
  base::ListValue entries;
  for (size_t i = 0; i < password_exception_list.size(); ++i) {
    entries.Append(new base::StringValue(
        net::FormatUrl(password_exception_list[i]->origin, languages_)));
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
                                   entries);
}

}  // namespace options
<commit_msg>Prettify URIs for blacklisted entries on the chrome://settings/passwords page.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/options/password_manager_handler.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile.h"
#if defined(OS_WIN) && defined(USE_ASH)
#include "chrome/browser/ui/ash/ash_util.h"
#endif
#include "chrome/browser/ui/passwords/manage_passwords_view_utils.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "components/autofill/core/common/password_form.h"
#include "components/password_manager/core/common/experiments.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/common/content_switches.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"

namespace options {

PasswordManagerHandler::PasswordManagerHandler()
    : password_manager_presenter_(this) {}

PasswordManagerHandler::~PasswordManagerHandler() {}

Profile* PasswordManagerHandler::GetProfile() {
  return Profile::FromWebUI(web_ui());
}

#if !defined(OS_ANDROID)
gfx::NativeWindow PasswordManagerHandler::GetNativeWindow() const {
  return web_ui()->GetWebContents()->GetTopLevelNativeWindow();
}
#endif

void PasswordManagerHandler::GetLocalizedValues(
    base::DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  static const OptionsStringResource resources[] = {
    { "autoSigninTitle",
      IDS_PASSWORDS_AUTO_SIGNIN_TITLE },
    { "autoSigninDescription",
      IDS_PASSWORDS_AUTO_SIGNIN_DESCRIPTION },
    { "savedPasswordsTitle",
      IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
    { "passwordExceptionsTitle",
      IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
    { "passwordSearchPlaceholder",
      IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
    { "passwordShowButton",
      IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
    { "passwordHideButton",
      IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
    { "passwordsNoPasswordsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
    { "passwordsNoExceptionsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
  };

  RegisterStrings(localized_strings, resources, arraysize(resources));
  RegisterTitle(localized_strings, "passwordsPage",
                IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);

  localized_strings->SetString("passwordManagerLearnMoreURL",
                               chrome::kPasswordManagerLearnMoreURL);
  localized_strings->SetString("passwordsManagePasswordsLink",
                               chrome::kPasswordManagerAccountDashboardURL);

  std::vector<base::string16> pieces;
  base::SplitStringDontTrim(
      l10n_util::GetStringUTF16(IDS_MANAGE_PASSWORDS_REMOTE_TEXT),
      '|',  // separator
      &pieces);
  DCHECK_EQ(3U, pieces.size());
  localized_strings->SetString("passwordsManagePasswordsBeforeLinkText",
                               pieces[0]);
  localized_strings->SetString("passwordsManagePasswordsLinkText", pieces[1]);
  localized_strings->SetString("passwordsManagePasswordsAfterLinkText",
                               pieces[2]);

  bool disable_show_passwords = false;

#if defined(OS_WIN) && defined(USE_ASH)
  // We disable the ability to show passwords when running in Windows Metro
  // interface.  This is because we cannot pop native Win32 dialogs from the
  // Metro process.
  // TODO(wfh): Revisit this if Metro usage grows.
  if (chrome::IsNativeWindowInAsh(GetNativeWindow()))
    disable_show_passwords = true;
#endif

  localized_strings->SetBoolean("disableShowPasswords", disable_show_passwords);
  localized_strings->SetBoolean(
      "enableCredentialManagerAPI",
      base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableCredentialManagerAPI));
}

void PasswordManagerHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "updatePasswordLists",
      base::Bind(&PasswordManagerHandler::HandleUpdatePasswordLists,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "removeSavedPassword",
      base::Bind(&PasswordManagerHandler::HandleRemoveSavedPassword,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "removePasswordException",
      base::Bind(&PasswordManagerHandler::HandleRemovePasswordException,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "requestShowPassword",
      base::Bind(&PasswordManagerHandler::HandleRequestShowPassword,
                 base::Unretained(this)));
}

void PasswordManagerHandler::InitializeHandler() {
  password_manager_presenter_.Initialize();
}

void PasswordManagerHandler::InitializePage() {
  base::FundamentalValue visible(
      password_manager::ManageAccountLinkExperimentEnabled());
  web_ui()->CallJavascriptFunction(
      "PasswordManager.setManageAccountLinkVisibility", visible);
}

void PasswordManagerHandler::HandleRemoveSavedPassword(
    const base::ListValue* args) {
  std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0) {
    password_manager_presenter_.RemoveSavedPassword(static_cast<size_t>(index));
  }
}

void PasswordManagerHandler::HandleRemovePasswordException(
    const base::ListValue* args) {
  std::string string_value = base::UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0) {
    password_manager_presenter_.RemovePasswordException(
        static_cast<size_t>(index));
  }
}

void PasswordManagerHandler::HandleRequestShowPassword(
    const base::ListValue* args) {
  int index;
  if (!ExtractIntegerValue(args, &index))
    NOTREACHED();

  password_manager_presenter_.RequestShowPassword(static_cast<size_t>(index));
}

void PasswordManagerHandler::ShowPassword(
    size_t index,
    const base::string16& password_value) {
  // Call back the front end to reveal the password.
  web_ui()->CallJavascriptFunction(
      "PasswordManager.showPassword",
      base::FundamentalValue(static_cast<int>(index)),
      base::StringValue(password_value));
}

void PasswordManagerHandler::HandleUpdatePasswordLists(
    const base::ListValue* args) {
  password_manager_presenter_.UpdatePasswordLists();
}

void PasswordManagerHandler::SetPasswordList(
    const ScopedVector<autofill::PasswordForm>& password_list,
    bool show_passwords) {
  base::ListValue entries;
  languages_ = GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages);
  base::string16 placeholder(base::ASCIIToUTF16("        "));
  for (size_t i = 0; i < password_list.size(); ++i) {
    base::ListValue* entry = new base::ListValue();
    entry->AppendString(GetHumanReadableOrigin(*password_list[i], languages_));
    entry->AppendString(password_list[i]->username_value);
    if (show_passwords) {
      entry->AppendString(password_list[i]->password_value);
    } else {
      // Use a placeholder value with the same length as the password.
      entry->AppendString(
          base::string16(password_list[i]->password_value.length(), ' '));
    }
    const GURL& federation_url = password_list[i]->federation_url;
    if (!federation_url.is_empty()) {
      entry->AppendString(l10n_util::GetStringFUTF16(
          IDS_PASSWORDS_VIA_FEDERATION,
          base::UTF8ToUTF16(federation_url.host())));
    }
    entries.Append(entry);
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
                                   entries);
}

void PasswordManagerHandler::SetPasswordExceptionList(
    const ScopedVector<autofill::PasswordForm>& password_exception_list) {
  base::ListValue entries;
  for (size_t i = 0; i < password_exception_list.size(); ++i) {
    entries.AppendString(
        GetHumanReadableOrigin(*password_exception_list[i], languages_));
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
                                   entries);
}

}  // namespace options
<|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/webui/options2/options_ui2_browsertest.h"

#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace options2 {

OptionsBrowserTest::OptionsBrowserTest() {
  EnableDOMAutomation();
}

void OptionsBrowserTest::NavigateToSettings() {
  const GURL& url = GURL(chrome::kChromeUISettingsURL);
  ui_test_utils::NavigateToURL(browser(), url);
}

void OptionsBrowserTest::VerifyNavbar() {
  bool navbar_exist = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedWebContents()->GetRenderViewHost(),
      L"",
      L"domAutomationController.send("
      L"!!document.getElementById('navigation'))", &navbar_exist));
  EXPECT_EQ(true, navbar_exist);
}

void OptionsBrowserTest::VerifyTitle() {
  string16 title = browser()->GetSelectedWebContents()->GetTitle();
  string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
  EXPECT_NE(title.find(expected_title), string16::npos);
}

// If this flakes, use http://crbug.com/119671
IN_PROC_BROWSER_TEST_F(OptionsBrowserTest, LoadOptionsByURL) {
  NavigateToSettings();
  VerifyTitle();
  VerifyNavbar();
}

}  // namespace options2
<commit_msg>Mark OptionsBrowserTest.LoadOptionsByURL flaky on Win and Mac<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/webui/options2/options_ui2_browsertest.h"

#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace options2 {

OptionsBrowserTest::OptionsBrowserTest() {
  EnableDOMAutomation();
}

void OptionsBrowserTest::NavigateToSettings() {
  const GURL& url = GURL(chrome::kChromeUISettingsURL);
  ui_test_utils::NavigateToURL(browser(), url);
}

void OptionsBrowserTest::VerifyNavbar() {
  bool navbar_exist = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedWebContents()->GetRenderViewHost(),
      L"",
      L"domAutomationController.send("
      L"!!document.getElementById('navigation'))", &navbar_exist));
  EXPECT_EQ(true, navbar_exist);
}

void OptionsBrowserTest::VerifyTitle() {
  string16 title = browser()->GetSelectedWebContents()->GetTitle();
  string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
  EXPECT_NE(title.find(expected_title), string16::npos);
}

// Observed flaky on Win and Mac, see http://crbug.com/119671.
#if defined(OS_WIN) || defined(OS_MACOSX)
#define MAYBE_LoadOptionsByURL FLAKY_LoadOptionsByURL
#else
#define MAYBE_LoadOptionsByURL LoadOptionsByURL
#endif

IN_PROC_BROWSER_TEST_F(OptionsBrowserTest, MAYBE_LoadOptionsByURL) {
  NavigateToSettings();
  VerifyTitle();
  VerifyNavbar();
}

}  // namespace options2
<|endoftext|>