<commit_before>
/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkExampleDataStructure.h"
#include "mitkGeometry3D.h"

// implementation of virtual methods

void mitk::ExampleDataStructure::UpdateOutputInformation()
{

}

void mitk::ExampleDataStructure::SetRequestedRegionToLargestPossibleRegion()
{

}

bool mitk::ExampleDataStructure::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  return false;
}

bool mitk::ExampleDataStructure::VerifyRequestedRegion()
{
  return true;
}

void mitk::ExampleDataStructure::SetRequestedRegion(const itk::DataObject *)
{

}

/* Constructor and Destructor */
mitk::ExampleDataStructure::ExampleDataStructure()
: m_Data("Initialized")
{
  this->SetGeometry(mitk::Geometry3D::New());
}

mitk::ExampleDataStructure::~ExampleDataStructure()
{
}

void mitk::ExampleDataStructure::AppendAString(const std::string input)
{
  m_Data.append( input );
}

bool mitk::Equal( mitk::ExampleDataStructure* leftHandSide, mitk::ExampleDataStructure* rightHandSide, mitk::ScalarType eps, bool verbose )
{
  bool noDifferenceFound = true;

    if( rightHandSide == NULL )
  {
    if(verbose)
    {
      MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] rightHandSide NULL.";
    }
    return false;
  }

  if( leftHandSide == NULL )
  {
    if(verbose)
    {
      MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] leftHandSide NULL.";
    }
    return false;
  }

  if (!(leftHandSide->GetData() == rightHandSide->GetData()) )
    {
      if(verbose)
      {
        MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] Data not equal. ";
        MITK_INFO << leftHandSide->GetData() << " != " << rightHandSide->GetData();
      }
      noDifferenceFound = false;
    }

  return noDifferenceFound;
}
<commit_msg>Comment out unused variable<commit_after>
/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkExampleDataStructure.h"
#include "mitkGeometry3D.h"

// implementation of virtual methods

void mitk::ExampleDataStructure::UpdateOutputInformation()
{

}

void mitk::ExampleDataStructure::SetRequestedRegionToLargestPossibleRegion()
{

}

bool mitk::ExampleDataStructure::RequestedRegionIsOutsideOfTheBufferedRegion()
{
  return false;
}

bool mitk::ExampleDataStructure::VerifyRequestedRegion()
{
  return true;
}

void mitk::ExampleDataStructure::SetRequestedRegion(const itk::DataObject *)
{

}

/* Constructor and Destructor */
mitk::ExampleDataStructure::ExampleDataStructure()
: m_Data("Initialized")
{
  this->SetGeometry(mitk::Geometry3D::New());
}

mitk::ExampleDataStructure::~ExampleDataStructure()
{
}

void mitk::ExampleDataStructure::AppendAString(const std::string input)
{
  m_Data.append( input );
}

bool mitk::Equal( mitk::ExampleDataStructure* leftHandSide, mitk::ExampleDataStructure* rightHandSide, mitk::ScalarType /*eps*/, bool verbose )
{
  bool noDifferenceFound = true;

    if( rightHandSide == NULL )
  {
    if(verbose)
    {
      MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] rightHandSide NULL.";
    }
    return false;
  }

  if( leftHandSide == NULL )
  {
    if(verbose)
    {
      MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] leftHandSide NULL.";
    }
    return false;
  }

  if (!(leftHandSide->GetData() == rightHandSide->GetData()) )
    {
      if(verbose)
      {
        MITK_INFO << "[Equal( ExampleDataStructure*, ExampleDataStructure* )] Data not equal. ";
        MITK_INFO << leftHandSide->GetData() << " != " << rightHandSide->GetData();
      }
      noDifferenceFound = false;
    }

  return noDifferenceFound;
}
<|endoftext|>


<commit_before><commit_msg>Prevent duplicate issued orders log output on listen servers.<commit_after><|endoftext|>


<commit_before>#include "visgraph.hpp"
#include "../utils/utils.hpp"
#include <cstring>
#include <cstdio>
#include <cerrno>

static unsigned int Npolys = 500;
static unsigned int Maxverts = 8;
static double Minrad = 0.05;
static double Maxrad = 0.075;
static const char *outfile;

static void randpolys(std::vector<Polygon>&);
static double rnddbl(double, double);
static void usage(void);

int main(int argc, char *argv[]) {
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-h") == 0)
			usage();
		else if (i < argc - 1 && strcmp(argv[i], "-n") == 0)
			Npolys = strtoll(argv[++i], NULL, 10);
		else if (i < argc - 1 && strcmp(argv[i], "-v") == 0)
			Maxverts = strtoll(argv[++i], NULL, 10);
		else if (i < argc - 1 && strcmp(argv[i], "-o") == 0)
			outfile = argv[++i];
		else if (i < argc - 1 && strcmp(argv[i], "-m") == 0)
			Minrad = strtod(argv[++i], NULL);
		else if (i < argc - 1 && strcmp(argv[i], "-x") == 0)
			Maxrad = strtod(argv[++i], NULL);
	}

	std::vector<Polygon> polys;
	randpolys(polys);

	VisGraph graph(polys);
	if (outfile) {
		FILE *f = fopen(outfile, "w");
		if (!f)
			fatalx(errno, "Failed to open %s:", outfile);
		graph.output(stdout);
		fclose(f);
	} else {
		graph.output(stdout);
	}

	return 0;
}

static void randpolys(std::vector<Polygon> &polys) {
	for (unsigned int i = 0; i < Npolys; i++) {
redo:
		double r = rnddbl(Minrad, Maxrad);
		double x = rnddbl(r, 1 - r);
		double y = rnddbl(r, 1 - r);

		assert (x >= 0.0);
		assert (y >= 0.0);
		assert (r >= 0.0);

		Polygon p = Polygon::random(randgen.integer(3, Maxverts), x, y, r);

		for (unsigned int i = 0; i < polys.size(); i++) {
			if (polys[i].bbox.isect(p.bbox))
				goto redo;
		}

		polys.push_back(p);
	}
}

static double rnddbl(double min, double max) {
	assert (max > min);
	return randgen.real() * (max - min) + min;
}

static void usage(void) {
	puts("Usage: rand [options]");
	puts("\nPlaces random polygons in the unit square.  Computes the");
	puts("visibility graph and prints the instance to standard output");
	puts("\nOptions:");
	puts("	-h	prints this help message");
	puts("	-n <num>	specify the number of polygons (default: 500)");
	puts("	-v <num>	specify the max number of vertices (default: 8)");
	puts("	-o <file>	output to the specified file instead of standard output");
	puts("	-m <num>	minimum polygon radius (default: 0.05)");
	puts("	-x <num>	maximum polygon radius (default: 0.075)");
	exit(0);
}<commit_msg>visnav: tiny formatting fix.<commit_after>#include "visgraph.hpp"
#include "../utils/utils.hpp"
#include <cstring>
#include <cstdio>
#include <cerrno>

static void randpolys(std::vector<Polygon>&);
static double rnddbl(double, double);
static void usage(void);

static unsigned int Npolys = 500;
static unsigned int Maxverts = 8;
static double Minrad = 0.05;
static double Maxrad = 0.075;
static const char *outfile;

int main(int argc, char *argv[]) {
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-h") == 0)
			usage();
		else if (i < argc - 1 && strcmp(argv[i], "-n") == 0)
			Npolys = strtoll(argv[++i], NULL, 10);
		else if (i < argc - 1 && strcmp(argv[i], "-v") == 0)
			Maxverts = strtoll(argv[++i], NULL, 10);
		else if (i < argc - 1 && strcmp(argv[i], "-o") == 0)
			outfile = argv[++i];
		else if (i < argc - 1 && strcmp(argv[i], "-m") == 0)
			Minrad = strtod(argv[++i], NULL);
		else if (i < argc - 1 && strcmp(argv[i], "-x") == 0)
			Maxrad = strtod(argv[++i], NULL);
	}

	std::vector<Polygon> polys;
	randpolys(polys);

	VisGraph graph(polys);
	if (outfile) {
		FILE *f = fopen(outfile, "w");
		if (!f)
			fatalx(errno, "Failed to open %s:", outfile);
		graph.output(stdout);
		fclose(f);
	} else {
		graph.output(stdout);
	}

	return 0;
}

static void randpolys(std::vector<Polygon> &polys) {
	for (unsigned int i = 0; i < Npolys; i++) {
redo:
		double r = rnddbl(Minrad, Maxrad);
		double x = rnddbl(r, 1 - r);
		double y = rnddbl(r, 1 - r);

		assert (x >= 0.0);
		assert (y >= 0.0);
		assert (r >= 0.0);

		Polygon p = Polygon::random(randgen.integer(3, Maxverts), x, y, r);

		for (unsigned int i = 0; i < polys.size(); i++) {
			if (polys[i].bbox.isect(p.bbox))
				goto redo;
		}

		polys.push_back(p);
	}
}

static double rnddbl(double min, double max) {
	assert (max > min);
	return randgen.real() * (max - min) + min;
}

static void usage(void) {
	puts("Usage: rand [options]");
	puts("\nPlaces random polygons in the unit square.  Computes the");
	puts("visibility graph and prints the instance to standard output");
	puts("\nOptions:");
	puts("	-h	prints this help message");
	puts("	-n <num>	specify the number of polygons (default: 500)");
	puts("	-v <num>	specify the max number of vertices (default: 8)");
	puts("	-o <file>	output to the specified file instead of standard output");
	puts("	-m <num>	minimum polygon radius (default: 0.05)");
	puts("	-x <num>	maximum polygon radius (default: 0.075)");
	exit(0);
}<|endoftext|>


<commit_before>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "common/linux/google_crashdump_uploader.h"
#include "third_party/linux/include/gflags/gflags.h"
#include <string>
#include <iostream>

using std::string;

DEFINE_string(crash_server, "http://clients2.google.com/cr",
              "The crash server to upload minidumps to.");
DEFINE_string(product_name, "",
              "The product name that the minidump corresponds to.");
DEFINE_string(product_version, "",
              "The version of the product that produced the minidump.");
DEFINE_string(client_id, "",
              "The client GUID");
DEFINE_string(minidump_path, "",
              "The path of the minidump file.");
DEFINE_string(ptime, "",
              "The process uptime in milliseconds.");
DEFINE_string(ctime, "",
              "The cumulative process uptime in milliseconds.");
DEFINE_string(email, "",
              "The user's email address.");
DEFINE_string(comments, "",
              "Extra user comments");
DEFINE_string(proxy_host, "",
              "Proxy host");
DEFINE_string(proxy_userpasswd, "",
              "Proxy username/password in user:pass format.");

bool CheckForRequiredFlagsOrDie() {
  std::string error_text = "";
  if (FLAGS_product_name.empty()) {
    error_text.append("\nProduct name must be specified.");
  }

  if (FLAGS_product_version.empty()) {
    error_text.append("\nProduct version must be specified.");
  }

  if (FLAGS_client_id.empty()) {
    error_text.append("\nClient ID must be specified.");
  }

  if (FLAGS_minidump_path.empty()) {
    error_text.append("\nMinidump pathname must be specified.");
  }

  if (!error_text.empty()) {
    std::cout << error_text;
    return false;
  }
  return true;
}

int main(int argc, char *argv[]) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);
  if (!CheckForRequiredFlagsOrDie()) {
    return 1;
  }
  google_breakpad::GoogleCrashdumpUploader g(FLAGS_product_name,
                                             FLAGS_product_version,
                                             FLAGS_client_id,
                                             FLAGS_ptime,
                                             FLAGS_ctime,
                                             FLAGS_email,
                                             FLAGS_comments,
                                             FLAGS_minidump_path,
                                             FLAGS_crash_server,
                                             FLAGS_proxy_host,
                                             FLAGS_proxy_userpasswd);
  g.Upload();
}
<commit_msg>Send crash dumps to Google via HTTPS instead of HTTP, since they might contain sensitive information.<commit_after>// Copyright (c) 2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "common/linux/google_crashdump_uploader.h"
#include "third_party/linux/include/gflags/gflags.h"
#include <string>
#include <iostream>

using std::string;

DEFINE_string(crash_server, "https://clients2.google.com/cr",
              "The crash server to upload minidumps to.");
DEFINE_string(product_name, "",
              "The product name that the minidump corresponds to.");
DEFINE_string(product_version, "",
              "The version of the product that produced the minidump.");
DEFINE_string(client_id, "",
              "The client GUID");
DEFINE_string(minidump_path, "",
              "The path of the minidump file.");
DEFINE_string(ptime, "",
              "The process uptime in milliseconds.");
DEFINE_string(ctime, "",
              "The cumulative process uptime in milliseconds.");
DEFINE_string(email, "",
              "The user's email address.");
DEFINE_string(comments, "",
              "Extra user comments");
DEFINE_string(proxy_host, "",
              "Proxy host");
DEFINE_string(proxy_userpasswd, "",
              "Proxy username/password in user:pass format.");

bool CheckForRequiredFlagsOrDie() {
  std::string error_text = "";
  if (FLAGS_product_name.empty()) {
    error_text.append("\nProduct name must be specified.");
  }

  if (FLAGS_product_version.empty()) {
    error_text.append("\nProduct version must be specified.");
  }

  if (FLAGS_client_id.empty()) {
    error_text.append("\nClient ID must be specified.");
  }

  if (FLAGS_minidump_path.empty()) {
    error_text.append("\nMinidump pathname must be specified.");
  }

  if (!error_text.empty()) {
    std::cout << error_text;
    return false;
  }
  return true;
}

int main(int argc, char *argv[]) {
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);
  if (!CheckForRequiredFlagsOrDie()) {
    return 1;
  }
  google_breakpad::GoogleCrashdumpUploader g(FLAGS_product_name,
                                             FLAGS_product_version,
                                             FLAGS_client_id,
                                             FLAGS_ptime,
                                             FLAGS_ctime,
                                             FLAGS_email,
                                             FLAGS_comments,
                                             FLAGS_minidump_path,
                                             FLAGS_crash_server,
                                             FLAGS_proxy_host,
                                             FLAGS_proxy_userpasswd);
  g.Upload();
}
<|endoftext|>


<commit_before>/***************************************************************************
 * main.cpp
 * copyright (C)2003 by Sebastian Sauer (mail@dipe.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 * You should have received a copy of the GNU Library General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 ***************************************************************************/

#include <Python.h>

#include <qstring.h>
#include <qstringlist.h>
#include <qfile.h>

#include <kdebug.h>
#include <kinstance.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>

#include "../CXX/Objects.hxx"
#include "../kexidb/pythonkexidb.h"
#include "../kexidb/pythonkexidbdriver.h"
#include "../main/pythonmanager.h"

KApplication *app = 0;

static KCmdLineOptions options[] =
{
    { "file <filename>", I18N_NOOP("Pythonfile to execute."), "test.py" },
    { 0, 0, 0}
};

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

    KCmdLineArgs::init(argc, argv,
        new KAboutData("KrossPythonTest", "KrossPythonTest",
            "0.1", "", KAboutData::License_GPL,
            "(c) 2004, Sebastian Sauer (mail@dipe.org)\n"
            "http://www.koffice.org/kexi\n"
            "http://www.dipe.org/kross",
            "kross@dipe.org"
        )
    );
    KCmdLineArgs::addCmdLineOptions(options);
    app = new KApplication(true, true);
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    Kross::PythonManager* pymanager = new Kross::PythonManager("Kross");

    QFile f(QFile::encodeName( args->getOption("file") ));
    if(f.exists() && f.open(IO_ReadOnly)) {
        QString data = f.readAll();
        f.close();

        kdDebug() << "##############################################" << endl;
        pymanager->execute(data, QStringList() << "kexidb");
        kdDebug() << "##############################################" << endl;
    }
    else {
        kdWarning() << "Failed to load Python scriptfile: " << args->getOption("file") << endl;
        result = -1;
    }

    delete pymanager;
    delete app;
    return result;
}
<commit_msg>s/GPL/LGPL/; as well.<commit_after>/***************************************************************************
 * main.cpp
 * copyright (C)2003 by Sebastian Sauer (mail@dipe.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 * You should have received a copy of the GNU Library General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 ***************************************************************************/

#include <Python.h>

#include <qstring.h>
#include <qstringlist.h>
#include <qfile.h>

#include <kdebug.h>
#include <kinstance.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>

#include "../CXX/Objects.hxx"
#include "../kexidb/pythonkexidb.h"
#include "../kexidb/pythonkexidbdriver.h"
#include "../main/pythonmanager.h"

KApplication *app = 0;

static KCmdLineOptions options[] =
{
    { "file <filename>", I18N_NOOP("Pythonfile to execute."), "test.py" },
    { 0, 0, 0}
};

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

    KCmdLineArgs::init(argc, argv,
        new KAboutData("KrossPythonTest", "KrossPythonTest",
            "0.1", "", KAboutData::License_LGPL,
            "(c) 2004, Sebastian Sauer (mail@dipe.org)\n"
            "http://www.koffice.org/kexi\n"
            "http://www.dipe.org/kross",
            "kross@dipe.org"
        )
    );
    KCmdLineArgs::addCmdLineOptions(options);
    app = new KApplication(true, true);
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

    Kross::PythonManager* pymanager = new Kross::PythonManager("Kross");

    QFile f(QFile::encodeName( args->getOption("file") ));
    if(f.exists() && f.open(IO_ReadOnly)) {
        QString data = f.readAll();
        f.close();

        kdDebug() << "##############################################" << endl;
        pymanager->execute(data, QStringList() << "kexidb");
        kdDebug() << "##############################################" << endl;
    }
    else {
        kdWarning() << "Failed to load Python scriptfile: " << args->getOption("file") << endl;
        result = -1;
    }

    delete pymanager;
    delete app;
    return result;
}
<|endoftext|>


<commit_before>/*
    Copyright 2012 Brain Research Institute, Melbourne, Australia

    Written by David Raffelt, 17/02/2012.

    This file is part of MRtrix.

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

    MRtrix 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "command.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "image/filter/gaussian_smooth.h"
#include "image/filter/anisotropic_smooth.h"
#include "progressbar.h"

using namespace MR;
using namespace App;

void usage ()
{
  DESCRIPTION
  + "smooth n-dimensional images by a convolution with a Gaussian kernel. "
  + "Note that if the input volume is 4D, then by default each 3D volume is smoothed independently. However "
    "this behaviour can be overridden by manually setting the stdev for all dimensions.";

  ARGUMENTS
  + Argument ("input", "input image to be smoothed.").type_image_in ()
  + Argument ("output", "the output image.").type_image_out ();

  OPTIONS
  + Option ("stdev", "apply Gaussian smoothing with the specified standard deviation. "
            "The standard deviation is defined in mm (Default 1 voxel). "
            "This can be specified either as a single value to be used for all axes, "
            "or as a comma-separated list of the stdev for each axis.")
  + Argument ("mm").type_sequence_float()

  + Option ("fwhm", "apply Gaussian smoothing with the specified full-width half maximum. "
            "The FWHM is defined in mm (Default 1 voxel * 2.3548). "
            "This can be specified either as a single value to be used for all axes, "
            "or as a comma-separated list of the FWHM for each axis.")
  + Argument ("mm").type_sequence_float()

  + Option ("extent", "specify the extent (width) of kernel size in voxels. "
            "This can be specified either as a single value to be used for all axes, "
            "or as a comma-separated list of the extent for each axis. "
            "The default extent is 2 * ceil(2.5 * stdev / voxel_size) - 1.")
  + Argument ("voxels").type_sequence_int()

  + Option ("anisotropic", "smooth each 3D volume of a 4D image using an anisotropic gaussian kernel "
                           "oriented along a corresponding direction. Note that when this option is used "
                           "the -stdev option takes two comma separated values, the first value defines the standard "
                           "deviation along the major eigenvector of the kernel (default: 1.27mm (FWHM = 3mm)) and "
                           "the second value defines the standard deviation along the other two eigenvectors "
                           "(default: 0.42mm (FWHM = 1mm)). The directions can be specified within the header of the input image, "
                           "or by using the -directions option.")

  + Option ("directions", "the directions for anisotropic smoothing.")
  + Argument ("file", "a list of directions [az el] generated using the gendir command.").type_file()

  + Image::Stride::StrideOption;
}

void run () {

  Image::Header header (argument[0]);
  Image::BufferPreload<float> input_data (header);
  Image::BufferPreload<float>::voxel_type input_vox (input_data);

  bool do_anisotropic = false;
  Options opt = get_options ("anisotropic");
  if (opt.size())
    do_anisotropic = true;

  std::vector<float> stdev;
  if (do_anisotropic) {
    stdev.resize(2, 3.0 / 2.3548);
    stdev[1] = 1.0 / 2.3548;
  } else {
    stdev.resize(3);
    for (size_t dim = 0; dim < 3; dim++)
      stdev[dim] = input_data.vox (dim);
  }

  opt = get_options ("stdev");
  int stdev_supplied = opt.size();
  if (stdev_supplied) {
    stdev = parse_floats (opt[0][0]);
  }

  opt = get_options ("fwhm");
  if (opt.size()) {
    if (stdev_supplied)
      throw Exception ("The stdev and FWHM options are mutually exclusive.");
    stdev = parse_floats (opt[0][0]);
    for (size_t d = 0; d < stdev.size(); ++d)
      stdev[d] = stdev[d] / 2.3548;  //convert FWHM to stdev
  }

  opt = get_options ("stride");
  std::vector<int> strides;
  if (opt.size()) {
    strides = opt[0][0];
    if (strides.size() > header.ndim())
      throw Exception ("too many axes supplied to -stride option");
  }

  if (do_anisotropic) {

    Math::Matrix<float> directions;;
    opt = get_options ("directions");
    if (opt.size()) {
      directions.load(opt[0][0]);
    } else {
      if (!header["directions"].size())
        throw Exception ("no mask directions have been specified.");
      std::vector<float> dir_vector;
      std::vector<std::string > lines = split (header["directions"], "\n", true);
      for (size_t l = 0; l < lines.size(); l++) {
        std::vector<float> v (parse_floats(lines[l]));
        dir_vector.insert (dir_vector.end(), v.begin(), v.end());
      }
      directions.resize(dir_vector.size() / 2, 2);
      for (size_t i = 0; i < dir_vector.size(); i += 2) {
        directions(i / 2, 0) = dir_vector[i];
        directions(i / 2, 1) = dir_vector[i + 1];
      }
    }
    Image::Filter::AnisotropicSmooth smooth_filter (input_vox, stdev, directions);
    header.info() = smooth_filter.info();
    if (strides.size()) {
      for (size_t n = 0; n < strides.size(); ++n)
        header.stride(n) = strides[n];
    }
    Image::Buffer<float> output_data (argument[1], header);
    Image::Buffer<float>::voxel_type output_vox (output_data);
    smooth_filter (input_vox, output_vox);

  } else {

    Image::Filter::GaussianSmooth<> smooth_filter (input_vox, stdev);
    opt = get_options ("extent");
    if (opt.size())
      smooth_filter.set_extent(parse_ints (opt[0][0]));

    header.info() = smooth_filter.info();
    if (strides.size()) {
      for (size_t n = 0; n < strides.size(); ++n)
        header.stride(n) = strides[n];
    }
    Image::Buffer<float> output_data (argument[1], header);
    Image::Buffer<float>::voxel_type output_vox (output_data);
    smooth_filter (input_vox, output_vox);
  }
}
<commit_msg>removed -anisotropic (directional smoothing) option from mrsmooth<commit_after>/*
    Copyright 2012 Brain Research Institute, Melbourne, Australia

    Written by David Raffelt, 17/02/2012.

    This file is part of MRtrix.

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

    MRtrix 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with MRtrix.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "command.h"
#include "image/buffer.h"
#include "image/buffer_preload.h"
#include "image/voxel.h"
#include "image/filter/gaussian_smooth.h"
#include "progressbar.h"

using namespace MR;
using namespace App;

void usage ()
{
  DESCRIPTION
  + "smooth n-dimensional images by a convolution with a Gaussian kernel. "
  + "Note that if the input volume is 4D, then by default each 3D volume is smoothed independently. However "
    "this behaviour can be overridden by manually setting the stdev for all dimensions.";

  ARGUMENTS
  + Argument ("input", "input image to be smoothed.").type_image_in ()
  + Argument ("output", "the output image.").type_image_out ();

  OPTIONS
  + Option ("stdev", "apply Gaussian smoothing with the specified standard deviation. "
            "The standard deviation is defined in mm (Default 1 voxel). "
            "This can be specified either as a single value to be used for all axes, "
            "or as a comma-separated list of the stdev for each axis.")
  + Argument ("mm").type_sequence_float()

  + Option ("fwhm", "apply Gaussian smoothing with the specified full-width half maximum. "
            "The FWHM is defined in mm (Default 1 voxel * 2.3548). "
            "This can be specified either as a single value to be used for all axes, "
            "or as a comma-separated list of the FWHM for each axis.")
  + Argument ("mm").type_sequence_float()

  + Option ("extent", "specify the extent (width) of kernel size in voxels. "
            "This can be specified either as a single value to be used for all axes, "
            "or as a comma-separated list of the extent for each axis. "
            "The default extent is 2 * ceil(2.5 * stdev / voxel_size) - 1.")
  + Argument ("voxels").type_sequence_int()

  + Image::Stride::StrideOption;
}

void run () {

  Image::Header header (argument[0]);
  Image::BufferPreload<float> input_data (header);
  Image::BufferPreload<float>::voxel_type input_vox (input_data);

  std::vector<float> stdev;
  stdev.resize(3);
  for (size_t dim = 0; dim < 3; dim++)
    stdev[dim] = input_data.vox (dim);

  Options opt = get_options ("stdev");
  int stdev_supplied = opt.size();
  if (stdev_supplied) {
    stdev = parse_floats (opt[0][0]);
  }

  opt = get_options ("fwhm");
  if (opt.size()) {
    if (stdev_supplied)
      throw Exception ("The stdev and FWHM options are mutually exclusive.");
    stdev = parse_floats (opt[0][0]);
    for (size_t d = 0; d < stdev.size(); ++d)
      stdev[d] = stdev[d] / 2.3548;  //convert FWHM to stdev
  }

  opt = get_options ("stride");
  std::vector<int> strides;
  if (opt.size()) {
    strides = opt[0][0];
    if (strides.size() > header.ndim())
      throw Exception ("too many axes supplied to -stride option");
  }

  Image::Filter::GaussianSmooth<> smooth_filter (input_vox, stdev);
  opt = get_options ("extent");
  if (opt.size())
    smooth_filter.set_extent(parse_ints (opt[0][0]));

  header.info() = smooth_filter.info();
  if (strides.size()) {
    for (size_t n = 0; n < strides.size(); ++n)
      header.stride(n) = strides[n];
  }
  Image::Buffer<float> output_data (argument[1], header);
  Image::Buffer<float>::voxel_type output_vox (output_data);
  smooth_filter (input_vox, output_vox);
}
<|endoftext|>


<commit_before>#include "update_dialog.hpp"
#include "info_dialog.hpp"

#include "../platform/settings.hpp"

#include "../base/assert.hpp"

#include "../std/bind.hpp"

#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTreeWidget>
#include <QtGui/QHeaderView>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtCore/QDateTime>

#define CHECK_FOR_UPDATE "Check for update"
#define LAST_UPDATE_CHECK "Last update check: "
/// used in settings
#define LAST_CHECK_TIME_KEY "LastUpdateCheckTime"

using namespace storage;

enum
{
//  KItemIndexFlag = 0,
  KColumnIndexCountry,
  KColumnIndexStatus,
  KColumnIndexSize,
  KNumberOfColumns
};

#define COLOR_NOTDOWNLOADED   Qt::black
#define COLOR_ONDISK          Qt::darkGreen
#define COLOR_INPROGRESS      Qt::blue
#define COLOR_DOWNLOADFAILED  Qt::red
#define COLOR_INQUEUE         Qt::gray

namespace qt
{
///////////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////////
  /// adds custom sorting for "Size" column
  class QTreeWidgetItemWithCustomSorting : public QTreeWidgetItem
  {
  public:
    virtual bool operator<(QTreeWidgetItem const & other) const
    {
      return data(KColumnIndexSize, Qt::UserRole).toULongLong() < other.data(KColumnIndexSize, Qt::UserRole).toULongLong();
    }
  };
////////////////////////////////////////////////////////////////////////////////

  UpdateDialog::UpdateDialog(QWidget * parent, Storage & storage)
    : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), m_storage(storage)
  {
    setWindowModality(Qt::WindowModal);

    QPushButton * closeButton = new QPushButton(QObject::tr("Close"), this);
    closeButton->setDefault(true);
    connect(closeButton, SIGNAL(clicked()), this, SLOT(OnCloseClick()));

    m_tree = new QTreeWidget(this);
    m_tree->setColumnCount(KNumberOfColumns);
    QStringList columnLabels;
    columnLabels << tr("Country") << tr("Status") << tr("Size");
    m_tree->setHeaderLabels(columnLabels);
    connect(m_tree, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(OnItemClick(QTreeWidgetItem *, int)));

    QHBoxLayout * horizontalLayout = new QHBoxLayout();
    horizontalLayout->addStretch();
    horizontalLayout->addWidget(closeButton);

    QVBoxLayout * verticalLayout = new QVBoxLayout();
    verticalLayout->addWidget(m_tree);
    verticalLayout->addLayout(horizontalLayout);
    setLayout(verticalLayout);

    setWindowTitle(tr("Geographical Regions"));
    resize(600, 500);

    // we want to receive all download progress and result events
    m_storage.Subscribe(bind(&UpdateDialog::OnCountryChanged, this, _1),
                        bind(&UpdateDialog::OnCountryDownloadProgress, this, _1, _2));
  }

  UpdateDialog::~UpdateDialog()
  {
    // tell download manager that we're gone...
    m_storage.Unsubscribe();
  }

  /// when user clicks on any map row in the table
  void UpdateDialog::OnItemClick(QTreeWidgetItem * item, int /*column*/)
  {
    // calculate index of clicked item
    QList<int> treeIndex;
    {
      QTreeWidgetItem * parent = item;
      while (parent)
      {
        treeIndex.insert(0, parent->data(KColumnIndexCountry, Qt::UserRole).toInt());
        parent = parent->parent();
      }
      while (treeIndex.size() < 3)
        treeIndex.append(TIndex::INVALID);
    }

    TIndex const countryIndex(treeIndex[0], treeIndex[1], treeIndex[2]);
    switch (m_storage.CountryStatus(countryIndex))
    {
    case EOnDisk:
      {
        // map is already downloaded, so ask user about deleting!
        QMessageBox ask(this);
        ask.setText(tr("Do you want to delete %1?").arg(item->text(KColumnIndexCountry)));
        ask.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        ask.setDefaultButton(QMessageBox::No);
        if (ask.exec() == QMessageBox::Yes)
          m_storage.DeleteCountry(countryIndex);
      }
      break;

    case ENotDownloaded:
    case EDownloadFailed:
      m_storage.DownloadCountry(countryIndex);
      break;

    case EInQueue:
    case EDownloading:
      m_storage.DeleteCountry(countryIndex);
      break;

    case EGeneratingIndex:
      // we can't stop index genertion at this moment
      break;
    }
  }

  QTreeWidgetItem * MatchedItem(QTreeWidgetItem & parent, int index)
  {
    if (index >= 0)
    {
      for (int i = 0; i < parent.childCount(); ++i)
      {
        QTreeWidgetItem * item = parent.child(i);
        if (index == item->data(KColumnIndexCountry, Qt::UserRole).toInt())
          return item;
      }
    }
    return NULL;
  }

  /// @return can be null if index is invalid
  QTreeWidgetItem * GetTreeItemByIndex(QTreeWidget & tree, TIndex const & index)
  {
    QTreeWidgetItem * item = 0;
    if (index.m_group >= 0)
    {
      for (int i = 0; i < tree.topLevelItemCount(); ++i)
      {
        QTreeWidgetItem * grItem = tree.topLevelItem(i);
        if (index.m_group == grItem->data(KColumnIndexCountry, Qt::UserRole).toInt())
        {
          item = grItem;
          break;
        }
      }
    }
    if (item && index.m_country >= 0)
    {
      item = MatchedItem(*item, index.m_country);
      if (item && index.m_region >= 0)
        item = MatchedItem(*item, index.m_region);
    }
    return item;
  }

  void UpdateDialog::OnCloseClick()
  {
    done(0);
  }

  /// Changes row's text color
  void SetRowColor(QTreeWidgetItem & item, QColor const & color)
  {
    for (int column = 0; column < item.columnCount(); ++column)
      item.setTextColor(column, color);
  }

  void UpdateDialog::UpdateRowWithCountryInfo(TIndex const & index)
  {
    QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
    if (item)
    {
      QColor rowColor;
      QString statusString;
      LocalAndRemoteSizeT size(0, 0);
      switch (m_storage.CountryStatus(index))
      {
      case ENotDownloaded:
        statusString = tr("Click to download");
        rowColor = COLOR_NOTDOWNLOADED;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EOnDisk:
        statusString = tr("Installed (click to delete)");
        rowColor = COLOR_ONDISK;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EDownloadFailed:
        statusString = tr("Download has failed");
        rowColor = COLOR_DOWNLOADFAILED;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EDownloading:
        statusString = tr("Downloading ...");
        rowColor = COLOR_INPROGRESS;
        break;

      case EInQueue:
        statusString = tr("Marked for download");
        rowColor = COLOR_INQUEUE;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EGeneratingIndex:
        statusString = tr("Generatin search index ...");
        rowColor = COLOR_INPROGRESS;
        break;
      }

      if (statusString.size())
        item->setText(KColumnIndexStatus, statusString);

      if (size.second)
      {
        if (size.second > 1000 * 1000 * 1000)
          item->setText(KColumnIndexSize, QString("%1/%2 GB").arg(
              uint(size.first / (1000 * 1000 * 1000))).arg(uint(size.second / (1000 * 1000 * 1000))));
        else if (size.second > 1000 * 1000)
          item->setText(KColumnIndexSize, QString("%1/%2 MB").arg(
              uint(size.first / (1000 * 1000))).arg(uint(size.second / (1000 * 1000))));
        else
          item->setText(KColumnIndexSize, QString("%1/%2 kB").arg(
              uint((size.first + 999) / 1000)).arg(uint((size.second + 999) / 1000)));
        // needed for column sorting
        item->setData(KColumnIndexSize, Qt::UserRole, QVariant(qint64(size.second)));
      }

      if (statusString.size())
        SetRowColor(*item, rowColor);
    }
  }

  void UpdateDialog::FillTree()
  {
    m_tree->setSortingEnabled(false);
    m_tree->clear();

    for (int group = 0; group < static_cast<int>(m_storage.CountriesCount(TIndex())); ++group)
    {
      TIndex const grIndex(group);
      QStringList groupText(QString::fromUtf8(m_storage.CountryName(grIndex).c_str()));
      QTreeWidgetItem * groupItem = new QTreeWidgetItem(groupText);
      groupItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(group));
      m_tree->addTopLevelItem(groupItem);
      // set color by status and update country size
      UpdateRowWithCountryInfo(grIndex);

      for (int country = 0; country < static_cast<int>(m_storage.CountriesCount(grIndex)); ++country)
      {
        TIndex cIndex(group, country);
        QStringList countryText(QString::fromUtf8(m_storage.CountryName(cIndex).c_str()));
        QTreeWidgetItem * countryItem = new QTreeWidgetItem(groupItem, countryText);
        countryItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(country));
        // set color by status and update country size
        UpdateRowWithCountryInfo(cIndex);

        for (int region = 0; region < static_cast<int>(m_storage.CountriesCount(cIndex)); ++region)
        {
          TIndex const rIndex(group, country, region);
          QStringList regionText(QString::fromUtf8(m_storage.CountryName(rIndex).c_str()));
          QTreeWidgetItem * regionItem = new QTreeWidgetItem(countryItem, regionText);
          regionItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(region));
          // set color by status and update country size
          UpdateRowWithCountryInfo(rIndex);
        }
      }
    }
//        // Size column, actual size will be set later
//        QTableWidgetItemWithCustomSorting * sizeItem = new QTableWidgetItemWithCustomSorting;
//        sizeItem->setFlags(sizeItem->flags() ^ Qt::ItemIsEditable);
//        m_table->setItem(row, KItemIndexSize, sizeItem);

    m_tree->sortByColumn(KColumnIndexCountry, Qt::AscendingOrder);
    m_tree->setSortingEnabled(true);
    m_tree->header()->setResizeMode(KColumnIndexCountry, QHeaderView::ResizeToContents);
    m_tree->header()->setResizeMode(KColumnIndexStatus, QHeaderView::ResizeToContents);
  }

  void UpdateDialog::OnCountryChanged(TIndex const & index)
  {
    UpdateRowWithCountryInfo(index);
  }

  void UpdateDialog::OnCountryDownloadProgress(TIndex const & index,
                                               pair<int64_t, int64_t> const & progress)
  {
    QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
    if (item)
    {
//      QString speed;
//      if (progress.m_bytesPerSec > 1000 * 1000)
//        speed = QString(" %1 MB/s").arg(QString::number(static_cast<double>(progress.m_bytesPerSec) / (1000.0 * 1000.0),
//                                                         'f', 1));
//      else if (progress.m_bytesPerSec > 1000)
//        speed = QString(" %1 kB/s").arg(progress.m_bytesPerSec / 1000);
//      else if (progress.m_bytesPerSec >= 0)
//        speed = QString(" %1 B/sec").arg(progress.m_bytesPerSec);

      item->setText(KColumnIndexSize, QString("%1%").arg(progress.first * 100 / progress.second));
//      item->setText(KColumnIndexSize, QString("%1%%2").arg(progress.m_current * 100 / progress.m_total)
//                    .arg(speed));
    }
  }

  void UpdateDialog::ShowDialog()
  {
    // if called for first time
    if (!m_tree->topLevelItemCount())
      FillTree();

    exec();
  }

}
<commit_msg>Spelling fix.<commit_after>#include "update_dialog.hpp"
#include "info_dialog.hpp"

#include "../platform/settings.hpp"

#include "../base/assert.hpp"

#include "../std/bind.hpp"

#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QTreeWidget>
#include <QtGui/QHeaderView>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtCore/QDateTime>

#define CHECK_FOR_UPDATE "Check for update"
#define LAST_UPDATE_CHECK "Last update check: "
/// used in settings
#define LAST_CHECK_TIME_KEY "LastUpdateCheckTime"

using namespace storage;

enum
{
//  KItemIndexFlag = 0,
  KColumnIndexCountry,
  KColumnIndexStatus,
  KColumnIndexSize,
  KNumberOfColumns
};

#define COLOR_NOTDOWNLOADED   Qt::black
#define COLOR_ONDISK          Qt::darkGreen
#define COLOR_INPROGRESS      Qt::blue
#define COLOR_DOWNLOADFAILED  Qt::red
#define COLOR_INQUEUE         Qt::gray

namespace qt
{
///////////////////////////////////////////////////////////////////////////////
// Helpers
///////////////////////////////////////////////////////////////////////////////
  /// adds custom sorting for "Size" column
  class QTreeWidgetItemWithCustomSorting : public QTreeWidgetItem
  {
  public:
    virtual bool operator<(QTreeWidgetItem const & other) const
    {
      return data(KColumnIndexSize, Qt::UserRole).toULongLong() < other.data(KColumnIndexSize, Qt::UserRole).toULongLong();
    }
  };
////////////////////////////////////////////////////////////////////////////////

  UpdateDialog::UpdateDialog(QWidget * parent, Storage & storage)
    : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), m_storage(storage)
  {
    setWindowModality(Qt::WindowModal);

    QPushButton * closeButton = new QPushButton(QObject::tr("Close"), this);
    closeButton->setDefault(true);
    connect(closeButton, SIGNAL(clicked()), this, SLOT(OnCloseClick()));

    m_tree = new QTreeWidget(this);
    m_tree->setColumnCount(KNumberOfColumns);
    QStringList columnLabels;
    columnLabels << tr("Country") << tr("Status") << tr("Size");
    m_tree->setHeaderLabels(columnLabels);
    connect(m_tree, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(OnItemClick(QTreeWidgetItem *, int)));

    QHBoxLayout * horizontalLayout = new QHBoxLayout();
    horizontalLayout->addStretch();
    horizontalLayout->addWidget(closeButton);

    QVBoxLayout * verticalLayout = new QVBoxLayout();
    verticalLayout->addWidget(m_tree);
    verticalLayout->addLayout(horizontalLayout);
    setLayout(verticalLayout);

    setWindowTitle(tr("Geographical Regions"));
    resize(600, 500);

    // we want to receive all download progress and result events
    m_storage.Subscribe(bind(&UpdateDialog::OnCountryChanged, this, _1),
                        bind(&UpdateDialog::OnCountryDownloadProgress, this, _1, _2));
  }

  UpdateDialog::~UpdateDialog()
  {
    // tell download manager that we're gone...
    m_storage.Unsubscribe();
  }

  /// when user clicks on any map row in the table
  void UpdateDialog::OnItemClick(QTreeWidgetItem * item, int /*column*/)
  {
    // calculate index of clicked item
    QList<int> treeIndex;
    {
      QTreeWidgetItem * parent = item;
      while (parent)
      {
        treeIndex.insert(0, parent->data(KColumnIndexCountry, Qt::UserRole).toInt());
        parent = parent->parent();
      }
      while (treeIndex.size() < 3)
        treeIndex.append(TIndex::INVALID);
    }

    TIndex const countryIndex(treeIndex[0], treeIndex[1], treeIndex[2]);
    switch (m_storage.CountryStatus(countryIndex))
    {
    case EOnDisk:
      {
        // map is already downloaded, so ask user about deleting!
        QMessageBox ask(this);
        ask.setText(tr("Do you want to delete %1?").arg(item->text(KColumnIndexCountry)));
        ask.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        ask.setDefaultButton(QMessageBox::No);
        if (ask.exec() == QMessageBox::Yes)
          m_storage.DeleteCountry(countryIndex);
      }
      break;

    case ENotDownloaded:
    case EDownloadFailed:
      m_storage.DownloadCountry(countryIndex);
      break;

    case EInQueue:
    case EDownloading:
      m_storage.DeleteCountry(countryIndex);
      break;

    case EGeneratingIndex:
      // we can't stop index genertion at this moment
      break;
    }
  }

  QTreeWidgetItem * MatchedItem(QTreeWidgetItem & parent, int index)
  {
    if (index >= 0)
    {
      for (int i = 0; i < parent.childCount(); ++i)
      {
        QTreeWidgetItem * item = parent.child(i);
        if (index == item->data(KColumnIndexCountry, Qt::UserRole).toInt())
          return item;
      }
    }
    return NULL;
  }

  /// @return can be null if index is invalid
  QTreeWidgetItem * GetTreeItemByIndex(QTreeWidget & tree, TIndex const & index)
  {
    QTreeWidgetItem * item = 0;
    if (index.m_group >= 0)
    {
      for (int i = 0; i < tree.topLevelItemCount(); ++i)
      {
        QTreeWidgetItem * grItem = tree.topLevelItem(i);
        if (index.m_group == grItem->data(KColumnIndexCountry, Qt::UserRole).toInt())
        {
          item = grItem;
          break;
        }
      }
    }
    if (item && index.m_country >= 0)
    {
      item = MatchedItem(*item, index.m_country);
      if (item && index.m_region >= 0)
        item = MatchedItem(*item, index.m_region);
    }
    return item;
  }

  void UpdateDialog::OnCloseClick()
  {
    done(0);
  }

  /// Changes row's text color
  void SetRowColor(QTreeWidgetItem & item, QColor const & color)
  {
    for (int column = 0; column < item.columnCount(); ++column)
      item.setTextColor(column, color);
  }

  void UpdateDialog::UpdateRowWithCountryInfo(TIndex const & index)
  {
    QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
    if (item)
    {
      QColor rowColor;
      QString statusString;
      LocalAndRemoteSizeT size(0, 0);
      switch (m_storage.CountryStatus(index))
      {
      case ENotDownloaded:
        statusString = tr("Click to download");
        rowColor = COLOR_NOTDOWNLOADED;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EOnDisk:
        statusString = tr("Installed (click to delete)");
        rowColor = COLOR_ONDISK;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EDownloadFailed:
        statusString = tr("Download has failed");
        rowColor = COLOR_DOWNLOADFAILED;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EDownloading:
        statusString = tr("Downloading ...");
        rowColor = COLOR_INPROGRESS;
        break;

      case EInQueue:
        statusString = tr("Marked for download");
        rowColor = COLOR_INQUEUE;
        size = m_storage.CountrySizeInBytes(index);
        break;

      case EGeneratingIndex:
        statusString = tr("Generating search index ...");
        rowColor = COLOR_INPROGRESS;
        break;
      }

      if (statusString.size())
        item->setText(KColumnIndexStatus, statusString);

      if (size.second)
      {
        if (size.second > 1000 * 1000 * 1000)
          item->setText(KColumnIndexSize, QString("%1/%2 GB").arg(
              uint(size.first / (1000 * 1000 * 1000))).arg(uint(size.second / (1000 * 1000 * 1000))));
        else if (size.second > 1000 * 1000)
          item->setText(KColumnIndexSize, QString("%1/%2 MB").arg(
              uint(size.first / (1000 * 1000))).arg(uint(size.second / (1000 * 1000))));
        else
          item->setText(KColumnIndexSize, QString("%1/%2 kB").arg(
              uint((size.first + 999) / 1000)).arg(uint((size.second + 999) / 1000)));
        // needed for column sorting
        item->setData(KColumnIndexSize, Qt::UserRole, QVariant(qint64(size.second)));
      }

      if (statusString.size())
        SetRowColor(*item, rowColor);
    }
  }

  void UpdateDialog::FillTree()
  {
    m_tree->setSortingEnabled(false);
    m_tree->clear();

    for (int group = 0; group < static_cast<int>(m_storage.CountriesCount(TIndex())); ++group)
    {
      TIndex const grIndex(group);
      QStringList groupText(QString::fromUtf8(m_storage.CountryName(grIndex).c_str()));
      QTreeWidgetItem * groupItem = new QTreeWidgetItem(groupText);
      groupItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(group));
      m_tree->addTopLevelItem(groupItem);
      // set color by status and update country size
      UpdateRowWithCountryInfo(grIndex);

      for (int country = 0; country < static_cast<int>(m_storage.CountriesCount(grIndex)); ++country)
      {
        TIndex cIndex(group, country);
        QStringList countryText(QString::fromUtf8(m_storage.CountryName(cIndex).c_str()));
        QTreeWidgetItem * countryItem = new QTreeWidgetItem(groupItem, countryText);
        countryItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(country));
        // set color by status and update country size
        UpdateRowWithCountryInfo(cIndex);

        for (int region = 0; region < static_cast<int>(m_storage.CountriesCount(cIndex)); ++region)
        {
          TIndex const rIndex(group, country, region);
          QStringList regionText(QString::fromUtf8(m_storage.CountryName(rIndex).c_str()));
          QTreeWidgetItem * regionItem = new QTreeWidgetItem(countryItem, regionText);
          regionItem->setData(KColumnIndexCountry, Qt::UserRole, QVariant(region));
          // set color by status and update country size
          UpdateRowWithCountryInfo(rIndex);
        }
      }
    }
//        // Size column, actual size will be set later
//        QTableWidgetItemWithCustomSorting * sizeItem = new QTableWidgetItemWithCustomSorting;
//        sizeItem->setFlags(sizeItem->flags() ^ Qt::ItemIsEditable);
//        m_table->setItem(row, KItemIndexSize, sizeItem);

    m_tree->sortByColumn(KColumnIndexCountry, Qt::AscendingOrder);
    m_tree->setSortingEnabled(true);
    m_tree->header()->setResizeMode(KColumnIndexCountry, QHeaderView::ResizeToContents);
    m_tree->header()->setResizeMode(KColumnIndexStatus, QHeaderView::ResizeToContents);
  }

  void UpdateDialog::OnCountryChanged(TIndex const & index)
  {
    UpdateRowWithCountryInfo(index);
  }

  void UpdateDialog::OnCountryDownloadProgress(TIndex const & index,
                                               pair<int64_t, int64_t> const & progress)
  {
    QTreeWidgetItem * item = GetTreeItemByIndex(*m_tree, index);
    if (item)
    {
//      QString speed;
//      if (progress.m_bytesPerSec > 1000 * 1000)
//        speed = QString(" %1 MB/s").arg(QString::number(static_cast<double>(progress.m_bytesPerSec) / (1000.0 * 1000.0),
//                                                         'f', 1));
//      else if (progress.m_bytesPerSec > 1000)
//        speed = QString(" %1 kB/s").arg(progress.m_bytesPerSec / 1000);
//      else if (progress.m_bytesPerSec >= 0)
//        speed = QString(" %1 B/sec").arg(progress.m_bytesPerSec);

      item->setText(KColumnIndexSize, QString("%1%").arg(progress.first * 100 / progress.second));
//      item->setText(KColumnIndexSize, QString("%1%%2").arg(progress.m_current * 100 / progress.m_total)
//                    .arg(speed));
    }
  }

  void UpdateDialog::ShowDialog()
  {
    // if called for first time
    if (!m_tree->topLevelItemCount())
      FillTree();

    exec();
  }

}
<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#include <os>
#include <memdisk>
#include <net/inet>
#include <net/interfaces>
#include "serial.hpp"

// transport streams used when testing
#include "../fuzz/fuzzy_stream.hpp"
static fuzzy::Stream* ossl_fuzz_ptr = nullptr;
static fuzzy::Stream* s2n_fuzz_ptr = nullptr;

inline fuzzy::Stream_ptr create_stream(fuzzy::Stream** dest)
{
  return std::make_unique<fuzzy::Stream> (net::Socket{}, net::Socket{},
    [dest] (net::Stream::buffer_t buffer) -> void {
      (*dest)->give_payload(std::move(buffer));
    }, true);
}

static void do_test_serializing_tls(int index);
static void do_test_send_data();
static void do_test_completed();
static bool are_all_streams_at_stage(int stage);
static bool are_all_streams_atleast_stage(int stage);
static void test_failure(const std::string& data) {
  printf("Received unexpected data: %s\n", data.c_str());
  printf("Length: %zu bytes\n", data.size());
  std::abort();
}
static std::string long_string(32000, '-');

struct Testing
{
  static const int NUM_STAGES = 7;
  int index = 0;
  int test_stage = 0;
  s2n::TLS_stream* stream = nullptr;
  std::string read_buffer = "";

  void send_data()
  {
    this->stream->write("Hello!");
    this->stream->write("Second write");
    this->stream->write(long_string);
  }
  void onread_function(net::Stream::buffer_t buffer)
  {
    assert(this->stream != nullptr && stream->is_connected());
    read_buffer += std::string(buffer->begin(), buffer->end());
    if (read_buffer == "Hello!") this->test_stage_advance();
    else if (read_buffer == "Second write") this->test_stage_advance();
    else if (read_buffer == long_string) this->test_stage_advance();
    // else: ... wait for more data
  }
  void connect_function(net::Stream& stream)
  {
    this->test_stage_advance();
    printf("TLS stream connected (%d / 2)\n", test_stage);
    this->send_data();
  }
  void test_stage_advance()
  {
    this->test_stage ++;
    this->read_buffer.clear();
    printf("[%d] Test stage: %d / %d\n",
           this->index, this->test_stage, NUM_STAGES);

    if (are_all_streams_atleast_stage(1))
    {
      // serialize and deserialize TLS after connected
      do_test_serializing_tls(this->index);
    }
    if (are_all_streams_at_stage(4))
    {
      printf("Now resending test data\n");
      // perform some writes at stage 4
      do_test_send_data();
    }
    if (are_all_streams_atleast_stage(1))
    {
      // serialize and deserialize TLS again
      do_test_serializing_tls(this->index);
    }
    if (are_all_streams_at_stage(NUM_STAGES)) {
      do_test_completed();
    }
  }
  void setup_callbacks()
  {
    stream->on_connect({this, &Testing::connect_function});
    stream->on_read(8192, {this, &Testing::onread_function});
  }
};
static struct Testing server_test;
static struct Testing client_test;

bool are_all_streams_at_stage(int stage)
{
  return server_test.test_stage == stage &&
         client_test.test_stage == stage;
}
bool are_all_streams_atleast_stage(int stage)
{
  return server_test.test_stage >= stage &&
         client_test.test_stage >= stage;
}
void do_test_serializing_tls(int index)
{
  char sbuffer[64*1024]; // 64KB server buffer
  char cbuffer[64*1024]; // 64KB client buffer
  printf("Now serializing TLS state\n");
  // 1. serialize TLS, destroy streams
  const size_t sbytes =
      server_test.stream->serialize_to(sbuffer, sizeof(sbuffer));
  assert(sbytes > 0 && "Its only failed if it returned zero");
  //printf("Server channel used %zu bytes\n", sbytes);
  const size_t cbytes =
      client_test.stream->serialize_to(cbuffer, sizeof(cbuffer));
  assert(cbytes > 0 && "Its only failed if it returned zero");
  //printf("Client channel used %zu bytes\n", cbytes);

  // 2. deserialize TLS, create new streams
  printf("Now deserializing TLS state\n");

  // 2.1: create new transport streams
  auto server_side = create_stream(&ossl_fuzz_ptr);
  s2n_fuzz_ptr = server_side.get();
  auto client_side = create_stream(&s2n_fuzz_ptr);
  ossl_fuzz_ptr = client_side.get();

  // 2.2: deserialize TLS config/context
  auto* config = s2n::serial_get_config();

  // 2.3: deserialize TLS streams
  // 2.3.1:
  auto dstream = s2n::TLS_stream::deserialize_from(
                  config,
                  std::move(server_side),
                  false,
                  sbuffer, sbytes
                );
  assert(dstream != nullptr && "Deserialization must return stream");
  server_test.stream = dstream.release();

  dstream = s2n::TLS_stream::deserialize_from(
                  config,
                  std::move(client_side),
                  false,
                  cbuffer, cbytes
                );
  assert(dstream != nullptr && "Deserialization must return stream");
  client_test.stream = dstream.release();

  // 3. set all delegates again
  server_test.setup_callbacks();
  client_test.setup_callbacks();
}
void do_test_send_data()
{
  server_test.send_data();
  client_test.send_data();
}
void do_test_completed()
{
  printf("SUCCESS\n");
  s2n::serial_test_over();
  OS::shutdown();
}

void Service::start()
{
  fs::memdisk().init_fs(
  [] (fs::error_t err, fs::File_system&) {
    assert(!err);
  });

  auto& filesys = fs::memdisk().fs();
  auto ca_cert = filesys.read_file("/test.pem");
  assert(ca_cert.is_valid());
  auto ca_key  = filesys.read_file("/test.key");
  assert(ca_key.is_valid());
  auto srv_key = filesys.read_file("/server.key");
  assert(srv_key.is_valid());
  printf("*** Loaded certificates and keys\n");

  // initialize S2N
  s2n::serial_test(ca_cert.to_string(), ca_key.to_string());

  // server fuzzy stream
  auto server_side = create_stream(&ossl_fuzz_ptr);
  s2n_fuzz_ptr = server_side.get();
  // client fuzzy stream
  auto client_side = create_stream(&s2n_fuzz_ptr);
  ossl_fuzz_ptr = client_side.get();

  server_test.index = 0;
  server_test.stream =
    new s2n::TLS_stream(s2n::serial_get_config(), std::move(server_side), false);
  client_test.index = 1;
  client_test.stream =
    new s2n::TLS_stream(s2n::serial_get_config(), std::move(client_side), true);

  server_test.setup_callbacks();
  client_test.setup_callbacks();
}
<commit_msg>s2n: Do more serialization passes early on<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#include <os>
#include <memdisk>
#include <net/inet>
#include <net/interfaces>
#include "serial.hpp"

// transport streams used when testing
#include "../fuzz/fuzzy_stream.hpp"
static fuzzy::Stream* ossl_fuzz_ptr = nullptr;
static fuzzy::Stream* s2n_fuzz_ptr = nullptr;

inline fuzzy::Stream_ptr create_stream(fuzzy::Stream** dest)
{
  return std::make_unique<fuzzy::Stream> (net::Socket{}, net::Socket{},
    [dest] (net::Stream::buffer_t buffer) -> void {
      (*dest)->give_payload(std::move(buffer));
    }, true);
}

static void do_test_serializing_tls(int index);
static void do_test_send_data();
static void do_test_completed();
static bool are_all_streams_at_stage(int stage);
static bool are_all_streams_atleast_stage(int stage);
static void test_failure(const std::string& data) {
  printf("Received unexpected data: %s\n", data.c_str());
  printf("Length: %zu bytes\n", data.size());
  std::abort();
}
static std::string long_string(32000, '-');

struct Testing
{
  static const int NUM_STAGES = 7;
  int index = 0;
  int test_stage = 0;
  s2n::TLS_stream* stream = nullptr;
  std::string read_buffer = "";

  void send_data()
  {
    this->stream->write("Hello!");
    this->stream->write("Second write");
    this->stream->write(long_string);
  }
  void onread_function(net::Stream::buffer_t buffer)
  {
    assert(this->stream != nullptr && stream->is_connected());
    read_buffer += std::string(buffer->begin(), buffer->end());
    if (read_buffer == "Hello!") this->test_stage_advance();
    else if (read_buffer == "Second write") this->test_stage_advance();
    else if (read_buffer == long_string) this->test_stage_advance();
    // else: ... wait for more data
  }
  void connect_function(net::Stream& stream)
  {
    this->test_stage_advance();
    printf("TLS stream connected (%d / 2)\n", test_stage);
    this->send_data();
  }
  void test_stage_advance()
  {
    this->test_stage ++;
    this->read_buffer.clear();
    printf("[%d] Test stage: %d / %d\n",
           this->index, this->test_stage, NUM_STAGES);

    // serialize and deserialize TLS after connected
    do_test_serializing_tls(this->index);

    if (are_all_streams_at_stage(4))
    {
      printf("Now resending test data\n");
      // perform some writes at stage 4
      do_test_send_data();
    }

    // serialize and deserialize TLS again
    do_test_serializing_tls(this->index);

    if (are_all_streams_at_stage(NUM_STAGES)) {
      do_test_completed();
    }
  }
  void setup_callbacks()
  {
    stream->on_connect({this, &Testing::connect_function});
    stream->on_read(8192, {this, &Testing::onread_function});
  }
};
static struct Testing server_test;
static struct Testing client_test;

bool are_all_streams_at_stage(int stage)
{
  return server_test.test_stage == stage &&
         client_test.test_stage == stage;
}
bool are_all_streams_atleast_stage(int stage)
{
  return server_test.test_stage >= stage &&
         client_test.test_stage >= stage;
}
void do_test_serializing_tls(int index)
{
  char sbuffer[128*1024]; // server buffer
  char cbuffer[128*1024]; // client buffer
  printf(">>> Performing serialization / deserialization\n");
  // 1. serialize TLS, destroy streams
  const size_t sbytes =
      server_test.stream->serialize_to(sbuffer, sizeof(sbuffer));
  assert(sbytes > 0 && "Its only failed if it returned zero");
  const size_t cbytes =
      client_test.stream->serialize_to(cbuffer, sizeof(cbuffer));
  assert(cbytes > 0 && "Its only failed if it returned zero");

  // 2. deserialize TLS, create new streams
  //printf("Now deserializing TLS state\n");

  // 2.1: create new transport streams
  auto server_side = create_stream(&ossl_fuzz_ptr);
  s2n_fuzz_ptr = server_side.get();
  auto client_side = create_stream(&s2n_fuzz_ptr);
  ossl_fuzz_ptr = client_side.get();

  // 2.2: deserialize TLS config/context
  auto* config = s2n::serial_get_config();

  // 2.3: deserialize TLS streams
  // 2.3.1:
  auto dstream = s2n::TLS_stream::deserialize_from(
                  config,
                  std::move(server_side),
                  false,
                  sbuffer, sbytes
                );
  assert(dstream != nullptr && "Deserialization must return stream");
  server_test.stream = dstream.release();

  dstream = s2n::TLS_stream::deserialize_from(
                  config,
                  std::move(client_side),
                  false,
                  cbuffer, cbytes
                );
  assert(dstream != nullptr && "Deserialization must return stream");
  client_test.stream = dstream.release();

  // 3. set all delegates again
  server_test.setup_callbacks();
  client_test.setup_callbacks();
}
void do_test_send_data()
{
  server_test.send_data();
  client_test.send_data();
}
void do_test_completed()
{
  printf("SUCCESS\n");
  s2n::serial_test_over();
  OS::shutdown();
}

void Service::start()
{
  fs::memdisk().init_fs(
  [] (fs::error_t err, fs::File_system&) {
    assert(!err);
  });

  auto& filesys = fs::memdisk().fs();
  auto ca_cert = filesys.read_file("/test.pem");
  assert(ca_cert.is_valid());
  auto ca_key  = filesys.read_file("/test.key");
  assert(ca_key.is_valid());
  auto srv_key = filesys.read_file("/server.key");
  assert(srv_key.is_valid());
  printf("*** Loaded certificates and keys\n");

  // initialize S2N
  s2n::serial_test(ca_cert.to_string(), ca_key.to_string());

  // server fuzzy stream
  auto server_side = create_stream(&ossl_fuzz_ptr);
  s2n_fuzz_ptr = server_side.get();
  // client fuzzy stream
  auto client_side = create_stream(&s2n_fuzz_ptr);
  ossl_fuzz_ptr = client_side.get();

  server_test.index = 0;
  server_test.stream =
    new s2n::TLS_stream(s2n::serial_get_config(), std::move(server_side), false);
  client_test.index = 1;
  client_test.stream =
    new s2n::TLS_stream(s2n::serial_get_config(), std::move(client_side), true);

  server_test.setup_callbacks();
  client_test.setup_callbacks();
  printf("* TLS streams created!\n");

  // try serializing and deserializing just after creation
  do_test_serializing_tls(0);
}
<|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 "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/net_util.h"
#include "webkit/dom_storage/dom_storage_area.h"

namespace {

// The tests server is started separately for each test function (including PRE_
// functions). We need a test server which always uses the same port, so that
// the pages can be accessed with the same URLs after restoring the browser
// session.
class FixedPortTestServer : public net::LocalTestServer {
 public:
  explicit FixedPortTestServer(uint16 port)
      :  LocalTestServer(
             net::TestServer::TYPE_HTTP,
             net::TestServer::kLocalhost,
             FilePath().AppendASCII("chrome/test/data")) {
    BaseTestServer::SetPort(port);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(FixedPortTestServer);
};

}  // namespace

class BetterSessionRestoreTest : public InProcessBrowserTest {
 public:
  BetterSessionRestoreTest()
      : test_server_(8001),
        title_pass_(ASCIIToUTF16("PASS")),
        title_storing_(ASCIIToUTF16("STORING")),
        title_error_write_failed_(ASCIIToUTF16("ERROR_WRITE_FAILED")),
        title_error_empty_(ASCIIToUTF16("ERROR_EMPTY")) {
    CHECK(test_server_.Start());
  }
 protected:
  void StoreDataWithPage(const std::string& filename) {
    GURL url = test_server_.GetURL("files/session_restore/" + filename);
    content::WebContents* web_contents =
        chrome::GetActiveWebContents(browser());
    content::TitleWatcher title_watcher(web_contents, title_storing_);
    title_watcher.AlsoWaitForTitle(title_pass_);
    title_watcher.AlsoWaitForTitle(title_error_write_failed_);
    title_watcher.AlsoWaitForTitle(title_error_empty_);
    ui_test_utils::NavigateToURL(browser(), url);
    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(title_storing_, final_title);
  }

  void CheckReloadedPage() {
    content::WebContents* web_contents = chrome::GetWebContentsAt(browser(), 0);
    content::TitleWatcher title_watcher(web_contents, title_pass_);
    title_watcher.AlsoWaitForTitle(title_storing_);
    title_watcher.AlsoWaitForTitle(title_error_write_failed_);
    title_watcher.AlsoWaitForTitle(title_error_empty_);
    // It's possible that the title was already the right one before
    // title_watcher was created.
    if (web_contents->GetTitle() != title_pass_) {
      string16 final_title = title_watcher.WaitAndGetTitle();
      EXPECT_EQ(title_pass_, final_title);
    }
  }

 private:
  FixedPortTestServer test_server_;
  string16 title_pass_;
  string16 title_storing_;
  string16 title_error_write_failed_;
  string16 title_error_empty_;

  DISALLOW_COPY_AND_ASSIGN(BetterSessionRestoreTest);
};

// BetterSessionRestoreTest tests fail under AddressSanitizer, see
// http://crbug.com/156444.
#if defined(ADDRESS_SANITIZER)
# define MAYBE_PRE_SessionCookies DISABLED_PRE_SessionCookies
# define MAYBE_SessionCookies DISABLED_SessionCookies
# define MAYBE_PRE_SessionStorage DISABLED_PRE_SessionStorage
# define MAYBE_SessionStorage DISABLED_SessionStorage
#else
// SessionCookies and SessionStorage are failing consistently on webkit canary
// builders. http://crbug.com/156444.
# define MAYBE_PRE_SessionCookies DISABLED_PRE_SessionCookies
# define MAYBE_SessionCookies DISABLED_SessionCookies
# define MAYBE_PRE_SessionStorage DISABLED_PRE_SessionStorage
# define MAYBE_SessionStorage DISABLED_SessionStorage
#endif

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionCookies) {
  // Set the startup preference to "continue where I left off" and visit a page
  // which stores a session cookie.
  SessionStartupPref::SetStartupPref(
      browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
  StoreDataWithPage("session_cookies.html");
}

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionCookies) {
  // The browsing session will be continued; just wait for the page to reload
  // and check the stored data.
  CheckReloadedPage();
}

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionStorage) {
  // Write the data on disk less lazily.
  dom_storage::DomStorageArea::DisableCommitDelayForTesting();
  SessionStartupPref::SetStartupPref(
      browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
  StoreDataWithPage("session_storage.html");
}

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionStorage) {
  CheckReloadedPage();
}
<commit_msg>Better session restore test fix: Don't use a test server with a fixed port.<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 "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_filter.h"
#include "net/url_request/url_request_test_job.h"
#include "webkit/dom_storage/dom_storage_area.h"

namespace {

// We need to serve the test files so that PRE_Test and Test can access the same
// page using the same URL. In addition, perceived security origin of the page
// needs to stay the same, so e.g., redirecting the URL requests doesn't
// work. (If we used a test server, the PRE_Test and Test would have separate
// instances running on separate ports.)

static base::LazyInstance<std::map<std::string, std::string> > file_contents =
    LAZY_INSTANCE_INITIALIZER;

net::URLRequestJob* URLRequestFaker(
    net::URLRequest* request,
    net::NetworkDelegate* network_delegate,
    const std::string& scheme) {
  return new net::URLRequestTestJob(
      request, network_delegate, net::URLRequestTestJob::test_headers(),
      file_contents.Get()[request->url().path()], true);
}

}  // namespace

class BetterSessionRestoreTest : public InProcessBrowserTest {
 public:
  BetterSessionRestoreTest()
      : title_pass_(ASCIIToUTF16("PASS")),
        title_storing_(ASCIIToUTF16("STORING")),
        title_error_write_failed_(ASCIIToUTF16("ERROR_WRITE_FAILED")),
        title_error_empty_(ASCIIToUTF16("ERROR_EMPTY")),
        fake_server_address_("http://www.test.com/"),
        test_path_("session_restore/") {
    // Set up the URL request filtering.
    std::vector<std::string> test_files;
    test_files.push_back("common.js");
    test_files.push_back("session_cookies.html");
    test_files.push_back("session_storage.html");
    FilePath test_file_dir;
    CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &test_file_dir));
    test_file_dir =
        test_file_dir.AppendASCII("chrome/test/data").AppendASCII(test_path_);

    for (std::vector<std::string>::const_iterator it = test_files.begin();
         it != test_files.end(); ++it) {
      FilePath path = test_file_dir.AppendASCII(*it);
      std::string contents;
      CHECK(file_util::ReadFileToString(path, &contents));
      file_contents.Get()["/" + test_path_ + *it] = contents;
      net::URLRequestFilter::GetInstance()->AddUrlHandler(
          GURL(fake_server_address_ + test_path_ + *it),
          &URLRequestFaker);
    }
  }

 protected:
  void StoreDataWithPage(const std::string& filename) {
    content::WebContents* web_contents =
        chrome::GetActiveWebContents(browser());
    content::TitleWatcher title_watcher(web_contents, title_storing_);
    title_watcher.AlsoWaitForTitle(title_pass_);
    title_watcher.AlsoWaitForTitle(title_error_write_failed_);
    title_watcher.AlsoWaitForTitle(title_error_empty_);
    ui_test_utils::NavigateToURL(
        browser(), GURL(fake_server_address_ + test_path_ + filename));
    string16 final_title = title_watcher.WaitAndGetTitle();
    EXPECT_EQ(title_storing_, final_title);
  }

  void CheckReloadedPage() {
    content::WebContents* web_contents = chrome::GetWebContentsAt(browser(), 0);
    content::TitleWatcher title_watcher(web_contents, title_pass_);
    title_watcher.AlsoWaitForTitle(title_storing_);
    title_watcher.AlsoWaitForTitle(title_error_write_failed_);
    title_watcher.AlsoWaitForTitle(title_error_empty_);
    // It's possible that the title was already the right one before
    // title_watcher was created.
    if (web_contents->GetTitle() != title_pass_) {
      string16 final_title = title_watcher.WaitAndGetTitle();
      EXPECT_EQ(title_pass_, final_title);
    }
  }

 private:
  string16 title_pass_;
  string16 title_storing_;
  string16 title_error_write_failed_;
  string16 title_error_empty_;
  std::string fake_server_address_;
  std::string test_path_;

  DISALLOW_COPY_AND_ASSIGN(BetterSessionRestoreTest);
};

// BetterSessionRestoreTest tests fail under AddressSanitizer, see
// http://crbug.com/156444.
#if defined(ADDRESS_SANITIZER)
# define MAYBE_PRE_SessionCookies DISABLED_PRE_SessionCookies
# define MAYBE_SessionCookies DISABLED_SessionCookies
# define MAYBE_PRE_SessionStorage DISABLED_PRE_SessionStorage
# define MAYBE_SessionStorage DISABLED_SessionStorage
#else
# define MAYBE_PRE_SessionCookies PRE_SessionCookies
# define MAYBE_SessionCookies SessionCookies
# define MAYBE_PRE_SessionStorage PRE_SessionStorage
# define MAYBE_SessionStorage SessionStorage
#endif

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionCookies) {
  // Set the startup preference to "continue where I left off" and visit a page
  // which stores a session cookie.
  SessionStartupPref::SetStartupPref(
      browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
  StoreDataWithPage("session_cookies.html");
}

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionCookies) {
  // The browsing session will be continued; just wait for the page to reload
  // and check the stored data.
  CheckReloadedPage();
}

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_PRE_SessionStorage) {
  // Write the data on disk less lazily.
  dom_storage::DomStorageArea::DisableCommitDelayForTesting();
  SessionStartupPref::SetStartupPref(
      browser()->profile(), SessionStartupPref(SessionStartupPref::LAST));
  StoreDataWithPage("session_storage.html");
}

// crbug.com/156981
IN_PROC_BROWSER_TEST_F(BetterSessionRestoreTest, MAYBE_SessionStorage) {
  CheckReloadedPage();
}
<|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/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/debug/dump_without_crashing.h"
#include "base/rand_util.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_version_info.h"

namespace browser_sync {

void ChromeReportUnrecoverableError() {
  // Only upload on canary/dev builds to avoid overwhelming crash server.
  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel != chrome::VersionInfo::CHANNEL_CANARY &&
      channel != chrome::VersionInfo::CHANNEL_DEV) {
    return;
  }

  // We only want to upload |kErrorUploadRatio| ratio of errors.
  const double kErrorUploadRatio = 0.15;
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  base::debug::DumpWithoutCrashing();
}

}  // namespace browser_sync
<commit_msg>[Sync] Disable unrecoverable error uploading<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/sync/glue/chrome_report_unrecoverable_error.h"

#include "base/debug/dump_without_crashing.h"
#include "base/rand_util.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_version_info.h"

namespace browser_sync {

void ChromeReportUnrecoverableError() {
  // Only upload on canary/dev builds to avoid overwhelming crash server.
  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel != chrome::VersionInfo::CHANNEL_CANARY &&
      channel != chrome::VersionInfo::CHANNEL_DEV) {
    return;
  }

  // We only want to upload |kErrorUploadRatio| ratio of errors.
  const double kErrorUploadRatio = 0.0;
  if (kErrorUploadRatio <= 0.0)
    return; // We are not allowed to upload errors.
  double random_number = base::RandDouble();
  if (random_number > kErrorUploadRatio)
    return;

  base::debug::DumpWithoutCrashing();
}

}  // namespace browser_sync
<|endoftext|>


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

#include "chrome/browser/ui/views/crypto_module_password_dialog_view.h"

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/window.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"

int kInputPasswordMinWidth = 8;

namespace browser {

// CryptoModulePasswordDialogView
////////////////////////////////////////////////////////////////////////////////
CryptoModulePasswordDialogView::CryptoModulePasswordDialogView(
    const std::string& slot_name,
    browser::CryptoModulePasswordReason reason,
    const std::string& server,
    const base::Callback<void(const char*)>& callback)
    : callback_(callback) {
  Init(server, slot_name, reason);
}

CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() {
}

void CryptoModulePasswordDialogView::Init(
    const std::string& server,
    const std::string& slot_name,
    browser::CryptoModulePasswordReason reason) {
  // Select an appropriate text for the reason.
  std::string text;
  const string16& server16 = UTF8ToUTF16(server);
  const string16& slot16 = UTF8ToUTF16(slot_name);
  switch (reason) {
    case browser::kCryptoModulePasswordKeygen:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16);
      break;
    case browser::kCryptoModulePasswordCertEnrollment:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16);
      break;
    case browser::kCryptoModulePasswordClientAuth:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16);
      break;
    case browser::kCryptoModulePasswordListCerts:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16);
      break;
    case browser::kCryptoModulePasswordCertImport:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16);
      break;
    case browser::kCryptoModulePasswordCertExport:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16);
      break;
    default:
      NOTREACHED();
  }
  reason_label_ = new views::Label(UTF8ToUTF16(text));
  reason_label_->SetMultiLine(true);

  password_label_ = new views::Label(l10n_util::GetStringUTF16(
      IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD));

  password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED);
  password_entry_->SetController(this);

  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
  SetLayoutManager(layout);

  views::ColumnSet* reason_column_set = layout->AddColumnSet(0);
  reason_column_set->AddColumn(
      views::GridLayout::LEADING, views::GridLayout::LEADING, 1,
      views::GridLayout::USE_PREF, 0, 0);

  views::ColumnSet* column_set = layout->AddColumnSet(1);
  column_set->AddColumn(views::GridLayout::LEADING,
                        views::GridLayout::LEADING, 0,
                        views::GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(
      0, views::kUnrelatedControlLargeHorizontalSpacing);
  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                        views::GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, 0);
  layout->AddView(reason_label_);
  layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);

  layout->StartRow(0, 1);
  layout->AddView(password_label_);
  layout->AddView(password_entry_);
}

views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() {
  return password_entry_;
}
ui::ModalType CryptoModulePasswordDialogView::GetModalType() const {
  return ui::MODAL_TYPE_WINDOW;
}
views::View* CryptoModulePasswordDialogView::GetContentsView() {
  return this;
}

string16 CryptoModulePasswordDialogView::GetDialogButtonLabel(
    ui::DialogButton button) const {
  if (button == ui::DIALOG_BUTTON_OK)
    return UTF8ToUTF16(l10n_util::GetStringUTF8(
        IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL));
  else if (button == ui::DIALOG_BUTTON_CANCEL)
    return UTF8ToUTF16(l10n_util::GetStringUTF8(IDS_CANCEL));
  const string16 empty;
  return empty;
}

bool CryptoModulePasswordDialogView::Accept() {
  callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str());
  const string16 empty;
  password_entry_->SetText(empty);
  return true;
}

bool CryptoModulePasswordDialogView::Cancel() {
  callback_.Run(static_cast<const char*>(NULL));
  const string16 empty;
  password_entry_->SetText(empty);
  return true;
}

bool CryptoModulePasswordDialogView::HandleKeyEvent(
    views::Textfield* sender,
    const views::KeyEvent& keystroke) {
  return false;
}

void CryptoModulePasswordDialogView::ContentsChanged(
    views::Textfield* sender,
    const string16& new_contents) {
}

string16 CryptoModulePasswordDialogView::GetWindowTitle() const {
  return UTF8ToUTF16(l10n_util::GetStringUTF8(
      IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE));
}

void ShowCryptoModulePasswordDialog(
    const std::string& slot_name,
    bool retry,
    CryptoModulePasswordReason reason,
    const std::string& server,
    const CryptoModulePasswordCallback& callback) {
  CryptoModulePasswordDialogView* dialog =
      new CryptoModulePasswordDialogView(
          slot_name, reason, server, callback);
  views::Widget::CreateWindowWithParent(dialog, NULL)->Show();
}

}  // namespace browser
<commit_msg>views: Avoid conversions from UTF8 to UTF16 in CryptoModulePasswordDialogView.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/crypto_module_password_dialog_view.h"

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/views/window.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/layout/layout_constants.h"
#include "ui/views/widget/widget.h"

int kInputPasswordMinWidth = 8;

namespace browser {

// CryptoModulePasswordDialogView
////////////////////////////////////////////////////////////////////////////////
CryptoModulePasswordDialogView::CryptoModulePasswordDialogView(
    const std::string& slot_name,
    browser::CryptoModulePasswordReason reason,
    const std::string& server,
    const base::Callback<void(const char*)>& callback)
    : callback_(callback) {
  Init(server, slot_name, reason);
}

CryptoModulePasswordDialogView::~CryptoModulePasswordDialogView() {
}

void CryptoModulePasswordDialogView::Init(
    const std::string& server,
    const std::string& slot_name,
    browser::CryptoModulePasswordReason reason) {
  // Select an appropriate text for the reason.
  std::string text;
  const string16& server16 = UTF8ToUTF16(server);
  const string16& slot16 = UTF8ToUTF16(slot_name);
  switch (reason) {
    case browser::kCryptoModulePasswordKeygen:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_KEYGEN, slot16, server16);
      break;
    case browser::kCryptoModulePasswordCertEnrollment:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_ENROLLMENT, slot16, server16);
      break;
    case browser::kCryptoModulePasswordClientAuth:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CLIENT_AUTH, slot16, server16);
      break;
    case browser::kCryptoModulePasswordListCerts:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_LIST_CERTS, slot16);
      break;
    case browser::kCryptoModulePasswordCertImport:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_IMPORT, slot16);
      break;
    case browser::kCryptoModulePasswordCertExport:
      text = l10n_util::GetStringFUTF8(
          IDS_CRYPTO_MODULE_AUTH_DIALOG_TEXT_CERT_EXPORT, slot16);
      break;
    default:
      NOTREACHED();
  }
  reason_label_ = new views::Label(UTF8ToUTF16(text));
  reason_label_->SetMultiLine(true);

  password_label_ = new views::Label(l10n_util::GetStringUTF16(
      IDS_CRYPTO_MODULE_AUTH_DIALOG_PASSWORD_FIELD));

  password_entry_ = new views::Textfield(views::Textfield::STYLE_OBSCURED);
  password_entry_->SetController(this);

  views::GridLayout* layout = views::GridLayout::CreatePanel(this);
  SetLayoutManager(layout);

  views::ColumnSet* reason_column_set = layout->AddColumnSet(0);
  reason_column_set->AddColumn(
      views::GridLayout::LEADING, views::GridLayout::LEADING, 1,
      views::GridLayout::USE_PREF, 0, 0);

  views::ColumnSet* column_set = layout->AddColumnSet(1);
  column_set->AddColumn(views::GridLayout::LEADING,
                        views::GridLayout::LEADING, 0,
                        views::GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(
      0, views::kUnrelatedControlLargeHorizontalSpacing);
  column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
                        views::GridLayout::USE_PREF, 0, 0);

  layout->StartRow(0, 0);
  layout->AddView(reason_label_);
  layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing);

  layout->StartRow(0, 1);
  layout->AddView(password_label_);
  layout->AddView(password_entry_);
}

views::View* CryptoModulePasswordDialogView::GetInitiallyFocusedView() {
  return password_entry_;
}
ui::ModalType CryptoModulePasswordDialogView::GetModalType() const {
  return ui::MODAL_TYPE_WINDOW;
}
views::View* CryptoModulePasswordDialogView::GetContentsView() {
  return this;
}

string16 CryptoModulePasswordDialogView::GetDialogButtonLabel(
    ui::DialogButton button) const {
  return l10n_util::GetStringUTF16(button == ui::DIALOG_BUTTON_OK ?
      IDS_CRYPTO_MODULE_AUTH_DIALOG_OK_BUTTON_LABEL : IDS_CANCEL);
}

bool CryptoModulePasswordDialogView::Accept() {
  callback_.Run(UTF16ToUTF8(password_entry_->text()).c_str());
  const string16 empty;
  password_entry_->SetText(empty);
  return true;
}

bool CryptoModulePasswordDialogView::Cancel() {
  callback_.Run(static_cast<const char*>(NULL));
  const string16 empty;
  password_entry_->SetText(empty);
  return true;
}

bool CryptoModulePasswordDialogView::HandleKeyEvent(
    views::Textfield* sender,
    const views::KeyEvent& keystroke) {
  return false;
}

void CryptoModulePasswordDialogView::ContentsChanged(
    views::Textfield* sender,
    const string16& new_contents) {
}

string16 CryptoModulePasswordDialogView::GetWindowTitle() const {
  return l10n_util::GetStringUTF16(IDS_CRYPTO_MODULE_AUTH_DIALOG_TITLE);
}

void ShowCryptoModulePasswordDialog(
    const std::string& slot_name,
    bool retry,
    CryptoModulePasswordReason reason,
    const std::string& server,
    const CryptoModulePasswordCallback& callback) {
  CryptoModulePasswordDialogView* dialog =
      new CryptoModulePasswordDialogView(slot_name, reason, server, callback);
  views::Widget::CreateWindowWithParent(dialog, NULL)->Show();
}

}  // namespace browser
<|endoftext|>